diff --git a/.eslintignore b/.eslintignore
index 3c3629e6..3b0a90db 100644
--- a/.eslintignore
+++ b/.eslintignore
@@ -1 +1,5 @@
node_modules
+/dist
+/node_modules
+.eslintrc.js
+*.js
diff --git a/.github/workflows/build-test.yml b/.github/workflows/build-test.yml
index cf5dde5a..ddf834d9 100644
--- a/.github/workflows/build-test.yml
+++ b/.github/workflows/build-test.yml
@@ -4,7 +4,7 @@ on:
push:
pull_request:
schedule:
- - cron: '0 1 * * SUN'
+ - cron: '0 1 * * *'
workflow_dispatch:
jobs:
@@ -22,18 +22,18 @@ jobs:
submodules: true
- uses: actions/setup-node@v4
with:
- node-version: '16.x'
+ node-version: '20.x'
# How to consume GitHub packages, from this message (!): https://github.community/t/download-from-github-package-registry-without-authentication/14407/35
# Inspired from here: https://github.com/jcansdale-test/npmrc-configurations/blob/master/.github/workflows/blank.yml
- name: Authenticate to GitHub Packages
run: |
echo "//npm.pkg.github.com/:_authToken=${{ secrets.GITHUB_TOKEN }}" > ~/.npmrc
echo "@${{ github.repository_owner }}:registry=https://npm.pkg.github.com/" >> ~/.npmrc
- - run: |
- npm install
- npm run test
- name: build and test
- shell: bash
+ - run: npm install
+ - run: npm run build
+ - run: npm run lint
+ - run: npm run test
+ - run: npm run pack
- name: Coveralls
uses: coverallsapp/github-action@v2
with:
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index a8a0a18f..1e2f7f63 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -1,16 +1,25 @@
# Contributing
- * [Prerequisites](#prerequisites)
- * [Building](#build-and-lint)
- * [Packaging](#packaging)
- * [Testing](#testing)
+- [Contributing](#contributing)
+ - [Prerequisites](#prerequisites)
+ - [Setup for consuming GitHub Registry public packages](#setup-for-consuming-github-registry-public-packages)
+ - [Build and lint](#build-and-lint)
+ - [Packaging](#packaging)
+ - [Testing](#testing)
The software is provided as is, there is no warranty of any kind. All users are encouraged to improve the [source code](https://github.com/lukka/run-vcpkg) with fixes and new features contributed by means of Pull Requests.
## Prerequisites
-[gulp 4](https://www.npmjs.com/package/gulp4) globally installed.
-### Setup for GitHub Registry public packages
+Run
+
+```bash
+npm install
+```
+
+to populate the dependencies in `./node_modules` directory.
+
+### Setup for consuming GitHub Registry public packages
`run-vcpkg` depends on public NPM packages published by [lukka/run-cmake-vcpkg-action-libs](https://github.com/lukka/run-cmake-vcpkg-action-libs) in the [GitHub Packages registry](https://docs.github.com/en/free-pro-team@latest/packages/using-github-packages-with-your-projects-ecosystem/configuring-npm-for-use-with-github-packages).
Unexpectedly, a public package still requires authentication when downloading it, hence if you want to `npm install` those packages correctly, you need to obtain a token with `read:packages` scope. Then create in the root of the repository a `.npmrc` file with the following content:
diff --git a/LICENSE.txt b/LICENSE.txt
index 09b8d0df..6fafb4fd 100644
--- a/LICENSE.txt
+++ b/LICENSE.txt
@@ -1,5 +1,5 @@
The MIT License (MIT)
-Copyright (c) 2019-2020-2021-2022 Luca Cappa
+Copyright (c) 2019-2020-2021-2022-2023 Luca Cappa
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
diff --git a/README.md b/README.md
index c151fc55..7b8f48d1 100644
--- a/README.md
+++ b/README.md
@@ -2,7 +2,7 @@
[![Coverage Status](https://coveralls.io/repos/github/lukka/run-vcpkg/badge.svg?branch=main)](https://coveralls.io/github/lukka/run-vcpkg?branch=main)
-- [**run-vcpkg@v11 requires vcpkg more recent than 2023-03-29 (e.g. commit id 5b1214315250939257ef5d62ecdcbca18cf4fb1c)**](#run-vcpkgv11-requires-vcpkg-more-recent-than-2023-03-29-eg-commit-id-5b1214315250939257ef5d62ecdcbca18cf4fb1c)
+- [Important: **run-vcpkg@v11 requirements**](#important-run-vcpkgv11-requirements)
- [Quickstart with a C++ project template](#quickstart-with-a-c-project-template)
- [The **run-vcpkg@v11** action](#the-run-vcpkgv11-action)
- [Quickstart with instructions](#quickstart-with-instructions)
@@ -17,7 +17,9 @@
- [Disclaimer](#disclaimer)
- [Contributing](#contributing)
-# **run-vcpkg@v11 requires vcpkg more recent than 2023-03-29 (e.g. commit id 5b1214315250939257ef5d62ecdcbca18cf4fb1c)**
+# Important: **run-vcpkg@v11 requirements**
+
+`run-vcpkg@v11` requires vcpkg more recent than 2023-03-29 (e.g. commit id `5b1214315250939257ef5d62ecdcbca18cf4fb1c`).
# Quickstart with a C++ project template
@@ -25,23 +27,23 @@ Take a look at this [C++ project template](https://github.com/lukka/CppCMakeVcpk
# [The **run-vcpkg@v11** action](https://github.com/marketplace/actions/run-vcpkg)
-The **run-vcpkg** action setups (and optionally runs) [vcpkg](https://github.com/microsoft/vcpkg) to install the packages specified in the `vcpkg.json` manifest file.
-It leverages the vcpkg's Binary Caching backed to GitHub Action cache, delegating cache and key management to vpckg.
+The **run-vcpkg@v11** action setups (and optionally runs) [vcpkg](https://github.com/microsoft/vcpkg) to install the packages specified in the `vcpkg.json` manifest file.
+It leverages the vcpkg's [Binary Caching](https://learn.microsoft.com/en-us/vcpkg/users/binarycaching) backed to [GitHub Action cache](https://docs.github.com/en/actions/using-workflows/caching-dependencies-to-speed-up-workflows), delegating cache and key management to vpckg.
Special features which provide added value over a __pure__ workflow are:
- automatic caching leveraging `vcpkg`'s ability to store its [Binary Caching](https://learn.microsoft.com/en-us/vcpkg/users/binarycaching) artifacts onto the [GitHub Action cache](https://docs.github.com/en/actions/using-workflows/caching-dependencies-to-speed-up-workflows) so that packages are built only once and reused in subsequent workflow runs. The user can customize the behavior by setting the environment variable `VCPKG_BINARY_SOURCES` *before* vcpkg runs.
- set the workflow variables `ACTIONS_CACHE_URL` and `ACTIONS_RUNTIME_TOKEN` to let users easily running vcpkg
- in a `run` step such as `- run: vcpkg install` or `- run: vcpkg integrate install` without forcing the
+ in a `run` step such as `- run: vcpkg install` or `- run: vcpkg integrate install` without forcing the
users to set the variables manually.
- automatic dump of log files created by `CMake` (e.g., `CMakeOutput.log`) and `vcpkg`. The content of those files flow into the workflow output log. Customizable by the user by setting the input `logCollectionRegExps`.
- automatic parsing of `CMake`, `vcpkg` and `gcc`, `clang`, `msvc` errors, reporting them contextually in the workflow summary by means of annotations.
- - although disabled by default (see input `doNotCache`), `run-vcpkg` can cache vcpkg's executable and data files to speed up subsequent workflow runs. Since bootstrapping `vcpkg` already downloads a prebuilt binary saving the time to build `vcpkg`,
+ - although disabled by default (see input `doNotCache`), `run-vcpkg` can cache vcpkg's executable and data files to speed up subsequent workflow runs. Since bootstrapping `vcpkg` already downloads a prebuilt binary saving the time to build `vcpkg`,
this form of caching is useful only when the prebuilt executable is not served as it happens for the ARM platform.
Note this cache does not contain the libraries built by vcpkg, which is instead managed by vcpkg itself.
The provided [samples](#samples) use [GitHub hosted runners](https://help.github.com/en/actions/automating-your-workflow-with-github-actions/virtual-environments-for-github-hosted-runners).
-Good companions are the [run-cmake](https://github.com/marketplace/actions/run-cmake) action and the
+Good companions are the [run-cmake](https://github.com/marketplace/actions/run-cmake) and the
[get-cmake](https://github.com/marketplace/actions/get-cmake) actions.
@@ -57,30 +59,39 @@ It is __highly recommended__ to use:
jobs:
build:
steps:
- #-uses: actions/cache@v1 <===== YOU DO NOT NEED THIS!
+ #-uses: actions/cache@v3 <===== YOU DO NOT NEED THIS!
- # Install latest CMake.
+ # Install latest CMake and Ninja.
- uses: lukka/get-cmake@latest
# Or pin to a specific CMake version:
- # lukka/get-cmake@v3.21.2
+ # lukka/get-cmake@v3.27
# Setup vcpkg: ensures vcpkg is downloaded and built.
# Since vcpkg.json is being used later on to install the packages
- # when `run-cmake` runs, no packages are installed at this time
+ # when `run-cmake` runs, no packages are installed at this time
# (and vcpkg does not run).
- - name: Setup vcpkg (it does not install any package yet)
- uses: lukka/run-vcpkg@v11
+ - name: Setup anew (or from cache) vcpkg (and does not build any package)
+ uses: lukka/run-vcpkg@v11 # Always specify the specific _version_ of the
+ # action you need, `v10` in this case to stay up
+ # to date with fixes on the v11 branch.
#with:
# This is the default location of the directory containing vcpkg sources.
# Change it to the right location if needed.
# vcpkgDirectory: '${{ github.workspace }}/vcpkg'
# If not using a submodule for vcpkg sources, this specifies which commit
- # id must be checkout from a Git repo.
+ # id must be checkout from a Git repo.
# Note: it must not be set if using a Git submodule for vcpkg.
# vcpkgGitCommitId: '${{ matrix.vcpkgCommitId }}'
- # This is the glob expression used to locate the vcpkg.json.
+ # This is only needed if the command `vcpkg install` must run at this step.
+ # Instead it is highly suggested to let `run-cmake` to run vcpkg later on
+ # using the vcpkg.cmake toolchain. The default is `false`.
+ # runVcpkgInstall: true
+
+ # This is only needed if `runVpkgInstall` is `true`.
+ # This glob expression used to locate the vcpkg.json and use
+ # its directory location as `working directory` when running `vcpkg install`.
# Change it to match a single manifest file you want to use.
# Note: do not use `${{ github.context }}` to compose the value as it
# contains backslashes that would be misinterpreted. Instead
@@ -88,12 +99,7 @@ jobs:
# `**/path/from/root/of/repo/to/vcpkg.json` to match the desired `vcpkg.json`.
# vcpkgJsonGlob: '**/vcpkg.json'
- # This is only needed if the command `vcpkg install` must run at this step.
- # Instead it is highly suggested to let `run-cmake` to run vcpkg later on
- # using the vcpkg.cmake toolchain. The default is `false`.
- # runVcpkgInstall: true
-
- - name: Run CMake consuming CMakePreset.json and run vcpkg to build dependencies
+ - name: Run CMake consuming CMakePreset.json and run vcpkg to build packages
uses: lukka/run-cmake@v10
with:
# This is the default path to the CMakeLists.txt along side the
@@ -101,29 +107,54 @@ jobs:
# located elsewhere.
# cmakeListsTxtPath: '${{ github.workspace }}/CMakeLists.txt'
+ # You could use CMake workflow presets defined in the CMakePresets.json
+ # with just this line below. Note this one cannot be used with any other
+ # preset input, it is mutually exclusive.
+ # workflowPreset: 'workflow-name'
+
# This is the name of the CMakePresets.json's configuration to use to generate
# the project files. This configuration leverages the vcpkg.cmake toolchain file to
# run vcpkg and install all dependencies specified in vcpkg.json.
configurePreset: 'ninja-multi-vcpkg'
+ # Additional arguments can be appended to the cmake command.
+ # This is useful to reduce the number of CMake's Presets since you can reuse
+ # an existing preset with different variables.
+ configurePresetAdditionalArgs: "['-DENABLE_YOUR_FEATURE=1']"
# This is the name of the CMakePresets.json's configuration to build the project.
buildPreset: 'ninja-multi-vcpkg'
+ # Additional arguments can be appended when building, for example to specify the
+ # configuration to build.
+ # This is useful to reduce the number of CMake's Presets you need in CMakePresets.json.
+ buildPresetAdditionalArgs: "['--config Release']"
+
+ # This is the name of the CMakePresets.json's configuration to test the project with.
+ testPreset: 'ninja-multi-vcpkg'
+ # Additional arguments can be appended when testing, for example to specify the config
+ # to test.
+ # This is useful to reduce the number of CMake's Presets you need in CMakePresets.json.
+ testPresetAdditionalArgs: "['--config Release']"
#env:
- # By default the action disables vcpkg's telemetry by defining VCPKG_DISABLE_METRICS.
- # This behavior can be disabled by defining `VCPKG_ENABLE_METRICS` as follows.
- # VCPKG_ENABLE_METRICS: 1
- #
# [OPTIONAL] Define the vcpkg's triplet you want to enforce, otherwise the default one
# for the hosting system will be automatically choosen (x64 is the default on all
# platforms, e.g. `x64-osx`).
# VCPKG_DEFAULT_TRIPLET: ${{ matrix.triplet }}
+ #
+ # [OPTIONAL] By default the action disables vcpkg's telemetry by defining VCPKG_DISABLE_METRICS.
+ # This behavior can be disabled by defining `VCPKG_ENABLE_METRICS` as follows.
+ # VCPKG_ENABLE_METRICS: 1
+ #
```
+
+
## Action reference: all input/output parameters
Description of all input parameters: [action.yml](https://github.com/lukka/run-vcpkg/blob/main/action.yml)
+
+
## Flowchart
Flowchart with related input in [action.yml](https://github.com/lukka/run-vcpkg/blob/main/action.yml) which let customize the flow.
@@ -179,7 +210,7 @@ Flowchart with related input in [action.yml](https://github.com/lukka/run-vcpkg/
│ │ - `VCPKG_INSTALLED_DIR` is used as value for
│ │ `--x-install-root` when running `vcpkg install`.
│ │ Check out the `runVcpkgFormatString` input.
- ▼ │ - `VCPKG_BINARY_SOURCES` is used. If not yet
+ ▼ │ - `VCPKG_BINARY_SOURCES` is used. If not yet
┌─────────────────────────┐ │ set, it is set to leverage the GitHub Action
│ Set `VCPKG_ROOT` and │ │ cache storage for Binary Caching artifacts.
│ `VCPKG_DEFAULT_TRIPLET` │ │
@@ -198,6 +229,7 @@ Flowchart with related input in [action.yml](https://github.com/lukka/run-vcpkg/
⬬
```
+
## Best practices
@@ -244,10 +276,14 @@ All the content in this repository is licensed under the [MIT License](LICENSE.t
Copyright © 2019-2020-2021-2022-2023 Luca Cappa
+
+
# Disclaimer
The software is provided as is, there is no warranty of any kind. All users are encouraged to improve the [source code](https://github.com/lukka/run-vcpkg) with fixes and new features.
+
+
# Contributing
Read [CONTRIBUTING.md](CONTRIBUTING.md)
diff --git a/action.yml b/action.yml
index 2e3cdabd..b8b841cb 100644
--- a/action.yml
+++ b/action.yml
@@ -58,7 +58,7 @@ inputs:
description: "Specifies a semicolon separated list of regular expressions that are used to identify log file paths in the workflow output. A regular expression must have a single capturing group, that is a single pair of parenthesis such as 'See also (.+.log)'. When a match occurs, the content of the file is written into the workflow output for disclosing its content to the user. The default regular expressions are for CMake's and vcpkg's log files."
runs:
- using: 'node16'
+ using: 'node20'
main: 'dist/index.js'
branding:
diff --git a/dist/index.js b/dist/index.js
index 739b09e3..99221b5b 100644
--- a/dist/index.js
+++ b/dist/index.js
@@ -1,4 +1,3 @@
-module.exports =
/******/ (() => { // webpackBootstrap
/******/ var __webpack_modules__ = ({
@@ -25,7 +24,7 @@ const baseUtilLib = __nccwpck_require__(2365);
const core = __nccwpck_require__(2186);
const vcpkgAction = __nccwpck_require__(2929);
function main() {
- var _a, _b;
+ var _a;
return __awaiter(this, void 0, void 0, function* () {
try {
const actionLib = new actionlib.ActionLib();
@@ -40,7 +39,7 @@ function main() {
if (error === null || error === void 0 ? void 0 : error.stack) {
core.info(error.stack);
}
- const errorAsString = (_b = (_a = err) === null || _a === void 0 ? void 0 : _a.message) !== null && _b !== void 0 ? _b : "undefined error";
+ const errorAsString = (_a = err === null || err === void 0 ? void 0 : err.message) !== null && _a !== void 0 ? _a : "undefined error";
core.setFailed(`run-vcpkg action execution failed: ${errorAsString}`);
process.exitCode = -1000;
}
@@ -48,10 +47,8 @@ function main() {
}
// Main entry point of the task.
main().catch(error => console.error("main() failed!", error));
-
//# sourceMappingURL=action.js.map
-
/***/ }),
/***/ 2929:
@@ -73,7 +70,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.VcpkgAction = exports.logCollectionRegExpsInput = exports.vcpkgUrlInput = exports.doNotUpdateVcpkgInput = exports.vcpkgCommitIdInput = exports.vcpkgDirectoryInput = exports.runVcpkgFormatStringInput = exports.runVcpkgInstallInput = exports.vcpkgJsonIgnoresInput = exports.vcpkgJsonGlobInput = exports.binaryCachePathInput = exports.additionalCachedPathsInput = exports.doNotCacheInput = void 0;
-const path = __nccwpck_require__(5622);
+const path = __nccwpck_require__(1017);
const cache = __nccwpck_require__(7799);
const runvcpkglib = __nccwpck_require__(4393);
const vcpkgutil = __nccwpck_require__(4534);
@@ -137,10 +134,13 @@ class VcpkgAction {
if (!this.vcpkgRootDir) {
throw new Error(`vcpkgRootDir is not defined!`);
}
- const vcpkgJsonFilePath = yield this.baseUtilLib.wrapOp(`Searching for vcpkg.json with glob expression '${this.vcpkgJsonGlob}'`, () => __awaiter(this, void 0, void 0, function* () {
- const vcpkgJsonPath = yield vcpkgutil.Utils.getVcpkgJsonPath(this.baseUtilLib, this.vcpkgJsonGlob, this.vcpkgJsonIgnores);
- return yield this.getCurrentDirectoryForRunningVcpkg(vcpkgJsonPath);
- }));
+ let vcpkgJsonFilePath = null;
+ if (this.runVcpkgInstall) {
+ vcpkgJsonFilePath = yield this.baseUtilLib.wrapOp(`Searching for vcpkg.json with glob expression '${this.vcpkgJsonGlob}'`, () => __awaiter(this, void 0, void 0, function* () {
+ const vcpkgJsonPath = yield vcpkgutil.Utils.getVcpkgJsonPath(this.baseUtilLib, this.vcpkgJsonGlob, this.vcpkgJsonIgnores);
+ return yield this.getCurrentDirectoryForRunningVcpkg(vcpkgJsonPath);
+ }));
+ }
let isCacheHit = null;
let cacheKey = null;
if (this.doNotCache) {
@@ -178,7 +178,7 @@ class VcpkgAction {
let isCacheHit = false;
this.baseUtilLib.baseLib.debug("restoreCache()<<");
yield this.baseUtilLib.wrapOp('Restore vcpkg installation from cache (not the packages, that is done by vcpkg via Binary Caching stored onto the GitHub Action cache)', () => __awaiter(this, void 0, void 0, function* () {
- var _a, _b;
+ var _a;
if (!this.vcpkgRootDir)
throw new Error("VCPKG_ROOT must be defined");
const pathsToCache = vcpkgutil.Utils.getAllCachedPaths(this.baseUtilLib.baseLib, this.vcpkgRootDir);
@@ -190,7 +190,7 @@ class VcpkgAction {
keyCacheHit = yield cache.restoreCache(pathsToCache, keys.primary, keys.restore);
}
catch (err) {
- this.baseUtilLib.baseLib.warning(`cache.restoreCache() failed: '${(_b = (_a = err) === null || _a === void 0 ? void 0 : _a.message) !== null && _b !== void 0 ? _b : ""}', skipping restoring from cache.`);
+ this.baseUtilLib.baseLib.warning(`cache.restoreCache() failed: '${(_a = err === null || err === void 0 ? void 0 : err.message) !== null && _a !== void 0 ? _a : ""}', skipping restoring from cache.`);
}
if (keyCacheHit) {
this.baseUtilLib.baseLib.info(`Cache hit, key = '${keyCacheHit}'.`);
@@ -217,13 +217,11 @@ class VcpkgAction {
this.baseUtilLib.baseLib.debug(`getCurrentDirectoryForRunningVcpkg(${vcpkgJsonFile}) << `);
// When running 'vcpkg install' is requested, ensure the target directory is well known, fail otherwise.
let vcpkgJsonPath = null;
- if (this.runVcpkgInstall) {
- vcpkgJsonPath = vcpkgJsonFile === null ? null : path.dirname(path.resolve(vcpkgJsonFile));
- this.baseUtilLib.baseLib.debug(`vcpkgJsonFile='${vcpkgJsonFile}', vcpkgJsonPath='${vcpkgJsonPath}'.`);
- if (vcpkgJsonPath === null) {
- this.baseUtilLib.baseLib.error(`Failing the workflow since the 'vcpkg.json' file has not been found: its directory is used as the 'working directory' when launching vcpkg with arguments:
+ vcpkgJsonPath = vcpkgJsonFile === null ? null : path.dirname(path.resolve(vcpkgJsonFile));
+ this.baseUtilLib.baseLib.debug(`vcpkgJsonFile='${vcpkgJsonFile}', vcpkgJsonPath='${vcpkgJsonPath}'.`);
+ if (vcpkgJsonPath === null) {
+ this.baseUtilLib.baseLib.error(`Failing the workflow since the 'vcpkg.json' file has not been found: its directory is used as the 'working directory' when launching vcpkg with arguments:
'${this.runVcpkgFormatString}'. `);
- }
}
this.baseUtilLib.baseLib.debug(`getCurrentDirectoryForRunningVcpkg()>> -> ${vcpkgJsonPath}`);
return vcpkgJsonPath;
@@ -235,10 +233,8 @@ VcpkgAction.VCPKG_DEFAULT_BINARY_CACHE = "VCPKG_DEFAULT_BINARY_CACHE";
VcpkgAction.VCPKGJSON_GLOB = "**/vcpkg.json";
VcpkgAction.VCPKGJSON_IGNORES = "['**/vcpkg/**']";
VcpkgAction.DEFAULTVCPKGURL = 'https://github.com/microsoft/vcpkg.git';
-
//# sourceMappingURL=vcpkg-action.js.map
-
/***/ }),
/***/ 4534:
@@ -260,8 +256,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Utils = void 0;
-const path = __nccwpck_require__(5622);
-const fs = __nccwpck_require__(5747);
+const path = __nccwpck_require__(1017);
+const fs = __nccwpck_require__(7147);
const runvcpkglib = __nccwpck_require__(4393);
const baseutillib = __nccwpck_require__(2365);
const cache = __nccwpck_require__(7799);
@@ -434,10 +430,8 @@ class Utils {
}
}
exports.Utils = Utils;
-
//# sourceMappingURL=vcpkg-utils.js.map
-
/***/ }),
/***/ 7799:
@@ -445,6 +439,29 @@ exports.Utils = Utils;
"use strict";
+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ var desc = Object.getOwnPropertyDescriptor(m, k);
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+ desc = { enumerable: true, get: function() { return m[k]; } };
+ }
+ Object.defineProperty(o, k2, desc);
+}) : (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ o[k2] = m[k];
+}));
+var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
+}) : function(o, v) {
+ o["default"] = v;
+});
+var __importStar = (this && this.__importStar) || function (mod) {
+ if (mod && mod.__esModule) return mod;
+ var result = {};
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
+ __setModuleDefault(result, mod);
+ return result;
+};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
@@ -454,16 +471,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
-var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
- result["default"] = mod;
- return result;
-};
Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.saveCache = exports.restoreCache = exports.isFeatureAvailable = exports.ReserveCacheError = exports.ValidationError = void 0;
const core = __importStar(__nccwpck_require__(2186));
-const path = __importStar(__nccwpck_require__(5622));
+const path = __importStar(__nccwpck_require__(1017));
const utils = __importStar(__nccwpck_require__(1518));
const cacheHttpClient = __importStar(__nccwpck_require__(8245));
const tar_1 = __nccwpck_require__(6490);
@@ -513,9 +524,10 @@ exports.isFeatureAvailable = isFeatureAvailable;
* @param primaryKey an explicit key for restoring the cache
* @param restoreKeys an optional ordered list of keys to use for restoring the cache if no cache hit occurred for key
* @param downloadOptions cache download options
+ * @param enableCrossOsArchive an optional boolean enabled to restore on windows any cache created on any platform
* @returns string returns the key for the cache hit, otherwise returns undefined
*/
-function restoreCache(paths, primaryKey, restoreKeys, options) {
+function restoreCache(paths, primaryKey, restoreKeys, options, enableCrossOsArchive = false) {
return __awaiter(this, void 0, void 0, function* () {
checkPaths(paths);
restoreKeys = restoreKeys || [];
@@ -533,22 +545,27 @@ function restoreCache(paths, primaryKey, restoreKeys, options) {
try {
// path are needed to compute version
const cacheEntry = yield cacheHttpClient.getCacheEntry(keys, paths, {
- compressionMethod
+ compressionMethod,
+ enableCrossOsArchive
});
if (!(cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.archiveLocation)) {
// Cache not found
return undefined;
}
+ if (options === null || options === void 0 ? void 0 : options.lookupOnly) {
+ core.info('Lookup only - skipping download');
+ return cacheEntry.cacheKey;
+ }
archivePath = path.join(yield utils.createTempDirectory(), utils.getCacheFileName(compressionMethod));
core.debug(`Archive Path: ${archivePath}`);
// Download the cache from the cache entry
yield cacheHttpClient.downloadCache(cacheEntry.archiveLocation, archivePath, options);
if (core.isDebug()) {
- yield tar_1.listTar(archivePath, compressionMethod);
+ yield (0, tar_1.listTar)(archivePath, compressionMethod);
}
const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath);
core.info(`Cache Size: ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B)`);
- yield tar_1.extractTar(archivePath, compressionMethod);
+ yield (0, tar_1.extractTar)(archivePath, compressionMethod);
core.info('Cache restored successfully');
return cacheEntry.cacheKey;
}
@@ -580,10 +597,11 @@ exports.restoreCache = restoreCache;
*
* @param paths a list of file paths to be cached
* @param key an explicit key for restoring the cache
+ * @param enableCrossOsArchive an optional boolean enabled to save cache on windows which could be restored on any platform
* @param options cache upload options
* @returns number returns cacheId if the cache was saved successfully and throws an error if save fails
*/
-function saveCache(paths, key, options) {
+function saveCache(paths, key, options, enableCrossOsArchive = false) {
var _a, _b, _c, _d, _e;
return __awaiter(this, void 0, void 0, function* () {
checkPaths(paths);
@@ -600,9 +618,9 @@ function saveCache(paths, key, options) {
const archivePath = path.join(archiveFolder, utils.getCacheFileName(compressionMethod));
core.debug(`Archive Path: ${archivePath}`);
try {
- yield tar_1.createTar(archiveFolder, cachePaths, compressionMethod);
+ yield (0, tar_1.createTar)(archiveFolder, cachePaths, compressionMethod);
if (core.isDebug()) {
- yield tar_1.listTar(archivePath, compressionMethod);
+ yield (0, tar_1.listTar)(archivePath, compressionMethod);
}
const fileSizeLimit = 10 * 1024 * 1024 * 1024; // 10GB per repo limit
const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath);
@@ -614,6 +632,7 @@ function saveCache(paths, key, options) {
core.debug('Reserving Cache');
const reserveCacheResponse = yield cacheHttpClient.reserveCache(key, paths, {
compressionMethod,
+ enableCrossOsArchive,
cacheSize: archiveFileSize
});
if ((_a = reserveCacheResponse === null || reserveCacheResponse === void 0 ? void 0 : reserveCacheResponse.result) === null || _a === void 0 ? void 0 : _a.cacheId) {
@@ -662,6 +681,29 @@ exports.saveCache = saveCache;
"use strict";
+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ var desc = Object.getOwnPropertyDescriptor(m, k);
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+ desc = { enumerable: true, get: function() { return m[k]; } };
+ }
+ Object.defineProperty(o, k2, desc);
+}) : (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ o[k2] = m[k];
+}));
+var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
+}) : function(o, v) {
+ o["default"] = v;
+});
+var __importStar = (this && this.__importStar) || function (mod) {
+ if (mod && mod.__esModule) return mod;
+ var result = {};
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
+ __setModuleDefault(result, mod);
+ return result;
+};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
@@ -671,22 +713,15 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
-var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
- result["default"] = mod;
- return result;
-};
Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.saveCache = exports.reserveCache = exports.downloadCache = exports.getCacheEntry = exports.getCacheVersion = void 0;
const core = __importStar(__nccwpck_require__(2186));
const http_client_1 = __nccwpck_require__(6255);
const auth_1 = __nccwpck_require__(5526);
-const crypto = __importStar(__nccwpck_require__(6417));
-const fs = __importStar(__nccwpck_require__(5747));
-const url_1 = __nccwpck_require__(8835);
+const crypto = __importStar(__nccwpck_require__(6113));
+const fs = __importStar(__nccwpck_require__(7147));
+const url_1 = __nccwpck_require__(7310);
const utils = __importStar(__nccwpck_require__(1518));
-const constants_1 = __nccwpck_require__(8840);
const downloadUtils_1 = __nccwpck_require__(5500);
const options_1 = __nccwpck_require__(6215);
const requestUtils_1 = __nccwpck_require__(3981);
@@ -716,33 +751,43 @@ function createHttpClient() {
const bearerCredentialHandler = new auth_1.BearerCredentialHandler(token);
return new http_client_1.HttpClient('actions/cache', [bearerCredentialHandler], getRequestOptions());
}
-function getCacheVersion(paths, compressionMethod) {
- const components = paths.concat(!compressionMethod || compressionMethod === constants_1.CompressionMethod.Gzip
- ? []
- : [compressionMethod]);
+function getCacheVersion(paths, compressionMethod, enableCrossOsArchive = false) {
+ const components = paths;
+ // Add compression method to cache version to restore
+ // compressed cache as per compression method
+ if (compressionMethod) {
+ components.push(compressionMethod);
+ }
+ // Only check for windows platforms if enableCrossOsArchive is false
+ if (process.platform === 'win32' && !enableCrossOsArchive) {
+ components.push('windows-only');
+ }
// Add salt to cache version to support breaking changes in cache entry
components.push(versionSalt);
- return crypto
- .createHash('sha256')
- .update(components.join('|'))
- .digest('hex');
+ return crypto.createHash('sha256').update(components.join('|')).digest('hex');
}
exports.getCacheVersion = getCacheVersion;
function getCacheEntry(keys, paths, options) {
return __awaiter(this, void 0, void 0, function* () {
const httpClient = createHttpClient();
- const version = getCacheVersion(paths, options === null || options === void 0 ? void 0 : options.compressionMethod);
+ const version = getCacheVersion(paths, options === null || options === void 0 ? void 0 : options.compressionMethod, options === null || options === void 0 ? void 0 : options.enableCrossOsArchive);
const resource = `cache?keys=${encodeURIComponent(keys.join(','))}&version=${version}`;
- const response = yield requestUtils_1.retryTypedResponse('getCacheEntry', () => __awaiter(this, void 0, void 0, function* () { return httpClient.getJson(getCacheApiUrl(resource)); }));
+ const response = yield (0, requestUtils_1.retryTypedResponse)('getCacheEntry', () => __awaiter(this, void 0, void 0, function* () { return httpClient.getJson(getCacheApiUrl(resource)); }));
+ // Cache not found
if (response.statusCode === 204) {
+ // List cache for primary key only if cache miss occurs
+ if (core.isDebug()) {
+ yield printCachesListForDiagnostics(keys[0], httpClient, version);
+ }
return null;
}
- if (!requestUtils_1.isSuccessStatusCode(response.statusCode)) {
+ if (!(0, requestUtils_1.isSuccessStatusCode)(response.statusCode)) {
throw new Error(`Cache service responded with ${response.statusCode}`);
}
const cacheResult = response.result;
const cacheDownloadUrl = cacheResult === null || cacheResult === void 0 ? void 0 : cacheResult.archiveLocation;
if (!cacheDownloadUrl) {
+ // Cache achiveLocation not found. This should never happen, and hence bail out.
throw new Error('Cache not found.');
}
core.setSecret(cacheDownloadUrl);
@@ -752,18 +797,42 @@ function getCacheEntry(keys, paths, options) {
});
}
exports.getCacheEntry = getCacheEntry;
+function printCachesListForDiagnostics(key, httpClient, version) {
+ return __awaiter(this, void 0, void 0, function* () {
+ const resource = `caches?key=${encodeURIComponent(key)}`;
+ const response = yield (0, requestUtils_1.retryTypedResponse)('listCache', () => __awaiter(this, void 0, void 0, function* () { return httpClient.getJson(getCacheApiUrl(resource)); }));
+ if (response.statusCode === 200) {
+ const cacheListResult = response.result;
+ const totalCount = cacheListResult === null || cacheListResult === void 0 ? void 0 : cacheListResult.totalCount;
+ if (totalCount && totalCount > 0) {
+ core.debug(`No matching cache found for cache key '${key}', version '${version} and scope ${process.env['GITHUB_REF']}. There exist one or more cache(s) with similar key but they have different version or scope. See more info on cache matching here: https://docs.github.com/en/actions/using-workflows/caching-dependencies-to-speed-up-workflows#matching-a-cache-key \nOther caches with similar key:`);
+ for (const cacheEntry of (cacheListResult === null || cacheListResult === void 0 ? void 0 : cacheListResult.artifactCaches) || []) {
+ core.debug(`Cache Key: ${cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.cacheKey}, Cache Version: ${cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.cacheVersion}, Cache Scope: ${cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.scope}, Cache Created: ${cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.creationTime}`);
+ }
+ }
+ }
+ });
+}
function downloadCache(archiveLocation, archivePath, options) {
return __awaiter(this, void 0, void 0, function* () {
const archiveUrl = new url_1.URL(archiveLocation);
- const downloadOptions = options_1.getDownloadOptions(options);
- if (downloadOptions.useAzureSdk &&
- archiveUrl.hostname.endsWith('.blob.core.windows.net')) {
- // Use Azure storage SDK to download caches hosted on Azure to improve speed and reliability.
- yield downloadUtils_1.downloadCacheStorageSDK(archiveLocation, archivePath, downloadOptions);
+ const downloadOptions = (0, options_1.getDownloadOptions)(options);
+ if (archiveUrl.hostname.endsWith('.blob.core.windows.net')) {
+ if (downloadOptions.useAzureSdk) {
+ // Use Azure storage SDK to download caches hosted on Azure to improve speed and reliability.
+ yield (0, downloadUtils_1.downloadCacheStorageSDK)(archiveLocation, archivePath, downloadOptions);
+ }
+ else if (downloadOptions.concurrentBlobDownloads) {
+ // Use concurrent implementation with HttpClient to work around blob SDK issue
+ yield (0, downloadUtils_1.downloadCacheHttpClientConcurrent)(archiveLocation, archivePath, downloadOptions);
+ }
+ else {
+ // Otherwise, download using the Actions http-client.
+ yield (0, downloadUtils_1.downloadCacheHttpClient)(archiveLocation, archivePath);
+ }
}
else {
- // Otherwise, download using the Actions http-client.
- yield downloadUtils_1.downloadCacheHttpClient(archiveLocation, archivePath);
+ yield (0, downloadUtils_1.downloadCacheHttpClient)(archiveLocation, archivePath);
}
});
}
@@ -772,13 +841,13 @@ exports.downloadCache = downloadCache;
function reserveCache(key, paths, options) {
return __awaiter(this, void 0, void 0, function* () {
const httpClient = createHttpClient();
- const version = getCacheVersion(paths, options === null || options === void 0 ? void 0 : options.compressionMethod);
+ const version = getCacheVersion(paths, options === null || options === void 0 ? void 0 : options.compressionMethod, options === null || options === void 0 ? void 0 : options.enableCrossOsArchive);
const reserveCacheRequest = {
key,
version,
cacheSize: options === null || options === void 0 ? void 0 : options.cacheSize
};
- const response = yield requestUtils_1.retryTypedResponse('reserveCache', () => __awaiter(this, void 0, void 0, function* () {
+ const response = yield (0, requestUtils_1.retryTypedResponse)('reserveCache', () => __awaiter(this, void 0, void 0, function* () {
return httpClient.postJson(getCacheApiUrl('caches'), reserveCacheRequest);
}));
return response;
@@ -795,17 +864,15 @@ function getContentRange(start, end) {
}
function uploadChunk(httpClient, resourceUrl, openStream, start, end) {
return __awaiter(this, void 0, void 0, function* () {
- core.debug(`Uploading chunk of size ${end -
- start +
- 1} bytes at offset ${start} with content range: ${getContentRange(start, end)}`);
+ core.debug(`Uploading chunk of size ${end - start + 1} bytes at offset ${start} with content range: ${getContentRange(start, end)}`);
const additionalHeaders = {
'Content-Type': 'application/octet-stream',
'Content-Range': getContentRange(start, end)
};
- const uploadChunkResponse = yield requestUtils_1.retryHttpClientResponse(`uploadChunk (start: ${start}, end: ${end})`, () => __awaiter(this, void 0, void 0, function* () {
+ const uploadChunkResponse = yield (0, requestUtils_1.retryHttpClientResponse)(`uploadChunk (start: ${start}, end: ${end})`, () => __awaiter(this, void 0, void 0, function* () {
return httpClient.sendStream('PATCH', resourceUrl, openStream(), additionalHeaders);
}));
- if (!requestUtils_1.isSuccessStatusCode(uploadChunkResponse.message.statusCode)) {
+ if (!(0, requestUtils_1.isSuccessStatusCode)(uploadChunkResponse.message.statusCode)) {
throw new Error(`Cache service responded with ${uploadChunkResponse.message.statusCode} during upload chunk.`);
}
});
@@ -816,7 +883,7 @@ function uploadFile(httpClient, cacheId, archivePath, options) {
const fileSize = utils.getArchiveFileSizeInBytes(archivePath);
const resourceUrl = getCacheApiUrl(`caches/${cacheId.toString()}`);
const fd = fs.openSync(archivePath, 'r');
- const uploadOptions = options_1.getUploadOptions(options);
+ const uploadOptions = (0, options_1.getUploadOptions)(options);
const concurrency = utils.assertDefined('uploadConcurrency', uploadOptions.uploadConcurrency);
const maxChunkSize = utils.assertDefined('uploadChunkSize', uploadOptions.uploadChunkSize);
const parallelUploads = [...new Array(concurrency).keys()];
@@ -851,7 +918,7 @@ function uploadFile(httpClient, cacheId, archivePath, options) {
function commitCache(httpClient, cacheId, filesize) {
return __awaiter(this, void 0, void 0, function* () {
const commitCacheRequest = { size: filesize };
- return yield requestUtils_1.retryTypedResponse('commitCache', () => __awaiter(this, void 0, void 0, function* () {
+ return yield (0, requestUtils_1.retryTypedResponse)('commitCache', () => __awaiter(this, void 0, void 0, function* () {
return httpClient.postJson(getCacheApiUrl(`caches/${cacheId.toString()}`), commitCacheRequest);
}));
});
@@ -866,7 +933,7 @@ function saveCache(cacheId, archivePath, options) {
const cacheSize = utils.getArchiveFileSizeInBytes(archivePath);
core.info(`Cache Size: ~${Math.round(cacheSize / (1024 * 1024))} MB (${cacheSize} B)`);
const commitCacheResponse = yield commitCache(httpClient, cacheId, cacheSize);
- if (!requestUtils_1.isSuccessStatusCode(commitCacheResponse.statusCode)) {
+ if (!(0, requestUtils_1.isSuccessStatusCode)(commitCacheResponse.statusCode)) {
throw new Error(`Cache service responded with ${commitCacheResponse.statusCode} during commit cache.`);
}
core.info('Cache saved successfully');
@@ -882,6 +949,29 @@ exports.saveCache = saveCache;
"use strict";
+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ var desc = Object.getOwnPropertyDescriptor(m, k);
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+ desc = { enumerable: true, get: function() { return m[k]; } };
+ }
+ Object.defineProperty(o, k2, desc);
+}) : (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ o[k2] = m[k];
+}));
+var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
+}) : function(o, v) {
+ o["default"] = v;
+});
+var __importStar = (this && this.__importStar) || function (mod) {
+ if (mod && mod.__esModule) return mod;
+ var result = {};
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
+ __setModuleDefault(result, mod);
+ return result;
+};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
@@ -898,22 +988,16 @@ var __asyncValues = (this && this.__asyncValues) || function (o) {
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
};
-var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
- result["default"] = mod;
- return result;
-};
Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.isGhes = exports.assertDefined = exports.getGnuTarPathOnWindows = exports.getCacheFileName = exports.getCompressionMethod = exports.unlinkFile = exports.resolvePaths = exports.getArchiveFileSizeInBytes = exports.createTempDirectory = void 0;
const core = __importStar(__nccwpck_require__(2186));
const exec = __importStar(__nccwpck_require__(1514));
const glob = __importStar(__nccwpck_require__(1597));
const io = __importStar(__nccwpck_require__(7436));
-const fs = __importStar(__nccwpck_require__(5747));
-const path = __importStar(__nccwpck_require__(5622));
+const fs = __importStar(__nccwpck_require__(7147));
+const path = __importStar(__nccwpck_require__(1017));
const semver = __importStar(__nccwpck_require__(5911));
-const util = __importStar(__nccwpck_require__(1669));
+const util = __importStar(__nccwpck_require__(3837));
const uuid_1 = __nccwpck_require__(2155);
const constants_1 = __nccwpck_require__(8840);
// From https://github.com/actions/toolkit/blob/main/packages/tool-cache/src/tool-cache.ts#L23
@@ -937,7 +1021,7 @@ function createTempDirectory() {
}
tempDirectory = path.join(baseLocation, 'actions', 'temp');
}
- const dest = path.join(tempDirectory, uuid_1.v4());
+ const dest = path.join(tempDirectory, (0, uuid_1.v4)());
yield io.mkdirP(dest);
return dest;
});
@@ -948,35 +1032,42 @@ function getArchiveFileSizeInBytes(filePath) {
}
exports.getArchiveFileSizeInBytes = getArchiveFileSizeInBytes;
function resolvePaths(patterns) {
- var e_1, _a;
- var _b;
+ var _a, e_1, _b, _c;
+ var _d;
return __awaiter(this, void 0, void 0, function* () {
const paths = [];
- const workspace = (_b = process.env['GITHUB_WORKSPACE']) !== null && _b !== void 0 ? _b : process.cwd();
+ const workspace = (_d = process.env['GITHUB_WORKSPACE']) !== null && _d !== void 0 ? _d : process.cwd();
const globber = yield glob.create(patterns.join('\n'), {
implicitDescendants: false
});
try {
- for (var _c = __asyncValues(globber.globGenerator()), _d; _d = yield _c.next(), !_d.done;) {
- const file = _d.value;
- const relativeFile = path
- .relative(workspace, file)
- .replace(new RegExp(`\\${path.sep}`, 'g'), '/');
- core.debug(`Matched: ${relativeFile}`);
- // Paths are made relative so the tar entries are all relative to the root of the workspace.
- if (relativeFile === '') {
- // path.relative returns empty string if workspace and file are equal
- paths.push('.');
+ for (var _e = true, _f = __asyncValues(globber.globGenerator()), _g; _g = yield _f.next(), _a = _g.done, !_a;) {
+ _c = _g.value;
+ _e = false;
+ try {
+ const file = _c;
+ const relativeFile = path
+ .relative(workspace, file)
+ .replace(new RegExp(`\\${path.sep}`, 'g'), '/');
+ core.debug(`Matched: ${relativeFile}`);
+ // Paths are made relative so the tar entries are all relative to the root of the workspace.
+ if (relativeFile === '') {
+ // path.relative returns empty string if workspace and file are equal
+ paths.push('.');
+ }
+ else {
+ paths.push(`${relativeFile}`);
+ }
}
- else {
- paths.push(`${relativeFile}`);
+ finally {
+ _e = true;
}
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
- if (_d && !_d.done && (_a = _c.return)) yield _a.call(_c);
+ if (!_e && !_a && (_b = _f.return)) yield _b.call(_f);
}
finally { if (e_1) throw e_1.error; }
}
@@ -990,12 +1081,13 @@ function unlinkFile(filePath) {
});
}
exports.unlinkFile = unlinkFile;
-function getVersion(app) {
+function getVersion(app, additionalArgs = []) {
return __awaiter(this, void 0, void 0, function* () {
- core.debug(`Checking ${app} --version`);
let versionOutput = '';
+ additionalArgs.push('--version');
+ core.debug(`Checking ${app} ${additionalArgs.join(' ')}`);
try {
- yield exec.exec(`${app} --version`, [], {
+ yield exec.exec(`${app}`, additionalArgs, {
ignoreReturnCode: true,
silent: true,
listeners: {
@@ -1015,23 +1107,14 @@ function getVersion(app) {
// Use zstandard if possible to maximize cache performance
function getCompressionMethod() {
return __awaiter(this, void 0, void 0, function* () {
- if (process.platform === 'win32' && !(yield isGnuTarInstalled())) {
- // Disable zstd due to bug https://github.com/actions/cache/issues/301
- return constants_1.CompressionMethod.Gzip;
- }
- const versionOutput = yield getVersion('zstd');
+ const versionOutput = yield getVersion('zstd', ['--quiet']);
const version = semver.clean(versionOutput);
- if (!versionOutput.toLowerCase().includes('zstd command line interface')) {
- // zstd is not installed
+ core.debug(`zstd version: ${version}`);
+ if (versionOutput === '') {
return constants_1.CompressionMethod.Gzip;
}
- else if (!version || semver.lt(version, 'v1.3.2')) {
- // zstd is installed but using a version earlier than v1.3.2
- // v1.3.2 is required to use the `--long` options in zstd
- return constants_1.CompressionMethod.ZstdWithoutLong;
- }
else {
- return constants_1.CompressionMethod.Zstd;
+ return constants_1.CompressionMethod.ZstdWithoutLong;
}
});
}
@@ -1042,13 +1125,16 @@ function getCacheFileName(compressionMethod) {
: constants_1.CacheFilename.Zstd;
}
exports.getCacheFileName = getCacheFileName;
-function isGnuTarInstalled() {
+function getGnuTarPathOnWindows() {
return __awaiter(this, void 0, void 0, function* () {
+ if (fs.existsSync(constants_1.GnuTarPathOnWindows)) {
+ return constants_1.GnuTarPathOnWindows;
+ }
const versionOutput = yield getVersion('tar');
- return versionOutput.toLowerCase().includes('gnu tar');
+ return versionOutput.toLowerCase().includes('gnu tar') ? io.which('tar') : '';
});
}
-exports.isGnuTarInstalled = isGnuTarInstalled;
+exports.getGnuTarPathOnWindows = getGnuTarPathOnWindows;
function assertDefined(name, value) {
if (value === undefined) {
throw Error(`Expected ${name} but value was undefiend`);
@@ -1071,6 +1157,7 @@ exports.isGhes = isGhes;
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.ManifestFilename = exports.TarFilename = exports.SystemTarPathOnWindows = exports.GnuTarPathOnWindows = exports.SocketTimeout = exports.DefaultRetryDelay = exports.DefaultRetryAttempts = exports.ArchiveToolType = exports.CompressionMethod = exports.CacheFilename = void 0;
var CacheFilename;
(function (CacheFilename) {
CacheFilename["Gzip"] = "cache.tgz";
@@ -1084,6 +1171,11 @@ var CompressionMethod;
CompressionMethod["ZstdWithoutLong"] = "zstd-without-long";
CompressionMethod["Zstd"] = "zstd";
})(CompressionMethod = exports.CompressionMethod || (exports.CompressionMethod = {}));
+var ArchiveToolType;
+(function (ArchiveToolType) {
+ ArchiveToolType["GNU"] = "gnu";
+ ArchiveToolType["BSD"] = "bsd";
+})(ArchiveToolType = exports.ArchiveToolType || (exports.ArchiveToolType = {}));
// The default number of retry attempts.
exports.DefaultRetryAttempts = 2;
// The default delay in milliseconds between retry attempts.
@@ -1092,6 +1184,12 @@ exports.DefaultRetryDelay = 5000;
// over the socket during this period, the socket is destroyed and the download
// is aborted.
exports.SocketTimeout = 5000;
+// The default path of GNUtar on hosted Windows runners
+exports.GnuTarPathOnWindows = `${process.env['PROGRAMFILES']}\\Git\\usr\\bin\\tar.exe`;
+// The default path of BSDtar on hosted Windows runners
+exports.SystemTarPathOnWindows = `${process.env['SYSTEMDRIVE']}\\Windows\\System32\\tar.exe`;
+exports.TarFilename = 'cache.tar';
+exports.ManifestFilename = 'manifest.txt';
//# sourceMappingURL=constants.js.map
/***/ }),
@@ -1101,6 +1199,29 @@ exports.SocketTimeout = 5000;
"use strict";
+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ var desc = Object.getOwnPropertyDescriptor(m, k);
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+ desc = { enumerable: true, get: function() { return m[k]; } };
+ }
+ Object.defineProperty(o, k2, desc);
+}) : (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ o[k2] = m[k];
+}));
+var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
+}) : function(o, v) {
+ o["default"] = v;
+});
+var __importStar = (this && this.__importStar) || function (mod) {
+ if (mod && mod.__esModule) return mod;
+ var result = {};
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
+ __setModuleDefault(result, mod);
+ return result;
+};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
@@ -1110,21 +1231,15 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
-var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
- result["default"] = mod;
- return result;
-};
Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.downloadCacheStorageSDK = exports.downloadCacheHttpClientConcurrent = exports.downloadCacheHttpClient = exports.DownloadProgress = void 0;
const core = __importStar(__nccwpck_require__(2186));
const http_client_1 = __nccwpck_require__(6255);
const storage_blob_1 = __nccwpck_require__(4100);
-const buffer = __importStar(__nccwpck_require__(4293));
-const fs = __importStar(__nccwpck_require__(5747));
-const stream = __importStar(__nccwpck_require__(2413));
-const util = __importStar(__nccwpck_require__(1669));
+const buffer = __importStar(__nccwpck_require__(4300));
+const fs = __importStar(__nccwpck_require__(7147));
+const stream = __importStar(__nccwpck_require__(2781));
+const util = __importStar(__nccwpck_require__(3837));
const utils = __importStar(__nccwpck_require__(1518));
const constants_1 = __nccwpck_require__(8840);
const requestUtils_1 = __nccwpck_require__(3981);
@@ -1252,7 +1367,7 @@ function downloadCacheHttpClient(archiveLocation, archivePath) {
return __awaiter(this, void 0, void 0, function* () {
const writeStream = fs.createWriteStream(archivePath);
const httpClient = new http_client_1.HttpClient('actions/cache');
- const downloadResponse = yield requestUtils_1.retryHttpClientResponse('downloadCache', () => __awaiter(this, void 0, void 0, function* () { return httpClient.get(archiveLocation); }));
+ const downloadResponse = yield (0, requestUtils_1.retryHttpClientResponse)('downloadCache', () => __awaiter(this, void 0, void 0, function* () { return httpClient.get(archiveLocation); }));
// Abort download if no traffic received over the socket.
downloadResponse.message.socket.setTimeout(constants_1.SocketTimeout, () => {
downloadResponse.message.destroy();
@@ -1274,6 +1389,115 @@ function downloadCacheHttpClient(archiveLocation, archivePath) {
});
}
exports.downloadCacheHttpClient = downloadCacheHttpClient;
+/**
+ * Download the cache using the Actions toolkit http-client concurrently
+ *
+ * @param archiveLocation the URL for the cache
+ * @param archivePath the local path where the cache is saved
+ */
+function downloadCacheHttpClientConcurrent(archiveLocation, archivePath, options) {
+ var _a;
+ return __awaiter(this, void 0, void 0, function* () {
+ const archiveDescriptor = yield fs.promises.open(archivePath, 'w');
+ const httpClient = new http_client_1.HttpClient('actions/cache', undefined, {
+ socketTimeout: options.timeoutInMs,
+ keepAlive: true
+ });
+ try {
+ const res = yield (0, requestUtils_1.retryHttpClientResponse)('downloadCacheMetadata', () => __awaiter(this, void 0, void 0, function* () { return yield httpClient.request('HEAD', archiveLocation, null, {}); }));
+ const lengthHeader = res.message.headers['content-length'];
+ if (lengthHeader === undefined || lengthHeader === null) {
+ throw new Error('Content-Length not found on blob response');
+ }
+ const length = parseInt(lengthHeader);
+ if (Number.isNaN(length)) {
+ throw new Error(`Could not interpret Content-Length: ${length}`);
+ }
+ const downloads = [];
+ const blockSize = 4 * 1024 * 1024;
+ for (let offset = 0; offset < length; offset += blockSize) {
+ const count = Math.min(blockSize, length - offset);
+ downloads.push({
+ offset,
+ promiseGetter: () => __awaiter(this, void 0, void 0, function* () {
+ return yield downloadSegmentRetry(httpClient, archiveLocation, offset, count);
+ })
+ });
+ }
+ // reverse to use .pop instead of .shift
+ downloads.reverse();
+ let actives = 0;
+ let bytesDownloaded = 0;
+ const progress = new DownloadProgress(length);
+ progress.startDisplayTimer();
+ const progressFn = progress.onProgress();
+ const activeDownloads = [];
+ let nextDownload;
+ const waitAndWrite = () => __awaiter(this, void 0, void 0, function* () {
+ const segment = yield Promise.race(Object.values(activeDownloads));
+ yield archiveDescriptor.write(segment.buffer, 0, segment.count, segment.offset);
+ actives--;
+ delete activeDownloads[segment.offset];
+ bytesDownloaded += segment.count;
+ progressFn({ loadedBytes: bytesDownloaded });
+ });
+ while ((nextDownload = downloads.pop())) {
+ activeDownloads[nextDownload.offset] = nextDownload.promiseGetter();
+ actives++;
+ if (actives >= ((_a = options.downloadConcurrency) !== null && _a !== void 0 ? _a : 10)) {
+ yield waitAndWrite();
+ }
+ }
+ while (actives > 0) {
+ yield waitAndWrite();
+ }
+ }
+ finally {
+ httpClient.dispose();
+ yield archiveDescriptor.close();
+ }
+ });
+}
+exports.downloadCacheHttpClientConcurrent = downloadCacheHttpClientConcurrent;
+function downloadSegmentRetry(httpClient, archiveLocation, offset, count) {
+ return __awaiter(this, void 0, void 0, function* () {
+ const retries = 5;
+ let failures = 0;
+ while (true) {
+ try {
+ const timeout = 30000;
+ const result = yield promiseWithTimeout(timeout, downloadSegment(httpClient, archiveLocation, offset, count));
+ if (typeof result === 'string') {
+ throw new Error('downloadSegmentRetry failed due to timeout');
+ }
+ return result;
+ }
+ catch (err) {
+ if (failures >= retries) {
+ throw err;
+ }
+ failures++;
+ }
+ }
+ });
+}
+function downloadSegment(httpClient, archiveLocation, offset, count) {
+ return __awaiter(this, void 0, void 0, function* () {
+ const partRes = yield (0, requestUtils_1.retryHttpClientResponse)('downloadCachePart', () => __awaiter(this, void 0, void 0, function* () {
+ return yield httpClient.get(archiveLocation, {
+ Range: `bytes=${offset}-${offset + count - 1}`
+ });
+ }));
+ if (!partRes.readBodyBuffer) {
+ throw new Error('Expected HttpClientResponse to implement readBodyBuffer');
+ }
+ return {
+ offset,
+ count,
+ buffer: yield partRes.readBodyBuffer()
+ };
+ });
+}
/**
* Download the cache using the Azure Storage SDK. Only call this method if the
* URL points to an Azure Storage endpoint.
@@ -1307,7 +1531,8 @@ function downloadCacheStorageSDK(archiveLocation, archivePath, options) {
// If the file exceeds the buffer maximum length (~1 GB on 32-bit systems and ~2 GB
// on 64-bit systems), split the download into multiple segments
// ~2 GB = 2147483647, beyond this, we start getting out of range error. So, capping it accordingly.
- const maxSegmentSize = Math.min(2147483647, buffer.constants.MAX_LENGTH);
+ // Updated segment size to 128MB = 134217728 bytes, to complete a segment faster and fail fast
+ const maxSegmentSize = Math.min(134217728, buffer.constants.MAX_LENGTH);
const downloadProgress = new DownloadProgress(contentLength);
const fd = fs.openSync(archivePath, 'w');
try {
@@ -1359,6 +1584,29 @@ const promiseWithTimeout = (timeoutMs, promise) => __awaiter(void 0, void 0, voi
"use strict";
+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ var desc = Object.getOwnPropertyDescriptor(m, k);
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+ desc = { enumerable: true, get: function() { return m[k]; } };
+ }
+ Object.defineProperty(o, k2, desc);
+}) : (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ o[k2] = m[k];
+}));
+var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
+}) : function(o, v) {
+ o["default"] = v;
+});
+var __importStar = (this && this.__importStar) || function (mod) {
+ if (mod && mod.__esModule) return mod;
+ var result = {};
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
+ __setModuleDefault(result, mod);
+ return result;
+};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
@@ -1368,14 +1616,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
-var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
- result["default"] = mod;
- return result;
-};
Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.retryHttpClientResponse = exports.retryTypedResponse = exports.retry = exports.isRetryableStatusCode = exports.isServerErrorStatusCode = exports.isSuccessStatusCode = void 0;
const core = __importStar(__nccwpck_require__(2186));
const http_client_1 = __nccwpck_require__(6255);
const constants_1 = __nccwpck_require__(8840);
@@ -1486,6 +1728,29 @@ exports.retryHttpClientResponse = retryHttpClientResponse;
"use strict";
+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ var desc = Object.getOwnPropertyDescriptor(m, k);
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+ desc = { enumerable: true, get: function() { return m[k]; } };
+ }
+ Object.defineProperty(o, k2, desc);
+}) : (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ o[k2] = m[k];
+}));
+var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
+}) : function(o, v) {
+ o["default"] = v;
+});
+var __importStar = (this && this.__importStar) || function (mod) {
+ if (mod && mod.__esModule) return mod;
+ var result = {};
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
+ __setModuleDefault(result, mod);
+ return result;
+};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
@@ -1495,36 +1760,28 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
-var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
- result["default"] = mod;
- return result;
-};
Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.createTar = exports.extractTar = exports.listTar = void 0;
const exec_1 = __nccwpck_require__(1514);
const io = __importStar(__nccwpck_require__(7436));
-const fs_1 = __nccwpck_require__(5747);
-const path = __importStar(__nccwpck_require__(5622));
+const fs_1 = __nccwpck_require__(7147);
+const path = __importStar(__nccwpck_require__(1017));
const utils = __importStar(__nccwpck_require__(1518));
const constants_1 = __nccwpck_require__(8840);
const IS_WINDOWS = process.platform === 'win32';
-function getTarPath(args, compressionMethod) {
+// Returns tar path and type: BSD or GNU
+function getTarPath() {
return __awaiter(this, void 0, void 0, function* () {
switch (process.platform) {
case 'win32': {
- const systemTar = `${process.env['windir']}\\System32\\tar.exe`;
- if (compressionMethod !== constants_1.CompressionMethod.Gzip) {
- // We only use zstandard compression on windows when gnu tar is installed due to
- // a bug with compressing large files with bsdtar + zstd
- args.push('--force-local');
- }
- else if (fs_1.existsSync(systemTar)) {
- return systemTar;
+ const gnuTar = yield utils.getGnuTarPathOnWindows();
+ const systemTar = constants_1.SystemTarPathOnWindows;
+ if (gnuTar) {
+ // Use GNUtar as default on windows
+ return { path: gnuTar, type: constants_1.ArchiveToolType.GNU };
}
- else if (yield utils.isGnuTarInstalled()) {
- args.push('--force-local');
+ else if ((0, fs_1.existsSync)(systemTar)) {
+ return { path: systemTar, type: constants_1.ArchiveToolType.BSD };
}
break;
}
@@ -1532,25 +1789,92 @@ function getTarPath(args, compressionMethod) {
const gnuTar = yield io.which('gtar', false);
if (gnuTar) {
// fix permission denied errors when extracting BSD tar archive with GNU tar - https://github.com/actions/cache/issues/527
- args.push('--delay-directory-restore');
- return gnuTar;
+ return { path: gnuTar, type: constants_1.ArchiveToolType.GNU };
+ }
+ else {
+ return {
+ path: yield io.which('tar', true),
+ type: constants_1.ArchiveToolType.BSD
+ };
}
- break;
}
default:
break;
}
- return yield io.which('tar', true);
+ // Default assumption is GNU tar is present in path
+ return {
+ path: yield io.which('tar', true),
+ type: constants_1.ArchiveToolType.GNU
+ };
});
}
-function execTar(args, compressionMethod, cwd) {
+// Return arguments for tar as per tarPath, compressionMethod, method type and os
+function getTarArgs(tarPath, compressionMethod, type, archivePath = '') {
return __awaiter(this, void 0, void 0, function* () {
- try {
- yield exec_1.exec(`"${yield getTarPath(args, compressionMethod)}"`, args, { cwd });
+ const args = [`"${tarPath.path}"`];
+ const cacheFileName = utils.getCacheFileName(compressionMethod);
+ const tarFile = 'cache.tar';
+ const workingDirectory = getWorkingDirectory();
+ // Speficic args for BSD tar on windows for workaround
+ const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD &&
+ compressionMethod !== constants_1.CompressionMethod.Gzip &&
+ IS_WINDOWS;
+ // Method specific args
+ switch (type) {
+ case 'create':
+ args.push('--posix', '-cf', BSD_TAR_ZSTD
+ ? tarFile
+ : cacheFileName.replace(new RegExp(`\\${path.sep}`, 'g'), '/'), '--exclude', BSD_TAR_ZSTD
+ ? tarFile
+ : cacheFileName.replace(new RegExp(`\\${path.sep}`, 'g'), '/'), '-P', '-C', workingDirectory.replace(new RegExp(`\\${path.sep}`, 'g'), '/'), '--files-from', constants_1.ManifestFilename);
+ break;
+ case 'extract':
+ args.push('-xf', BSD_TAR_ZSTD
+ ? tarFile
+ : archivePath.replace(new RegExp(`\\${path.sep}`, 'g'), '/'), '-P', '-C', workingDirectory.replace(new RegExp(`\\${path.sep}`, 'g'), '/'));
+ break;
+ case 'list':
+ args.push('-tf', BSD_TAR_ZSTD
+ ? tarFile
+ : archivePath.replace(new RegExp(`\\${path.sep}`, 'g'), '/'), '-P');
+ break;
}
- catch (error) {
- throw new Error(`Tar failed with error: ${error === null || error === void 0 ? void 0 : error.message}`);
+ // Platform specific args
+ if (tarPath.type === constants_1.ArchiveToolType.GNU) {
+ switch (process.platform) {
+ case 'win32':
+ args.push('--force-local');
+ break;
+ case 'darwin':
+ args.push('--delay-directory-restore');
+ break;
+ }
+ }
+ return args;
+ });
+}
+// Returns commands to run tar and compression program
+function getCommands(compressionMethod, type, archivePath = '') {
+ return __awaiter(this, void 0, void 0, function* () {
+ let args;
+ const tarPath = yield getTarPath();
+ const tarArgs = yield getTarArgs(tarPath, compressionMethod, type, archivePath);
+ const compressionArgs = type !== 'create'
+ ? yield getDecompressionProgram(tarPath, compressionMethod, archivePath)
+ : yield getCompressionProgram(tarPath, compressionMethod);
+ const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD &&
+ compressionMethod !== constants_1.CompressionMethod.Gzip &&
+ IS_WINDOWS;
+ if (BSD_TAR_ZSTD && type !== 'create') {
+ args = [[...compressionArgs].join(' '), [...tarArgs].join(' ')];
+ }
+ else {
+ args = [[...tarArgs].join(' '), [...compressionArgs].join(' ')];
+ }
+ if (BSD_TAR_ZSTD) {
+ return args;
}
+ return [args.join(' ')];
});
}
function getWorkingDirectory() {
@@ -1558,91 +1882,119 @@ function getWorkingDirectory() {
return (_a = process.env['GITHUB_WORKSPACE']) !== null && _a !== void 0 ? _a : process.cwd();
}
// Common function for extractTar and listTar to get the compression method
-function getCompressionProgram(compressionMethod) {
- // -d: Decompress.
- // unzstd is equivalent to 'zstd -d'
- // --long=#: Enables long distance matching with # bits. Maximum is 30 (1GB) on 32-bit OS and 31 (2GB) on 64-bit.
- // Using 30 here because we also support 32-bit self-hosted runners.
- switch (compressionMethod) {
- case constants_1.CompressionMethod.Zstd:
- return [
- '--use-compress-program',
- IS_WINDOWS ? 'zstd -d --long=30' : 'unzstd --long=30'
- ];
- case constants_1.CompressionMethod.ZstdWithoutLong:
- return ['--use-compress-program', IS_WINDOWS ? 'zstd -d' : 'unzstd'];
- default:
- return ['-z'];
- }
+function getDecompressionProgram(tarPath, compressionMethod, archivePath) {
+ return __awaiter(this, void 0, void 0, function* () {
+ // -d: Decompress.
+ // unzstd is equivalent to 'zstd -d'
+ // --long=#: Enables long distance matching with # bits. Maximum is 30 (1GB) on 32-bit OS and 31 (2GB) on 64-bit.
+ // Using 30 here because we also support 32-bit self-hosted runners.
+ const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD &&
+ compressionMethod !== constants_1.CompressionMethod.Gzip &&
+ IS_WINDOWS;
+ switch (compressionMethod) {
+ case constants_1.CompressionMethod.Zstd:
+ return BSD_TAR_ZSTD
+ ? [
+ 'zstd -d --long=30 --force -o',
+ constants_1.TarFilename,
+ archivePath.replace(new RegExp(`\\${path.sep}`, 'g'), '/')
+ ]
+ : [
+ '--use-compress-program',
+ IS_WINDOWS ? '"zstd -d --long=30"' : 'unzstd --long=30'
+ ];
+ case constants_1.CompressionMethod.ZstdWithoutLong:
+ return BSD_TAR_ZSTD
+ ? [
+ 'zstd -d --force -o',
+ constants_1.TarFilename,
+ archivePath.replace(new RegExp(`\\${path.sep}`, 'g'), '/')
+ ]
+ : ['--use-compress-program', IS_WINDOWS ? '"zstd -d"' : 'unzstd'];
+ default:
+ return ['-z'];
+ }
+ });
+}
+// Used for creating the archive
+// -T#: Compress using # working thread. If # is 0, attempt to detect and use the number of physical CPU cores.
+// zstdmt is equivalent to 'zstd -T0'
+// --long=#: Enables long distance matching with # bits. Maximum is 30 (1GB) on 32-bit OS and 31 (2GB) on 64-bit.
+// Using 30 here because we also support 32-bit self-hosted runners.
+// Long range mode is added to zstd in v1.3.2 release, so we will not use --long in older version of zstd.
+function getCompressionProgram(tarPath, compressionMethod) {
+ return __awaiter(this, void 0, void 0, function* () {
+ const cacheFileName = utils.getCacheFileName(compressionMethod);
+ const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD &&
+ compressionMethod !== constants_1.CompressionMethod.Gzip &&
+ IS_WINDOWS;
+ switch (compressionMethod) {
+ case constants_1.CompressionMethod.Zstd:
+ return BSD_TAR_ZSTD
+ ? [
+ 'zstd -T0 --long=30 --force -o',
+ cacheFileName.replace(new RegExp(`\\${path.sep}`, 'g'), '/'),
+ constants_1.TarFilename
+ ]
+ : [
+ '--use-compress-program',
+ IS_WINDOWS ? '"zstd -T0 --long=30"' : 'zstdmt --long=30'
+ ];
+ case constants_1.CompressionMethod.ZstdWithoutLong:
+ return BSD_TAR_ZSTD
+ ? [
+ 'zstd -T0 --force -o',
+ cacheFileName.replace(new RegExp(`\\${path.sep}`, 'g'), '/'),
+ constants_1.TarFilename
+ ]
+ : ['--use-compress-program', IS_WINDOWS ? '"zstd -T0"' : 'zstdmt'];
+ default:
+ return ['-z'];
+ }
+ });
+}
+// Executes all commands as separate processes
+function execCommands(commands, cwd) {
+ return __awaiter(this, void 0, void 0, function* () {
+ for (const command of commands) {
+ try {
+ yield (0, exec_1.exec)(command, undefined, {
+ cwd,
+ env: Object.assign(Object.assign({}, process.env), { MSYS: 'winsymlinks:nativestrict' })
+ });
+ }
+ catch (error) {
+ throw new Error(`${command.split(' ')[0]} failed with error: ${error === null || error === void 0 ? void 0 : error.message}`);
+ }
+ }
+ });
}
+// List the contents of a tar
function listTar(archivePath, compressionMethod) {
return __awaiter(this, void 0, void 0, function* () {
- const args = [
- ...getCompressionProgram(compressionMethod),
- '-tf',
- archivePath.replace(new RegExp(`\\${path.sep}`, 'g'), '/'),
- '-P'
- ];
- yield execTar(args, compressionMethod);
+ const commands = yield getCommands(compressionMethod, 'list', archivePath);
+ yield execCommands(commands);
});
}
exports.listTar = listTar;
+// Extract a tar
function extractTar(archivePath, compressionMethod) {
return __awaiter(this, void 0, void 0, function* () {
// Create directory to extract tar into
const workingDirectory = getWorkingDirectory();
yield io.mkdirP(workingDirectory);
- const args = [
- ...getCompressionProgram(compressionMethod),
- '-xf',
- archivePath.replace(new RegExp(`\\${path.sep}`, 'g'), '/'),
- '-P',
- '-C',
- workingDirectory.replace(new RegExp(`\\${path.sep}`, 'g'), '/')
- ];
- yield execTar(args, compressionMethod);
+ const commands = yield getCommands(compressionMethod, 'extract', archivePath);
+ yield execCommands(commands);
});
}
exports.extractTar = extractTar;
+// Create a tar
function createTar(archiveFolder, sourceDirectories, compressionMethod) {
return __awaiter(this, void 0, void 0, function* () {
// Write source directories to manifest.txt to avoid command length limits
- const manifestFilename = 'manifest.txt';
- const cacheFileName = utils.getCacheFileName(compressionMethod);
- fs_1.writeFileSync(path.join(archiveFolder, manifestFilename), sourceDirectories.join('\n'));
- const workingDirectory = getWorkingDirectory();
- // -T#: Compress using # working thread. If # is 0, attempt to detect and use the number of physical CPU cores.
- // zstdmt is equivalent to 'zstd -T0'
- // --long=#: Enables long distance matching with # bits. Maximum is 30 (1GB) on 32-bit OS and 31 (2GB) on 64-bit.
- // Using 30 here because we also support 32-bit self-hosted runners.
- // Long range mode is added to zstd in v1.3.2 release, so we will not use --long in older version of zstd.
- function getCompressionProgram() {
- switch (compressionMethod) {
- case constants_1.CompressionMethod.Zstd:
- return [
- '--use-compress-program',
- IS_WINDOWS ? 'zstd -T0 --long=30' : 'zstdmt --long=30'
- ];
- case constants_1.CompressionMethod.ZstdWithoutLong:
- return ['--use-compress-program', IS_WINDOWS ? 'zstd -T0' : 'zstdmt'];
- default:
- return ['-z'];
- }
- }
- const args = [
- '--posix',
- ...getCompressionProgram(),
- '-cf',
- cacheFileName.replace(new RegExp(`\\${path.sep}`, 'g'), '/'),
- '--exclude',
- cacheFileName.replace(new RegExp(`\\${path.sep}`, 'g'), '/'),
- '-P',
- '-C',
- workingDirectory.replace(new RegExp(`\\${path.sep}`, 'g'), '/'),
- '--files-from',
- manifestFilename
- ];
- yield execTar(args, compressionMethod, archiveFolder);
+ (0, fs_1.writeFileSync)(path.join(archiveFolder, constants_1.ManifestFilename), sourceDirectories.join('\n'));
+ const commands = yield getCommands(compressionMethod, 'create');
+ yield execCommands(commands, archiveFolder);
});
}
exports.createTar = createTar;
@@ -1655,14 +2007,31 @@ exports.createTar = createTar;
"use strict";
+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ var desc = Object.getOwnPropertyDescriptor(m, k);
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+ desc = { enumerable: true, get: function() { return m[k]; } };
+ }
+ Object.defineProperty(o, k2, desc);
+}) : (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ o[k2] = m[k];
+}));
+var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
+}) : function(o, v) {
+ o["default"] = v;
+});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
- if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
- result["default"] = mod;
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
+ __setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.getDownloadOptions = exports.getUploadOptions = void 0;
const core = __importStar(__nccwpck_require__(2186));
/**
* Returns a copy of the upload options with defaults filled in.
@@ -1694,15 +2063,20 @@ exports.getUploadOptions = getUploadOptions;
*/
function getDownloadOptions(copy) {
const result = {
- useAzureSdk: true,
+ useAzureSdk: false,
+ concurrentBlobDownloads: true,
downloadConcurrency: 8,
timeoutInMs: 30000,
- segmentTimeoutInMs: 3600000
+ segmentTimeoutInMs: 600000,
+ lookupOnly: false
};
if (copy) {
if (typeof copy.useAzureSdk === 'boolean') {
result.useAzureSdk = copy.useAzureSdk;
}
+ if (typeof copy.concurrentBlobDownloads === 'boolean') {
+ result.concurrentBlobDownloads = copy.concurrentBlobDownloads;
+ }
if (typeof copy.downloadConcurrency === 'number') {
result.downloadConcurrency = copy.downloadConcurrency;
}
@@ -1712,6 +2086,9 @@ function getDownloadOptions(copy) {
if (typeof copy.segmentTimeoutInMs === 'number') {
result.segmentTimeoutInMs = copy.segmentTimeoutInMs;
}
+ if (typeof copy.lookupOnly === 'boolean') {
+ result.lookupOnly = copy.lookupOnly;
+ }
}
const segmentDownloadTimeoutMins = process.env['SEGMENT_DOWNLOAD_TIMEOUT_MINS'];
if (segmentDownloadTimeoutMins &&
@@ -1724,6 +2101,7 @@ function getDownloadOptions(copy) {
core.debug(`Request timeout (ms): ${result.timeoutInMs}`);
core.debug(`Cache segment download timeout mins env var: ${process.env['SEGMENT_DOWNLOAD_TIMEOUT_MINS']}`);
core.debug(`Segment download timeout (ms): ${result.segmentTimeoutInMs}`);
+ core.debug(`Lookup only: ${result.lookupOnly}`);
return result;
}
exports.getDownloadOptions = getDownloadOptions;
@@ -1876,9 +2254,9 @@ var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _ar
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.DefaultGlobber = void 0;
const core = __importStar(__nccwpck_require__(2186));
-const fs = __importStar(__nccwpck_require__(5747));
+const fs = __importStar(__nccwpck_require__(7147));
const globOptionsHelper = __importStar(__nccwpck_require__(9350));
-const path = __importStar(__nccwpck_require__(5622));
+const path = __importStar(__nccwpck_require__(1017));
const patternHelper = __importStar(__nccwpck_require__(5186));
const internal_match_kind_1 = __nccwpck_require__(836);
const internal_pattern_1 = __nccwpck_require__(5343);
@@ -2117,8 +2495,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.safeTrimTrailingSeparator = exports.normalizeSeparators = exports.hasRoot = exports.hasAbsoluteRoot = exports.ensureAbsoluteRoot = exports.dirname = void 0;
-const path = __importStar(__nccwpck_require__(5622));
-const assert_1 = __importDefault(__nccwpck_require__(2357));
+const path = __importStar(__nccwpck_require__(1017));
+const assert_1 = __importDefault(__nccwpck_require__(9491));
const IS_WINDOWS = process.platform === 'win32';
/**
* Similar to path.dirname except normalizes the path separators and slightly better handling for Windows UNC paths.
@@ -2322,9 +2700,9 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Path = void 0;
-const path = __importStar(__nccwpck_require__(5622));
+const path = __importStar(__nccwpck_require__(1017));
const pathHelper = __importStar(__nccwpck_require__(22));
-const assert_1 = __importDefault(__nccwpck_require__(2357));
+const assert_1 = __importDefault(__nccwpck_require__(9491));
const IS_WINDOWS = process.platform === 'win32';
/**
* Helper class for parsing paths into segments
@@ -2543,10 +2921,10 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Pattern = void 0;
-const os = __importStar(__nccwpck_require__(2087));
-const path = __importStar(__nccwpck_require__(5622));
+const os = __importStar(__nccwpck_require__(2037));
+const path = __importStar(__nccwpck_require__(1017));
const pathHelper = __importStar(__nccwpck_require__(22));
-const assert_1 = __importDefault(__nccwpck_require__(2357));
+const assert_1 = __importDefault(__nccwpck_require__(9491));
const minimatch_1 = __nccwpck_require__(3973);
const internal_match_kind_1 = __nccwpck_require__(836);
const internal_path_1 = __nccwpck_require__(9413);
@@ -2820,7 +3198,7 @@ var __importStar = (this && this.__importStar) || function (mod) {
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.issue = exports.issueCommand = void 0;
-const os = __importStar(__nccwpck_require__(2087));
+const os = __importStar(__nccwpck_require__(2037));
const utils_1 = __nccwpck_require__(5278);
/**
* Commands
@@ -2931,8 +3309,8 @@ exports.getIDToken = exports.getState = exports.saveState = exports.group = expo
const command_1 = __nccwpck_require__(7351);
const file_command_1 = __nccwpck_require__(717);
const utils_1 = __nccwpck_require__(5278);
-const os = __importStar(__nccwpck_require__(2087));
-const path = __importStar(__nccwpck_require__(5622));
+const os = __importStar(__nccwpck_require__(2037));
+const path = __importStar(__nccwpck_require__(1017));
const oidc_utils_1 = __nccwpck_require__(8041);
/**
* The code to exit an action
@@ -3265,9 +3643,9 @@ Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.prepareKeyValueMessage = exports.issueFileCommand = void 0;
// We use any as a valid input type
/* eslint-disable @typescript-eslint/no-explicit-any */
-const fs = __importStar(__nccwpck_require__(5747));
-const os = __importStar(__nccwpck_require__(2087));
-const uuid_1 = __nccwpck_require__(9826);
+const fs = __importStar(__nccwpck_require__(7147));
+const os = __importStar(__nccwpck_require__(2037));
+const uuid_1 = __nccwpck_require__(8974);
const utils_1 = __nccwpck_require__(5278);
function issueFileCommand(command, message) {
const filePath = process.env[`GITHUB_${command}`];
@@ -3351,7 +3729,7 @@ class OidcClient {
.catch(error => {
throw new Error(`Failed to get ID Token. \n
Error Code : ${error.statusCode}\n
- Error Message: ${error.result.message}`);
+ Error Message: ${error.message}`);
});
const id_token = (_a = res.result) === null || _a === void 0 ? void 0 : _a.value;
if (!id_token) {
@@ -3411,7 +3789,7 @@ var __importStar = (this && this.__importStar) || function (mod) {
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.toPlatformPath = exports.toWin32Path = exports.toPosixPath = void 0;
-const path = __importStar(__nccwpck_require__(5622));
+const path = __importStar(__nccwpck_require__(1017));
/**
* toPosixPath converts the given path to the posix form. On Windows, \\ will be
* replaced with /.
@@ -3466,8 +3844,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.summary = exports.markdownSummary = exports.SUMMARY_DOCS_URL = exports.SUMMARY_ENV_VAR = void 0;
-const os_1 = __nccwpck_require__(2087);
-const fs_1 = __nccwpck_require__(5747);
+const os_1 = __nccwpck_require__(2037);
+const fs_1 = __nccwpck_require__(7147);
const { access, appendFile, writeFile } = fs_1.promises;
exports.SUMMARY_ENV_VAR = 'GITHUB_STEP_SUMMARY';
exports.SUMMARY_DOCS_URL = 'https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#adding-a-job-summary';
@@ -3787,60 +4165,284 @@ exports.toCommandProperties = toCommandProperties;
/***/ }),
-/***/ 9826:
-/***/ ((__unused_webpack_module, __webpack_exports__, __nccwpck_require__) => {
+/***/ 8974:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
-// ESM COMPAT FLAG
-__nccwpck_require__.r(__webpack_exports__);
-
-// EXPORTS
-__nccwpck_require__.d(__webpack_exports__, {
- "NIL": () => /* reexport */ nil,
- "parse": () => /* reexport */ esm_node_parse,
- "stringify": () => /* reexport */ esm_node_stringify,
- "v1": () => /* reexport */ esm_node_v1,
- "v3": () => /* reexport */ esm_node_v3,
- "v4": () => /* reexport */ esm_node_v4,
- "v5": () => /* reexport */ esm_node_v5,
- "validate": () => /* reexport */ esm_node_validate,
- "version": () => /* reexport */ esm_node_version
-});
-// EXTERNAL MODULE: external "crypto"
-var external_crypto_ = __nccwpck_require__(6417);
-var external_crypto_default = /*#__PURE__*/__nccwpck_require__.n(external_crypto_);
-// CONCATENATED MODULE: ./node_modules/@actions/core/node_modules/uuid/dist/esm-node/rng.js
+Object.defineProperty(exports, "__esModule", ({
+ value: true
+}));
+Object.defineProperty(exports, "v1", ({
+ enumerable: true,
+ get: function () {
+ return _v.default;
+ }
+}));
+Object.defineProperty(exports, "v3", ({
+ enumerable: true,
+ get: function () {
+ return _v2.default;
+ }
+}));
+Object.defineProperty(exports, "v4", ({
+ enumerable: true,
+ get: function () {
+ return _v3.default;
+ }
+}));
+Object.defineProperty(exports, "v5", ({
+ enumerable: true,
+ get: function () {
+ return _v4.default;
+ }
+}));
+Object.defineProperty(exports, "NIL", ({
+ enumerable: true,
+ get: function () {
+ return _nil.default;
+ }
+}));
+Object.defineProperty(exports, "version", ({
+ enumerable: true,
+ get: function () {
+ return _version.default;
+ }
+}));
+Object.defineProperty(exports, "validate", ({
+ enumerable: true,
+ get: function () {
+ return _validate.default;
+ }
+}));
+Object.defineProperty(exports, "stringify", ({
+ enumerable: true,
+ get: function () {
+ return _stringify.default;
+ }
+}));
+Object.defineProperty(exports, "parse", ({
+ enumerable: true,
+ get: function () {
+ return _parse.default;
+ }
+}));
+
+var _v = _interopRequireDefault(__nccwpck_require__(1595));
+
+var _v2 = _interopRequireDefault(__nccwpck_require__(6993));
+
+var _v3 = _interopRequireDefault(__nccwpck_require__(1472));
+
+var _v4 = _interopRequireDefault(__nccwpck_require__(6217));
+
+var _nil = _interopRequireDefault(__nccwpck_require__(2381));
+
+var _version = _interopRequireDefault(__nccwpck_require__(427));
+
+var _validate = _interopRequireDefault(__nccwpck_require__(2609));
+
+var _stringify = _interopRequireDefault(__nccwpck_require__(1458));
+
+var _parse = _interopRequireDefault(__nccwpck_require__(6385));
+
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+/***/ }),
+
+/***/ 5842:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({
+ value: true
+}));
+exports["default"] = void 0;
+
+var _crypto = _interopRequireDefault(__nccwpck_require__(6113));
+
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+function md5(bytes) {
+ if (Array.isArray(bytes)) {
+ bytes = Buffer.from(bytes);
+ } else if (typeof bytes === 'string') {
+ bytes = Buffer.from(bytes, 'utf8');
+ }
+
+ return _crypto.default.createHash('md5').update(bytes).digest();
+}
+
+var _default = md5;
+exports["default"] = _default;
+
+/***/ }),
+
+/***/ 2381:
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({
+ value: true
+}));
+exports["default"] = void 0;
+var _default = '00000000-0000-0000-0000-000000000000';
+exports["default"] = _default;
+
+/***/ }),
+
+/***/ 6385:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({
+ value: true
+}));
+exports["default"] = void 0;
+
+var _validate = _interopRequireDefault(__nccwpck_require__(2609));
+
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+function parse(uuid) {
+ if (!(0, _validate.default)(uuid)) {
+ throw TypeError('Invalid UUID');
+ }
+
+ let v;
+ const arr = new Uint8Array(16); // Parse ########-....-....-....-............
+
+ arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;
+ arr[1] = v >>> 16 & 0xff;
+ arr[2] = v >>> 8 & 0xff;
+ arr[3] = v & 0xff; // Parse ........-####-....-....-............
+
+ arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;
+ arr[5] = v & 0xff; // Parse ........-....-####-....-............
+
+ arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;
+ arr[7] = v & 0xff; // Parse ........-....-....-####-............
+
+ arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;
+ arr[9] = v & 0xff; // Parse ........-....-....-....-############
+ // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes)
+
+ arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff;
+ arr[11] = v / 0x100000000 & 0xff;
+ arr[12] = v >>> 24 & 0xff;
+ arr[13] = v >>> 16 & 0xff;
+ arr[14] = v >>> 8 & 0xff;
+ arr[15] = v & 0xff;
+ return arr;
+}
+
+var _default = parse;
+exports["default"] = _default;
+
+/***/ }),
+
+/***/ 6230:
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({
+ value: true
+}));
+exports["default"] = void 0;
+var _default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;
+exports["default"] = _default;
+
+/***/ }),
+
+/***/ 9784:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({
+ value: true
+}));
+exports["default"] = rng;
+
+var _crypto = _interopRequireDefault(__nccwpck_require__(6113));
+
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate
let poolPtr = rnds8Pool.length;
+
function rng() {
if (poolPtr > rnds8Pool.length - 16) {
- external_crypto_default().randomFillSync(rnds8Pool);
+ _crypto.default.randomFillSync(rnds8Pool);
+
poolPtr = 0;
}
return rnds8Pool.slice(poolPtr, poolPtr += 16);
}
-// CONCATENATED MODULE: ./node_modules/@actions/core/node_modules/uuid/dist/esm-node/regex.js
-/* harmony default export */ const regex = (/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i);
-// CONCATENATED MODULE: ./node_modules/@actions/core/node_modules/uuid/dist/esm-node/validate.js
+/***/ }),
-function validate(uuid) {
- return typeof uuid === 'string' && regex.test(uuid);
+/***/ 8844:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({
+ value: true
+}));
+exports["default"] = void 0;
+
+var _crypto = _interopRequireDefault(__nccwpck_require__(6113));
+
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+function sha1(bytes) {
+ if (Array.isArray(bytes)) {
+ bytes = Buffer.from(bytes);
+ } else if (typeof bytes === 'string') {
+ bytes = Buffer.from(bytes, 'utf8');
+ }
+
+ return _crypto.default.createHash('sha1').update(bytes).digest();
}
-/* harmony default export */ const esm_node_validate = (validate);
-// CONCATENATED MODULE: ./node_modules/@actions/core/node_modules/uuid/dist/esm-node/stringify.js
+var _default = sha1;
+exports["default"] = _default;
+
+/***/ }),
+
+/***/ 1458:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({
+ value: true
+}));
+exports["default"] = void 0;
+
+var _validate = _interopRequireDefault(__nccwpck_require__(2609));
+
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Convert array of 16 byte values to UUID string format of the form:
* XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
*/
-
const byteToHex = [];
for (let i = 0; i < 256; ++i) {
@@ -3856,21 +4458,39 @@ function stringify(arr, offset = 0) {
// "undefined" in the uuid)
// - Invalid input values for the RFC `version` or `variant` fields
- if (!esm_node_validate(uuid)) {
+ if (!(0, _validate.default)(uuid)) {
throw TypeError('Stringified UUID is invalid');
}
return uuid;
}
-/* harmony default export */ const esm_node_stringify = (stringify);
-// CONCATENATED MODULE: ./node_modules/@actions/core/node_modules/uuid/dist/esm-node/v1.js
+var _default = stringify;
+exports["default"] = _default;
+
+/***/ }),
+
+/***/ 1595:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({
+ value: true
+}));
+exports["default"] = void 0;
+
+var _rng = _interopRequireDefault(__nccwpck_require__(9784));
+
+var _stringify = _interopRequireDefault(__nccwpck_require__(1458));
+
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- // **`v1()` - Generate time-based UUID**
+// **`v1()` - Generate time-based UUID**
//
// Inspired by https://github.com/LiosK/UUID.js
// and http://docs.python.org/library/uuid.html
-
let _nodeId;
let _clockseq; // Previous uuid creation time
@@ -3889,7 +4509,7 @@ function v1(options, buf, offset) {
// system entropy. See #189
if (node == null || clockseq == null) {
- const seedBytes = options.random || (options.rng || rng)();
+ const seedBytes = options.random || (options.rng || _rng.default)();
if (node == null) {
// Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
@@ -3956,49 +4576,54 @@ function v1(options, buf, offset) {
b[i + n] = node[n];
}
- return buf || esm_node_stringify(b);
+ return buf || (0, _stringify.default)(b);
}
-/* harmony default export */ const esm_node_v1 = (v1);
-// CONCATENATED MODULE: ./node_modules/@actions/core/node_modules/uuid/dist/esm-node/parse.js
+var _default = v1;
+exports["default"] = _default;
+/***/ }),
-function parse(uuid) {
- if (!esm_node_validate(uuid)) {
- throw TypeError('Invalid UUID');
- }
+/***/ 6993:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- let v;
- const arr = new Uint8Array(16); // Parse ########-....-....-....-............
+"use strict";
- arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;
- arr[1] = v >>> 16 & 0xff;
- arr[2] = v >>> 8 & 0xff;
- arr[3] = v & 0xff; // Parse ........-####-....-....-............
- arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;
- arr[5] = v & 0xff; // Parse ........-....-####-....-............
+Object.defineProperty(exports, "__esModule", ({
+ value: true
+}));
+exports["default"] = void 0;
- arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;
- arr[7] = v & 0xff; // Parse ........-....-....-####-............
+var _v = _interopRequireDefault(__nccwpck_require__(5920));
- arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;
- arr[9] = v & 0xff; // Parse ........-....-....-....-############
- // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes)
+var _md = _interopRequireDefault(__nccwpck_require__(5842));
- arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff;
- arr[11] = v / 0x100000000 & 0xff;
- arr[12] = v >>> 24 & 0xff;
- arr[13] = v >>> 16 & 0xff;
- arr[14] = v >>> 8 & 0xff;
- arr[15] = v & 0xff;
- return arr;
-}
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
-/* harmony default export */ const esm_node_parse = (parse);
-// CONCATENATED MODULE: ./node_modules/@actions/core/node_modules/uuid/dist/esm-node/v35.js
+const v3 = (0, _v.default)('v3', 0x30, _md.default);
+var _default = v3;
+exports["default"] = _default;
+/***/ }),
+
+/***/ 5920:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({
+ value: true
+}));
+exports["default"] = _default;
+exports.URL = exports.DNS = void 0;
+
+var _stringify = _interopRequireDefault(__nccwpck_require__(1458));
+
+var _parse = _interopRequireDefault(__nccwpck_require__(6385));
+
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function stringToBytes(str) {
str = unescape(encodeURIComponent(str)); // UTF8 escape
@@ -4013,15 +4638,18 @@ function stringToBytes(str) {
}
const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
+exports.DNS = DNS;
const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';
-/* harmony default export */ function v35(name, version, hashfunc) {
+exports.URL = URL;
+
+function _default(name, version, hashfunc) {
function generateUUID(value, namespace, buf, offset) {
if (typeof value === 'string') {
value = stringToBytes(value);
}
if (typeof namespace === 'string') {
- namespace = esm_node_parse(namespace);
+ namespace = (0, _parse.default)(namespace);
}
if (namespace.length !== 16) {
@@ -4048,7 +4676,7 @@ const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';
return buf;
}
- return esm_node_stringify(bytes);
+ return (0, _stringify.default)(bytes);
} // Function#name is not settable on some platforms (#270)
@@ -4061,32 +4689,31 @@ const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';
generateUUID.URL = URL;
return generateUUID;
}
-// CONCATENATED MODULE: ./node_modules/@actions/core/node_modules/uuid/dist/esm-node/md5.js
+/***/ }),
-function md5(bytes) {
- if (Array.isArray(bytes)) {
- bytes = Buffer.from(bytes);
- } else if (typeof bytes === 'string') {
- bytes = Buffer.from(bytes, 'utf8');
- }
+/***/ 1472:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- return external_crypto_default().createHash('md5').update(bytes).digest();
-}
+"use strict";
-/* harmony default export */ const esm_node_md5 = (md5);
-// CONCATENATED MODULE: ./node_modules/@actions/core/node_modules/uuid/dist/esm-node/v3.js
+Object.defineProperty(exports, "__esModule", ({
+ value: true
+}));
+exports["default"] = void 0;
-const v3 = v35('v3', 0x30, esm_node_md5);
-/* harmony default export */ const esm_node_v3 = (v3);
-// CONCATENATED MODULE: ./node_modules/@actions/core/node_modules/uuid/dist/esm-node/v4.js
+var _rng = _interopRequireDefault(__nccwpck_require__(9784));
+var _stringify = _interopRequireDefault(__nccwpck_require__(1458));
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function v4(options, buf, offset) {
options = options || {};
- const rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
+
+ const rnds = options.random || (options.rng || _rng.default)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
+
rnds[6] = rnds[6] & 0x0f | 0x40;
rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided
@@ -4101,53 +4728,86 @@ function v4(options, buf, offset) {
return buf;
}
- return esm_node_stringify(rnds);
+ return (0, _stringify.default)(rnds);
}
-/* harmony default export */ const esm_node_v4 = (v4);
-// CONCATENATED MODULE: ./node_modules/@actions/core/node_modules/uuid/dist/esm-node/sha1.js
+var _default = v4;
+exports["default"] = _default;
+/***/ }),
-function sha1(bytes) {
- if (Array.isArray(bytes)) {
- bytes = Buffer.from(bytes);
- } else if (typeof bytes === 'string') {
- bytes = Buffer.from(bytes, 'utf8');
- }
+/***/ 6217:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- return external_crypto_default().createHash('sha1').update(bytes).digest();
-}
+"use strict";
-/* harmony default export */ const esm_node_sha1 = (sha1);
-// CONCATENATED MODULE: ./node_modules/@actions/core/node_modules/uuid/dist/esm-node/v5.js
+Object.defineProperty(exports, "__esModule", ({
+ value: true
+}));
+exports["default"] = void 0;
-const v5 = v35('v5', 0x50, esm_node_sha1);
-/* harmony default export */ const esm_node_v5 = (v5);
-// CONCATENATED MODULE: ./node_modules/@actions/core/node_modules/uuid/dist/esm-node/nil.js
-/* harmony default export */ const nil = ('00000000-0000-0000-0000-000000000000');
-// CONCATENATED MODULE: ./node_modules/@actions/core/node_modules/uuid/dist/esm-node/version.js
+var _v = _interopRequireDefault(__nccwpck_require__(5920));
+var _sha = _interopRequireDefault(__nccwpck_require__(8844));
-function version(uuid) {
- if (!esm_node_validate(uuid)) {
- throw TypeError('Invalid UUID');
- }
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- return parseInt(uuid.substr(14, 1), 16);
+const v5 = (0, _v.default)('v5', 0x50, _sha.default);
+var _default = v5;
+exports["default"] = _default;
+
+/***/ }),
+
+/***/ 2609:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({
+ value: true
+}));
+exports["default"] = void 0;
+
+var _regex = _interopRequireDefault(__nccwpck_require__(6230));
+
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+function validate(uuid) {
+ return typeof uuid === 'string' && _regex.default.test(uuid);
}
-/* harmony default export */ const esm_node_version = (version);
-// CONCATENATED MODULE: ./node_modules/@actions/core/node_modules/uuid/dist/esm-node/index.js
+var _default = validate;
+exports["default"] = _default;
+
+/***/ }),
+/***/ 427:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+"use strict";
+Object.defineProperty(exports, "__esModule", ({
+ value: true
+}));
+exports["default"] = void 0;
+var _validate = _interopRequireDefault(__nccwpck_require__(2609));
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+function version(uuid) {
+ if (!(0, _validate.default)(uuid)) {
+ throw TypeError('Invalid UUID');
+ }
+ return parseInt(uuid.substr(14, 1), 16);
+}
+var _default = version;
+exports["default"] = _default;
/***/ }),
@@ -4186,7 +4846,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getExecOutput = exports.exec = void 0;
-const string_decoder_1 = __nccwpck_require__(4304);
+const string_decoder_1 = __nccwpck_require__(1576);
const tr = __importStar(__nccwpck_require__(8159));
/**
* Exec a command.
@@ -4296,13 +4956,13 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.argStringToArray = exports.ToolRunner = void 0;
-const os = __importStar(__nccwpck_require__(2087));
-const events = __importStar(__nccwpck_require__(8614));
-const child = __importStar(__nccwpck_require__(3129));
-const path = __importStar(__nccwpck_require__(5622));
+const os = __importStar(__nccwpck_require__(2037));
+const events = __importStar(__nccwpck_require__(2361));
+const child = __importStar(__nccwpck_require__(2081));
+const path = __importStar(__nccwpck_require__(1017));
const io = __importStar(__nccwpck_require__(7436));
const ioUtil = __importStar(__nccwpck_require__(1962));
-const timers_1 = __nccwpck_require__(8213);
+const timers_1 = __nccwpck_require__(9512);
/* eslint-disable @typescript-eslint/unbound-method */
const IS_WINDOWS = process.platform === 'win32';
/*
@@ -4920,16 +5580,18 @@ exports.create = create;
* Computes the sha256 hash of a glob
*
* @param patterns Patterns separated by newlines
+ * @param currentWorkspace Workspace used when matching files
* @param options Glob options
+ * @param verbose Enables verbose logging
*/
-function hashFiles(patterns, options, verbose = false) {
+function hashFiles(patterns, currentWorkspace = '', options, verbose = false) {
return __awaiter(this, void 0, void 0, function* () {
let followSymbolicLinks = true;
if (options && typeof options.followSymbolicLinks === 'boolean') {
followSymbolicLinks = options.followSymbolicLinks;
}
const globber = yield create(patterns, { followSymbolicLinks });
- return internal_hash_files_1.hashFiles(globber, verbose);
+ return internal_hash_files_1.hashFiles(globber, currentWorkspace, verbose);
});
}
exports.hashFiles = hashFiles;
@@ -5054,9 +5716,9 @@ var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _ar
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.DefaultGlobber = void 0;
const core = __importStar(__nccwpck_require__(2186));
-const fs = __importStar(__nccwpck_require__(5747));
+const fs = __importStar(__nccwpck_require__(7147));
const globOptionsHelper = __importStar(__nccwpck_require__(1026));
-const path = __importStar(__nccwpck_require__(5622));
+const path = __importStar(__nccwpck_require__(1017));
const patternHelper = __importStar(__nccwpck_require__(9005));
const internal_match_kind_1 = __nccwpck_require__(1063);
const internal_pattern_1 = __nccwpck_require__(4536);
@@ -5283,19 +5945,21 @@ var __asyncValues = (this && this.__asyncValues) || function (o) {
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.hashFiles = void 0;
-const crypto = __importStar(__nccwpck_require__(6417));
+const crypto = __importStar(__nccwpck_require__(6113));
const core = __importStar(__nccwpck_require__(2186));
-const fs = __importStar(__nccwpck_require__(5747));
-const stream = __importStar(__nccwpck_require__(2413));
-const util = __importStar(__nccwpck_require__(1669));
-const path = __importStar(__nccwpck_require__(5622));
-function hashFiles(globber, verbose = false) {
+const fs = __importStar(__nccwpck_require__(7147));
+const stream = __importStar(__nccwpck_require__(2781));
+const util = __importStar(__nccwpck_require__(3837));
+const path = __importStar(__nccwpck_require__(1017));
+function hashFiles(globber, currentWorkspace, verbose = false) {
var e_1, _a;
var _b;
return __awaiter(this, void 0, void 0, function* () {
const writeDelegate = verbose ? core.info : core.debug;
let hasMatch = false;
- const githubWorkspace = (_b = process.env['GITHUB_WORKSPACE']) !== null && _b !== void 0 ? _b : process.cwd();
+ const githubWorkspace = currentWorkspace
+ ? currentWorkspace
+ : (_b = process.env['GITHUB_WORKSPACE']) !== null && _b !== void 0 ? _b : process.cwd();
const result = crypto.createHash('sha256');
let count = 0;
try {
@@ -5397,8 +6061,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.safeTrimTrailingSeparator = exports.normalizeSeparators = exports.hasRoot = exports.hasAbsoluteRoot = exports.ensureAbsoluteRoot = exports.dirname = void 0;
-const path = __importStar(__nccwpck_require__(5622));
-const assert_1 = __importDefault(__nccwpck_require__(2357));
+const path = __importStar(__nccwpck_require__(1017));
+const assert_1 = __importDefault(__nccwpck_require__(9491));
const IS_WINDOWS = process.platform === 'win32';
/**
* Similar to path.dirname except normalizes the path separators and slightly better handling for Windows UNC paths.
@@ -5602,9 +6266,9 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Path = void 0;
-const path = __importStar(__nccwpck_require__(5622));
+const path = __importStar(__nccwpck_require__(1017));
const pathHelper = __importStar(__nccwpck_require__(1849));
-const assert_1 = __importDefault(__nccwpck_require__(2357));
+const assert_1 = __importDefault(__nccwpck_require__(9491));
const IS_WINDOWS = process.platform === 'win32';
/**
* Helper class for parsing paths into segments
@@ -5823,10 +6487,10 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Pattern = void 0;
-const os = __importStar(__nccwpck_require__(2087));
-const path = __importStar(__nccwpck_require__(5622));
+const os = __importStar(__nccwpck_require__(2037));
+const path = __importStar(__nccwpck_require__(1017));
const pathHelper = __importStar(__nccwpck_require__(1849));
-const assert_1 = __importDefault(__nccwpck_require__(2357));
+const assert_1 = __importDefault(__nccwpck_require__(9491));
const minimatch_1 = __nccwpck_require__(3973);
const internal_match_kind_1 = __nccwpck_require__(1063);
const internal_path_1 = __nccwpck_require__(6836);
@@ -6170,7 +6834,11 @@ exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHand
/* eslint-disable @typescript-eslint/no-explicit-any */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
+ var desc = Object.getOwnPropertyDescriptor(m, k);
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+ desc = { enumerable: true, get: function() { return m[k]; } };
+ }
+ Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
@@ -6183,7 +6851,7 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
@@ -6198,10 +6866,11 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.HttpClient = exports.isHttps = exports.HttpClientResponse = exports.HttpClientError = exports.getProxyUrl = exports.MediaTypes = exports.Headers = exports.HttpCodes = void 0;
-const http = __importStar(__nccwpck_require__(8605));
-const https = __importStar(__nccwpck_require__(7211));
+const http = __importStar(__nccwpck_require__(3685));
+const https = __importStar(__nccwpck_require__(5687));
const pm = __importStar(__nccwpck_require__(9835));
const tunnel = __importStar(__nccwpck_require__(4294));
+const undici_1 = __nccwpck_require__(1773);
var HttpCodes;
(function (HttpCodes) {
HttpCodes[HttpCodes["OK"] = 200] = "OK";
@@ -6231,16 +6900,16 @@ var HttpCodes;
HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway";
HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable";
HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout";
-})(HttpCodes = exports.HttpCodes || (exports.HttpCodes = {}));
+})(HttpCodes || (exports.HttpCodes = HttpCodes = {}));
var Headers;
(function (Headers) {
Headers["Accept"] = "accept";
Headers["ContentType"] = "content-type";
-})(Headers = exports.Headers || (exports.Headers = {}));
+})(Headers || (exports.Headers = Headers = {}));
var MediaTypes;
(function (MediaTypes) {
MediaTypes["ApplicationJson"] = "application/json";
-})(MediaTypes = exports.MediaTypes || (exports.MediaTypes = {}));
+})(MediaTypes || (exports.MediaTypes = MediaTypes = {}));
/**
* Returns the proxy URL, depending upon the supplied url and proxy environment variables.
* @param serverUrl The server URL where the request will be sent. For example, https://api.github.com
@@ -6291,6 +6960,19 @@ class HttpClientResponse {
}));
});
}
+ readBodyBuffer() {
+ return __awaiter(this, void 0, void 0, function* () {
+ return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () {
+ const chunks = [];
+ this.message.on('data', (chunk) => {
+ chunks.push(chunk);
+ });
+ this.message.on('end', () => {
+ resolve(Buffer.concat(chunks));
+ });
+ }));
+ });
+ }
}
exports.HttpClientResponse = HttpClientResponse;
function isHttps(requestUrl) {
@@ -6596,6 +7278,15 @@ class HttpClient {
const parsedUrl = new URL(serverUrl);
return this._getAgent(parsedUrl);
}
+ getAgentDispatcher(serverUrl) {
+ const parsedUrl = new URL(serverUrl);
+ const proxyUrl = pm.getProxyUrl(parsedUrl);
+ const useProxy = proxyUrl && proxyUrl.hostname;
+ if (!useProxy) {
+ return;
+ }
+ return this._getProxyAgentDispatcher(parsedUrl, proxyUrl);
+ }
_prepareRequest(method, requestUrl, headers) {
const info = {};
info.parsedUrl = requestUrl;
@@ -6695,6 +7386,30 @@ class HttpClient {
}
return agent;
}
+ _getProxyAgentDispatcher(parsedUrl, proxyUrl) {
+ let proxyAgent;
+ if (this._keepAlive) {
+ proxyAgent = this._proxyAgentDispatcher;
+ }
+ // if agent is already assigned use that agent.
+ if (proxyAgent) {
+ return proxyAgent;
+ }
+ const usingSsl = parsedUrl.protocol === 'https:';
+ proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, ((proxyUrl.username || proxyUrl.password) && {
+ token: `${proxyUrl.username}:${proxyUrl.password}`
+ })));
+ this._proxyAgentDispatcher = proxyAgent;
+ if (usingSsl && this._ignoreSslError) {
+ // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process
+ // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options
+ // we have to cast it to any and change it directly
+ proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, {
+ rejectUnauthorized: false
+ });
+ }
+ return proxyAgent;
+ }
_performExponentialBackoff(retryNumber) {
return __awaiter(this, void 0, void 0, function* () {
retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber);
@@ -6795,7 +7510,13 @@ function getProxyUrl(reqUrl) {
}
})();
if (proxyVar) {
- return new URL(proxyVar);
+ try {
+ return new URL(proxyVar);
+ }
+ catch (_a) {
+ if (!proxyVar.startsWith('http://') && !proxyVar.startsWith('https://'))
+ return new URL(`http://${proxyVar}`);
+ }
}
else {
return undefined;
@@ -6806,6 +7527,10 @@ function checkBypass(reqUrl) {
if (!reqUrl.hostname) {
return false;
}
+ const reqHost = reqUrl.hostname;
+ if (isLoopbackAddress(reqHost)) {
+ return true;
+ }
const noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || '';
if (!noProxy) {
return false;
@@ -6831,13 +7556,24 @@ function checkBypass(reqUrl) {
.split(',')
.map(x => x.trim().toUpperCase())
.filter(x => x)) {
- if (upperReqHosts.some(x => x === upperNoProxyItem)) {
+ if (upperNoProxyItem === '*' ||
+ upperReqHosts.some(x => x === upperNoProxyItem ||
+ x.endsWith(`.${upperNoProxyItem}`) ||
+ (upperNoProxyItem.startsWith('.') &&
+ x.endsWith(`${upperNoProxyItem}`)))) {
return true;
}
}
return false;
}
exports.checkBypass = checkBypass;
+function isLoopbackAddress(host) {
+ const hostLower = host.toLowerCase();
+ return (hostLower === 'localhost' ||
+ hostLower.startsWith('127.') ||
+ hostLower.startsWith('[::1]') ||
+ hostLower.startsWith('[0:0:0:0:0:0:0:1]'));
+}
//# sourceMappingURL=proxy.js.map
/***/ }),
@@ -6877,11 +7613,17 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
};
var _a;
Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.getCmdPath = exports.tryGetExecutablePath = exports.isRooted = exports.isDirectory = exports.exists = exports.IS_WINDOWS = exports.unlink = exports.symlink = exports.stat = exports.rmdir = exports.rename = exports.readlink = exports.readdir = exports.mkdir = exports.lstat = exports.copyFile = exports.chmod = void 0;
-const fs = __importStar(__nccwpck_require__(5747));
-const path = __importStar(__nccwpck_require__(5622));
-_a = fs.promises, exports.chmod = _a.chmod, exports.copyFile = _a.copyFile, exports.lstat = _a.lstat, exports.mkdir = _a.mkdir, exports.readdir = _a.readdir, exports.readlink = _a.readlink, exports.rename = _a.rename, exports.rmdir = _a.rmdir, exports.stat = _a.stat, exports.symlink = _a.symlink, exports.unlink = _a.unlink;
+exports.getCmdPath = exports.tryGetExecutablePath = exports.isRooted = exports.isDirectory = exports.exists = exports.READONLY = exports.UV_FS_O_EXLOCK = exports.IS_WINDOWS = exports.unlink = exports.symlink = exports.stat = exports.rmdir = exports.rm = exports.rename = exports.readlink = exports.readdir = exports.open = exports.mkdir = exports.lstat = exports.copyFile = exports.chmod = void 0;
+const fs = __importStar(__nccwpck_require__(7147));
+const path = __importStar(__nccwpck_require__(1017));
+_a = fs.promises
+// export const {open} = 'fs'
+, exports.chmod = _a.chmod, exports.copyFile = _a.copyFile, exports.lstat = _a.lstat, exports.mkdir = _a.mkdir, exports.open = _a.open, exports.readdir = _a.readdir, exports.readlink = _a.readlink, exports.rename = _a.rename, exports.rm = _a.rm, exports.rmdir = _a.rmdir, exports.stat = _a.stat, exports.symlink = _a.symlink, exports.unlink = _a.unlink;
+// export const {open} = 'fs'
exports.IS_WINDOWS = process.platform === 'win32';
+// See https://github.com/nodejs/node/blob/d0153aee367422d0858105abec186da4dff0a0c5/deps/uv/include/uv/win.h#L691
+exports.UV_FS_O_EXLOCK = 0x10000000;
+exports.READONLY = fs.constants.O_RDONLY;
function exists(fsPath) {
return __awaiter(this, void 0, void 0, function* () {
try {
@@ -7061,13 +7803,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.findInPath = exports.which = exports.mkdirP = exports.rmRF = exports.mv = exports.cp = void 0;
-const assert_1 = __nccwpck_require__(2357);
-const childProcess = __importStar(__nccwpck_require__(3129));
-const path = __importStar(__nccwpck_require__(5622));
-const util_1 = __nccwpck_require__(1669);
+const assert_1 = __nccwpck_require__(9491);
+const path = __importStar(__nccwpck_require__(1017));
const ioUtil = __importStar(__nccwpck_require__(1962));
-const exec = util_1.promisify(childProcess.exec);
-const execFile = util_1.promisify(childProcess.execFile);
/**
* Copies a file or folder.
* Based off of shelljs - https://github.com/shelljs/shelljs/blob/9237f66c52e5daa40458f94f9565e18e8132f5a6/src/cp.js
@@ -7148,61 +7886,23 @@ exports.mv = mv;
function rmRF(inputPath) {
return __awaiter(this, void 0, void 0, function* () {
if (ioUtil.IS_WINDOWS) {
- // Node doesn't provide a delete operation, only an unlink function. This means that if the file is being used by another
- // program (e.g. antivirus), it won't be deleted. To address this, we shell out the work to rd/del.
// Check for invalid characters
// https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
if (/[*"<>|]/.test(inputPath)) {
throw new Error('File path must not contain `*`, `"`, `<`, `>` or `|` on Windows');
}
- try {
- const cmdPath = ioUtil.getCmdPath();
- if (yield ioUtil.isDirectory(inputPath, true)) {
- yield exec(`${cmdPath} /s /c "rd /s /q "%inputPath%""`, {
- env: { inputPath }
- });
- }
- else {
- yield exec(`${cmdPath} /s /c "del /f /a "%inputPath%""`, {
- env: { inputPath }
- });
- }
- }
- catch (err) {
- // if you try to delete a file that doesn't exist, desired result is achieved
- // other errors are valid
- if (err.code !== 'ENOENT')
- throw err;
- }
- // Shelling out fails to remove a symlink folder with missing source, this unlink catches that
- try {
- yield ioUtil.unlink(inputPath);
- }
- catch (err) {
- // if you try to delete a file that doesn't exist, desired result is achieved
- // other errors are valid
- if (err.code !== 'ENOENT')
- throw err;
- }
}
- else {
- let isDir = false;
- try {
- isDir = yield ioUtil.isDirectory(inputPath);
- }
- catch (err) {
- // if you try to delete a file that doesn't exist, desired result is achieved
- // other errors are valid
- if (err.code !== 'ENOENT')
- throw err;
- return;
- }
- if (isDir) {
- yield execFile(`rm`, [`-rf`, `${inputPath}`]);
- }
- else {
- yield ioUtil.unlink(inputPath);
- }
+ try {
+ // note if path does not exist, error is silent
+ yield ioUtil.rm(inputPath, {
+ force: true,
+ maxRetries: 3,
+ recursive: true,
+ retryDelay: 300
+ });
+ }
+ catch (err) {
+ throw new Error(`File was unable to be removed ${err}`);
}
});
}
@@ -7622,13 +8322,15 @@ exports.AbortSignal = AbortSignal;
/***/ }),
/***/ 9645:
-/***/ ((__unused_webpack_module, exports) => {
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
+var coreUtil = __nccwpck_require__(1333);
+
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
/**
@@ -7636,6 +8338,12 @@ Object.defineProperty(exports, "__esModule", ({ value: true }));
* the underlying key value.
*/
class AzureKeyCredential {
+ /**
+ * The value of the key to be used in authentication
+ */
+ get key() {
+ return this._key;
+ }
/**
* Create an instance of an AzureKeyCredential for use
* with a service client.
@@ -7648,12 +8356,6 @@ class AzureKeyCredential {
}
this._key = key;
}
- /**
- * The value of the key to be used in authentication
- */
- get key() {
- return this._key;
- }
/**
* Change the value of the key.
*
@@ -7667,51 +8369,24 @@ class AzureKeyCredential {
}
}
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-/**
- * Helper TypeGuard that checks if something is defined or not.
- * @param thing - Anything
- * @internal
- */
-function isDefined(thing) {
- return typeof thing !== "undefined" && thing !== null;
-}
-/**
- * Helper TypeGuard that checks if the input is an object with the specified properties.
- * Note: The properties may be inherited.
- * @param thing - Anything.
- * @param properties - The name of the properties that should appear in the object.
- * @internal
- */
-function isObjectWithProperties(thing, properties) {
- if (!isDefined(thing) || typeof thing !== "object") {
- return false;
- }
- for (const property of properties) {
- if (!objectHasProperty(thing, property)) {
- return false;
- }
- }
- return true;
-}
-/**
- * Helper TypeGuard that checks if the input is an object with the specified property.
- * Note: The property may be inherited.
- * @param thing - Any object.
- * @param property - The name of the property that should appear in the object.
- * @internal
- */
-function objectHasProperty(thing, property) {
- return typeof thing === "object" && property in thing;
-}
-
// Copyright (c) Microsoft Corporation.
/**
* A static name/key-based credential that supports updating
* the underlying name and key values.
*/
class AzureNamedKeyCredential {
+ /**
+ * The value of the key to be used in authentication.
+ */
+ get key() {
+ return this._key;
+ }
+ /**
+ * The value of the name to be used in authentication.
+ */
+ get name() {
+ return this._name;
+ }
/**
* Create an instance of an AzureNamedKeyCredential for use
* with a service client.
@@ -7726,18 +8401,6 @@ class AzureNamedKeyCredential {
this._name = name;
this._key = key;
}
- /**
- * The value of the key to be used in authentication.
- */
- get key() {
- return this._key;
- }
- /**
- * The value of the name to be used in authentication.
- */
- get name() {
- return this._name;
- }
/**
* Change the value of the key.
*
@@ -7761,7 +8424,7 @@ class AzureNamedKeyCredential {
* @param credential - The assumed NamedKeyCredential to be tested.
*/
function isNamedKeyCredential(credential) {
- return (isObjectWithProperties(credential, ["name", "key"]) &&
+ return (coreUtil.isObjectWithProperties(credential, ["name", "key"]) &&
typeof credential.key === "string" &&
typeof credential.name === "string");
}
@@ -7772,6 +8435,12 @@ function isNamedKeyCredential(credential) {
* the underlying signature value.
*/
class AzureSASCredential {
+ /**
+ * The value of the shared access signature to be used in authentication
+ */
+ get signature() {
+ return this._signature;
+ }
/**
* Create an instance of an AzureSASCredential for use
* with a service client.
@@ -7784,12 +8453,6 @@ class AzureSASCredential {
}
this._signature = signature;
}
- /**
- * The value of the shared access signature to be used in authentication
- */
- get signature() {
- return this._signature;
- }
/**
* Change the value of the signature.
*
@@ -7811,7 +8474,7 @@ class AzureSASCredential {
* @param credential - The assumed SASCredential to be tested.
*/
function isSASCredential(credential) {
- return (isObjectWithProperties(credential, ["signature"]) && typeof credential.signature === "string");
+ return (coreUtil.isObjectWithProperties(credential, ["signature"]) && typeof credential.signature === "string");
}
// Copyright (c) Microsoft Corporation.
@@ -7852,19 +8515,19 @@ exports.isTokenCredential = isTokenCredential;
Object.defineProperty(exports, "__esModule", ({ value: true }));
-var uuid = __nccwpck_require__(3206);
-var util = __nccwpck_require__(1669);
-var tslib = __nccwpck_require__(4331);
+var uuid = __nccwpck_require__(3415);
+var util = __nccwpck_require__(3837);
+var tslib = __nccwpck_require__(4351);
var xml2js = __nccwpck_require__(6189);
-var abortController = __nccwpck_require__(2557);
+var coreUtil = __nccwpck_require__(1333);
var logger$1 = __nccwpck_require__(3233);
var coreAuth = __nccwpck_require__(9645);
-var os = __nccwpck_require__(2087);
-var http = __nccwpck_require__(8605);
-var https = __nccwpck_require__(7211);
-var tough = __nccwpck_require__(7372);
+var os = __nccwpck_require__(2037);
+var http = __nccwpck_require__(3685);
+var https = __nccwpck_require__(5687);
+var abortController = __nccwpck_require__(2557);
var tunnel = __nccwpck_require__(4294);
-var stream = __nccwpck_require__(2413);
+var stream = __nccwpck_require__(2781);
var FormData = __nccwpck_require__(6279);
var node_fetch = __nccwpck_require__(467);
var coreTracing = __nccwpck_require__(4175);
@@ -7893,7 +8556,6 @@ var xml2js__namespace = /*#__PURE__*/_interopNamespace(xml2js);
var os__namespace = /*#__PURE__*/_interopNamespace(os);
var http__namespace = /*#__PURE__*/_interopNamespace(http);
var https__namespace = /*#__PURE__*/_interopNamespace(https);
-var tough__namespace = /*#__PURE__*/_interopNamespace(tough);
var tunnel__namespace = /*#__PURE__*/_interopNamespace(tunnel);
var FormData__default = /*#__PURE__*/_interopDefaultLegacy(FormData);
var node_fetch__default = /*#__PURE__*/_interopDefaultLegacy(node_fetch);
@@ -8085,7 +8747,7 @@ const Constants = {
/**
* The core-http version
*/
- coreHttpVersion: "2.2.6",
+ coreHttpVersion: "3.0.3",
/**
* Specifies HTTP.
*/
@@ -8163,13 +8825,6 @@ const XML_CHARKEY = "_";
// Copyright (c) Microsoft Corporation.
const validUuidRegex = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/i;
-/**
- * A constant that indicates whether the environment is node.js or browser based.
- */
-const isNode = typeof process !== "undefined" &&
- !!process.version &&
- !!process.versions &&
- !!process.versions.node;
/**
* Encodes an URI.
*
@@ -9002,7 +9657,8 @@ function isSpecialXmlProperty(propertyName, options) {
return [XML_ATTRKEY, options.xmlCharKey].includes(propertyName);
}
function deserializeCompositeType(serializer, mapper, responseBody, objectName, options) {
- var _a;
+ var _a, _b;
+ const xmlCharKey = (_a = options.xmlCharKey) !== null && _a !== void 0 ? _a : XML_CHARKEY;
if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) {
mapper = getPolymorphicMapper(serializer, mapper, responseBody, "serializedName");
}
@@ -9033,6 +9689,16 @@ function deserializeCompositeType(serializer, mapper, responseBody, objectName,
if (propertyMapper.xmlIsAttribute && responseBody[XML_ATTRKEY]) {
instance[key] = serializer.deserialize(propertyMapper, responseBody[XML_ATTRKEY][xmlName], propertyObjectName, options);
}
+ else if (propertyMapper.xmlIsMsText) {
+ if (responseBody[xmlCharKey] !== undefined) {
+ instance[key] = responseBody[xmlCharKey];
+ }
+ else if (typeof responseBody === "string") {
+ // The special case where xml parser parses "content" into JSON of
+ // `{ name: "content"}` instead of `{ name: { "_": "content" }}`
+ instance[key] = responseBody;
+ }
+ }
else {
const propertyName = xmlElementName || xmlName || serializedName;
if (propertyMapper.xmlIsWrapped) {
@@ -9051,12 +9717,14 @@ function deserializeCompositeType(serializer, mapper, responseBody, objectName,
xmlName is "Cors" and xmlElementName is"CorsRule".
*/
const wrapped = responseBody[xmlName];
- const elementList = (_a = wrapped === null || wrapped === void 0 ? void 0 : wrapped[xmlElementName]) !== null && _a !== void 0 ? _a : [];
+ const elementList = (_b = wrapped === null || wrapped === void 0 ? void 0 : wrapped[xmlElementName]) !== null && _b !== void 0 ? _b : [];
instance[key] = serializer.deserialize(propertyMapper, elementList, propertyObjectName, options);
+ handledPropertyNames.push(xmlName);
}
else {
const property = responseBody[propertyName];
instance[key] = serializer.deserialize(propertyMapper, property, propertyObjectName, options);
+ handledPropertyNames.push(propertyName);
}
}
}
@@ -10389,7 +11057,6 @@ class NodeFetchHttpClient {
// a mapping of proxy settings string `${host}:${port}:${username}:${password}` to agent
this.proxyAgentMap = new Map();
this.keepAliveAgents = {};
- this.cookieJar = new tough__namespace.CookieJar(undefined, { looseMode: true });
}
/**
* Provides minimum viable error handling and the logic that executes the abstract methods.
@@ -10477,7 +11144,11 @@ class NodeFetchHttpClient {
body = uploadReportStream;
}
const platformSpecificRequestInit = await this.prepareRequest(httpRequest);
- const requestInit = Object.assign({ body: body, headers: httpRequest.headers.rawHeaders(), method: httpRequest.method, signal: abortController$1.signal, redirect: "manual" }, platformSpecificRequestInit);
+ const requestInit = Object.assign({ body: body, headers: httpRequest.headers.rawHeaders(), method: httpRequest.method,
+ // the types for RequestInit are from the browser, which expects AbortSignal to
+ // have `reason` and `throwIfAborted`, but these don't exist on our polyfill
+ // for Node.
+ signal: abortController$1.signal, redirect: "manual" }, platformSpecificRequestInit);
let operationResponse;
try {
const response = await this.fetch(httpRequest.url, requestInit);
@@ -10602,43 +11273,16 @@ class NodeFetchHttpClient {
*/
async prepareRequest(httpRequest) {
const requestInit = {};
- if (this.cookieJar && !httpRequest.headers.get("Cookie")) {
- const cookieString = await new Promise((resolve, reject) => {
- this.cookieJar.getCookieString(httpRequest.url, (err, cookie) => {
- if (err) {
- reject(err);
- }
- else {
- resolve(cookie);
- }
- });
- });
- httpRequest.headers.set("Cookie", cookieString);
- }
// Set the http(s) agent
requestInit.agent = this.getOrCreateAgent(httpRequest);
requestInit.compress = httpRequest.decompressResponse;
return requestInit;
}
/**
- * Process an HTTP response. Handles persisting a cookie for subsequent requests if the response has a "Set-Cookie" header.
+ * Process an HTTP response.
*/
- async processRequest(operationResponse) {
- if (this.cookieJar) {
- const setCookieHeader = operationResponse.headers.get("Set-Cookie");
- if (setCookieHeader !== undefined) {
- await new Promise((resolve, reject) => {
- this.cookieJar.setCookie(setCookieHeader, operationResponse.request.url, { ignoreError: true }, (err) => {
- if (err) {
- reject(err);
- }
- else {
- resolve();
- }
- });
- });
- }
- }
+ async processRequest(_operationResponse) {
+ /* no_op */
}
}
@@ -10972,7 +11616,7 @@ function deserializeResponseBody(jsonContentTypes, xmlContentTypes, response, op
parsedResponse.parsedBody = response.status >= 200 && response.status < 300;
}
if (responseSpec.headersMapper) {
- parsedResponse.parsedHeaders = operationSpec.serializer.deserialize(responseSpec.headersMapper, parsedResponse.headers.rawHeaders(), "operationRes.parsedHeaders", options);
+ parsedResponse.parsedHeaders = operationSpec.serializer.deserialize(responseSpec.headersMapper, parsedResponse.headers.toJson(), "operationRes.parsedHeaders", options);
}
}
return parsedResponse;
@@ -11038,7 +11682,7 @@ function handleErrorResponse(parsedResponse, operationSpec, responseSpec) {
}
// If error response has headers, try to deserialize it using default header mapper
if (parsedResponse.headers && defaultHeadersMapper) {
- error.response.parsedHeaders = operationSpec.serializer.deserialize(defaultHeadersMapper, parsedResponse.headers.rawHeaders(), "operationRes.parsedHeaders");
+ error.response.parsedHeaders = operationSpec.serializer.deserialize(defaultHeadersMapper, parsedResponse.headers.toJson(), "operationRes.parsedHeaders");
}
}
catch (defaultError) {
@@ -11239,60 +11883,6 @@ function updateRetryData(retryOptions, retryData = { retryCount: 0, retryInterva
return retryData;
}
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-/**
- * Helper TypeGuard that checks if the value is not null or undefined.
- * @param thing - Anything
- * @internal
- */
-function isDefined(thing) {
- return typeof thing !== "undefined" && thing !== null;
-}
-
-// Copyright (c) Microsoft Corporation.
-const StandardAbortMessage$1 = "The operation was aborted.";
-/**
- * A wrapper for setTimeout that resolves a promise after delayInMs milliseconds.
- * @param delayInMs - The number of milliseconds to be delayed.
- * @param value - The value to be resolved with after a timeout of t milliseconds.
- * @param options - The options for delay - currently abort options
- * @param abortSignal - The abortSignal associated with containing operation.
- * @param abortErrorMsg - The abort error message associated with containing operation.
- * @returns - Resolved promise
- */
-function delay(delayInMs, value, options) {
- return new Promise((resolve, reject) => {
- let timer = undefined;
- let onAborted = undefined;
- const rejectOnAbort = () => {
- return reject(new abortController.AbortError((options === null || options === void 0 ? void 0 : options.abortErrorMsg) ? options === null || options === void 0 ? void 0 : options.abortErrorMsg : StandardAbortMessage$1));
- };
- const removeListeners = () => {
- if ((options === null || options === void 0 ? void 0 : options.abortSignal) && onAborted) {
- options.abortSignal.removeEventListener("abort", onAborted);
- }
- };
- onAborted = () => {
- if (isDefined(timer)) {
- clearTimeout(timer);
- }
- removeListeners();
- return rejectOnAbort();
- };
- if ((options === null || options === void 0 ? void 0 : options.abortSignal) && options.abortSignal.aborted) {
- return rejectOnAbort();
- }
- timer = setTimeout(() => {
- removeListeners();
- resolve(value);
- }, delayInMs);
- if (options === null || options === void 0 ? void 0 : options.abortSignal) {
- options.abortSignal.addEventListener("abort", onAborted);
- }
- });
-}
-
// Copyright (c) Microsoft Corporation.
/**
* Policy that retries the request as many times as configured for as long as the max retry time interval specified, each retry waiting longer to begin than the last time.
@@ -11373,7 +11963,7 @@ async function retry$1(policy, request, response, retryData, requestError) {
if (!isAborted && shouldRetry(policy.retryCount, shouldPolicyRetry, retryData, response)) {
logger.info(`Retrying request in ${retryData.retryInterval}`);
try {
- await delay(retryData.retryInterval);
+ await coreUtil.delay(retryData.retryInterval);
const res = await policy._nextPolicy.sendRequest(request.clone());
return retry$1(policy, request, res, retryData);
}
@@ -11668,7 +12258,7 @@ async function beginRefresh(getAccessToken, retryIntervalInMs, timeoutInMs) {
}
let token = await tryGetAccessToken();
while (token === null) {
- await delay(retryIntervalInMs);
+ await coreUtil.delay(retryIntervalInMs);
token = await tryGetAccessToken();
}
return token;
@@ -12200,7 +12790,7 @@ async function getRegistrationStatus(policy, url, originalRequest) {
return true;
}
else {
- await delay(policy._retryTimeout * 1000);
+ await coreUtil.delay(policy._retryTimeout * 1000);
return getRegistrationStatus(policy, url, originalRequest);
}
}
@@ -12292,7 +12882,7 @@ async function retry(policy, request, operationResponse, err, retryData) {
if (shouldRetry(policy.retryCount, shouldPolicyRetry, retryData, operationResponse, err)) {
// If previous operation ended with an error and the policy allows a retry, do that
try {
- await delay(retryData.retryInterval);
+ await coreUtil.delay(retryData.retryInterval);
return policy._nextPolicy.sendRequest(request.clone());
}
catch (nestedErr) {
@@ -12367,7 +12957,7 @@ class ThrottlingRetryPolicy extends BaseRequestPolicy {
const delayInMs = ThrottlingRetryPolicy.parseRetryAfterHeader(retryAfterHeader);
if (delayInMs) {
this.numberOfRetries += 1;
- await delay(delayInMs, undefined, {
+ await coreUtil.delay(delayInMs, {
abortSignal: httpRequest.abortSignal,
abortErrorMsg: StandardAbortMessage,
});
@@ -12915,7 +13505,7 @@ function createDefaultRequestPolicyFactories(authPolicyFactory, options) {
factories.push(throttlingRetryPolicy());
}
factories.push(deserializationPolicy(options.deserializationContentTypes));
- if (isNode) {
+ if (coreUtil.isNode) {
factories.push(proxyPolicy(options.proxySettings));
}
factories.push(logPolicy({ logger: logger.info }));
@@ -12947,7 +13537,7 @@ function createPipelineFromOptions(pipelineOptions, authPolicyFactory) {
const keepAliveOptions = Object.assign(Object.assign({}, DefaultKeepAliveOptions), pipelineOptions.keepAliveOptions);
const retryOptions = Object.assign(Object.assign({}, DefaultRetryOptions), pipelineOptions.retryOptions);
const redirectOptions = Object.assign(Object.assign({}, DefaultRedirectOptions), pipelineOptions.redirectOptions);
- if (isNode) {
+ if (coreUtil.isNode) {
requestPolicyFactories.push(proxyPolicy(pipelineOptions.proxyOptions));
}
const deserializationOptions = Object.assign(Object.assign({}, DefaultDeserializationOptions), pipelineOptions.deserializationOptions);
@@ -12960,7 +13550,7 @@ function createPipelineFromOptions(pipelineOptions, authPolicyFactory) {
requestPolicyFactories.push(authPolicyFactory);
}
requestPolicyFactories.push(logPolicy(loggingOptions));
- if (isNode && pipelineOptions.decompressResponse === false) {
+ if (coreUtil.isNode && pipelineOptions.decompressResponse === false) {
requestPolicyFactories.push(disableResponseDecompressionPolicy());
}
return {
@@ -13091,10 +13681,7 @@ function flattenResponse(_response, responseSpec) {
}
function getCredentialScopes(options, baseUri) {
if (options === null || options === void 0 ? void 0 : options.credentialScopes) {
- const scopes = options.credentialScopes;
- return Array.isArray(scopes)
- ? scopes.map((scope) => new URL(scope).toString())
- : new URL(scopes).toString();
+ return options.credentialScopes;
}
if (baseUri) {
return `${baseUri}/.default`;
@@ -13323,6 +13910,14 @@ class TopicCredentials extends ApiKeyCredentials {
}
}
+Object.defineProperty(exports, "delay", ({
+ enumerable: true,
+ get: function () { return coreUtil.delay; }
+}));
+Object.defineProperty(exports, "isNode", ({
+ enumerable: true,
+ get: function () { return coreUtil.isNode; }
+}));
Object.defineProperty(exports, "isTokenCredential", ({
enumerable: true,
get: function () { return coreAuth.isTokenCredential; }
@@ -13350,7 +13945,6 @@ exports.applyMixins = applyMixins;
exports.bearerTokenAuthenticationPolicy = bearerTokenAuthenticationPolicy;
exports.createPipelineFromOptions = createPipelineFromOptions;
exports.createSpanFunction = createSpanFunction;
-exports.delay = delay;
exports.deserializationPolicy = deserializationPolicy;
exports.deserializeResponseBody = deserializeResponseBody;
exports.disableResponseDecompressionPolicy = disableResponseDecompressionPolicy;
@@ -13363,7 +13957,6 @@ exports.generateUuid = generateUuid;
exports.getDefaultProxySettings = getDefaultProxySettings;
exports.getDefaultUserAgentValue = getDefaultUserAgentValue;
exports.isDuration = isDuration;
-exports.isNode = isNode;
exports.isValidUuid = isValidUuid;
exports.keepAlivePolicy = keepAlivePolicy;
exports.logPolicy = logPolicy;
@@ -13391,13 +13984,13 @@ exports.userAgentPolicy = userAgentPolicy;
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
var CombinedStream = __nccwpck_require__(5443);
-var util = __nccwpck_require__(1669);
-var path = __nccwpck_require__(5622);
-var http = __nccwpck_require__(8605);
-var https = __nccwpck_require__(7211);
-var parseUrl = __nccwpck_require__(8835).parse;
-var fs = __nccwpck_require__(5747);
-var Stream = __nccwpck_require__(2413).Stream;
+var util = __nccwpck_require__(3837);
+var path = __nccwpck_require__(1017);
+var http = __nccwpck_require__(3685);
+var https = __nccwpck_require__(5687);
+var parseUrl = (__nccwpck_require__(7310).parse);
+var fs = __nccwpck_require__(7147);
+var Stream = (__nccwpck_require__(2781).Stream);
var mime = __nccwpck_require__(3583);
var asynckit = __nccwpck_require__(4812);
var populate = __nccwpck_require__(3971);
@@ -13912,468 +14505,154 @@ module.exports = function(dst, src) {
/***/ }),
-/***/ 4331:
-/***/ ((__unused_webpack_module, __webpack_exports__, __nccwpck_require__) => {
-
-"use strict";
-__nccwpck_require__.r(__webpack_exports__);
-/* harmony export */ __nccwpck_require__.d(__webpack_exports__, {
-/* harmony export */ "__extends": () => /* binding */ __extends,
-/* harmony export */ "__assign": () => /* binding */ __assign,
-/* harmony export */ "__rest": () => /* binding */ __rest,
-/* harmony export */ "__decorate": () => /* binding */ __decorate,
-/* harmony export */ "__param": () => /* binding */ __param,
-/* harmony export */ "__metadata": () => /* binding */ __metadata,
-/* harmony export */ "__awaiter": () => /* binding */ __awaiter,
-/* harmony export */ "__generator": () => /* binding */ __generator,
-/* harmony export */ "__createBinding": () => /* binding */ __createBinding,
-/* harmony export */ "__exportStar": () => /* binding */ __exportStar,
-/* harmony export */ "__values": () => /* binding */ __values,
-/* harmony export */ "__read": () => /* binding */ __read,
-/* harmony export */ "__spread": () => /* binding */ __spread,
-/* harmony export */ "__spreadArrays": () => /* binding */ __spreadArrays,
-/* harmony export */ "__spreadArray": () => /* binding */ __spreadArray,
-/* harmony export */ "__await": () => /* binding */ __await,
-/* harmony export */ "__asyncGenerator": () => /* binding */ __asyncGenerator,
-/* harmony export */ "__asyncDelegator": () => /* binding */ __asyncDelegator,
-/* harmony export */ "__asyncValues": () => /* binding */ __asyncValues,
-/* harmony export */ "__makeTemplateObject": () => /* binding */ __makeTemplateObject,
-/* harmony export */ "__importStar": () => /* binding */ __importStar,
-/* harmony export */ "__importDefault": () => /* binding */ __importDefault,
-/* harmony export */ "__classPrivateFieldGet": () => /* binding */ __classPrivateFieldGet,
-/* harmony export */ "__classPrivateFieldSet": () => /* binding */ __classPrivateFieldSet,
-/* harmony export */ "__classPrivateFieldIn": () => /* binding */ __classPrivateFieldIn
-/* harmony export */ });
-/******************************************************************************
-Copyright (c) Microsoft Corporation.
-
-Permission to use, copy, modify, and/or distribute this software for any
-purpose with or without fee is hereby granted.
-
-THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
-REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
-INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
-OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-PERFORMANCE OF THIS SOFTWARE.
-***************************************************************************** */
-/* global Reflect, Promise */
-
-var extendStatics = function(d, b) {
- extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
- return extendStatics(d, b);
-};
-
-function __extends(d, b) {
- if (typeof b !== "function" && b !== null)
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-}
-
-var __assign = function() {
- __assign = Object.assign || function __assign(t) {
- for (var s, i = 1, n = arguments.length; i < n; i++) {
- s = arguments[i];
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
- }
- return t;
- }
- return __assign.apply(this, arguments);
-}
-
-function __rest(s, e) {
- var t = {};
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
- t[p] = s[p];
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
- t[p[i]] = s[p[i]];
- }
- return t;
-}
-
-function __decorate(decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
-}
-
-function __param(paramIndex, decorator) {
- return function (target, key) { decorator(target, key, paramIndex); }
-}
-
-function __metadata(metadataKey, metadataValue) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
-}
-
-function __awaiter(thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-}
-
-function __generator(thisArg, body) {
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
- function verb(n) { return function (v) { return step([n, v]); }; }
- function step(op) {
- if (f) throw new TypeError("Generator is already executing.");
- while (_) try {
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
- if (y = 0, t) op = [op[0] & 2, t.value];
- switch (op[0]) {
- case 0: case 1: t = op; break;
- case 4: _.label++; return { value: op[1], done: false };
- case 5: _.label++; y = op[1]; op = [0]; continue;
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
- default:
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
- if (t[2]) _.ops.pop();
- _.trys.pop(); continue;
- }
- op = body.call(thisArg, _);
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
- }
-}
-
-var __createBinding = Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- var desc = Object.getOwnPropertyDescriptor(m, k);
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
- desc = { enumerable: true, get: function() { return m[k]; } };
- }
- Object.defineProperty(o, k2, desc);
-}) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
-});
-
-function __exportStar(m, o) {
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);
-}
-
-function __values(o) {
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
- if (m) return m.call(o);
- if (o && typeof o.length === "number") return {
- next: function () {
- if (o && i >= o.length) o = void 0;
- return { value: o && o[i++], done: !o };
- }
- };
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
-}
-
-function __read(o, n) {
- var m = typeof Symbol === "function" && o[Symbol.iterator];
- if (!m) return o;
- var i = m.call(o), r, ar = [], e;
- try {
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
- }
- catch (error) { e = { error: error }; }
- finally {
- try {
- if (r && !r.done && (m = i["return"])) m.call(i);
- }
- finally { if (e) throw e.error; }
- }
- return ar;
-}
-
-/** @deprecated */
-function __spread() {
- for (var ar = [], i = 0; i < arguments.length; i++)
- ar = ar.concat(__read(arguments[i]));
- return ar;
-}
-
-/** @deprecated */
-function __spreadArrays() {
- for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
- for (var r = Array(s), k = 0, i = 0; i < il; i++)
- for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
- r[k] = a[j];
- return r;
-}
-
-function __spreadArray(to, from, pack) {
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
- if (ar || !(i in from)) {
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
- ar[i] = from[i];
- }
- }
- return to.concat(ar || Array.prototype.slice.call(from));
-}
-
-function __await(v) {
- return this instanceof __await ? (this.v = v, this) : new __await(v);
-}
-
-function __asyncGenerator(thisArg, _arguments, generator) {
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
- var g = generator.apply(thisArg, _arguments || []), i, q = [];
- return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
- function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
- function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
- function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
- function fulfill(value) { resume("next", value); }
- function reject(value) { resume("throw", value); }
- function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
-}
-
-function __asyncDelegator(o) {
- var i, p;
- return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
- function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
-}
-
-function __asyncValues(o) {
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
- var m = o[Symbol.asyncIterator], i;
- return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
- function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
- function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
-}
-
-function __makeTemplateObject(cooked, raw) {
- if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
- return cooked;
-};
-
-var __setModuleDefault = Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-};
-
-function __importStar(mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
-}
-
-function __importDefault(mod) {
- return (mod && mod.__esModule) ? mod : { default: mod };
-}
-
-function __classPrivateFieldGet(receiver, state, kind, f) {
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
-}
-
-function __classPrivateFieldSet(receiver, state, value, kind, f) {
- if (kind === "m") throw new TypeError("Private method is not writable");
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
-}
-
-function __classPrivateFieldIn(state, receiver) {
- if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object");
- return typeof state === "function" ? receiver === state : state.has(receiver);
-}
-
-
-/***/ }),
-
-/***/ 3206:
-/***/ ((__unused_webpack_module, __webpack_exports__, __nccwpck_require__) => {
+/***/ 3415:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
-// ESM COMPAT FLAG
-__nccwpck_require__.r(__webpack_exports__);
-
-// EXPORTS
-__nccwpck_require__.d(__webpack_exports__, {
- "NIL": () => /* reexport */ nil,
- "parse": () => /* reexport */ esm_node_parse,
- "stringify": () => /* reexport */ esm_node_stringify,
- "v1": () => /* reexport */ esm_node_v1,
- "v3": () => /* reexport */ esm_node_v3,
- "v4": () => /* reexport */ esm_node_v4,
- "v5": () => /* reexport */ esm_node_v5,
- "validate": () => /* reexport */ esm_node_validate,
- "version": () => /* reexport */ esm_node_version
-});
-
-// EXTERNAL MODULE: external "crypto"
-var external_crypto_ = __nccwpck_require__(6417);
-var external_crypto_default = /*#__PURE__*/__nccwpck_require__.n(external_crypto_);
-// CONCATENATED MODULE: ./node_modules/@azure/core-http/node_modules/uuid/dist/esm-node/rng.js
-const rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate
-
-let poolPtr = rnds8Pool.length;
-function rng() {
- if (poolPtr > rnds8Pool.length - 16) {
- external_crypto_default().randomFillSync(rnds8Pool);
- poolPtr = 0;
+Object.defineProperty(exports, "__esModule", ({
+ value: true
+}));
+Object.defineProperty(exports, "v1", ({
+ enumerable: true,
+ get: function () {
+ return _v.default;
}
-
- return rnds8Pool.slice(poolPtr, poolPtr += 16);
-}
-// CONCATENATED MODULE: ./node_modules/@azure/core-http/node_modules/uuid/dist/esm-node/regex.js
-/* harmony default export */ const regex = (/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i);
-// CONCATENATED MODULE: ./node_modules/@azure/core-http/node_modules/uuid/dist/esm-node/validate.js
-
-
-function validate(uuid) {
- return typeof uuid === 'string' && regex.test(uuid);
-}
-
-/* harmony default export */ const esm_node_validate = (validate);
-// CONCATENATED MODULE: ./node_modules/@azure/core-http/node_modules/uuid/dist/esm-node/stringify.js
-
-/**
- * Convert array of 16 byte values to UUID string format of the form:
- * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
- */
-
-const byteToHex = [];
-
-for (let i = 0; i < 256; ++i) {
- byteToHex.push((i + 0x100).toString(16).substr(1));
-}
-
-function stringify(arr, offset = 0) {
- // Note: Be careful editing this code! It's been tuned for performance
- // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
- const uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one
- // of the following:
- // - One or more input array values don't map to a hex octet (leading to
- // "undefined" in the uuid)
- // - Invalid input values for the RFC `version` or `variant` fields
-
- if (!esm_node_validate(uuid)) {
- throw TypeError('Stringified UUID is invalid');
+}));
+Object.defineProperty(exports, "v3", ({
+ enumerable: true,
+ get: function () {
+ return _v2.default;
+ }
+}));
+Object.defineProperty(exports, "v4", ({
+ enumerable: true,
+ get: function () {
+ return _v3.default;
+ }
+}));
+Object.defineProperty(exports, "v5", ({
+ enumerable: true,
+ get: function () {
+ return _v4.default;
}
+}));
+Object.defineProperty(exports, "NIL", ({
+ enumerable: true,
+ get: function () {
+ return _nil.default;
+ }
+}));
+Object.defineProperty(exports, "version", ({
+ enumerable: true,
+ get: function () {
+ return _version.default;
+ }
+}));
+Object.defineProperty(exports, "validate", ({
+ enumerable: true,
+ get: function () {
+ return _validate.default;
+ }
+}));
+Object.defineProperty(exports, "stringify", ({
+ enumerable: true,
+ get: function () {
+ return _stringify.default;
+ }
+}));
+Object.defineProperty(exports, "parse", ({
+ enumerable: true,
+ get: function () {
+ return _parse.default;
+ }
+}));
- return uuid;
-}
+var _v = _interopRequireDefault(__nccwpck_require__(4757));
-/* harmony default export */ const esm_node_stringify = (stringify);
-// CONCATENATED MODULE: ./node_modules/@azure/core-http/node_modules/uuid/dist/esm-node/v1.js
+var _v2 = _interopRequireDefault(__nccwpck_require__(9982));
- // **`v1()` - Generate time-based UUID**
-//
-// Inspired by https://github.com/LiosK/UUID.js
-// and http://docs.python.org/library/uuid.html
+var _v3 = _interopRequireDefault(__nccwpck_require__(5393));
-let _nodeId;
+var _v4 = _interopRequireDefault(__nccwpck_require__(8788));
-let _clockseq; // Previous uuid creation time
+var _nil = _interopRequireDefault(__nccwpck_require__(657));
+var _version = _interopRequireDefault(__nccwpck_require__(7909));
-let _lastMSecs = 0;
-let _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details
+var _validate = _interopRequireDefault(__nccwpck_require__(4418));
-function v1(options, buf, offset) {
- let i = buf && offset || 0;
- const b = buf || new Array(16);
- options = options || {};
- let node = options.node || _nodeId;
- let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not
- // specified. We do this lazily to minimize issues related to insufficient
- // system entropy. See #189
+var _stringify = _interopRequireDefault(__nccwpck_require__(4794));
- if (node == null || clockseq == null) {
- const seedBytes = options.random || (options.rng || rng)();
+var _parse = _interopRequireDefault(__nccwpck_require__(7079));
- if (node == null) {
- // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
- node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]];
- }
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- if (clockseq == null) {
- // Per 4.2.2, randomize (14 bit) clockseq
- clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;
- }
- } // UUID timestamps are 100 nano-second units since the Gregorian epoch,
- // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so
- // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
- // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
+/***/ }),
+/***/ 4153:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock
- // cycle to simulate higher resolution clock
+"use strict";
- let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs)
- const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression
+Object.defineProperty(exports, "__esModule", ({
+ value: true
+}));
+exports["default"] = void 0;
- if (dt < 0 && options.clockseq === undefined) {
- clockseq = clockseq + 1 & 0x3fff;
- } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
- // time interval
+var _crypto = _interopRequireDefault(__nccwpck_require__(6113));
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {
- nsecs = 0;
- } // Per 4.2.1.2 Throw error if too many uuids are requested
+function md5(bytes) {
+ if (Array.isArray(bytes)) {
+ bytes = Buffer.from(bytes);
+ } else if (typeof bytes === 'string') {
+ bytes = Buffer.from(bytes, 'utf8');
+ }
+ return _crypto.default.createHash('md5').update(bytes).digest();
+}
- if (nsecs >= 10000) {
- throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");
- }
+var _default = md5;
+exports["default"] = _default;
- _lastMSecs = msecs;
- _lastNSecs = nsecs;
- _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch
+/***/ }),
- msecs += 12219292800000; // `time_low`
+/***/ 657:
+/***/ ((__unused_webpack_module, exports) => {
- const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
- b[i++] = tl >>> 24 & 0xff;
- b[i++] = tl >>> 16 & 0xff;
- b[i++] = tl >>> 8 & 0xff;
- b[i++] = tl & 0xff; // `time_mid`
+"use strict";
- const tmh = msecs / 0x100000000 * 10000 & 0xfffffff;
- b[i++] = tmh >>> 8 & 0xff;
- b[i++] = tmh & 0xff; // `time_high_and_version`
- b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
+Object.defineProperty(exports, "__esModule", ({
+ value: true
+}));
+exports["default"] = void 0;
+var _default = '00000000-0000-0000-0000-000000000000';
+exports["default"] = _default;
- b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
+/***/ }),
- b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low`
+/***/ 7079:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- b[i++] = clockseq & 0xff; // `node`
+"use strict";
- for (let n = 0; n < 6; ++n) {
- b[i + n] = node[n];
- }
- return buf || esm_node_stringify(b);
-}
+Object.defineProperty(exports, "__esModule", ({
+ value: true
+}));
+exports["default"] = void 0;
-/* harmony default export */ const esm_node_v1 = (v1);
-// CONCATENATED MODULE: ./node_modules/@azure/core-http/node_modules/uuid/dist/esm-node/parse.js
+var _validate = _interopRequireDefault(__nccwpck_require__(4418));
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function parse(uuid) {
- if (!esm_node_validate(uuid)) {
+ if (!(0, _validate.default)(uuid)) {
throw TypeError('Invalid UUID');
}
@@ -14404,10 +14683,287 @@ function parse(uuid) {
return arr;
}
-/* harmony default export */ const esm_node_parse = (parse);
-// CONCATENATED MODULE: ./node_modules/@azure/core-http/node_modules/uuid/dist/esm-node/v35.js
+var _default = parse;
+exports["default"] = _default;
+/***/ }),
+
+/***/ 690:
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({
+ value: true
+}));
+exports["default"] = void 0;
+var _default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;
+exports["default"] = _default;
+
+/***/ }),
+
+/***/ 979:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({
+ value: true
+}));
+exports["default"] = rng;
+
+var _crypto = _interopRequireDefault(__nccwpck_require__(6113));
+
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+const rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate
+
+let poolPtr = rnds8Pool.length;
+
+function rng() {
+ if (poolPtr > rnds8Pool.length - 16) {
+ _crypto.default.randomFillSync(rnds8Pool);
+
+ poolPtr = 0;
+ }
+
+ return rnds8Pool.slice(poolPtr, poolPtr += 16);
+}
+
+/***/ }),
+
+/***/ 6631:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({
+ value: true
+}));
+exports["default"] = void 0;
+
+var _crypto = _interopRequireDefault(__nccwpck_require__(6113));
+
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+function sha1(bytes) {
+ if (Array.isArray(bytes)) {
+ bytes = Buffer.from(bytes);
+ } else if (typeof bytes === 'string') {
+ bytes = Buffer.from(bytes, 'utf8');
+ }
+
+ return _crypto.default.createHash('sha1').update(bytes).digest();
+}
+
+var _default = sha1;
+exports["default"] = _default;
+
+/***/ }),
+
+/***/ 4794:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({
+ value: true
+}));
+exports["default"] = void 0;
+
+var _validate = _interopRequireDefault(__nccwpck_require__(4418));
+
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+/**
+ * Convert array of 16 byte values to UUID string format of the form:
+ * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
+ */
+const byteToHex = [];
+
+for (let i = 0; i < 256; ++i) {
+ byteToHex.push((i + 0x100).toString(16).substr(1));
+}
+
+function stringify(arr, offset = 0) {
+ // Note: Be careful editing this code! It's been tuned for performance
+ // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
+ const uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one
+ // of the following:
+ // - One or more input array values don't map to a hex octet (leading to
+ // "undefined" in the uuid)
+ // - Invalid input values for the RFC `version` or `variant` fields
+
+ if (!(0, _validate.default)(uuid)) {
+ throw TypeError('Stringified UUID is invalid');
+ }
+
+ return uuid;
+}
+
+var _default = stringify;
+exports["default"] = _default;
+
+/***/ }),
+
+/***/ 4757:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({
+ value: true
+}));
+exports["default"] = void 0;
+
+var _rng = _interopRequireDefault(__nccwpck_require__(979));
+
+var _stringify = _interopRequireDefault(__nccwpck_require__(4794));
+
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+// **`v1()` - Generate time-based UUID**
+//
+// Inspired by https://github.com/LiosK/UUID.js
+// and http://docs.python.org/library/uuid.html
+let _nodeId;
+
+let _clockseq; // Previous uuid creation time
+
+
+let _lastMSecs = 0;
+let _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details
+
+function v1(options, buf, offset) {
+ let i = buf && offset || 0;
+ const b = buf || new Array(16);
+ options = options || {};
+ let node = options.node || _nodeId;
+ let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not
+ // specified. We do this lazily to minimize issues related to insufficient
+ // system entropy. See #189
+
+ if (node == null || clockseq == null) {
+ const seedBytes = options.random || (options.rng || _rng.default)();
+
+ if (node == null) {
+ // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
+ node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]];
+ }
+
+ if (clockseq == null) {
+ // Per 4.2.2, randomize (14 bit) clockseq
+ clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;
+ }
+ } // UUID timestamps are 100 nano-second units since the Gregorian epoch,
+ // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so
+ // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
+ // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
+
+
+ let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock
+ // cycle to simulate higher resolution clock
+
+ let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs)
+
+ const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression
+
+ if (dt < 0 && options.clockseq === undefined) {
+ clockseq = clockseq + 1 & 0x3fff;
+ } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
+ // time interval
+
+
+ if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {
+ nsecs = 0;
+ } // Per 4.2.1.2 Throw error if too many uuids are requested
+
+
+ if (nsecs >= 10000) {
+ throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");
+ }
+
+ _lastMSecs = msecs;
+ _lastNSecs = nsecs;
+ _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch
+
+ msecs += 12219292800000; // `time_low`
+
+ const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
+ b[i++] = tl >>> 24 & 0xff;
+ b[i++] = tl >>> 16 & 0xff;
+ b[i++] = tl >>> 8 & 0xff;
+ b[i++] = tl & 0xff; // `time_mid`
+
+ const tmh = msecs / 0x100000000 * 10000 & 0xfffffff;
+ b[i++] = tmh >>> 8 & 0xff;
+ b[i++] = tmh & 0xff; // `time_high_and_version`
+
+ b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
+
+ b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
+
+ b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low`
+
+ b[i++] = clockseq & 0xff; // `node`
+
+ for (let n = 0; n < 6; ++n) {
+ b[i + n] = node[n];
+ }
+
+ return buf || (0, _stringify.default)(b);
+}
+var _default = v1;
+exports["default"] = _default;
+
+/***/ }),
+
+/***/ 9982:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({
+ value: true
+}));
+exports["default"] = void 0;
+
+var _v = _interopRequireDefault(__nccwpck_require__(4085));
+
+var _md = _interopRequireDefault(__nccwpck_require__(4153));
+
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+const v3 = (0, _v.default)('v3', 0x30, _md.default);
+var _default = v3;
+exports["default"] = _default;
+
+/***/ }),
+
+/***/ 4085:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({
+ value: true
+}));
+exports["default"] = _default;
+exports.URL = exports.DNS = void 0;
+
+var _stringify = _interopRequireDefault(__nccwpck_require__(4794));
+
+var _parse = _interopRequireDefault(__nccwpck_require__(7079));
+
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function stringToBytes(str) {
str = unescape(encodeURIComponent(str)); // UTF8 escape
@@ -14422,15 +14978,18 @@ function stringToBytes(str) {
}
const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
+exports.DNS = DNS;
const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';
-/* harmony default export */ function v35(name, version, hashfunc) {
+exports.URL = URL;
+
+function _default(name, version, hashfunc) {
function generateUUID(value, namespace, buf, offset) {
if (typeof value === 'string') {
value = stringToBytes(value);
}
if (typeof namespace === 'string') {
- namespace = esm_node_parse(namespace);
+ namespace = (0, _parse.default)(namespace);
}
if (namespace.length !== 16) {
@@ -14457,7 +15016,7 @@ const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';
return buf;
}
- return esm_node_stringify(bytes);
+ return (0, _stringify.default)(bytes);
} // Function#name is not settable on some platforms (#270)
@@ -14470,32 +15029,31 @@ const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';
generateUUID.URL = URL;
return generateUUID;
}
-// CONCATENATED MODULE: ./node_modules/@azure/core-http/node_modules/uuid/dist/esm-node/md5.js
+/***/ }),
-function md5(bytes) {
- if (Array.isArray(bytes)) {
- bytes = Buffer.from(bytes);
- } else if (typeof bytes === 'string') {
- bytes = Buffer.from(bytes, 'utf8');
- }
+/***/ 5393:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- return external_crypto_default().createHash('md5').update(bytes).digest();
-}
+"use strict";
-/* harmony default export */ const esm_node_md5 = (md5);
-// CONCATENATED MODULE: ./node_modules/@azure/core-http/node_modules/uuid/dist/esm-node/v3.js
+Object.defineProperty(exports, "__esModule", ({
+ value: true
+}));
+exports["default"] = void 0;
-const v3 = v35('v3', 0x30, esm_node_md5);
-/* harmony default export */ const esm_node_v3 = (v3);
-// CONCATENATED MODULE: ./node_modules/@azure/core-http/node_modules/uuid/dist/esm-node/v4.js
+var _rng = _interopRequireDefault(__nccwpck_require__(979));
+var _stringify = _interopRequireDefault(__nccwpck_require__(4794));
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function v4(options, buf, offset) {
options = options || {};
- const rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
+
+ const rnds = options.random || (options.rng || _rng.default)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
+
rnds[6] = rnds[6] & 0x0f | 0x40;
rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided
@@ -14510,53 +15068,86 @@ function v4(options, buf, offset) {
return buf;
}
- return esm_node_stringify(rnds);
+ return (0, _stringify.default)(rnds);
}
-/* harmony default export */ const esm_node_v4 = (v4);
-// CONCATENATED MODULE: ./node_modules/@azure/core-http/node_modules/uuid/dist/esm-node/sha1.js
+var _default = v4;
+exports["default"] = _default;
+/***/ }),
-function sha1(bytes) {
- if (Array.isArray(bytes)) {
- bytes = Buffer.from(bytes);
- } else if (typeof bytes === 'string') {
- bytes = Buffer.from(bytes, 'utf8');
- }
+/***/ 8788:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- return external_crypto_default().createHash('sha1').update(bytes).digest();
-}
+"use strict";
-/* harmony default export */ const esm_node_sha1 = (sha1);
-// CONCATENATED MODULE: ./node_modules/@azure/core-http/node_modules/uuid/dist/esm-node/v5.js
+Object.defineProperty(exports, "__esModule", ({
+ value: true
+}));
+exports["default"] = void 0;
-const v5 = v35('v5', 0x50, esm_node_sha1);
-/* harmony default export */ const esm_node_v5 = (v5);
-// CONCATENATED MODULE: ./node_modules/@azure/core-http/node_modules/uuid/dist/esm-node/nil.js
-/* harmony default export */ const nil = ('00000000-0000-0000-0000-000000000000');
-// CONCATENATED MODULE: ./node_modules/@azure/core-http/node_modules/uuid/dist/esm-node/version.js
+var _v = _interopRequireDefault(__nccwpck_require__(4085));
+var _sha = _interopRequireDefault(__nccwpck_require__(6631));
-function version(uuid) {
- if (!esm_node_validate(uuid)) {
- throw TypeError('Invalid UUID');
- }
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- return parseInt(uuid.substr(14, 1), 16);
+const v5 = (0, _v.default)('v5', 0x50, _sha.default);
+var _default = v5;
+exports["default"] = _default;
+
+/***/ }),
+
+/***/ 4418:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+Object.defineProperty(exports, "__esModule", ({
+ value: true
+}));
+exports["default"] = void 0;
+
+var _regex = _interopRequireDefault(__nccwpck_require__(690));
+
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+function validate(uuid) {
+ return typeof uuid === 'string' && _regex.default.test(uuid);
}
-/* harmony default export */ const esm_node_version = (version);
-// CONCATENATED MODULE: ./node_modules/@azure/core-http/node_modules/uuid/dist/esm-node/index.js
+var _default = validate;
+exports["default"] = _default;
+
+/***/ }),
+/***/ 7909:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+"use strict";
+Object.defineProperty(exports, "__esModule", ({
+ value: true
+}));
+exports["default"] = void 0;
+var _validate = _interopRequireDefault(__nccwpck_require__(4418));
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+function version(uuid) {
+ if (!(0, _validate.default)(uuid)) {
+ throw TypeError('Invalid UUID');
+ }
+ return parseInt(uuid.substr(14, 1), 16);
+}
+var _default = version;
+exports["default"] = _default;
/***/ }),
@@ -14569,240 +15160,972 @@ function version(uuid) {
Object.defineProperty(exports, "__esModule", ({ value: true }));
var logger$1 = __nccwpck_require__(3233);
+var abortController = __nccwpck_require__(2557);
+var coreUtil = __nccwpck_require__(1333);
+
+// Copyright (c) Microsoft Corporation.
+/**
+ * The `@azure/logger` configuration for this package.
+ * @internal
+ */
+const logger = logger$1.createClientLogger("core-lro");
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
/**
- * When a poller is manually stopped through the `stopPolling` method,
- * the poller will be rejected with an instance of the PollerStoppedError.
+ * The default time interval to wait before sending the next polling request.
*/
-class PollerStoppedError extends Error {
- constructor(message) {
- super(message);
- this.name = "PollerStoppedError";
- Object.setPrototypeOf(this, PollerStoppedError.prototype);
- }
-}
+const POLL_INTERVAL_IN_MS = 2000;
/**
- * When the operation is cancelled, the poller will be rejected with an instance
- * of the PollerCancelledError.
+ * The closed set of terminal states.
*/
-class PollerCancelledError extends Error {
- constructor(message) {
- super(message);
- this.name = "PollerCancelledError";
- Object.setPrototypeOf(this, PollerCancelledError.prototype);
- }
-}
+const terminalStates = ["succeeded", "canceled", "failed"];
+
+// Copyright (c) Microsoft Corporation.
/**
- * A class that represents the definition of a program that polls through consecutive requests
- * until it reaches a state of completion.
- *
- * A poller can be executed manually, by polling request by request by calling to the `poll()` method repeatedly, until its operation is completed.
- * It also provides a way to wait until the operation completes, by calling `pollUntilDone()` and waiting until the operation finishes.
- * Pollers can also request the cancellation of the ongoing process to whom is providing the underlying long running operation.
- *
- * ```ts
- * const poller = new MyPoller();
- *
- * // Polling just once:
- * await poller.poll();
- *
- * // We can try to cancel the request here, by calling:
- * //
- * // await poller.cancelOperation();
- * //
- *
- * // Getting the final result:
- * const result = await poller.pollUntilDone();
- * ```
- *
- * The Poller is defined by two types, a type representing the state of the poller, which
- * must include a basic set of properties from `PollOperationState`,
- * and a return type defined by `TResult`, which can be anything.
- *
- * The Poller class implements the `PollerLike` interface, which allows poller implementations to avoid having
- * to export the Poller's class directly, and instead only export the already instantiated poller with the PollerLike type.
- *
- * ```ts
- * class Client {
- * public async makePoller: PollerLike {
- * const poller = new MyPoller({});
- * // It might be preferred to return the poller after the first request is made,
- * // so that some information can be obtained right away.
- * await poller.poll();
- * return poller;
- * }
- * }
- *
- * const poller: PollerLike = myClient.makePoller();
- * ```
- *
- * A poller can be created through its constructor, then it can be polled until it's completed.
- * At any point in time, the state of the poller can be obtained without delay through the getOperationState method.
- * At any point in time, the intermediate forms of the result type can be requested without delay.
- * Once the underlying operation is marked as completed, the poller will stop and the final value will be returned.
- *
- * ```ts
- * const poller = myClient.makePoller();
- * const state: MyOperationState = poller.getOperationState();
- *
- * // The intermediate result can be obtained at any time.
- * const result: MyResult | undefined = poller.getResult();
- *
- * // The final result can only be obtained after the poller finishes.
- * const result: MyResult = await poller.pollUntilDone();
- * ```
- *
+ * Deserializes the state
*/
-// eslint-disable-next-line no-use-before-define
-class Poller {
- /**
- * A poller needs to be initialized by passing in at least the basic properties of the `PollOperation`.
- *
- * When writing an implementation of a Poller, this implementation needs to deal with the initialization
- * of any custom state beyond the basic definition of the poller. The basic poller assumes that the poller's
- * operation has already been defined, at least its basic properties. The code below shows how to approach
- * the definition of the constructor of a new custom poller.
- *
- * ```ts
- * export class MyPoller extends Poller {
- * constructor({
- * // Anything you might need outside of the basics
- * }) {
- * let state: MyOperationState = {
- * privateProperty: private,
- * publicProperty: public,
- * };
- *
- * const operation = {
- * state,
- * update,
- * cancel,
- * toString
- * }
- *
- * // Sending the operation to the parent's constructor.
- * super(operation);
- *
- * // You can assign more local properties here.
- * }
- * }
- * ```
- *
- * Inside of this constructor, a new promise is created. This will be used to
- * tell the user when the poller finishes (see `pollUntilDone()`). The promise's
- * resolve and reject methods are also used internally to control when to resolve
- * or reject anyone waiting for the poller to finish.
- *
- * The constructor of a custom implementation of a poller is where any serialized version of
- * a previous poller's operation should be deserialized into the operation sent to the
- * base constructor. For example:
- *
- * ```ts
- * export class MyPoller extends Poller {
- * constructor(
- * baseOperation: string | undefined
- * ) {
- * let state: MyOperationState = {};
- * if (baseOperation) {
- * state = {
- * ...JSON.parse(baseOperation).state,
- * ...state
- * };
- * }
- * const operation = {
- * state,
- * // ...
- * }
- * super(operation);
- * }
- * }
- * ```
- *
- * @param operation - Must contain the basic properties of `PollOperation`.
- */
- constructor(operation) {
- this.stopped = true;
- this.pollProgressCallbacks = [];
- this.operation = operation;
- this.promise = new Promise((resolve, reject) => {
- this.resolve = resolve;
- this.reject = reject;
- });
- // This prevents the UnhandledPromiseRejectionWarning in node.js from being thrown.
- // The above warning would get thrown if `poller.poll` is called, it returns an error,
- // and pullUntilDone did not have a .catch or await try/catch on it's return value.
- this.promise.catch(() => {
- /* intentionally blank */
- });
+function deserializeState(serializedState) {
+ try {
+ return JSON.parse(serializedState).state;
}
- /**
- * Starts a loop that will break only if the poller is done
- * or if the poller is stopped.
- */
- async startPolling() {
- if (this.stopped) {
- this.stopped = false;
- }
- while (!this.isStopped() && !this.isDone()) {
- await this.poll();
- await this.delay();
+ catch (e) {
+ throw new Error(`Unable to deserialize input state: ${serializedState}`);
+ }
+}
+function setStateError(inputs) {
+ const { state, stateProxy, isOperationError } = inputs;
+ return (error) => {
+ if (isOperationError(error)) {
+ stateProxy.setError(state, error);
+ stateProxy.setFailed(state);
}
+ throw error;
+ };
+}
+function appendReadableErrorMessage(currentMessage, innerMessage) {
+ let message = currentMessage;
+ if (message.slice(-1) !== ".") {
+ message = message + ".";
}
- /**
- * pollOnce does one polling, by calling to the update method of the underlying
- * poll operation to make any relevant change effective.
- *
- * It only optionally receives an object with an abortSignal property, from \@azure/abort-controller's AbortSignalLike.
- *
- * @param options - Optional properties passed to the operation's update method.
- */
- async pollOnce(options = {}) {
- if (!this.isDone()) {
- try {
- this.operation = await this.operation.update({
- abortSignal: options.abortSignal,
- fireProgress: this.fireProgress.bind(this),
- });
- }
- catch (e) {
- this.operation.state.error = e;
+ return message + " " + innerMessage;
+}
+function simplifyError(err) {
+ let message = err.message;
+ let code = err.code;
+ let curErr = err;
+ while (curErr.innererror) {
+ curErr = curErr.innererror;
+ code = curErr.code;
+ message = appendReadableErrorMessage(message, curErr.message);
+ }
+ return {
+ code,
+ message,
+ };
+}
+function processOperationStatus(result) {
+ const { state, stateProxy, status, isDone, processResult, getError, response, setErrorAsResult } = result;
+ switch (status) {
+ case "succeeded": {
+ stateProxy.setSucceeded(state);
+ break;
+ }
+ case "failed": {
+ const err = getError === null || getError === void 0 ? void 0 : getError(response);
+ let postfix = "";
+ if (err) {
+ const { code, message } = simplifyError(err);
+ postfix = `. ${code}. ${message}`;
}
+ const errStr = `The long-running operation has failed${postfix}`;
+ stateProxy.setError(state, new Error(errStr));
+ stateProxy.setFailed(state);
+ logger.warning(errStr);
+ break;
}
- this.processUpdatedState();
- }
- /**
- * fireProgress calls the functions passed in via onProgress the method of the poller.
- *
- * It loops over all of the callbacks received from onProgress, and executes them, sending them
- * the current operation state.
- *
- * @param state - The current operation state.
- */
- fireProgress(state) {
- for (const callback of this.pollProgressCallbacks) {
- callback(state);
+ case "canceled": {
+ stateProxy.setCanceled(state);
+ break;
}
}
- /**
- * Invokes the underlying operation's cancel method.
- */
- async cancelOnce(options = {}) {
- this.operation = await this.operation.cancel(options);
+ if ((isDone === null || isDone === void 0 ? void 0 : isDone(response, state)) ||
+ (isDone === undefined &&
+ ["succeeded", "canceled"].concat(setErrorAsResult ? [] : ["failed"]).includes(status))) {
+ stateProxy.setResult(state, buildResult({
+ response,
+ state,
+ processResult,
+ }));
}
- /**
- * Returns a promise that will resolve once a single polling request finishes.
- * It does this by calling the update method of the Poller's operation.
- *
- * It only optionally receives an object with an abortSignal property, from \@azure/abort-controller's AbortSignalLike.
- *
- * @param options - Optional properties passed to the operation's update method.
- */
- poll(options = {}) {
- if (!this.pollOncePromise) {
- this.pollOncePromise = this.pollOnce(options);
- const clearPollOncePromise = () => {
+}
+function buildResult(inputs) {
+ const { processResult, response, state } = inputs;
+ return processResult ? processResult(response, state) : response;
+}
+/**
+ * Initiates the long-running operation.
+ */
+async function initOperation(inputs) {
+ const { init, stateProxy, processResult, getOperationStatus, withOperationLocation, setErrorAsResult, } = inputs;
+ const { operationLocation, resourceLocation, metadata, response } = await init();
+ if (operationLocation)
+ withOperationLocation === null || withOperationLocation === void 0 ? void 0 : withOperationLocation(operationLocation, false);
+ const config = {
+ metadata,
+ operationLocation,
+ resourceLocation,
+ };
+ logger.verbose(`LRO: Operation description:`, config);
+ const state = stateProxy.initState(config);
+ const status = getOperationStatus({ response, state, operationLocation });
+ processOperationStatus({ state, status, stateProxy, response, setErrorAsResult, processResult });
+ return state;
+}
+async function pollOperationHelper(inputs) {
+ const { poll, state, stateProxy, operationLocation, getOperationStatus, getResourceLocation, isOperationError, options, } = inputs;
+ const response = await poll(operationLocation, options).catch(setStateError({
+ state,
+ stateProxy,
+ isOperationError,
+ }));
+ const status = getOperationStatus(response, state);
+ logger.verbose(`LRO: Status:\n\tPolling from: ${state.config.operationLocation}\n\tOperation status: ${status}\n\tPolling status: ${terminalStates.includes(status) ? "Stopped" : "Running"}`);
+ if (status === "succeeded") {
+ const resourceLocation = getResourceLocation(response, state);
+ if (resourceLocation !== undefined) {
+ return {
+ response: await poll(resourceLocation).catch(setStateError({ state, stateProxy, isOperationError })),
+ status,
+ };
+ }
+ }
+ return { response, status };
+}
+/** Polls the long-running operation. */
+async function pollOperation(inputs) {
+ const { poll, state, stateProxy, options, getOperationStatus, getResourceLocation, getOperationLocation, isOperationError, withOperationLocation, getPollingInterval, processResult, getError, updateState, setDelay, isDone, setErrorAsResult, } = inputs;
+ const { operationLocation } = state.config;
+ if (operationLocation !== undefined) {
+ const { response, status } = await pollOperationHelper({
+ poll,
+ getOperationStatus,
+ state,
+ stateProxy,
+ operationLocation,
+ getResourceLocation,
+ isOperationError,
+ options,
+ });
+ processOperationStatus({
+ status,
+ response,
+ state,
+ stateProxy,
+ isDone,
+ processResult,
+ getError,
+ setErrorAsResult,
+ });
+ if (!terminalStates.includes(status)) {
+ const intervalInMs = getPollingInterval === null || getPollingInterval === void 0 ? void 0 : getPollingInterval(response);
+ if (intervalInMs)
+ setDelay(intervalInMs);
+ const location = getOperationLocation === null || getOperationLocation === void 0 ? void 0 : getOperationLocation(response, state);
+ if (location !== undefined) {
+ const isUpdated = operationLocation !== location;
+ state.config.operationLocation = location;
+ withOperationLocation === null || withOperationLocation === void 0 ? void 0 : withOperationLocation(location, isUpdated);
+ }
+ else
+ withOperationLocation === null || withOperationLocation === void 0 ? void 0 : withOperationLocation(operationLocation, false);
+ }
+ updateState === null || updateState === void 0 ? void 0 : updateState(state, response);
+ }
+}
+
+// Copyright (c) Microsoft Corporation.
+function getOperationLocationPollingUrl(inputs) {
+ const { azureAsyncOperation, operationLocation } = inputs;
+ return operationLocation !== null && operationLocation !== void 0 ? operationLocation : azureAsyncOperation;
+}
+function getLocationHeader(rawResponse) {
+ return rawResponse.headers["location"];
+}
+function getOperationLocationHeader(rawResponse) {
+ return rawResponse.headers["operation-location"];
+}
+function getAzureAsyncOperationHeader(rawResponse) {
+ return rawResponse.headers["azure-asyncoperation"];
+}
+function findResourceLocation(inputs) {
+ var _a;
+ const { location, requestMethod, requestPath, resourceLocationConfig } = inputs;
+ switch (requestMethod) {
+ case "PUT": {
+ return requestPath;
+ }
+ case "DELETE": {
+ return undefined;
+ }
+ case "PATCH": {
+ return (_a = getDefault()) !== null && _a !== void 0 ? _a : requestPath;
+ }
+ default: {
+ return getDefault();
+ }
+ }
+ function getDefault() {
+ switch (resourceLocationConfig) {
+ case "azure-async-operation": {
+ return undefined;
+ }
+ case "original-uri": {
+ return requestPath;
+ }
+ case "location":
+ default: {
+ return location;
+ }
+ }
+ }
+}
+function inferLroMode(inputs) {
+ const { rawResponse, requestMethod, requestPath, resourceLocationConfig } = inputs;
+ const operationLocation = getOperationLocationHeader(rawResponse);
+ const azureAsyncOperation = getAzureAsyncOperationHeader(rawResponse);
+ const pollingUrl = getOperationLocationPollingUrl({ operationLocation, azureAsyncOperation });
+ const location = getLocationHeader(rawResponse);
+ const normalizedRequestMethod = requestMethod === null || requestMethod === void 0 ? void 0 : requestMethod.toLocaleUpperCase();
+ if (pollingUrl !== undefined) {
+ return {
+ mode: "OperationLocation",
+ operationLocation: pollingUrl,
+ resourceLocation: findResourceLocation({
+ requestMethod: normalizedRequestMethod,
+ location,
+ requestPath,
+ resourceLocationConfig,
+ }),
+ };
+ }
+ else if (location !== undefined) {
+ return {
+ mode: "ResourceLocation",
+ operationLocation: location,
+ };
+ }
+ else if (normalizedRequestMethod === "PUT" && requestPath) {
+ return {
+ mode: "Body",
+ operationLocation: requestPath,
+ };
+ }
+ else {
+ return undefined;
+ }
+}
+function transformStatus(inputs) {
+ const { status, statusCode } = inputs;
+ if (typeof status !== "string" && status !== undefined) {
+ throw new Error(`Polling was unsuccessful. Expected status to have a string value or no value but it has instead: ${status}. This doesn't necessarily indicate the operation has failed. Check your Azure subscription or resource status for more information.`);
+ }
+ switch (status === null || status === void 0 ? void 0 : status.toLocaleLowerCase()) {
+ case undefined:
+ return toOperationStatus(statusCode);
+ case "succeeded":
+ return "succeeded";
+ case "failed":
+ return "failed";
+ case "running":
+ case "accepted":
+ case "started":
+ case "canceling":
+ case "cancelling":
+ return "running";
+ case "canceled":
+ case "cancelled":
+ return "canceled";
+ default: {
+ logger.verbose(`LRO: unrecognized operation status: ${status}`);
+ return status;
+ }
+ }
+}
+function getStatus(rawResponse) {
+ var _a;
+ const { status } = (_a = rawResponse.body) !== null && _a !== void 0 ? _a : {};
+ return transformStatus({ status, statusCode: rawResponse.statusCode });
+}
+function getProvisioningState(rawResponse) {
+ var _a, _b;
+ const { properties, provisioningState } = (_a = rawResponse.body) !== null && _a !== void 0 ? _a : {};
+ const status = (_b = properties === null || properties === void 0 ? void 0 : properties.provisioningState) !== null && _b !== void 0 ? _b : provisioningState;
+ return transformStatus({ status, statusCode: rawResponse.statusCode });
+}
+function toOperationStatus(statusCode) {
+ if (statusCode === 202) {
+ return "running";
+ }
+ else if (statusCode < 300) {
+ return "succeeded";
+ }
+ else {
+ return "failed";
+ }
+}
+function parseRetryAfter({ rawResponse }) {
+ const retryAfter = rawResponse.headers["retry-after"];
+ if (retryAfter !== undefined) {
+ // Retry-After header value is either in HTTP date format, or in seconds
+ const retryAfterInSeconds = parseInt(retryAfter);
+ return isNaN(retryAfterInSeconds)
+ ? calculatePollingIntervalFromDate(new Date(retryAfter))
+ : retryAfterInSeconds * 1000;
+ }
+ return undefined;
+}
+function getErrorFromResponse(response) {
+ const error = response.flatResponse.error;
+ if (!error) {
+ logger.warning(`The long-running operation failed but there is no error property in the response's body`);
+ return;
+ }
+ if (!error.code || !error.message) {
+ logger.warning(`The long-running operation failed but the error property in the response's body doesn't contain code or message`);
+ return;
+ }
+ return error;
+}
+function calculatePollingIntervalFromDate(retryAfterDate) {
+ const timeNow = Math.floor(new Date().getTime());
+ const retryAfterTime = retryAfterDate.getTime();
+ if (timeNow < retryAfterTime) {
+ return retryAfterTime - timeNow;
+ }
+ return undefined;
+}
+function getStatusFromInitialResponse(inputs) {
+ const { response, state, operationLocation } = inputs;
+ function helper() {
+ var _a;
+ const mode = (_a = state.config.metadata) === null || _a === void 0 ? void 0 : _a["mode"];
+ switch (mode) {
+ case undefined:
+ return toOperationStatus(response.rawResponse.statusCode);
+ case "Body":
+ return getOperationStatus(response, state);
+ default:
+ return "running";
+ }
+ }
+ const status = helper();
+ return status === "running" && operationLocation === undefined ? "succeeded" : status;
+}
+/**
+ * Initiates the long-running operation.
+ */
+async function initHttpOperation(inputs) {
+ const { stateProxy, resourceLocationConfig, processResult, lro, setErrorAsResult } = inputs;
+ return initOperation({
+ init: async () => {
+ const response = await lro.sendInitialRequest();
+ const config = inferLroMode({
+ rawResponse: response.rawResponse,
+ requestPath: lro.requestPath,
+ requestMethod: lro.requestMethod,
+ resourceLocationConfig,
+ });
+ return Object.assign({ response, operationLocation: config === null || config === void 0 ? void 0 : config.operationLocation, resourceLocation: config === null || config === void 0 ? void 0 : config.resourceLocation }, ((config === null || config === void 0 ? void 0 : config.mode) ? { metadata: { mode: config.mode } } : {}));
+ },
+ stateProxy,
+ processResult: processResult
+ ? ({ flatResponse }, state) => processResult(flatResponse, state)
+ : ({ flatResponse }) => flatResponse,
+ getOperationStatus: getStatusFromInitialResponse,
+ setErrorAsResult,
+ });
+}
+function getOperationLocation({ rawResponse }, state) {
+ var _a;
+ const mode = (_a = state.config.metadata) === null || _a === void 0 ? void 0 : _a["mode"];
+ switch (mode) {
+ case "OperationLocation": {
+ return getOperationLocationPollingUrl({
+ operationLocation: getOperationLocationHeader(rawResponse),
+ azureAsyncOperation: getAzureAsyncOperationHeader(rawResponse),
+ });
+ }
+ case "ResourceLocation": {
+ return getLocationHeader(rawResponse);
+ }
+ case "Body":
+ default: {
+ return undefined;
+ }
+ }
+}
+function getOperationStatus({ rawResponse }, state) {
+ var _a;
+ const mode = (_a = state.config.metadata) === null || _a === void 0 ? void 0 : _a["mode"];
+ switch (mode) {
+ case "OperationLocation": {
+ return getStatus(rawResponse);
+ }
+ case "ResourceLocation": {
+ return toOperationStatus(rawResponse.statusCode);
+ }
+ case "Body": {
+ return getProvisioningState(rawResponse);
+ }
+ default:
+ throw new Error(`Internal error: Unexpected operation mode: ${mode}`);
+ }
+}
+function getResourceLocation({ flatResponse }, state) {
+ if (typeof flatResponse === "object") {
+ const resourceLocation = flatResponse.resourceLocation;
+ if (resourceLocation !== undefined) {
+ state.config.resourceLocation = resourceLocation;
+ }
+ }
+ return state.config.resourceLocation;
+}
+function isOperationError(e) {
+ return e.name === "RestError";
+}
+/** Polls the long-running operation. */
+async function pollHttpOperation(inputs) {
+ const { lro, stateProxy, options, processResult, updateState, setDelay, state, setErrorAsResult, } = inputs;
+ return pollOperation({
+ state,
+ stateProxy,
+ setDelay,
+ processResult: processResult
+ ? ({ flatResponse }, inputState) => processResult(flatResponse, inputState)
+ : ({ flatResponse }) => flatResponse,
+ getError: getErrorFromResponse,
+ updateState,
+ getPollingInterval: parseRetryAfter,
+ getOperationLocation,
+ getOperationStatus,
+ isOperationError,
+ getResourceLocation,
+ options,
+ /**
+ * The expansion here is intentional because `lro` could be an object that
+ * references an inner this, so we need to preserve a reference to it.
+ */
+ poll: async (location, inputOptions) => lro.sendPollRequest(location, inputOptions),
+ setErrorAsResult,
+ });
+}
+
+// Copyright (c) Microsoft Corporation.
+const createStateProxy$1 = () => ({
+ /**
+ * The state at this point is created to be of type OperationState.
+ * It will be updated later to be of type TState when the
+ * customer-provided callback, `updateState`, is called during polling.
+ */
+ initState: (config) => ({ status: "running", config }),
+ setCanceled: (state) => (state.status = "canceled"),
+ setError: (state, error) => (state.error = error),
+ setResult: (state, result) => (state.result = result),
+ setRunning: (state) => (state.status = "running"),
+ setSucceeded: (state) => (state.status = "succeeded"),
+ setFailed: (state) => (state.status = "failed"),
+ getError: (state) => state.error,
+ getResult: (state) => state.result,
+ isCanceled: (state) => state.status === "canceled",
+ isFailed: (state) => state.status === "failed",
+ isRunning: (state) => state.status === "running",
+ isSucceeded: (state) => state.status === "succeeded",
+});
+/**
+ * Returns a poller factory.
+ */
+function buildCreatePoller(inputs) {
+ const { getOperationLocation, getStatusFromInitialResponse, getStatusFromPollResponse, isOperationError, getResourceLocation, getPollingInterval, getError, resolveOnUnsuccessful, } = inputs;
+ return async ({ init, poll }, options) => {
+ const { processResult, updateState, withOperationLocation: withOperationLocationCallback, intervalInMs = POLL_INTERVAL_IN_MS, restoreFrom, } = options || {};
+ const stateProxy = createStateProxy$1();
+ const withOperationLocation = withOperationLocationCallback
+ ? (() => {
+ let called = false;
+ return (operationLocation, isUpdated) => {
+ if (isUpdated)
+ withOperationLocationCallback(operationLocation);
+ else if (!called)
+ withOperationLocationCallback(operationLocation);
+ called = true;
+ };
+ })()
+ : undefined;
+ const state = restoreFrom
+ ? deserializeState(restoreFrom)
+ : await initOperation({
+ init,
+ stateProxy,
+ processResult,
+ getOperationStatus: getStatusFromInitialResponse,
+ withOperationLocation,
+ setErrorAsResult: !resolveOnUnsuccessful,
+ });
+ let resultPromise;
+ const abortController$1 = new abortController.AbortController();
+ const handlers = new Map();
+ const handleProgressEvents = async () => handlers.forEach((h) => h(state));
+ const cancelErrMsg = "Operation was canceled";
+ let currentPollIntervalInMs = intervalInMs;
+ const poller = {
+ getOperationState: () => state,
+ getResult: () => state.result,
+ isDone: () => ["succeeded", "failed", "canceled"].includes(state.status),
+ isStopped: () => resultPromise === undefined,
+ stopPolling: () => {
+ abortController$1.abort();
+ },
+ toString: () => JSON.stringify({
+ state,
+ }),
+ onProgress: (callback) => {
+ const s = Symbol();
+ handlers.set(s, callback);
+ return () => handlers.delete(s);
+ },
+ pollUntilDone: (pollOptions) => (resultPromise !== null && resultPromise !== void 0 ? resultPromise : (resultPromise = (async () => {
+ const { abortSignal: inputAbortSignal } = pollOptions || {};
+ const { signal: abortSignal } = inputAbortSignal
+ ? new abortController.AbortController([inputAbortSignal, abortController$1.signal])
+ : abortController$1;
+ if (!poller.isDone()) {
+ await poller.poll({ abortSignal });
+ while (!poller.isDone()) {
+ await coreUtil.delay(currentPollIntervalInMs, { abortSignal });
+ await poller.poll({ abortSignal });
+ }
+ }
+ if (resolveOnUnsuccessful) {
+ return poller.getResult();
+ }
+ else {
+ switch (state.status) {
+ case "succeeded":
+ return poller.getResult();
+ case "canceled":
+ throw new Error(cancelErrMsg);
+ case "failed":
+ throw state.error;
+ case "notStarted":
+ case "running":
+ throw new Error(`Polling completed without succeeding or failing`);
+ }
+ }
+ })().finally(() => {
+ resultPromise = undefined;
+ }))),
+ async poll(pollOptions) {
+ if (resolveOnUnsuccessful) {
+ if (poller.isDone())
+ return;
+ }
+ else {
+ switch (state.status) {
+ case "succeeded":
+ return;
+ case "canceled":
+ throw new Error(cancelErrMsg);
+ case "failed":
+ throw state.error;
+ }
+ }
+ await pollOperation({
+ poll,
+ state,
+ stateProxy,
+ getOperationLocation,
+ isOperationError,
+ withOperationLocation,
+ getPollingInterval,
+ getOperationStatus: getStatusFromPollResponse,
+ getResourceLocation,
+ processResult,
+ getError,
+ updateState,
+ options: pollOptions,
+ setDelay: (pollIntervalInMs) => {
+ currentPollIntervalInMs = pollIntervalInMs;
+ },
+ setErrorAsResult: !resolveOnUnsuccessful,
+ });
+ await handleProgressEvents();
+ if (!resolveOnUnsuccessful) {
+ switch (state.status) {
+ case "canceled":
+ throw new Error(cancelErrMsg);
+ case "failed":
+ throw state.error;
+ }
+ }
+ },
+ };
+ return poller;
+ };
+}
+
+// Copyright (c) Microsoft Corporation.
+/**
+ * Creates a poller that can be used to poll a long-running operation.
+ * @param lro - Description of the long-running operation
+ * @param options - options to configure the poller
+ * @returns an initialized poller
+ */
+async function createHttpPoller(lro, options) {
+ const { resourceLocationConfig, intervalInMs, processResult, restoreFrom, updateState, withOperationLocation, resolveOnUnsuccessful = false, } = options || {};
+ return buildCreatePoller({
+ getStatusFromInitialResponse,
+ getStatusFromPollResponse: getOperationStatus,
+ isOperationError,
+ getOperationLocation,
+ getResourceLocation,
+ getPollingInterval: parseRetryAfter,
+ getError: getErrorFromResponse,
+ resolveOnUnsuccessful,
+ })({
+ init: async () => {
+ const response = await lro.sendInitialRequest();
+ const config = inferLroMode({
+ rawResponse: response.rawResponse,
+ requestPath: lro.requestPath,
+ requestMethod: lro.requestMethod,
+ resourceLocationConfig,
+ });
+ return Object.assign({ response, operationLocation: config === null || config === void 0 ? void 0 : config.operationLocation, resourceLocation: config === null || config === void 0 ? void 0 : config.resourceLocation }, ((config === null || config === void 0 ? void 0 : config.mode) ? { metadata: { mode: config.mode } } : {}));
+ },
+ poll: lro.sendPollRequest,
+ }, {
+ intervalInMs,
+ withOperationLocation,
+ restoreFrom,
+ updateState,
+ processResult: processResult
+ ? ({ flatResponse }, state) => processResult(flatResponse, state)
+ : ({ flatResponse }) => flatResponse,
+ });
+}
+
+// Copyright (c) Microsoft Corporation.
+const createStateProxy = () => ({
+ initState: (config) => ({ config, isStarted: true }),
+ setCanceled: (state) => (state.isCancelled = true),
+ setError: (state, error) => (state.error = error),
+ setResult: (state, result) => (state.result = result),
+ setRunning: (state) => (state.isStarted = true),
+ setSucceeded: (state) => (state.isCompleted = true),
+ setFailed: () => {
+ /** empty body */
+ },
+ getError: (state) => state.error,
+ getResult: (state) => state.result,
+ isCanceled: (state) => !!state.isCancelled,
+ isFailed: (state) => !!state.error,
+ isRunning: (state) => !!state.isStarted,
+ isSucceeded: (state) => Boolean(state.isCompleted && !state.isCancelled && !state.error),
+});
+class GenericPollOperation {
+ constructor(state, lro, setErrorAsResult, lroResourceLocationConfig, processResult, updateState, isDone) {
+ this.state = state;
+ this.lro = lro;
+ this.setErrorAsResult = setErrorAsResult;
+ this.lroResourceLocationConfig = lroResourceLocationConfig;
+ this.processResult = processResult;
+ this.updateState = updateState;
+ this.isDone = isDone;
+ }
+ setPollerConfig(pollerConfig) {
+ this.pollerConfig = pollerConfig;
+ }
+ async update(options) {
+ var _a;
+ const stateProxy = createStateProxy();
+ if (!this.state.isStarted) {
+ this.state = Object.assign(Object.assign({}, this.state), (await initHttpOperation({
+ lro: this.lro,
+ stateProxy,
+ resourceLocationConfig: this.lroResourceLocationConfig,
+ processResult: this.processResult,
+ setErrorAsResult: this.setErrorAsResult,
+ })));
+ }
+ const updateState = this.updateState;
+ const isDone = this.isDone;
+ if (!this.state.isCompleted && this.state.error === undefined) {
+ await pollHttpOperation({
+ lro: this.lro,
+ state: this.state,
+ stateProxy,
+ processResult: this.processResult,
+ updateState: updateState
+ ? (state, { rawResponse }) => updateState(state, rawResponse)
+ : undefined,
+ isDone: isDone
+ ? ({ flatResponse }, state) => isDone(flatResponse, state)
+ : undefined,
+ options,
+ setDelay: (intervalInMs) => {
+ this.pollerConfig.intervalInMs = intervalInMs;
+ },
+ setErrorAsResult: this.setErrorAsResult,
+ });
+ }
+ (_a = options === null || options === void 0 ? void 0 : options.fireProgress) === null || _a === void 0 ? void 0 : _a.call(options, this.state);
+ return this;
+ }
+ async cancel() {
+ logger.error("`cancelOperation` is deprecated because it wasn't implemented");
+ return this;
+ }
+ /**
+ * Serializes the Poller operation.
+ */
+ toString() {
+ return JSON.stringify({
+ state: this.state,
+ });
+ }
+}
+
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+/**
+ * When a poller is manually stopped through the `stopPolling` method,
+ * the poller will be rejected with an instance of the PollerStoppedError.
+ */
+class PollerStoppedError extends Error {
+ constructor(message) {
+ super(message);
+ this.name = "PollerStoppedError";
+ Object.setPrototypeOf(this, PollerStoppedError.prototype);
+ }
+}
+/**
+ * When the operation is cancelled, the poller will be rejected with an instance
+ * of the PollerCancelledError.
+ */
+class PollerCancelledError extends Error {
+ constructor(message) {
+ super(message);
+ this.name = "PollerCancelledError";
+ Object.setPrototypeOf(this, PollerCancelledError.prototype);
+ }
+}
+/**
+ * A class that represents the definition of a program that polls through consecutive requests
+ * until it reaches a state of completion.
+ *
+ * A poller can be executed manually, by polling request by request by calling to the `poll()` method repeatedly, until its operation is completed.
+ * It also provides a way to wait until the operation completes, by calling `pollUntilDone()` and waiting until the operation finishes.
+ * Pollers can also request the cancellation of the ongoing process to whom is providing the underlying long running operation.
+ *
+ * ```ts
+ * const poller = new MyPoller();
+ *
+ * // Polling just once:
+ * await poller.poll();
+ *
+ * // We can try to cancel the request here, by calling:
+ * //
+ * // await poller.cancelOperation();
+ * //
+ *
+ * // Getting the final result:
+ * const result = await poller.pollUntilDone();
+ * ```
+ *
+ * The Poller is defined by two types, a type representing the state of the poller, which
+ * must include a basic set of properties from `PollOperationState`,
+ * and a return type defined by `TResult`, which can be anything.
+ *
+ * The Poller class implements the `PollerLike` interface, which allows poller implementations to avoid having
+ * to export the Poller's class directly, and instead only export the already instantiated poller with the PollerLike type.
+ *
+ * ```ts
+ * class Client {
+ * public async makePoller: PollerLike {
+ * const poller = new MyPoller({});
+ * // It might be preferred to return the poller after the first request is made,
+ * // so that some information can be obtained right away.
+ * await poller.poll();
+ * return poller;
+ * }
+ * }
+ *
+ * const poller: PollerLike = myClient.makePoller();
+ * ```
+ *
+ * A poller can be created through its constructor, then it can be polled until it's completed.
+ * At any point in time, the state of the poller can be obtained without delay through the getOperationState method.
+ * At any point in time, the intermediate forms of the result type can be requested without delay.
+ * Once the underlying operation is marked as completed, the poller will stop and the final value will be returned.
+ *
+ * ```ts
+ * const poller = myClient.makePoller();
+ * const state: MyOperationState = poller.getOperationState();
+ *
+ * // The intermediate result can be obtained at any time.
+ * const result: MyResult | undefined = poller.getResult();
+ *
+ * // The final result can only be obtained after the poller finishes.
+ * const result: MyResult = await poller.pollUntilDone();
+ * ```
+ *
+ */
+// eslint-disable-next-line no-use-before-define
+class Poller {
+ /**
+ * A poller needs to be initialized by passing in at least the basic properties of the `PollOperation`.
+ *
+ * When writing an implementation of a Poller, this implementation needs to deal with the initialization
+ * of any custom state beyond the basic definition of the poller. The basic poller assumes that the poller's
+ * operation has already been defined, at least its basic properties. The code below shows how to approach
+ * the definition of the constructor of a new custom poller.
+ *
+ * ```ts
+ * export class MyPoller extends Poller {
+ * constructor({
+ * // Anything you might need outside of the basics
+ * }) {
+ * let state: MyOperationState = {
+ * privateProperty: private,
+ * publicProperty: public,
+ * };
+ *
+ * const operation = {
+ * state,
+ * update,
+ * cancel,
+ * toString
+ * }
+ *
+ * // Sending the operation to the parent's constructor.
+ * super(operation);
+ *
+ * // You can assign more local properties here.
+ * }
+ * }
+ * ```
+ *
+ * Inside of this constructor, a new promise is created. This will be used to
+ * tell the user when the poller finishes (see `pollUntilDone()`). The promise's
+ * resolve and reject methods are also used internally to control when to resolve
+ * or reject anyone waiting for the poller to finish.
+ *
+ * The constructor of a custom implementation of a poller is where any serialized version of
+ * a previous poller's operation should be deserialized into the operation sent to the
+ * base constructor. For example:
+ *
+ * ```ts
+ * export class MyPoller extends Poller {
+ * constructor(
+ * baseOperation: string | undefined
+ * ) {
+ * let state: MyOperationState = {};
+ * if (baseOperation) {
+ * state = {
+ * ...JSON.parse(baseOperation).state,
+ * ...state
+ * };
+ * }
+ * const operation = {
+ * state,
+ * // ...
+ * }
+ * super(operation);
+ * }
+ * }
+ * ```
+ *
+ * @param operation - Must contain the basic properties of `PollOperation`.
+ */
+ constructor(operation) {
+ /** controls whether to throw an error if the operation failed or was canceled. */
+ this.resolveOnUnsuccessful = false;
+ this.stopped = true;
+ this.pollProgressCallbacks = [];
+ this.operation = operation;
+ this.promise = new Promise((resolve, reject) => {
+ this.resolve = resolve;
+ this.reject = reject;
+ });
+ // This prevents the UnhandledPromiseRejectionWarning in node.js from being thrown.
+ // The above warning would get thrown if `poller.poll` is called, it returns an error,
+ // and pullUntilDone did not have a .catch or await try/catch on it's return value.
+ this.promise.catch(() => {
+ /* intentionally blank */
+ });
+ }
+ /**
+ * Starts a loop that will break only if the poller is done
+ * or if the poller is stopped.
+ */
+ async startPolling(pollOptions = {}) {
+ if (this.stopped) {
+ this.stopped = false;
+ }
+ while (!this.isStopped() && !this.isDone()) {
+ await this.poll(pollOptions);
+ await this.delay();
+ }
+ }
+ /**
+ * pollOnce does one polling, by calling to the update method of the underlying
+ * poll operation to make any relevant change effective.
+ *
+ * It only optionally receives an object with an abortSignal property, from \@azure/abort-controller's AbortSignalLike.
+ *
+ * @param options - Optional properties passed to the operation's update method.
+ */
+ async pollOnce(options = {}) {
+ if (!this.isDone()) {
+ this.operation = await this.operation.update({
+ abortSignal: options.abortSignal,
+ fireProgress: this.fireProgress.bind(this),
+ });
+ }
+ this.processUpdatedState();
+ }
+ /**
+ * fireProgress calls the functions passed in via onProgress the method of the poller.
+ *
+ * It loops over all of the callbacks received from onProgress, and executes them, sending them
+ * the current operation state.
+ *
+ * @param state - The current operation state.
+ */
+ fireProgress(state) {
+ for (const callback of this.pollProgressCallbacks) {
+ callback(state);
+ }
+ }
+ /**
+ * Invokes the underlying operation's cancel method.
+ */
+ async cancelOnce(options = {}) {
+ this.operation = await this.operation.cancel(options);
+ }
+ /**
+ * Returns a promise that will resolve once a single polling request finishes.
+ * It does this by calling the update method of the Poller's operation.
+ *
+ * It only optionally receives an object with an abortSignal property, from \@azure/abort-controller's AbortSignalLike.
+ *
+ * @param options - Optional properties passed to the operation's update method.
+ */
+ poll(options = {}) {
+ if (!this.pollOncePromise) {
+ this.pollOncePromise = this.pollOnce(options);
+ const clearPollOncePromise = () => {
this.pollOncePromise = undefined;
};
this.pollOncePromise.then(clearPollOncePromise, clearPollOncePromise).catch(this.reject);
@@ -14812,30 +16135,34 @@ class Poller {
processUpdatedState() {
if (this.operation.state.error) {
this.stopped = true;
- this.reject(this.operation.state.error);
- throw this.operation.state.error;
+ if (!this.resolveOnUnsuccessful) {
+ this.reject(this.operation.state.error);
+ throw this.operation.state.error;
+ }
}
if (this.operation.state.isCancelled) {
this.stopped = true;
- const error = new PollerCancelledError("Poller cancelled");
- this.reject(error);
- throw error;
+ if (!this.resolveOnUnsuccessful) {
+ const error = new PollerCancelledError("Operation was canceled");
+ this.reject(error);
+ throw error;
+ }
}
- else if (this.isDone() && this.resolve) {
+ if (this.isDone() && this.resolve) {
// If the poller has finished polling, this means we now have a result.
// However, it can be the case that TResult is instantiated to void, so
// we are not expecting a result anyway. To assert that we might not
// have a result eventually after finishing polling, we cast the result
// to TResult.
- this.resolve(this.operation.state.result);
+ this.resolve(this.getResult());
}
}
/**
* Returns a promise that will resolve once the underlying operation is completed.
*/
- async pollUntilDone() {
+ async pollUntilDone(pollOptions = {}) {
if (this.stopped) {
- this.startPolling().catch(this.reject);
+ this.startPolling(pollOptions).catch(this.reject);
}
// This is needed because the state could have been updated by
// `cancelOperation`, e.g. the operation is canceled or an error occurred.
@@ -14968,403 +16295,25 @@ class Poller {
// Copyright (c) Microsoft Corporation.
/**
- * The `@azure/logger` configuration for this package.
- * @internal
+ * The LRO Engine, a class that performs polling.
*/
-const logger = logger$1.createClientLogger("core-lro");
-
-// Copyright (c) Microsoft Corporation.
-function throwIfUndefined(input, options = {}) {
- var _a;
- if (input === undefined) {
- throw new Error((_a = options.errorMessage) !== null && _a !== void 0 ? _a : "undefined variable");
+class LroEngine extends Poller {
+ constructor(lro, options) {
+ const { intervalInMs = POLL_INTERVAL_IN_MS, resumeFrom, resolveOnUnsuccessful = false, isDone, lroResourceLocationConfig, processResult, updateState, } = options || {};
+ const state = resumeFrom
+ ? deserializeState(resumeFrom)
+ : {};
+ const operation = new GenericPollOperation(state, lro, !resolveOnUnsuccessful, lroResourceLocationConfig, processResult, updateState, isDone);
+ super(operation);
+ this.resolveOnUnsuccessful = resolveOnUnsuccessful;
+ this.config = { intervalInMs: intervalInMs };
+ operation.setPollerConfig(this.config);
}
- return input;
-}
-function updatePollingUrl(inputs) {
- var _a, _b;
- const { info, rawResponse } = inputs;
- switch (info.mode) {
- case "OperationLocation": {
- const operationLocation = getOperationLocation(rawResponse);
- const azureAsyncOperation = getAzureAsyncOperation(rawResponse);
- info.pollingUrl =
- (_a = getOperationLocationPollingUrl({ operationLocation, azureAsyncOperation })) !== null && _a !== void 0 ? _a : throwIfUndefined(info.pollingUrl);
- break;
- }
- case "ResourceLocation": {
- info.pollingUrl = (_b = getLocation(rawResponse)) !== null && _b !== void 0 ? _b : throwIfUndefined(info.pollingUrl);
- break;
- }
- }
-}
-function getOperationLocationPollingUrl(inputs) {
- const { azureAsyncOperation, operationLocation } = inputs;
- return operationLocation !== null && operationLocation !== void 0 ? operationLocation : azureAsyncOperation;
-}
-function getLocation(rawResponse) {
- return rawResponse.headers["location"];
-}
-function getOperationLocation(rawResponse) {
- return rawResponse.headers["operation-location"];
-}
-function getAzureAsyncOperation(rawResponse) {
- return rawResponse.headers["azure-asyncoperation"];
-}
-function findResourceLocation(inputs) {
- const { location, requestMethod, requestPath, lroResourceLocationConfig } = inputs;
- switch (requestMethod) {
- case "PUT": {
- return requestPath;
- }
- case "DELETE": {
- return undefined;
- }
- default: {
- switch (lroResourceLocationConfig) {
- case "azure-async-operation": {
- return undefined;
- }
- case "original-uri": {
- return requestPath;
- }
- case "location":
- default: {
- return location;
- }
- }
- }
- }
-}
-function inferLroMode(inputs) {
- const { rawResponse, requestMethod, requestPath, lroResourceLocationConfig } = inputs;
- const operationLocation = getOperationLocation(rawResponse);
- const azureAsyncOperation = getAzureAsyncOperation(rawResponse);
- const location = getLocation(rawResponse);
- if (operationLocation !== undefined || azureAsyncOperation !== undefined) {
- return {
- mode: "OperationLocation",
- pollingUrl: operationLocation !== null && operationLocation !== void 0 ? operationLocation : azureAsyncOperation,
- resourceLocation: findResourceLocation({
- requestMethod,
- location,
- requestPath,
- lroResourceLocationConfig,
- }),
- };
- }
- else if (location !== undefined) {
- return {
- mode: "ResourceLocation",
- pollingUrl: location,
- };
- }
- else if (requestMethod === "PUT") {
- return {
- mode: "Body",
- pollingUrl: requestPath,
- };
- }
- else {
- return {
- mode: "None",
- };
- }
-}
-class SimpleRestError extends Error {
- constructor(message, statusCode) {
- super(message);
- this.name = "RestError";
- this.statusCode = statusCode;
- Object.setPrototypeOf(this, SimpleRestError.prototype);
- }
-}
-function throwIfError(rawResponse) {
- const code = rawResponse.statusCode;
- if (code >= 400) {
- throw new SimpleRestError(`Received unexpected HTTP status code ${code} while polling. This may indicate a server issue.`, code);
- }
-}
-function getStatus(rawResponse) {
- var _a;
- const { status } = (_a = rawResponse.body) !== null && _a !== void 0 ? _a : {};
- return typeof status === "string" ? status.toLowerCase() : "succeeded";
-}
-function getProvisioningState(rawResponse) {
- var _a, _b;
- const { properties, provisioningState } = (_a = rawResponse.body) !== null && _a !== void 0 ? _a : {};
- const state = (_b = properties === null || properties === void 0 ? void 0 : properties.provisioningState) !== null && _b !== void 0 ? _b : provisioningState;
- return typeof state === "string" ? state.toLowerCase() : "succeeded";
-}
-function isCanceled(operation) {
- const { state, operationStatus } = operation;
- if (["canceled", "cancelled"].includes(operationStatus)) {
- state.isCancelled = true;
- return true;
- }
- return false;
-}
-function isTerminal(operation) {
- const { state, operationStatus } = operation;
- if (operationStatus === "failed") {
- throw new Error(`The long-running operation has failed.`);
- }
- return operationStatus === "succeeded" || isCanceled({ state, operationStatus });
-}
-function getOperationStatus(result) {
- const { rawResponse, state, info, responseKind = "Polling" } = result;
- throwIfError(rawResponse);
- switch (info.mode) {
- case "OperationLocation": {
- const operationStatus = getStatus(rawResponse);
- return {
- operationStatus,
- shouldStopPolling: responseKind === "Polling" && isTerminal({ state, operationStatus }),
- };
- }
- case "Body": {
- const operationStatus = getProvisioningState(rawResponse);
- return {
- operationStatus,
- shouldStopPolling: isTerminal({ state, operationStatus }),
- };
- }
- case "ResourceLocation": {
- const operationStatus = rawResponse.statusCode;
- return {
- operationStatus,
- shouldStopPolling: responseKind === "Polling" && operationStatus !== 202,
- };
- }
- case "None": {
- return {
- shouldStopPolling: true,
- };
- }
- }
-}
-function shouldStopPolling(result) {
- const { rawResponse, state, info, responseKind = "Polling" } = result;
- const { shouldStopPolling: isPollingStopped, operationStatus } = getOperationStatus({
- info,
- rawResponse,
- state,
- responseKind,
- });
- if (operationStatus) {
- logger.verbose(`LRO: Status:\n\tPolling from: ${info.pollingUrl}\n\tOperation status: ${operationStatus}\n\tPolling status: ${isPollingStopped ? "Stopped" : "Running"}`);
- }
- else {
- logger.verbose(`LRO: Status: Not an LRO`);
- }
- return isPollingStopped;
-}
-/**
- * Creates a polling operation.
- */
-function createPoll(lroPrimitives) {
- return async (path, pollerConfig, getLroStatusFromResponse) => {
- const response = await lroPrimitives.sendPollRequest(path);
- const retryAfter = response.rawResponse.headers["retry-after"];
- if (retryAfter !== undefined) {
- // Retry-After header value is either in HTTP date format, or in seconds
- const retryAfterInSeconds = parseInt(retryAfter);
- pollerConfig.intervalInMs = isNaN(retryAfterInSeconds)
- ? calculatePollingIntervalFromDate(new Date(retryAfter), pollerConfig.intervalInMs)
- : retryAfterInSeconds * 1000;
- }
- return getLroStatusFromResponse(response);
- };
-}
-function calculatePollingIntervalFromDate(retryAfterDate, defaultIntervalInMs) {
- const timeNow = Math.floor(new Date().getTime());
- const retryAfterTime = retryAfterDate.getTime();
- if (timeNow < retryAfterTime) {
- return retryAfterTime - timeNow;
- }
- return defaultIntervalInMs;
-}
-function buildResult(inputs) {
- const { processResult, response, state } = inputs;
- return processResult ? processResult(response, state) : response;
-}
-/**
- * Creates a callback to be used to initialize the polling operation state.
- */
-function createStateInitializer(inputs) {
- const { requestMethod, requestPath, state, lroResourceLocationConfig, processResult } = inputs;
- return (response) => {
- const { rawResponse } = response;
- state.isStarted = true;
- state.config = inferLroMode({
- rawResponse,
- requestPath,
- requestMethod,
- lroResourceLocationConfig,
- });
- logger.verbose(`LRO: Operation description:`, state.config);
- /** short circuit before polling */
- if (shouldStopPolling({
- rawResponse,
- state,
- info: state.config,
- responseKind: "Initial",
- })) {
- state.result = buildResult({
- response: response.flatResponse,
- state: state,
- processResult,
- });
- state.isCompleted = true;
- }
- };
-}
-function createGetLroStatusFromResponse(inputs) {
- const { lro, state, info } = inputs;
- const location = info.resourceLocation;
- return (response) => {
- const isTerminalStatus = shouldStopPolling({
- info,
- rawResponse: response.rawResponse,
- state,
- });
- return Object.assign(Object.assign({}, response), { done: isTerminalStatus && !location, next: !(isTerminalStatus && location)
- ? undefined
- : () => lro.sendPollRequest(location).then((res) => (Object.assign(Object.assign({}, res), { done: true }))) });
- };
-}
-
-// Copyright (c) Microsoft Corporation.
-class GenericPollOperation {
- constructor(state, lro, lroResourceLocationConfig, processResult, updateState, isDone) {
- this.state = state;
- this.lro = lro;
- this.lroResourceLocationConfig = lroResourceLocationConfig;
- this.processResult = processResult;
- this.updateState = updateState;
- this.isDone = isDone;
- }
- setPollerConfig(pollerConfig) {
- this.pollerConfig = pollerConfig;
- }
- /**
- * General update function for LROPoller, the general process is as follows
- * 1. Check initial operation result to determine the strategy to use
- * - Strategies: Location, Azure-AsyncOperation, Original Uri
- * 2. Check if the operation result has a terminal state
- * - Terminal state will be determined by each strategy
- * 2.1 If it is terminal state Check if a final GET request is required, if so
- * send final GET request and return result from operation. If no final GET
- * is required, just return the result from operation.
- * - Determining what to call for final request is responsibility of each strategy
- * 2.2 If it is not terminal state, call the polling operation and go to step 1
- * - Determining what to call for polling is responsibility of each strategy
- * - Strategies will always use the latest URI for polling if provided otherwise
- * the last known one
- */
- async update(options) {
- var _a, _b, _c;
- const state = this.state;
- let lastResponse = undefined;
- if (!state.isStarted) {
- const initializeState = createStateInitializer({
- state,
- requestPath: this.lro.requestPath,
- requestMethod: this.lro.requestMethod,
- lroResourceLocationConfig: this.lroResourceLocationConfig,
- processResult: this.processResult,
- });
- lastResponse = await this.lro.sendInitialRequest();
- initializeState(lastResponse);
- }
- if (!state.isCompleted) {
- const config = throwIfUndefined(state.config, {
- errorMessage: "Bad state: LRO mode is undefined. Check if the serialized state is well-formed.",
- });
- if (!this.poll) {
- this.poll = createPoll(this.lro);
- }
- if (!this.getLroStatusFromResponse) {
- const isDone = this.isDone;
- this.getLroStatusFromResponse = isDone
- ? (response) => (Object.assign(Object.assign({}, response), { done: isDone(response.flatResponse, this.state) }))
- : createGetLroStatusFromResponse({
- lro: this.lro,
- info: config,
- state: this.state,
- });
- }
- const currentState = await this.poll(throwIfUndefined(config.pollingUrl), this.pollerConfig, this.getLroStatusFromResponse);
- if (currentState.done) {
- state.result = buildResult({
- response: currentState.flatResponse,
- state,
- processResult: this.processResult,
- });
- state.isCompleted = true;
- }
- else {
- this.poll = (_a = currentState.next) !== null && _a !== void 0 ? _a : this.poll;
- updatePollingUrl({
- rawResponse: currentState.rawResponse,
- info: config,
- });
- /** for backward compatability */
- state.pollingURL = config.pollingUrl;
- }
- lastResponse = currentState;
- }
- if (lastResponse) {
- (_b = this.updateState) === null || _b === void 0 ? void 0 : _b.call(this, state, lastResponse === null || lastResponse === void 0 ? void 0 : lastResponse.rawResponse);
- }
- else {
- logger.error(`LRO: no response was received`);
- }
- (_c = options === null || options === void 0 ? void 0 : options.fireProgress) === null || _c === void 0 ? void 0 : _c.call(options, state);
- return this;
- }
- async cancel() {
- logger.error("`cancelOperation` is deprecated because it wasn't implemented");
- return this;
- }
- /**
- * Serializes the Poller operation.
- */
- toString() {
- return JSON.stringify({
- state: this.state,
- });
- }
-}
-
-// Copyright (c) Microsoft Corporation.
-function deserializeState(serializedState) {
- try {
- return JSON.parse(serializedState).state;
- }
- catch (e) {
- throw new Error(`LroEngine: Unable to deserialize state: ${serializedState}`);
- }
-}
-/**
- * The LRO Engine, a class that performs polling.
- */
-class LroEngine extends Poller {
- constructor(lro, options) {
- const { intervalInMs = 2000, resumeFrom } = options || {};
- const state = resumeFrom
- ? deserializeState(resumeFrom)
- : {};
- const operation = new GenericPollOperation(state, lro, options === null || options === void 0 ? void 0 : options.lroResourceLocationConfig, options === null || options === void 0 ? void 0 : options.processResult, options === null || options === void 0 ? void 0 : options.updateState, options === null || options === void 0 ? void 0 : options.isDone);
- super(operation);
- this.config = { intervalInMs: intervalInMs };
- operation.setPollerConfig(this.config);
- }
- /**
- * The method used by the poller to wait before attempting to update its operation.
- */
- delay() {
- return new Promise((resolve) => setTimeout(() => resolve(), this.config.intervalInMs));
+ /**
+ * The method used by the poller to wait before attempting to update its operation.
+ */
+ delay() {
+ return new Promise((resolve) => setTimeout(() => resolve(), this.config.intervalInMs));
}
}
@@ -15372,6 +16321,7 @@ exports.LroEngine = LroEngine;
exports.Poller = Poller;
exports.PollerCancelledError = PollerCancelledError;
exports.PollerStoppedError = PollerStoppedError;
+exports.createHttpPoller = createHttpPoller;
//# sourceMappingURL=index.js.map
@@ -15385,7 +16335,7 @@ exports.PollerStoppedError = PollerStoppedError;
Object.defineProperty(exports, "__esModule", ({ value: true }));
-var tslib = __nccwpck_require__(584);
+var tslib = __nccwpck_require__(4351);
// Copyright (c) Microsoft Corporation.
/**
@@ -15416,31 +16366,51 @@ function getPagedAsyncIterator(pagedResult) {
}
function getItemAsyncIterator(pagedResult) {
return tslib.__asyncGenerator(this, arguments, function* getItemAsyncIterator_1() {
- var e_1, _a;
+ var e_1, _a, e_2, _b;
const pages = getPageAsyncIterator(pagedResult);
const firstVal = yield tslib.__await(pages.next());
// if the result does not have an array shape, i.e. TPage = TElement, then we return it as is
if (!Array.isArray(firstVal.value)) {
- yield yield tslib.__await(firstVal.value);
- // `pages` is of type `AsyncIterableIterator` but TPage = TElement in this case
- yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(pages)));
+ // can extract elements from this page
+ const { toElements } = pagedResult;
+ if (toElements) {
+ yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(toElements(firstVal.value))));
+ try {
+ for (var pages_1 = tslib.__asyncValues(pages), pages_1_1; pages_1_1 = yield tslib.__await(pages_1.next()), !pages_1_1.done;) {
+ const page = pages_1_1.value;
+ yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(toElements(page))));
+ }
+ }
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
+ finally {
+ try {
+ if (pages_1_1 && !pages_1_1.done && (_a = pages_1.return)) yield tslib.__await(_a.call(pages_1));
+ }
+ finally { if (e_1) throw e_1.error; }
+ }
+ }
+ else {
+ yield yield tslib.__await(firstVal.value);
+ // `pages` is of type `AsyncIterableIterator` but TPage = TElement in this case
+ yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(pages)));
+ }
}
else {
yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(firstVal.value)));
try {
- for (var pages_1 = tslib.__asyncValues(pages), pages_1_1; pages_1_1 = yield tslib.__await(pages_1.next()), !pages_1_1.done;) {
- const page = pages_1_1.value;
+ for (var pages_2 = tslib.__asyncValues(pages), pages_2_1; pages_2_1 = yield tslib.__await(pages_2.next()), !pages_2_1.done;) {
+ const page = pages_2_1.value;
// pages is of type `AsyncIterableIterator` so `page` is of type `TPage`. In this branch,
// it must be the case that `TPage = TElement[]`
yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(page)));
}
}
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
finally {
try {
- if (pages_1_1 && !pages_1_1.done && (_a = pages_1.return)) yield tslib.__await(_a.call(pages_1));
+ if (pages_2_1 && !pages_2_1.done && (_b = pages_2.return)) yield tslib.__await(_b.call(pages_2));
}
- finally { if (e_1) throw e_1.error; }
+ finally { if (e_2) throw e_2.error; }
}
}
});
@@ -15449,9 +16419,15 @@ function getPageAsyncIterator(pagedResult, options = {}) {
return tslib.__asyncGenerator(this, arguments, function* getPageAsyncIterator_1() {
const { pageLink, maxPageSize } = options;
let response = yield tslib.__await(pagedResult.getPage(pageLink !== null && pageLink !== void 0 ? pageLink : pagedResult.firstPageLink, maxPageSize));
+ if (!response) {
+ return yield tslib.__await(void 0);
+ }
yield yield tslib.__await(response.page);
while (response.nextPageLink) {
response = yield tslib.__await(pagedResult.getPage(response.nextPageLink, maxPageSize));
+ if (!response) {
+ return yield tslib.__await(void 0);
+ }
yield yield tslib.__await(response.page);
}
});
@@ -15461,290 +16437,6 @@ exports.getPagedAsyncIterator = getPagedAsyncIterator;
//# sourceMappingURL=index.js.map
-/***/ }),
-
-/***/ 584:
-/***/ ((__unused_webpack_module, __webpack_exports__, __nccwpck_require__) => {
-
-"use strict";
-__nccwpck_require__.r(__webpack_exports__);
-/* harmony export */ __nccwpck_require__.d(__webpack_exports__, {
-/* harmony export */ "__extends": () => /* binding */ __extends,
-/* harmony export */ "__assign": () => /* binding */ __assign,
-/* harmony export */ "__rest": () => /* binding */ __rest,
-/* harmony export */ "__decorate": () => /* binding */ __decorate,
-/* harmony export */ "__param": () => /* binding */ __param,
-/* harmony export */ "__metadata": () => /* binding */ __metadata,
-/* harmony export */ "__awaiter": () => /* binding */ __awaiter,
-/* harmony export */ "__generator": () => /* binding */ __generator,
-/* harmony export */ "__createBinding": () => /* binding */ __createBinding,
-/* harmony export */ "__exportStar": () => /* binding */ __exportStar,
-/* harmony export */ "__values": () => /* binding */ __values,
-/* harmony export */ "__read": () => /* binding */ __read,
-/* harmony export */ "__spread": () => /* binding */ __spread,
-/* harmony export */ "__spreadArrays": () => /* binding */ __spreadArrays,
-/* harmony export */ "__spreadArray": () => /* binding */ __spreadArray,
-/* harmony export */ "__await": () => /* binding */ __await,
-/* harmony export */ "__asyncGenerator": () => /* binding */ __asyncGenerator,
-/* harmony export */ "__asyncDelegator": () => /* binding */ __asyncDelegator,
-/* harmony export */ "__asyncValues": () => /* binding */ __asyncValues,
-/* harmony export */ "__makeTemplateObject": () => /* binding */ __makeTemplateObject,
-/* harmony export */ "__importStar": () => /* binding */ __importStar,
-/* harmony export */ "__importDefault": () => /* binding */ __importDefault,
-/* harmony export */ "__classPrivateFieldGet": () => /* binding */ __classPrivateFieldGet,
-/* harmony export */ "__classPrivateFieldSet": () => /* binding */ __classPrivateFieldSet,
-/* harmony export */ "__classPrivateFieldIn": () => /* binding */ __classPrivateFieldIn
-/* harmony export */ });
-/******************************************************************************
-Copyright (c) Microsoft Corporation.
-
-Permission to use, copy, modify, and/or distribute this software for any
-purpose with or without fee is hereby granted.
-
-THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
-REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
-INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
-OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-PERFORMANCE OF THIS SOFTWARE.
-***************************************************************************** */
-/* global Reflect, Promise */
-
-var extendStatics = function(d, b) {
- extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
- return extendStatics(d, b);
-};
-
-function __extends(d, b) {
- if (typeof b !== "function" && b !== null)
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-}
-
-var __assign = function() {
- __assign = Object.assign || function __assign(t) {
- for (var s, i = 1, n = arguments.length; i < n; i++) {
- s = arguments[i];
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
- }
- return t;
- }
- return __assign.apply(this, arguments);
-}
-
-function __rest(s, e) {
- var t = {};
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
- t[p] = s[p];
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
- t[p[i]] = s[p[i]];
- }
- return t;
-}
-
-function __decorate(decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
-}
-
-function __param(paramIndex, decorator) {
- return function (target, key) { decorator(target, key, paramIndex); }
-}
-
-function __metadata(metadataKey, metadataValue) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
-}
-
-function __awaiter(thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-}
-
-function __generator(thisArg, body) {
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
- function verb(n) { return function (v) { return step([n, v]); }; }
- function step(op) {
- if (f) throw new TypeError("Generator is already executing.");
- while (_) try {
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
- if (y = 0, t) op = [op[0] & 2, t.value];
- switch (op[0]) {
- case 0: case 1: t = op; break;
- case 4: _.label++; return { value: op[1], done: false };
- case 5: _.label++; y = op[1]; op = [0]; continue;
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
- default:
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
- if (t[2]) _.ops.pop();
- _.trys.pop(); continue;
- }
- op = body.call(thisArg, _);
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
- }
-}
-
-var __createBinding = Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- var desc = Object.getOwnPropertyDescriptor(m, k);
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
- desc = { enumerable: true, get: function() { return m[k]; } };
- }
- Object.defineProperty(o, k2, desc);
-}) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
-});
-
-function __exportStar(m, o) {
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);
-}
-
-function __values(o) {
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
- if (m) return m.call(o);
- if (o && typeof o.length === "number") return {
- next: function () {
- if (o && i >= o.length) o = void 0;
- return { value: o && o[i++], done: !o };
- }
- };
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
-}
-
-function __read(o, n) {
- var m = typeof Symbol === "function" && o[Symbol.iterator];
- if (!m) return o;
- var i = m.call(o), r, ar = [], e;
- try {
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
- }
- catch (error) { e = { error: error }; }
- finally {
- try {
- if (r && !r.done && (m = i["return"])) m.call(i);
- }
- finally { if (e) throw e.error; }
- }
- return ar;
-}
-
-/** @deprecated */
-function __spread() {
- for (var ar = [], i = 0; i < arguments.length; i++)
- ar = ar.concat(__read(arguments[i]));
- return ar;
-}
-
-/** @deprecated */
-function __spreadArrays() {
- for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
- for (var r = Array(s), k = 0, i = 0; i < il; i++)
- for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
- r[k] = a[j];
- return r;
-}
-
-function __spreadArray(to, from, pack) {
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
- if (ar || !(i in from)) {
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
- ar[i] = from[i];
- }
- }
- return to.concat(ar || Array.prototype.slice.call(from));
-}
-
-function __await(v) {
- return this instanceof __await ? (this.v = v, this) : new __await(v);
-}
-
-function __asyncGenerator(thisArg, _arguments, generator) {
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
- var g = generator.apply(thisArg, _arguments || []), i, q = [];
- return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
- function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
- function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
- function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
- function fulfill(value) { resume("next", value); }
- function reject(value) { resume("throw", value); }
- function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
-}
-
-function __asyncDelegator(o) {
- var i, p;
- return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
- function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
-}
-
-function __asyncValues(o) {
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
- var m = o[Symbol.asyncIterator], i;
- return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
- function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
- function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
-}
-
-function __makeTemplateObject(cooked, raw) {
- if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
- return cooked;
-};
-
-var __setModuleDefault = Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-};
-
-function __importStar(mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
-}
-
-function __importDefault(mod) {
- return (mod && mod.__esModule) ? mod : { default: mod };
-}
-
-function __classPrivateFieldGet(receiver, state, kind, f) {
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
-}
-
-function __classPrivateFieldSet(receiver, state, value, kind, f) {
- if (kind === "m") throw new TypeError("Private method is not writable");
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
-}
-
-function __classPrivateFieldIn(state, receiver) {
- if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object");
- return typeof state === "function" ? receiver === state : state.has(receiver);
-}
-
-
/***/ }),
/***/ 4175:
@@ -15972,6 +16664,371 @@ exports.setSpanContext = setSpanContext;
//# sourceMappingURL=index.js.map
+/***/ }),
+
+/***/ 1333:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+var abortController = __nccwpck_require__(2557);
+var crypto = __nccwpck_require__(6113);
+
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+/**
+ * Creates an abortable promise.
+ * @param buildPromise - A function that takes the resolve and reject functions as parameters.
+ * @param options - The options for the abortable promise.
+ * @returns A promise that can be aborted.
+ */
+function createAbortablePromise(buildPromise, options) {
+ const { cleanupBeforeAbort, abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {};
+ return new Promise((resolve, reject) => {
+ function rejectOnAbort() {
+ reject(new abortController.AbortError(abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : "The operation was aborted."));
+ }
+ function removeListeners() {
+ abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.removeEventListener("abort", onAbort);
+ }
+ function onAbort() {
+ cleanupBeforeAbort === null || cleanupBeforeAbort === void 0 ? void 0 : cleanupBeforeAbort();
+ removeListeners();
+ rejectOnAbort();
+ }
+ if (abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.aborted) {
+ return rejectOnAbort();
+ }
+ try {
+ buildPromise((x) => {
+ removeListeners();
+ resolve(x);
+ }, (x) => {
+ removeListeners();
+ reject(x);
+ });
+ }
+ catch (err) {
+ reject(err);
+ }
+ abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.addEventListener("abort", onAbort);
+ });
+}
+
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+const StandardAbortMessage = "The delay was aborted.";
+/**
+ * A wrapper for setTimeout that resolves a promise after timeInMs milliseconds.
+ * @param timeInMs - The number of milliseconds to be delayed.
+ * @param options - The options for delay - currently abort options
+ * @returns Promise that is resolved after timeInMs
+ */
+function delay(timeInMs, options) {
+ let token;
+ const { abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {};
+ return createAbortablePromise((resolve) => {
+ token = setTimeout(resolve, timeInMs);
+ }, {
+ cleanupBeforeAbort: () => clearTimeout(token),
+ abortSignal,
+ abortErrorMsg: abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : StandardAbortMessage,
+ });
+}
+
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+/**
+ * promise.race() wrapper that aborts rest of promises as soon as the first promise settles.
+ */
+async function cancelablePromiseRace(abortablePromiseBuilders, options) {
+ var _a, _b;
+ const aborter = new abortController.AbortController();
+ function abortHandler() {
+ aborter.abort();
+ }
+ (_a = options === null || options === void 0 ? void 0 : options.abortSignal) === null || _a === void 0 ? void 0 : _a.addEventListener("abort", abortHandler);
+ try {
+ return await Promise.race(abortablePromiseBuilders.map((p) => p({ abortSignal: aborter.signal })));
+ }
+ finally {
+ aborter.abort();
+ (_b = options === null || options === void 0 ? void 0 : options.abortSignal) === null || _b === void 0 ? void 0 : _b.removeEventListener("abort", abortHandler);
+ }
+}
+
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+/**
+ * Returns a random integer value between a lower and upper bound,
+ * inclusive of both bounds.
+ * Note that this uses Math.random and isn't secure. If you need to use
+ * this for any kind of security purpose, find a better source of random.
+ * @param min - The smallest integer value allowed.
+ * @param max - The largest integer value allowed.
+ */
+function getRandomIntegerInclusive(min, max) {
+ // Make sure inputs are integers.
+ min = Math.ceil(min);
+ max = Math.floor(max);
+ // Pick a random offset from zero to the size of the range.
+ // Since Math.random() can never return 1, we have to make the range one larger
+ // in order to be inclusive of the maximum value after we take the floor.
+ const offset = Math.floor(Math.random() * (max - min + 1));
+ return offset + min;
+}
+
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+/**
+ * Helper to determine when an input is a generic JS object.
+ * @returns true when input is an object type that is not null, Array, RegExp, or Date.
+ */
+function isObject(input) {
+ return (typeof input === "object" &&
+ input !== null &&
+ !Array.isArray(input) &&
+ !(input instanceof RegExp) &&
+ !(input instanceof Date));
+}
+
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+/**
+ * Typeguard for an error object shape (has name and message)
+ * @param e - Something caught by a catch clause.
+ */
+function isError(e) {
+ if (isObject(e)) {
+ const hasName = typeof e.name === "string";
+ const hasMessage = typeof e.message === "string";
+ return hasName && hasMessage;
+ }
+ return false;
+}
+/**
+ * Given what is thought to be an error object, return the message if possible.
+ * If the message is missing, returns a stringified version of the input.
+ * @param e - Something thrown from a try block
+ * @returns The error message or a string of the input
+ */
+function getErrorMessage(e) {
+ if (isError(e)) {
+ return e.message;
+ }
+ else {
+ let stringified;
+ try {
+ if (typeof e === "object" && e) {
+ stringified = JSON.stringify(e);
+ }
+ else {
+ stringified = String(e);
+ }
+ }
+ catch (err) {
+ stringified = "[unable to stringify input]";
+ }
+ return `Unknown error ${stringified}`;
+ }
+}
+
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+/**
+ * Generates a SHA-256 HMAC signature.
+ * @param key - The HMAC key represented as a base64 string, used to generate the cryptographic HMAC hash.
+ * @param stringToSign - The data to be signed.
+ * @param encoding - The textual encoding to use for the returned HMAC digest.
+ */
+async function computeSha256Hmac(key, stringToSign, encoding) {
+ const decodedKey = Buffer.from(key, "base64");
+ return crypto.createHmac("sha256", decodedKey).update(stringToSign).digest(encoding);
+}
+/**
+ * Generates a SHA-256 hash.
+ * @param content - The data to be included in the hash.
+ * @param encoding - The textual encoding to use for the returned hash.
+ */
+async function computeSha256Hash(content, encoding) {
+ return crypto.createHash("sha256").update(content).digest(encoding);
+}
+
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+/**
+ * Helper TypeGuard that checks if something is defined or not.
+ * @param thing - Anything
+ */
+function isDefined(thing) {
+ return typeof thing !== "undefined" && thing !== null;
+}
+/**
+ * Helper TypeGuard that checks if the input is an object with the specified properties.
+ * @param thing - Anything.
+ * @param properties - The name of the properties that should appear in the object.
+ */
+function isObjectWithProperties(thing, properties) {
+ if (!isDefined(thing) || typeof thing !== "object") {
+ return false;
+ }
+ for (const property of properties) {
+ if (!objectHasProperty(thing, property)) {
+ return false;
+ }
+ }
+ return true;
+}
+/**
+ * Helper TypeGuard that checks if the input is an object with the specified property.
+ * @param thing - Any object.
+ * @param property - The name of the property that should appear in the object.
+ */
+function objectHasProperty(thing, property) {
+ return (isDefined(thing) && typeof thing === "object" && property in thing);
+}
+
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+/*
+ * NOTE: When moving this file, please update "react-native" section in package.json.
+ */
+/**
+ * Generated Universally Unique Identifier
+ *
+ * @returns RFC4122 v4 UUID.
+ */
+function generateUUID() {
+ let uuid = "";
+ for (let i = 0; i < 32; i++) {
+ // Generate a random number between 0 and 15
+ const randomNumber = Math.floor(Math.random() * 16);
+ // Set the UUID version to 4 in the 13th position
+ if (i === 12) {
+ uuid += "4";
+ }
+ else if (i === 16) {
+ // Set the UUID variant to "10" in the 17th position
+ uuid += (randomNumber & 0x3) | 0x8;
+ }
+ else {
+ // Add a random hexadecimal digit to the UUID string
+ uuid += randomNumber.toString(16);
+ }
+ // Add hyphens to the UUID string at the appropriate positions
+ if (i === 7 || i === 11 || i === 15 || i === 19) {
+ uuid += "-";
+ }
+ }
+ return uuid;
+}
+
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+var _a$1;
+// NOTE: This is a workaround until we can use `globalThis.crypto.randomUUID` in Node.js 19+.
+let uuidFunction = typeof ((_a$1 = globalThis === null || globalThis === void 0 ? void 0 : globalThis.crypto) === null || _a$1 === void 0 ? void 0 : _a$1.randomUUID) === "function"
+ ? globalThis.crypto.randomUUID.bind(globalThis.crypto)
+ : crypto.randomUUID;
+// Not defined in earlier versions of Node.js 14
+if (!uuidFunction) {
+ uuidFunction = generateUUID;
+}
+/**
+ * Generated Universally Unique Identifier
+ *
+ * @returns RFC4122 v4 UUID.
+ */
+function randomUUID() {
+ return uuidFunction();
+}
+
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+var _a, _b, _c, _d;
+/**
+ * A constant that indicates whether the environment the code is running is a Web Browser.
+ */
+// eslint-disable-next-line @azure/azure-sdk/ts-no-window
+const isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined";
+/**
+ * A constant that indicates whether the environment the code is running is a Web Worker.
+ */
+const isWebWorker = typeof self === "object" &&
+ typeof (self === null || self === void 0 ? void 0 : self.importScripts) === "function" &&
+ (((_a = self.constructor) === null || _a === void 0 ? void 0 : _a.name) === "DedicatedWorkerGlobalScope" ||
+ ((_b = self.constructor) === null || _b === void 0 ? void 0 : _b.name) === "ServiceWorkerGlobalScope" ||
+ ((_c = self.constructor) === null || _c === void 0 ? void 0 : _c.name) === "SharedWorkerGlobalScope");
+/**
+ * A constant that indicates whether the environment the code is running is Deno.
+ */
+const isDeno = typeof Deno !== "undefined" &&
+ typeof Deno.version !== "undefined" &&
+ typeof Deno.version.deno !== "undefined";
+/**
+ * A constant that indicates whether the environment the code is running is Node.JS.
+ */
+const isNode = typeof process !== "undefined" &&
+ Boolean(process.version) &&
+ Boolean((_d = process.versions) === null || _d === void 0 ? void 0 : _d.node) &&
+ // Deno thought it was a good idea to spoof process.versions.node, see https://deno.land/std@0.177.0/node/process.ts?s=versions
+ !isDeno;
+/**
+ * A constant that indicates whether the environment the code is running is Bun.sh.
+ */
+const isBun = typeof Bun !== "undefined" && typeof Bun.version !== "undefined";
+/**
+ * A constant that indicates whether the environment the code is running is in React-Native.
+ */
+// https://github.com/facebook/react-native/blob/main/packages/react-native/Libraries/Core/setUpNavigator.js
+const isReactNative = typeof navigator !== "undefined" && (navigator === null || navigator === void 0 ? void 0 : navigator.product) === "ReactNative";
+
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+/**
+ * The helper that transforms bytes with specific character encoding into string
+ * @param bytes - the uint8array bytes
+ * @param format - the format we use to encode the byte
+ * @returns a string of the encoded string
+ */
+function uint8ArrayToString(bytes, format) {
+ return Buffer.from(bytes).toString(format);
+}
+/**
+ * The helper that transforms string to specific character encoded bytes array.
+ * @param value - the string to be converted
+ * @param format - the format we use to decode the value
+ * @returns a uint8array
+ */
+function stringToUint8Array(value, format) {
+ return Buffer.from(value, format);
+}
+
+exports.cancelablePromiseRace = cancelablePromiseRace;
+exports.computeSha256Hash = computeSha256Hash;
+exports.computeSha256Hmac = computeSha256Hmac;
+exports.createAbortablePromise = createAbortablePromise;
+exports.delay = delay;
+exports.getErrorMessage = getErrorMessage;
+exports.getRandomIntegerInclusive = getRandomIntegerInclusive;
+exports.isBrowser = isBrowser;
+exports.isBun = isBun;
+exports.isDefined = isDefined;
+exports.isDeno = isDeno;
+exports.isError = isError;
+exports.isNode = isNode;
+exports.isObject = isObject;
+exports.isObjectWithProperties = isObjectWithProperties;
+exports.isReactNative = isReactNative;
+exports.isWebWorker = isWebWorker;
+exports.objectHasProperty = objectHasProperty;
+exports.randomUUID = randomUUID;
+exports.stringToUint8Array = stringToUint8Array;
+exports.uint8ArrayToString = uint8ArrayToString;
+//# sourceMappingURL=index.js.map
+
+
/***/ }),
/***/ 3233:
@@ -15982,14 +17039,16 @@ exports.setSpanContext = setSpanContext;
Object.defineProperty(exports, "__esModule", ({ value: true }));
-function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
+var os = __nccwpck_require__(2037);
+var util = __nccwpck_require__(3837);
-var util = _interopDefault(__nccwpck_require__(1669));
-var os = __nccwpck_require__(2087);
+function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
+
+var util__default = /*#__PURE__*/_interopDefaultLegacy(util);
// Copyright (c) Microsoft Corporation.
function log(message, ...args) {
- process.stderr.write(`${util.format(message, ...args)}${os.EOL}`);
+ process.stderr.write(`${util__default["default"].format(message, ...args)}${os.EOL}`);
}
// Copyright (c) Microsoft Corporation.
@@ -16007,7 +17066,7 @@ const debugObj = Object.assign((namespace) => {
enable,
enabled,
disable,
- log
+ log,
});
function enable(namespaces) {
enabledString = namespaces;
@@ -16054,7 +17113,7 @@ function createDebugger(namespace) {
destroy,
log: debugObj.log,
namespace,
- extend
+ extend,
});
function debug(...args) {
if (!newDebugger.enabled) {
@@ -16081,6 +17140,7 @@ function extend(namespace) {
newDebugger.log = this.log;
return newDebugger;
}
+var debug = debugObj;
// Copyright (c) Microsoft Corporation.
const registeredLoggers = new Set();
@@ -16091,9 +17151,9 @@ let azureLogLevel;
* By default, logs are sent to stderr.
* Override the `log` method to redirect logs to another location.
*/
-const AzureLogger = debugObj("azure");
+const AzureLogger = debug("azure");
AzureLogger.log = (...args) => {
- debugObj.log(...args);
+ debug.log(...args);
};
const AZURE_LOG_LEVELS = ["verbose", "info", "warning", "error"];
if (logLevelFromEnv) {
@@ -16106,7 +17166,7 @@ if (logLevelFromEnv) {
}
}
/**
- * Immediately enables logging at the specified log level.
+ * Immediately enables logging at the specified log level. If no level is specified, logging is disabled.
* @param level - The log level to enable for logging.
* Options from most verbose to least verbose are:
* - verbose
@@ -16125,7 +17185,7 @@ function setLogLevel(level) {
enabledNamespaces.push(logger.namespace);
}
}
- debugObj.enable(enabledNamespaces.join(","));
+ debug.enable(enabledNamespaces.join(","));
}
/**
* Retrieves the currently specified log level.
@@ -16137,7 +17197,7 @@ const levelMap = {
verbose: 400,
info: 300,
warning: 200,
- error: 100
+ error: 100,
};
/**
* Creates a logger for use by the Azure SDKs that inherits from `AzureLogger`.
@@ -16151,7 +17211,7 @@ function createClientLogger(namespace) {
error: createLogger(clientRootLogger, "error"),
warning: createLogger(clientRootLogger, "warning"),
info: createLogger(clientRootLogger, "info"),
- verbose: createLogger(clientRootLogger, "verbose")
+ verbose: createLogger(clientRootLogger, "verbose"),
};
}
function patchLogMethod(parent, child) {
@@ -16161,23 +17221,18 @@ function patchLogMethod(parent, child) {
}
function createLogger(parent, level) {
const logger = Object.assign(parent.extend(level), {
- level
+ level,
});
patchLogMethod(parent, logger);
if (shouldEnable(logger)) {
- const enabledNamespaces = debugObj.disable();
- debugObj.enable(enabledNamespaces + "," + logger.namespace);
+ const enabledNamespaces = debug.disable();
+ debug.enable(enabledNamespaces + "," + logger.namespace);
}
registeredLoggers.add(logger);
return logger;
}
function shouldEnable(logger) {
- if (azureLogLevel && levelMap[logger.level] <= levelMap[azureLogLevel]) {
- return true;
- }
- else {
- return false;
- }
+ return Boolean(azureLogLevel && levelMap[logger.level] <= levelMap[azureLogLevel]);
}
function isAzureLogLevel(logLevel) {
return AZURE_LOG_LEVELS.includes(logLevel);
@@ -16201,18 +17256,18 @@ exports.setLogLevel = setLogLevel;
Object.defineProperty(exports, "__esModule", ({ value: true }));
var coreHttp = __nccwpck_require__(4607);
-var tslib = __nccwpck_require__(6524);
+var tslib = __nccwpck_require__(4351);
var coreTracing = __nccwpck_require__(4175);
var logger$1 = __nccwpck_require__(3233);
var abortController = __nccwpck_require__(2557);
-var os = __nccwpck_require__(2087);
-var crypto = __nccwpck_require__(6417);
-var stream = __nccwpck_require__(2413);
+var os = __nccwpck_require__(2037);
+var crypto = __nccwpck_require__(6113);
+var stream = __nccwpck_require__(2781);
__nccwpck_require__(4559);
var coreLro = __nccwpck_require__(7094);
-var events = __nccwpck_require__(8614);
-var fs = __nccwpck_require__(5747);
-var util = __nccwpck_require__(1669);
+var events = __nccwpck_require__(2361);
+var fs = __nccwpck_require__(7147);
+var util = __nccwpck_require__(3837);
function _interopNamespace(e) {
if (e && e.__esModule) return e;
@@ -17286,6 +18341,7 @@ const BlobName = {
content: {
serializedName: "content",
xmlName: "content",
+ xmlIsMsText: true,
type: {
name: "String"
}
@@ -17514,7 +18570,8 @@ const BlobPropertiesInternal = {
"P80",
"Hot",
"Cool",
- "Archive"
+ "Archive",
+ "Cold"
]
}
},
@@ -17532,7 +18589,8 @@ const BlobPropertiesInternal = {
name: "Enum",
allowedValues: [
"rehydrate-pending-to-hot",
- "rehydrate-pending-to-cool"
+ "rehydrate-pending-to-cool",
+ "rehydrate-pending-to-cold"
]
}
},
@@ -20013,6 +21071,13 @@ const BlobDownloadHeaders = {
name: "DateTimeRfc1123"
}
},
+ createdOn: {
+ serializedName: "x-ms-creation-time",
+ xmlName: "x-ms-creation-time",
+ type: {
+ name: "DateTimeRfc1123"
+ }
+ },
metadata: {
serializedName: "x-ms-meta",
xmlName: "x-ms-meta",
@@ -24695,7 +25760,7 @@ const timeoutInSeconds = {
const version = {
parameterPath: "version",
mapper: {
- defaultValue: "2021-08-06",
+ defaultValue: "2023-08-03",
isConstant: true,
serializedName: "x-ms-version",
type: {
@@ -25560,7 +26625,8 @@ const tier = {
"P80",
"Hot",
"Cool",
- "Archive"
+ "Archive",
+ "Cold"
]
}
}
@@ -25787,7 +26853,8 @@ const tier1 = {
"P80",
"Hot",
"Cool",
- "Archive"
+ "Archive",
+ "Cold"
]
}
}
@@ -29296,6 +30363,7 @@ const uploadOperationSpec = {
blobTagsString,
legalHold1,
transactionalContentMD5,
+ transactionalContentCrc64,
contentType1,
accept2,
blobType2
@@ -29523,14 +30591,15 @@ const logger = logger$1.createClientLogger("storage-blob");
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
-const SDK_VERSION = "12.11.0";
-const SERVICE_VERSION = "2021-08-06";
+const SDK_VERSION = "12.16.0";
+const SERVICE_VERSION = "2023-08-03";
const BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES = 256 * 1024 * 1024; // 256MB
const BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES = 4000 * 1024 * 1024; // 4000MB
const BLOCK_BLOB_MAX_BLOCKS = 50000;
const DEFAULT_BLOCK_BUFFER_SIZE_BYTES = 8 * 1024 * 1024; // 8MB
const DEFAULT_BLOB_DOWNLOAD_BLOCK_BYTES = 4 * 1024 * 1024; // 4MB
const DEFAULT_MAX_DOWNLOAD_RETRY_REQUESTS = 5;
+const REQUEST_TIMEOUT = 100 * 1000; // In ms
/**
* The OAuth scope to use with Azure Storage.
*/
@@ -29718,6 +30787,30 @@ const StorageBlobLoggingAllowedQueryParameters = [
];
const BlobUsesCustomerSpecifiedEncryptionMsg = "BlobUsesCustomerSpecifiedEncryption";
const BlobDoesNotUseCustomerSpecifiedEncryption = "BlobDoesNotUseCustomerSpecifiedEncryption";
+/// List of ports used for path style addressing.
+/// Path style addressing means that storage account is put in URI's Path segment in instead of in host.
+const PathStylePorts = [
+ "10000",
+ "10001",
+ "10002",
+ "10003",
+ "10004",
+ "10100",
+ "10101",
+ "10102",
+ "10103",
+ "10104",
+ "11000",
+ "11001",
+ "11002",
+ "11003",
+ "11004",
+ "11100",
+ "11101",
+ "11102",
+ "11103",
+ "11104",
+];
// Copyright (c) Microsoft Corporation.
/**
@@ -29863,7 +30956,11 @@ function extractConnectionStringParts(connectionString) {
else {
// SAS connection string
const accountSas = getValueInConnString(connectionString, "SharedAccessSignature");
- const accountName = getAccountNameFromUrl(blobEndpoint);
+ let accountName = getValueInConnString(connectionString, "AccountName");
+ // if accountName is empty, try to read it from BlobEndpoint
+ if (!accountName) {
+ accountName = getAccountNameFromUrl(blobEndpoint);
+ }
if (!blobEndpoint) {
throw new Error("Invalid BlobEndpoint in the provided SAS Connection String");
}
@@ -29898,7 +30995,8 @@ function appendToURLPath(url, name) {
let path = urlParsed.getPath();
path = path ? (path.endsWith("/") ? `${path}${name}` : `${path}/${name}`) : name;
urlParsed.setPath(path);
- return urlParsed.toString();
+ const normalizedUrl = new URL(urlParsed.toString());
+ return normalizedUrl.toString();
}
/**
* Set URL parameter name and value. If name exists in URL parameters, old value
@@ -30156,10 +31254,11 @@ function isIpEndpointStyle(parsedUrl) {
}
const host = parsedUrl.getHost() + (parsedUrl.getPort() === undefined ? "" : ":" + parsedUrl.getPort());
// Case 1: Ipv6, use a broad regex to find out candidates whose host contains two ':'.
- // Case 2: localhost(:port), use broad regex to match port part.
+ // Case 2: localhost(:port) or host.docker.internal, use broad regex to match port part.
// Case 3: Ipv4, use broad regex which just check if host contains Ipv4.
// For valid host please refer to https://man7.org/linux/man-pages/man7/hostname.7.html.
- return /^.*:.*:.*$|^localhost(:[0-9]+)?$|^(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])(\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])){3}(:[0-9]+)?$/.test(host);
+ return (/^.*:.*:.*$|^(localhost|host.docker.internal)(:[0-9]+)?$|^(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])(\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])){3}(:[0-9]+)?$/.test(host) ||
+ (parsedUrl.getPort() !== undefined && PathStylePorts.includes(parsedUrl.getPort())));
}
/**
* Convert Tags to encoded string.
@@ -30334,9 +31433,7 @@ function ConvertInternalResponseOfListBlobHierarchy(internalResponse) {
var _a;
return Object.assign(Object.assign({}, internalResponse), { segment: {
blobPrefixes: (_a = internalResponse.segment.blobPrefixes) === null || _a === void 0 ? void 0 : _a.map((blobPrefixInternal) => {
- const blobPrefix = {
- name: BlobNameToString(blobPrefixInternal.name),
- };
+ const blobPrefix = Object.assign(Object.assign({}, blobPrefixInternal), { name: BlobNameToString(blobPrefixInternal.name) });
return blobPrefix;
}),
blobItems: internalResponse.segment.blobItems.map((blobItemInteral) => {
@@ -30345,296 +31442,6 @@ function ConvertInternalResponseOfListBlobHierarchy(internalResponse) {
}),
} });
}
-function decodeBase64String(value) {
- if (coreHttp.isNode) {
- return Buffer.from(value, "base64");
- }
- else {
- const byteString = atob(value);
- const arr = new Uint8Array(byteString.length);
- for (let i = 0; i < byteString.length; i++) {
- arr[i] = byteString.charCodeAt(i);
- }
- return arr;
- }
-}
-function ParseBoolean(content) {
- if (content === undefined)
- return undefined;
- if (content === "true")
- return true;
- if (content === "false")
- return false;
- return undefined;
-}
-function ParseBlobName(blobNameInXML) {
- if (blobNameInXML["$"] !== undefined && blobNameInXML["#"] !== undefined) {
- return {
- encoded: ParseBoolean(blobNameInXML["$"]["Encoded"]),
- content: blobNameInXML["#"],
- };
- }
- else {
- return {
- encoded: false,
- content: blobNameInXML,
- };
- }
-}
-function ParseBlobProperties(blobPropertiesInXML) {
- const blobProperties = blobPropertiesInXML;
- if (blobPropertiesInXML["Creation-Time"]) {
- blobProperties.createdOn = new Date(blobPropertiesInXML["Creation-Time"]);
- delete blobProperties["Creation-Time"];
- }
- if (blobPropertiesInXML["Last-Modified"]) {
- blobProperties.lastModified = new Date(blobPropertiesInXML["Last-Modified"]);
- delete blobProperties["Last-Modified"];
- }
- if (blobPropertiesInXML["Etag"]) {
- blobProperties.etag = blobPropertiesInXML["Etag"];
- delete blobProperties["Etag"];
- }
- if (blobPropertiesInXML["Content-Length"]) {
- blobProperties.contentLength = parseFloat(blobPropertiesInXML["Content-Length"]);
- delete blobProperties["Content-Length"];
- }
- if (blobPropertiesInXML["Content-Type"]) {
- blobProperties.contentType = blobPropertiesInXML["Content-Type"];
- delete blobProperties["Content-Type"];
- }
- if (blobPropertiesInXML["Content-Encoding"]) {
- blobProperties.contentEncoding = blobPropertiesInXML["Content-Encoding"];
- delete blobProperties["Content-Encoding"];
- }
- if (blobPropertiesInXML["Content-Language"]) {
- blobProperties.contentLanguage = blobPropertiesInXML["Content-Language"];
- delete blobProperties["Content-Language"];
- }
- if (blobPropertiesInXML["Content-MD5"]) {
- blobProperties.contentMD5 = decodeBase64String(blobPropertiesInXML["Content-MD5"]);
- delete blobProperties["Content-MD5"];
- }
- if (blobPropertiesInXML["Content-Disposition"]) {
- blobProperties.contentDisposition = blobPropertiesInXML["Content-Disposition"];
- delete blobProperties["Content-Disposition"];
- }
- if (blobPropertiesInXML["Cache-Control"]) {
- blobProperties.cacheControl = blobPropertiesInXML["Cache-Control"];
- delete blobProperties["Cache-Control"];
- }
- if (blobPropertiesInXML["x-ms-blob-sequence-number"]) {
- blobProperties.blobSequenceNumber = parseFloat(blobPropertiesInXML["x-ms-blob-sequence-number"]);
- delete blobProperties["x-ms-blob-sequence-number"];
- }
- if (blobPropertiesInXML["BlobType"]) {
- blobProperties.blobType = blobPropertiesInXML["BlobType"];
- delete blobProperties["BlobType"];
- }
- if (blobPropertiesInXML["LeaseStatus"]) {
- blobProperties.leaseStatus = blobPropertiesInXML["LeaseStatus"];
- delete blobProperties["LeaseStatus"];
- }
- if (blobPropertiesInXML["LeaseState"]) {
- blobProperties.leaseState = blobPropertiesInXML["LeaseState"];
- delete blobProperties["LeaseState"];
- }
- if (blobPropertiesInXML["LeaseDuration"]) {
- blobProperties.leaseDuration = blobPropertiesInXML["LeaseDuration"];
- delete blobProperties["LeaseDuration"];
- }
- if (blobPropertiesInXML["CopyId"]) {
- blobProperties.copyId = blobPropertiesInXML["CopyId"];
- delete blobProperties["CopyId"];
- }
- if (blobPropertiesInXML["CopyStatus"]) {
- blobProperties.copyStatus = blobPropertiesInXML["CopyStatus"];
- delete blobProperties["CopyStatus"];
- }
- if (blobPropertiesInXML["CopySource"]) {
- blobProperties.copySource = blobPropertiesInXML["CopySource"];
- delete blobProperties["CopySource"];
- }
- if (blobPropertiesInXML["CopyProgress"]) {
- blobProperties.copyProgress = blobPropertiesInXML["CopyProgress"];
- delete blobProperties["CopyProgress"];
- }
- if (blobPropertiesInXML["CopyCompletionTime"]) {
- blobProperties.copyCompletedOn = new Date(blobPropertiesInXML["CopyCompletionTime"]);
- delete blobProperties["CopyCompletionTime"];
- }
- if (blobPropertiesInXML["CopyStatusDescription"]) {
- blobProperties.copyStatusDescription = blobPropertiesInXML["CopyStatusDescription"];
- delete blobProperties["CopyStatusDescription"];
- }
- if (blobPropertiesInXML["ServerEncrypted"]) {
- blobProperties.serverEncrypted = ParseBoolean(blobPropertiesInXML["ServerEncrypted"]);
- delete blobProperties["ServerEncrypted"];
- }
- if (blobPropertiesInXML["IncrementalCopy"]) {
- blobProperties.incrementalCopy = ParseBoolean(blobPropertiesInXML["IncrementalCopy"]);
- delete blobProperties["IncrementalCopy"];
- }
- if (blobPropertiesInXML["DestinationSnapshot"]) {
- blobProperties.destinationSnapshot = blobPropertiesInXML["DestinationSnapshot"];
- delete blobProperties["DestinationSnapshot"];
- }
- if (blobPropertiesInXML["DeletedTime"]) {
- blobProperties.deletedOn = new Date(blobPropertiesInXML["DeletedTime"]);
- delete blobProperties["DeletedTime"];
- }
- if (blobPropertiesInXML["RemainingRetentionDays"]) {
- blobProperties.remainingRetentionDays = parseFloat(blobPropertiesInXML["RemainingRetentionDays"]);
- delete blobProperties["RemainingRetentionDays"];
- }
- if (blobPropertiesInXML["AccessTier"]) {
- blobProperties.accessTier = blobPropertiesInXML["AccessTier"];
- delete blobProperties["AccessTier"];
- }
- if (blobPropertiesInXML["AccessTierInferred"]) {
- blobProperties.accessTierInferred = ParseBoolean(blobPropertiesInXML["AccessTierInferred"]);
- delete blobProperties["AccessTierInferred"];
- }
- if (blobPropertiesInXML["ArchiveStatus"]) {
- blobProperties.archiveStatus = blobPropertiesInXML["ArchiveStatus"];
- delete blobProperties["ArchiveStatus"];
- }
- if (blobPropertiesInXML["CustomerProvidedKeySha256"]) {
- blobProperties.customerProvidedKeySha256 = blobPropertiesInXML["CustomerProvidedKeySha256"];
- delete blobProperties["CustomerProvidedKeySha256"];
- }
- if (blobPropertiesInXML["EncryptionScope"]) {
- blobProperties.encryptionScope = blobPropertiesInXML["EncryptionScope"];
- delete blobProperties["EncryptionScope"];
- }
- if (blobPropertiesInXML["AccessTierChangeTime"]) {
- blobProperties.accessTierChangedOn = new Date(blobPropertiesInXML["AccessTierChangeTime"]);
- delete blobProperties["AccessTierChangeTime"];
- }
- if (blobPropertiesInXML["TagCount"]) {
- blobProperties.tagCount = parseFloat(blobPropertiesInXML["TagCount"]);
- delete blobProperties["TagCount"];
- }
- if (blobPropertiesInXML["Expiry-Time"]) {
- blobProperties.expiresOn = new Date(blobPropertiesInXML["Expiry-Time"]);
- delete blobProperties["Expiry-Time"];
- }
- if (blobPropertiesInXML["Sealed"]) {
- blobProperties.isSealed = ParseBoolean(blobPropertiesInXML["Sealed"]);
- delete blobProperties["Sealed"];
- }
- if (blobPropertiesInXML["RehydratePriority"]) {
- blobProperties.rehydratePriority = blobPropertiesInXML["RehydratePriority"];
- delete blobProperties["RehydratePriority"];
- }
- if (blobPropertiesInXML["LastAccessTime"]) {
- blobProperties.lastAccessedOn = new Date(blobPropertiesInXML["LastAccessTime"]);
- delete blobProperties["LastAccessTime"];
- }
- if (blobPropertiesInXML["ImmutabilityPolicyUntilDate"]) {
- blobProperties.immutabilityPolicyExpiresOn = new Date(blobPropertiesInXML["ImmutabilityPolicyUntilDate"]);
- delete blobProperties["ImmutabilityPolicyUntilDate"];
- }
- if (blobPropertiesInXML["ImmutabilityPolicyMode"]) {
- blobProperties.immutabilityPolicyMode = blobPropertiesInXML["ImmutabilityPolicyMode"];
- delete blobProperties["ImmutabilityPolicyMode"];
- }
- if (blobPropertiesInXML["LegalHold"]) {
- blobProperties.legalHold = ParseBoolean(blobPropertiesInXML["LegalHold"]);
- delete blobProperties["LegalHold"];
- }
- return blobProperties;
-}
-function ParseBlobItem(blobInXML) {
- const blobItem = blobInXML;
- blobItem.properties = ParseBlobProperties(blobInXML["Properties"]);
- delete blobItem["Properties"];
- blobItem.name = ParseBlobName(blobInXML["Name"]);
- delete blobItem["Name"];
- blobItem.deleted = ParseBoolean(blobInXML["Deleted"]);
- delete blobItem["Deleted"];
- if (blobInXML["Snapshot"]) {
- blobItem.snapshot = blobInXML["Snapshot"];
- delete blobItem["Snapshot"];
- }
- if (blobInXML["VersionId"]) {
- blobItem.versionId = blobInXML["VersionId"];
- delete blobItem["VersionId"];
- }
- if (blobInXML["IsCurrentVersion"]) {
- blobItem.isCurrentVersion = ParseBoolean(blobInXML["IsCurrentVersion"]);
- delete blobItem["IsCurrentVersion"];
- }
- if (blobInXML["Metadata"]) {
- blobItem.metadata = blobInXML["Metadata"];
- delete blobItem["Metadata"];
- }
- if (blobInXML["Tags"]) {
- blobItem.blobTags = ParseBlobTags(blobInXML["Tags"]);
- delete blobItem["Tags"];
- }
- if (blobInXML["OrMetadata"]) {
- blobItem.objectReplicationMetadata = blobInXML["OrMetadata"];
- delete blobItem["OrMetadata"];
- }
- if (blobInXML["HasVersionsOnly"]) {
- blobItem.hasVersionsOnly = ParseBoolean(blobInXML["HasVersionsOnly"]);
- delete blobItem["HasVersionsOnly"];
- }
- return blobItem;
-}
-function ParseBlobPrefix(blobPrefixInXML) {
- return {
- name: ParseBlobName(blobPrefixInXML["Name"]),
- };
-}
-function ParseBlobTag(blobTagInXML) {
- return {
- key: blobTagInXML["Key"],
- value: blobTagInXML["Value"],
- };
-}
-function ParseBlobTags(blobTagsInXML) {
- if (blobTagsInXML === undefined ||
- blobTagsInXML["TagSet"] === undefined ||
- blobTagsInXML["TagSet"]["Tag"] === undefined) {
- return undefined;
- }
- const blobTagSet = [];
- if (blobTagsInXML["TagSet"]["Tag"] instanceof Array) {
- blobTagsInXML["TagSet"]["Tag"].forEach((blobTagInXML) => {
- blobTagSet.push(ParseBlobTag(blobTagInXML));
- });
- }
- else {
- blobTagSet.push(ParseBlobTag(blobTagsInXML["TagSet"]["Tag"]));
- }
- return { blobTagSet: blobTagSet };
-}
-function ProcessBlobItems(blobArrayInXML) {
- const blobItems = [];
- if (blobArrayInXML instanceof Array) {
- blobArrayInXML.forEach((blobInXML) => {
- blobItems.push(ParseBlobItem(blobInXML));
- });
- }
- else {
- blobItems.push(ParseBlobItem(blobArrayInXML));
- }
- return blobItems;
-}
-function ProcessBlobPrefixes(blobPrefixesInXML) {
- const blobPrefixes = [];
- if (blobPrefixesInXML instanceof Array) {
- blobPrefixesInXML.forEach((blobPrefixInXML) => {
- blobPrefixes.push(ParseBlobPrefix(blobPrefixInXML));
- });
- }
- else {
- blobPrefixes.push(ParseBlobPrefix(blobPrefixesInXML));
- }
- return blobPrefixes;
-}
function* ExtractPageRangeInfoItems(getPageRangesSegment) {
let pageRange = [];
let clearRange = [];
@@ -30677,6 +31484,16 @@ function* ExtractPageRangeInfoItems(getPageRangesSegment) {
};
}
}
+/**
+ * Escape the blobName but keep path separator ('/').
+ */
+function EscapePath(blobName) {
+ const split = blobName.split("/");
+ for (let i = 0; i < split.length; i++) {
+ split[i] = encodeURIComponent(split[i]);
+ }
+ return split.join("/");
+}
// Copyright (c) Microsoft Corporation.
/**
@@ -31635,7 +32452,7 @@ class StorageSharedKeyCredential extends Credential {
* Changes may cause incorrect behavior and will be lost if the code is regenerated.
*/
const packageName = "azure-storage-blob";
-const packageVersion = "12.11.0";
+const packageVersion = "12.16.0";
class StorageClientContext extends coreHttp__namespace.ServiceClient {
/**
* Initializes a new instance of the StorageClientContext class.
@@ -31661,7 +32478,7 @@ class StorageClientContext extends coreHttp__namespace.ServiceClient {
// Parameter assignments
this.url = url;
// Assigning values to Constant parameters
- this.version = options.version || "2021-08-06";
+ this.version = options.version || "2023-08-03";
}
}
@@ -33590,6 +34407,14 @@ class BlobDownloadResponse {
get lastAccessed() {
return this.originalResponse.lastAccessed;
}
+ /**
+ * Returns the date and time the blob was created.
+ *
+ * @readonly
+ */
+ get createdOn() {
+ return this.originalResponse.createdOn;
+ }
/**
* A name-value pair
* to associate with a file storage object.
@@ -34020,6 +34845,7 @@ class AvroUnionType extends AvroType {
this._types = types;
}
async read(stream, options = {}) {
+ // eslint-disable-line @typescript-eslint/ban-types
const typeIndex = await AvroParser.readInt(stream, options);
return this._types[typeIndex].read(stream, options);
}
@@ -34743,6 +35569,10 @@ exports.BlockBlobTier = void 0;
* Optimized for storing data that is infrequently accessed and stored for at least 30 days.
*/
BlockBlobTier["Cool"] = "Cool";
+ /**
+ * Optimized for storing data that is rarely accessed.
+ */
+ BlockBlobTier["Cold"] = "Cold";
/**
* Optimized for storing data that is rarely accessed and stored for at least 180 days
* with flexible latency requirements (on the order of hours).
@@ -35206,7 +36036,7 @@ class BuffersStream extends stream.Readable {
* maxBufferLength is max size of each buffer in the pooled buffers.
*/
// Can't use import as Typescript doesn't recognize "buffer".
-const maxBufferLength = __nccwpck_require__(4293).constants.MAX_LENGTH;
+const maxBufferLength = (__nccwpck_require__(4300).constants.MAX_LENGTH);
/**
* This class provides a buffer container which conceptually has no hard size limit.
* It accepts a capacity, an array of input buffers and the total length of input data.
@@ -35549,8 +36379,10 @@ async function streamToBuffer(stream, buffer, offset, end, encoding) {
let pos = 0; // Position in stream
const count = end - offset; // Total amount of data needed in stream
return new Promise((resolve, reject) => {
+ const timeout = setTimeout(() => reject(new Error(`The operation cannot be completed in timeout.`)), REQUEST_TIMEOUT);
stream.on("readable", () => {
if (pos >= count) {
+ clearTimeout(timeout);
resolve();
return;
}
@@ -35567,12 +36399,16 @@ async function streamToBuffer(stream, buffer, offset, end, encoding) {
pos += chunkLength;
});
stream.on("end", () => {
+ clearTimeout(timeout);
if (pos < count) {
reject(new Error(`Stream drains before getting enough data needed. Data read: ${pos}, data need: ${count}`));
}
resolve();
});
- stream.on("error", reject);
+ stream.on("error", (msg) => {
+ clearTimeout(timeout);
+ reject(msg);
+ });
});
}
/**
@@ -35668,6 +36504,9 @@ class BlobClient extends StorageClient {
// (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions)
// The second parameter is undefined. Use anonymous credential.
url = urlOrConnectionString;
+ if (blobNameOrOptions && typeof blobNameOrOptions !== "string") {
+ options = blobNameOrOptions;
+ }
pipeline = newPipeline(new AnonymousCredential(), options);
}
else if (credentialOrPipelineOrContainerName &&
@@ -36338,7 +37177,7 @@ class BlobClient extends StorageClient {
sourceIfModifiedSince: options.sourceConditions.ifModifiedSince,
sourceIfNoneMatch: options.sourceConditions.ifNoneMatch,
sourceIfUnmodifiedSince: options.sourceConditions.ifUnmodifiedSince,
- }, sourceContentMD5: options.sourceContentMD5, copySourceAuthorization: httpAuthorizationToString(options.sourceAuthorization), blobTagsString: toBlobTagsString(options.tags), immutabilityPolicyExpiry: (_b = options.immutabilityPolicy) === null || _b === void 0 ? void 0 : _b.expiriesOn, immutabilityPolicyMode: (_c = options.immutabilityPolicy) === null || _c === void 0 ? void 0 : _c.policyMode, legalHold: options.legalHold, encryptionScope: options.encryptionScope, copySourceTags: options.copySourceTags }, convertTracingToRequestOptionsBase(updatedOptions)));
+ }, sourceContentMD5: options.sourceContentMD5, copySourceAuthorization: httpAuthorizationToString(options.sourceAuthorization), tier: toAccessTier(options.tier), blobTagsString: toBlobTagsString(options.tags), immutabilityPolicyExpiry: (_b = options.immutabilityPolicy) === null || _b === void 0 ? void 0 : _b.expiriesOn, immutabilityPolicyMode: (_c = options.immutabilityPolicy) === null || _c === void 0 ? void 0 : _c.policyMode, legalHold: options.legalHold, encryptionScope: options.encryptionScope, copySourceTags: options.copySourceTags }, convertTracingToRequestOptionsBase(updatedOptions)));
}
catch (e) {
span.setStatus({
@@ -36971,6 +37810,9 @@ class BlockBlobClient extends BlobClient {
// (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions)
// The second parameter is undefined. Use anonymous credential.
url = urlOrConnectionString;
+ if (blobNameOrOptions && typeof blobNameOrOptions !== "string") {
+ options = blobNameOrOptions;
+ }
pipeline = newPipeline(new AnonymousCredential(), options);
}
else if (credentialOrPipelineOrContainerName &&
@@ -39064,6 +39906,7 @@ class ContainerClient extends StorageClient {
* Creates a new container under the specified account. If the container with
* the same name already exists, the operation fails.
* @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-container
+ * Naming rules: @see https://learn.microsoft.com/rest/api/storageservices/naming-and-referencing-containers--blobs--and-metadata
*
* @param options - Options to Container Create operation.
*
@@ -39098,6 +39941,7 @@ class ContainerClient extends StorageClient {
* Creates a new container under the specified account. If the container with
* the same name already exists, it is not changed.
* @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-container
+ * Naming rules: @see https://learn.microsoft.com/rest/api/storageservices/naming-and-referencing-containers--blobs--and-metadata
*
* @param options -
*/
@@ -39169,7 +40013,7 @@ class ContainerClient extends StorageClient {
* @returns A new BlobClient object for the given blob name.
*/
getBlobClient(blobName) {
- return new BlobClient(appendToURLPath(this.url, encodeURIComponent(blobName)), this.pipeline);
+ return new BlobClient(appendToURLPath(this.url, EscapePath(blobName)), this.pipeline);
}
/**
* Creates an {@link AppendBlobClient}
@@ -39177,7 +40021,7 @@ class ContainerClient extends StorageClient {
* @param blobName - An append blob name
*/
getAppendBlobClient(blobName) {
- return new AppendBlobClient(appendToURLPath(this.url, encodeURIComponent(blobName)), this.pipeline);
+ return new AppendBlobClient(appendToURLPath(this.url, EscapePath(blobName)), this.pipeline);
}
/**
* Creates a {@link BlockBlobClient}
@@ -39195,7 +40039,7 @@ class ContainerClient extends StorageClient {
* ```
*/
getBlockBlobClient(blobName) {
- return new BlockBlobClient(appendToURLPath(this.url, encodeURIComponent(blobName)), this.pipeline);
+ return new BlockBlobClient(appendToURLPath(this.url, EscapePath(blobName)), this.pipeline);
}
/**
* Creates a {@link PageBlobClient}
@@ -39203,7 +40047,7 @@ class ContainerClient extends StorageClient {
* @param blobName - A page blob name
*/
getPageBlobClient(blobName) {
- return new PageBlobClient(appendToURLPath(this.url, encodeURIComponent(blobName)), this.pipeline);
+ return new PageBlobClient(appendToURLPath(this.url, EscapePath(blobName)), this.pipeline);
}
/**
* Returns all user-defined metadata and system properties for the specified
@@ -39535,10 +40379,6 @@ class ContainerClient extends StorageClient {
const { span, updatedOptions } = createSpan("ContainerClient-listBlobFlatSegment", options);
try {
const response = await this.containerContext.listBlobFlatSegment(Object.assign(Object.assign({ marker }, options), convertTracingToRequestOptionsBase(updatedOptions)));
- response.segment.blobItems = [];
- if (response.segment["Blob"] !== undefined) {
- response.segment.blobItems = ProcessBlobItems(response.segment["Blob"]);
- }
const wrappedResponse = Object.assign(Object.assign({}, response), { _response: Object.assign(Object.assign({}, response._response), { parsedBody: ConvertInternalResponseOfListBlobFlat(response._response.parsedBody) }), segment: Object.assign(Object.assign({}, response.segment), { blobItems: response.segment.blobItems.map((blobItemInteral) => {
const blobItem = Object.assign(Object.assign({}, blobItemInteral), { name: BlobNameToString(blobItemInteral.name), tags: toTags(blobItemInteral.blobTags), objectReplicationSourceProperties: parseObjectReplicationRecord(blobItemInteral.objectReplicationMetadata) });
return blobItem;
@@ -39572,21 +40412,11 @@ class ContainerClient extends StorageClient {
const { span, updatedOptions } = createSpan("ContainerClient-listBlobHierarchySegment", options);
try {
const response = await this.containerContext.listBlobHierarchySegment(delimiter, Object.assign(Object.assign({ marker }, options), convertTracingToRequestOptionsBase(updatedOptions)));
- response.segment.blobItems = [];
- if (response.segment["Blob"] !== undefined) {
- response.segment.blobItems = ProcessBlobItems(response.segment["Blob"]);
- }
- response.segment.blobPrefixes = [];
- if (response.segment["BlobPrefix"] !== undefined) {
- response.segment.blobPrefixes = ProcessBlobPrefixes(response.segment["BlobPrefix"]);
- }
const wrappedResponse = Object.assign(Object.assign({}, response), { _response: Object.assign(Object.assign({}, response._response), { parsedBody: ConvertInternalResponseOfListBlobHierarchy(response._response.parsedBody) }), segment: Object.assign(Object.assign({}, response.segment), { blobItems: response.segment.blobItems.map((blobItemInteral) => {
const blobItem = Object.assign(Object.assign({}, blobItemInteral), { name: BlobNameToString(blobItemInteral.name), tags: toTags(blobItemInteral.blobTags), objectReplicationSourceProperties: parseObjectReplicationRecord(blobItemInteral.objectReplicationMetadata) });
return blobItem;
}), blobPrefixes: (_a = response.segment.blobPrefixes) === null || _a === void 0 ? void 0 : _a.map((blobPrefixInternal) => {
- const blobPrefix = {
- name: BlobNameToString(blobPrefixInternal.name),
- };
+ const blobPrefix = Object.assign(Object.assign({}, blobPrefixInternal), { name: BlobNameToString(blobPrefixInternal.name) });
return blobPrefix;
}) }) });
return wrappedResponse;
@@ -40791,7 +41621,7 @@ class BlobServiceClient extends StorageClient {
return new ContainerClient(appendToURLPath(this.url, encodeURIComponent(containerName)), this.pipeline);
}
/**
- * Create a Blob container.
+ * Create a Blob container. @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-container
*
* @param containerName - Name of the container to create.
* @param options - Options to configure Container Create operation.
@@ -41478,6 +42308,14 @@ class BlobServiceClient extends StorageClient {
}
}
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+/** Known values of {@link EncryptionAlgorithmType} that the service accepts. */
+exports.KnownEncryptionAlgorithmType = void 0;
+(function (KnownEncryptionAlgorithmType) {
+ KnownEncryptionAlgorithmType["AES256"] = "AES256";
+})(exports.KnownEncryptionAlgorithmType || (exports.KnownEncryptionAlgorithmType = {}));
+
Object.defineProperty(exports, "BaseRequestPolicy", ({
enumerable: true,
get: function () { return coreHttp.BaseRequestPolicy; }
@@ -41539,481 +42377,1626 @@ exports.newPipeline = newPipeline;
/***/ }),
-/***/ 6524:
-/***/ ((__unused_webpack_module, __webpack_exports__, __nccwpck_require__) => {
+/***/ 2856:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
-__nccwpck_require__.r(__webpack_exports__);
-/* harmony export */ __nccwpck_require__.d(__webpack_exports__, {
-/* harmony export */ "__extends": () => /* binding */ __extends,
-/* harmony export */ "__assign": () => /* binding */ __assign,
-/* harmony export */ "__rest": () => /* binding */ __rest,
-/* harmony export */ "__decorate": () => /* binding */ __decorate,
-/* harmony export */ "__param": () => /* binding */ __param,
-/* harmony export */ "__metadata": () => /* binding */ __metadata,
-/* harmony export */ "__awaiter": () => /* binding */ __awaiter,
-/* harmony export */ "__generator": () => /* binding */ __generator,
-/* harmony export */ "__createBinding": () => /* binding */ __createBinding,
-/* harmony export */ "__exportStar": () => /* binding */ __exportStar,
-/* harmony export */ "__values": () => /* binding */ __values,
-/* harmony export */ "__read": () => /* binding */ __read,
-/* harmony export */ "__spread": () => /* binding */ __spread,
-/* harmony export */ "__spreadArrays": () => /* binding */ __spreadArrays,
-/* harmony export */ "__spreadArray": () => /* binding */ __spreadArray,
-/* harmony export */ "__await": () => /* binding */ __await,
-/* harmony export */ "__asyncGenerator": () => /* binding */ __asyncGenerator,
-/* harmony export */ "__asyncDelegator": () => /* binding */ __asyncDelegator,
-/* harmony export */ "__asyncValues": () => /* binding */ __asyncValues,
-/* harmony export */ "__makeTemplateObject": () => /* binding */ __makeTemplateObject,
-/* harmony export */ "__importStar": () => /* binding */ __importStar,
-/* harmony export */ "__importDefault": () => /* binding */ __importDefault,
-/* harmony export */ "__classPrivateFieldGet": () => /* binding */ __classPrivateFieldGet,
-/* harmony export */ "__classPrivateFieldSet": () => /* binding */ __classPrivateFieldSet,
-/* harmony export */ "__classPrivateFieldIn": () => /* binding */ __classPrivateFieldIn
-/* harmony export */ });
-/******************************************************************************
-Copyright (c) Microsoft Corporation.
-
-Permission to use, copy, modify, and/or distribute this software for any
-purpose with or without fee is hereby granted.
-
-THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
-REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
-INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
-OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-PERFORMANCE OF THIS SOFTWARE.
-***************************************************************************** */
-/* global Reflect, Promise */
-
-var extendStatics = function(d, b) {
- extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
- return extendStatics(d, b);
-};
-
-function __extends(d, b) {
- if (typeof b !== "function" && b !== null)
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
-}
-
-var __assign = function() {
- __assign = Object.assign || function __assign(t) {
- for (var s, i = 1, n = arguments.length; i < n; i++) {
- s = arguments[i];
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
- }
- return t;
- }
- return __assign.apply(this, arguments);
-}
-
-function __rest(s, e) {
- var t = {};
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
- t[p] = s[p];
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
- t[p[i]] = s[p[i]];
- }
- return t;
-}
-
-function __decorate(decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
-}
-
-function __param(paramIndex, decorator) {
- return function (target, key) { decorator(target, key, paramIndex); }
-}
-
-function __metadata(metadataKey, metadataValue) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
-}
-
-function __awaiter(thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-}
-
-function __generator(thisArg, body) {
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
- function verb(n) { return function (v) { return step([n, v]); }; }
- function step(op) {
- if (f) throw new TypeError("Generator is already executing.");
- while (_) try {
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
- if (y = 0, t) op = [op[0] & 2, t.value];
- switch (op[0]) {
- case 0: case 1: t = op; break;
- case 4: _.label++; return { value: op[1], done: false };
- case 5: _.label++; y = op[1]; op = [0]; continue;
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
- default:
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
- if (t[2]) _.ops.pop();
- _.trys.pop(); continue;
- }
- op = body.call(thisArg, _);
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
- }
-}
-
-var __createBinding = Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- var desc = Object.getOwnPropertyDescriptor(m, k);
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
- desc = { enumerable: true, get: function() { return m[k]; } };
- }
- Object.defineProperty(o, k2, desc);
-}) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
-});
-
-function __exportStar(m, o) {
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);
-}
-
-function __values(o) {
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
- if (m) return m.call(o);
- if (o && typeof o.length === "number") return {
- next: function () {
- if (o && i >= o.length) o = void 0;
- return { value: o && o[i++], done: !o };
- }
- };
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
-}
-
-function __read(o, n) {
- var m = typeof Symbol === "function" && o[Symbol.iterator];
- if (!m) return o;
- var i = m.call(o), r, ar = [], e;
- try {
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
- }
- catch (error) { e = { error: error }; }
- finally {
- try {
- if (r && !r.done && (m = i["return"])) m.call(i);
- }
- finally { if (e) throw e.error; }
- }
- return ar;
-}
-
-/** @deprecated */
-function __spread() {
- for (var ar = [], i = 0; i < arguments.length; i++)
- ar = ar.concat(__read(arguments[i]));
- return ar;
-}
-
-/** @deprecated */
-function __spreadArrays() {
- for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
- for (var r = Array(s), k = 0, i = 0; i < il; i++)
- for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
- r[k] = a[j];
- return r;
-}
-
-function __spreadArray(to, from, pack) {
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
- if (ar || !(i in from)) {
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
- ar[i] = from[i];
- }
- }
- return to.concat(ar || Array.prototype.slice.call(from));
-}
-
-function __await(v) {
- return this instanceof __await ? (this.v = v, this) : new __await(v);
-}
-
-function __asyncGenerator(thisArg, _arguments, generator) {
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
- var g = generator.apply(thisArg, _arguments || []), i, q = [];
- return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
- function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
- function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
- function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
- function fulfill(value) { resume("next", value); }
- function reject(value) { resume("throw", value); }
- function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
-}
-
-function __asyncDelegator(o) {
- var i, p;
- return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
- function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
-}
-
-function __asyncValues(o) {
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
- var m = o[Symbol.asyncIterator], i;
- return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
- function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
- function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
-}
-
-function __makeTemplateObject(cooked, raw) {
- if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
- return cooked;
-};
-
-var __setModuleDefault = Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-};
-
-function __importStar(mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
-}
-
-function __importDefault(mod) {
- return (mod && mod.__esModule) ? mod : { default: mod };
-}
-
-function __classPrivateFieldGet(receiver, state, kind, f) {
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
-}
-
-function __classPrivateFieldSet(receiver, state, value, kind, f) {
- if (kind === "m") throw new TypeError("Private method is not writable");
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
-}
-
-function __classPrivateFieldIn(state, receiver) {
- if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object");
- return typeof state === "function" ? receiver === state : state.has(receiver);
-}
+
+
+const WritableStream = (__nccwpck_require__(4492).Writable)
+const inherits = (__nccwpck_require__(7261).inherits)
+
+const StreamSearch = __nccwpck_require__(8534)
+
+const PartStream = __nccwpck_require__(8710)
+const HeaderParser = __nccwpck_require__(333)
+
+const DASH = 45
+const B_ONEDASH = Buffer.from('-')
+const B_CRLF = Buffer.from('\r\n')
+const EMPTY_FN = function () {}
+
+function Dicer (cfg) {
+ if (!(this instanceof Dicer)) { return new Dicer(cfg) }
+ WritableStream.call(this, cfg)
+
+ if (!cfg || (!cfg.headerFirst && typeof cfg.boundary !== 'string')) { throw new TypeError('Boundary required') }
+
+ if (typeof cfg.boundary === 'string') { this.setBoundary(cfg.boundary) } else { this._bparser = undefined }
+
+ this._headerFirst = cfg.headerFirst
+
+ this._dashes = 0
+ this._parts = 0
+ this._finished = false
+ this._realFinish = false
+ this._isPreamble = true
+ this._justMatched = false
+ this._firstWrite = true
+ this._inHeader = true
+ this._part = undefined
+ this._cb = undefined
+ this._ignoreData = false
+ this._partOpts = { highWaterMark: cfg.partHwm }
+ this._pause = false
+
+ const self = this
+ this._hparser = new HeaderParser(cfg)
+ this._hparser.on('header', function (header) {
+ self._inHeader = false
+ self._part.emit('header', header)
+ })
+}
+inherits(Dicer, WritableStream)
+
+Dicer.prototype.emit = function (ev) {
+ if (ev === 'finish' && !this._realFinish) {
+ if (!this._finished) {
+ const self = this
+ process.nextTick(function () {
+ self.emit('error', new Error('Unexpected end of multipart data'))
+ if (self._part && !self._ignoreData) {
+ const type = (self._isPreamble ? 'Preamble' : 'Part')
+ self._part.emit('error', new Error(type + ' terminated early due to unexpected end of multipart data'))
+ self._part.push(null)
+ process.nextTick(function () {
+ self._realFinish = true
+ self.emit('finish')
+ self._realFinish = false
+ })
+ return
+ }
+ self._realFinish = true
+ self.emit('finish')
+ self._realFinish = false
+ })
+ }
+ } else { WritableStream.prototype.emit.apply(this, arguments) }
+}
+
+Dicer.prototype._write = function (data, encoding, cb) {
+ // ignore unexpected data (e.g. extra trailer data after finished)
+ if (!this._hparser && !this._bparser) { return cb() }
+
+ if (this._headerFirst && this._isPreamble) {
+ if (!this._part) {
+ this._part = new PartStream(this._partOpts)
+ if (this._events.preamble) { this.emit('preamble', this._part) } else { this._ignore() }
+ }
+ const r = this._hparser.push(data)
+ if (!this._inHeader && r !== undefined && r < data.length) { data = data.slice(r) } else { return cb() }
+ }
+
+ // allows for "easier" testing
+ if (this._firstWrite) {
+ this._bparser.push(B_CRLF)
+ this._firstWrite = false
+ }
+
+ this._bparser.push(data)
+
+ if (this._pause) { this._cb = cb } else { cb() }
+}
+
+Dicer.prototype.reset = function () {
+ this._part = undefined
+ this._bparser = undefined
+ this._hparser = undefined
+}
+
+Dicer.prototype.setBoundary = function (boundary) {
+ const self = this
+ this._bparser = new StreamSearch('\r\n--' + boundary)
+ this._bparser.on('info', function (isMatch, data, start, end) {
+ self._oninfo(isMatch, data, start, end)
+ })
+}
+
+Dicer.prototype._ignore = function () {
+ if (this._part && !this._ignoreData) {
+ this._ignoreData = true
+ this._part.on('error', EMPTY_FN)
+ // we must perform some kind of read on the stream even though we are
+ // ignoring the data, otherwise node's Readable stream will not emit 'end'
+ // after pushing null to the stream
+ this._part.resume()
+ }
+}
+
+Dicer.prototype._oninfo = function (isMatch, data, start, end) {
+ let buf; const self = this; let i = 0; let r; let shouldWriteMore = true
+
+ if (!this._part && this._justMatched && data) {
+ while (this._dashes < 2 && (start + i) < end) {
+ if (data[start + i] === DASH) {
+ ++i
+ ++this._dashes
+ } else {
+ if (this._dashes) { buf = B_ONEDASH }
+ this._dashes = 0
+ break
+ }
+ }
+ if (this._dashes === 2) {
+ if ((start + i) < end && this._events.trailer) { this.emit('trailer', data.slice(start + i, end)) }
+ this.reset()
+ this._finished = true
+ // no more parts will be added
+ if (self._parts === 0) {
+ self._realFinish = true
+ self.emit('finish')
+ self._realFinish = false
+ }
+ }
+ if (this._dashes) { return }
+ }
+ if (this._justMatched) { this._justMatched = false }
+ if (!this._part) {
+ this._part = new PartStream(this._partOpts)
+ this._part._read = function (n) {
+ self._unpause()
+ }
+ if (this._isPreamble && this._events.preamble) { this.emit('preamble', this._part) } else if (this._isPreamble !== true && this._events.part) { this.emit('part', this._part) } else { this._ignore() }
+ if (!this._isPreamble) { this._inHeader = true }
+ }
+ if (data && start < end && !this._ignoreData) {
+ if (this._isPreamble || !this._inHeader) {
+ if (buf) { shouldWriteMore = this._part.push(buf) }
+ shouldWriteMore = this._part.push(data.slice(start, end))
+ if (!shouldWriteMore) { this._pause = true }
+ } else if (!this._isPreamble && this._inHeader) {
+ if (buf) { this._hparser.push(buf) }
+ r = this._hparser.push(data.slice(start, end))
+ if (!this._inHeader && r !== undefined && r < end) { this._oninfo(false, data, start + r, end) }
+ }
+ }
+ if (isMatch) {
+ this._hparser.reset()
+ if (this._isPreamble) { this._isPreamble = false } else {
+ if (start !== end) {
+ ++this._parts
+ this._part.on('end', function () {
+ if (--self._parts === 0) {
+ if (self._finished) {
+ self._realFinish = true
+ self.emit('finish')
+ self._realFinish = false
+ } else {
+ self._unpause()
+ }
+ }
+ })
+ }
+ }
+ this._part.push(null)
+ this._part = undefined
+ this._ignoreData = false
+ this._justMatched = true
+ this._dashes = 0
+ }
+}
+
+Dicer.prototype._unpause = function () {
+ if (!this._pause) { return }
+
+ this._pause = false
+ if (this._cb) {
+ const cb = this._cb
+ this._cb = undefined
+ cb()
+ }
+}
+
+module.exports = Dicer
/***/ }),
-/***/ 7447:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+/***/ 333:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
-// Copyright (c) 2019-2020-2021-2022 Luca Cappa
-// Released under the term specified in file LICENSE.txt
-// SPDX short identifier: MIT
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
-}) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
-}));
-var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
-};
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.ActionLib = exports.ActionToolRunner = void 0;
-const utils = __importStar(__nccwpck_require__(2365));
-const core = __importStar(__nccwpck_require__(2186));
-const corecommand = __importStar(__nccwpck_require__(7351));
-const toolrunner = __importStar(__nccwpck_require__(8159));
-const actionglob = __importStar(__nccwpck_require__(8090));
-const ioutil = __importStar(__nccwpck_require__(1962));
-const io = __importStar(__nccwpck_require__(7436));
-const fs = __importStar(__nccwpck_require__(5747));
-const path = __importStar(__nccwpck_require__(5622));
-const cp = __importStar(__nccwpck_require__(3129));
-function escapeCmdCommand(command) {
- command = command.trim();
- if (!/^\".*\"$/.test(command))
- command = `\"${command}\"`;
- return command;
+
+const EventEmitter = (__nccwpck_require__(5673).EventEmitter)
+const inherits = (__nccwpck_require__(7261).inherits)
+const getLimit = __nccwpck_require__(9692)
+
+const StreamSearch = __nccwpck_require__(8534)
+
+const B_DCRLF = Buffer.from('\r\n\r\n')
+const RE_CRLF = /\r\n/g
+const RE_HDR = /^([^:]+):[ \t]?([\x00-\xFF]+)?$/ // eslint-disable-line no-control-regex
+
+function HeaderParser (cfg) {
+ EventEmitter.call(this)
+
+ cfg = cfg || {}
+ const self = this
+ this.nread = 0
+ this.maxed = false
+ this.npairs = 0
+ this.maxHeaderPairs = getLimit(cfg, 'maxHeaderPairs', 2000)
+ this.maxHeaderSize = getLimit(cfg, 'maxHeaderSize', 80 * 1024)
+ this.buffer = ''
+ this.header = {}
+ this.finished = false
+ this.ss = new StreamSearch(B_DCRLF)
+ this.ss.on('info', function (isMatch, data, start, end) {
+ if (data && !self.maxed) {
+ if (self.nread + end - start >= self.maxHeaderSize) {
+ end = self.maxHeaderSize - self.nread + start
+ self.nread = self.maxHeaderSize
+ self.maxed = true
+ } else { self.nread += (end - start) }
+
+ self.buffer += data.toString('binary', start, end)
+ }
+ if (isMatch) { self._finish() }
+ })
}
-function escapeShArgument(argument) {
- // escape all blanks: blank -> \blank
- return argument.replace(/ /g, '\\ ');
+inherits(HeaderParser, EventEmitter)
+
+HeaderParser.prototype.push = function (data) {
+ const r = this.ss.push(data)
+ if (this.finished) { return r }
}
-function escapeCmdExeArgument(argument) {
- // \" -> \\"
- argument = argument.replace(/(\\*)"/g, '$1$1\\"');
- // \$ -> \\$
- argument = argument.replace(/(\\*)$/g, '$1$1');
- // All other backslashes occur literally.
- // Quote the whole thing:
- argument = `"${argument}"`;
- // Prefix with caret ^ any character to be escaped, as in:
- // http://www.robvanderwoude.com/escapechars.php
- // Do not escape %, let variable be passed in as is.
- const metaCharsRegExp = /([()\][!^"`<>&|;, *?])/g;
- argument = argument.replace(metaCharsRegExp, '^$1');
- return argument;
+
+HeaderParser.prototype.reset = function () {
+ this.finished = false
+ this.buffer = ''
+ this.header = {}
+ this.ss.reset()
+}
+
+HeaderParser.prototype._finish = function () {
+ if (this.buffer) { this._parseHeader() }
+ this.ss.matches = this.ss.maxMatches
+ const header = this.header
+ this.header = {}
+ this.buffer = ''
+ this.finished = true
+ this.nread = this.npairs = 0
+ this.maxed = false
+ this.emit('header', header)
+}
+
+HeaderParser.prototype._parseHeader = function () {
+ if (this.npairs === this.maxHeaderPairs) { return }
+
+ const lines = this.buffer.split(RE_CRLF)
+ const len = lines.length
+ let m, h
+
+ for (var i = 0; i < len; ++i) { // eslint-disable-line no-var
+ if (lines[i].length === 0) { continue }
+ if (lines[i][0] === '\t' || lines[i][0] === ' ') {
+ // folded header content
+ // RFC2822 says to just remove the CRLF and not the whitespace following
+ // it, so we follow the RFC and include the leading whitespace ...
+ if (h) {
+ this.header[h][this.header[h].length - 1] += lines[i]
+ continue
+ }
+ }
+
+ const posColon = lines[i].indexOf(':')
+ if (
+ posColon === -1 ||
+ posColon === 0
+ ) {
+ return
+ }
+ m = RE_HDR.exec(lines[i])
+ h = m[1].toLowerCase()
+ this.header[h] = this.header[h] || []
+ this.header[h].push((m[2] || ''))
+ if (++this.npairs === this.maxHeaderPairs) { break }
+ }
+}
+
+module.exports = HeaderParser
+
+
+/***/ }),
+
+/***/ 8710:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+const inherits = (__nccwpck_require__(7261).inherits)
+const ReadableStream = (__nccwpck_require__(4492).Readable)
+
+function PartStream (opts) {
+ ReadableStream.call(this, opts)
}
+inherits(PartStream, ReadableStream)
+
+PartStream.prototype._read = function (n) {}
+
+module.exports = PartStream
+
+
+/***/ }),
+
+/***/ 8534:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+
+
/**
- * Run a command with arguments in a shell.
- * Note: -G Ninja or -GNinja? The former works witha shell, the second does not work without a shell.
- * e.spawnSync('cmake', ['-GNinja', '.'], {shell:false, stdio:'inherit', cwd:'/Users/git_repos/cmake-task-tests/'}) -> Configuring done.
- * e.spawnSync('cmake', ['-G Ninja', '.'], {shell:false, stdio:'inherit', cwd:'/Users/git_repos/cmake-task-tests/'}) -> CMake Error: Could not create named generator Ninja
- * e.spawnSync('cmake', ['-G Ninja', '.'], {shell:true, stdio:'inherit', cwd:'/Users/git_repos/cmake-task-tests/'}) -> -- Configuring done
- * e.spawnSync('cmake', ['-GNinja', '.'], {shell:true, stdio:'inherit', cwd:'/Users/git_repos/cmake-task-tests/'}) -> -- Configuring done
- * Hence the caller of this function is always using no spaces in between arguments.
- * Exception is arbitrary text coming from the user, which will hit this problem when not using a shell.
+ * Copyright Brian White. All rights reserved.
*
- * Other corner cases:
- * e.spawnSync('cmake', ['-GUnix Makefiles', '.'], {shell:true, stdio:'inherit', cwd:'/Users/git_repos/cmake-task-tests/'}) -> CMake Error: Could not create named generator Unix
- * e.spawnSync('cmake', ['-GUnix\ Makefiles', '.'], {shell:false, stdio:'inherit', cwd:'/Users/git_repos/cmake-task-tests/'}) -> -- Configuring done
- > e.spawnSync('cmake', ['-GUnix Makefiles', '.'], {shell:false, stdio:'inherit', cwd:'/Users/git_repos/cmake-task-tests/'}) -> -- Configuring done
- e.spawnSync('cmake', ['-G Unix Makefiles', '.'], {shell:false, stdio:'inherit', cwd:'/Users/git_repos/cmake-task-tests/'}) -> CMake Error: Could not create named generator Unix Makefiles
- * @static
- * @param {string} commandPath
- * @param {string[]} args
- * @param {baselib.ExecOptions} [execOptions]
- * @returns {Promise}
- * @memberof ActionLib
+ * @see https://github.com/mscdex/streamsearch
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to
+ * deal in the Software without restriction, including without limitation the
+ * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+ * sell copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+ * IN THE SOFTWARE.
+ *
+ * Based heavily on the Streaming Boyer-Moore-Horspool C++ implementation
+ * by Hongli Lai at: https://github.com/FooBarWidget/boyer-moore-horspool
*/
-function exec(commandPath, args, execOptions) {
- var _a;
- return __awaiter(this, void 0, void 0, function* () {
- core.debug(`exec(${commandPath}, ${JSON.stringify(args)}, {${execOptions === null || execOptions === void 0 ? void 0 : execOptions.cwd}})<<`);
- let useShell = false;
- if (process.env.INPUT_USESHELL === 'true')
- useShell = true;
- else if (process.env.INPUT_USESHELL === 'false') {
- useShell = false;
- }
- else if (process.env.INPUT_USESHELL) {
- useShell = process.env.INPUT_USESHELL;
- }
- const opts = {
- shell: useShell,
- windowsVerbatimArguments: false,
- cwd: execOptions === null || execOptions === void 0 ? void 0 : execOptions.cwd,
- env: execOptions === null || execOptions === void 0 ? void 0 : execOptions.env,
- stdio: "pipe",
- };
- let args2 = args;
- if ((typeof useShell === 'string' && useShell.includes('cmd')) ||
- (process.platform === 'win32' && typeof useShell === 'boolean' && useShell === true)) {
- args2 = [];
- args.map((arg) => args2.push(escapeCmdExeArgument(arg)));
- // When using a shell, the command must be enclosed by quotes to handle blanks correctly.
- commandPath = escapeCmdCommand(commandPath);
- }
- else if (((typeof useShell === 'string' && !useShell.includes('cmd')) ||
- (process.platform !== 'win32' && typeof useShell === 'boolean' && useShell === true))) {
- args2 = [];
- args.map((arg) => args2.push(escapeShArgument(arg)));
- // When using a Unix shell, blanks needs to be escaped in the command as well.
- commandPath = escapeShArgument(commandPath);
- }
- args = args2;
- core.info(`Running command '${commandPath}' with args '${args}' in current directory '${opts === null || opts === void 0 ? void 0 : opts.cwd}'.`);
- core.debug(`cp.spawn("${commandPath}", ${JSON.stringify(args)}, {cwd=${opts === null || opts === void 0 ? void 0 : opts.cwd}, shell=${opts === null || opts === void 0 ? void 0 : opts.shell}, path=${JSON.stringify((_a = opts === null || opts === void 0 ? void 0 : opts.env) === null || _a === void 0 ? void 0 : _a.PATH)}})`);
- return new Promise((resolve, reject) => {
- const child = cp.spawn(`${commandPath}`, args, opts);
- if (execOptions && child.stdout) {
- child.stdout.on('data', (chunk) => {
- if (execOptions.listeners && execOptions.listeners.stdout) {
- execOptions.listeners.stdout(chunk);
- }
- process.stdout.write(chunk);
- });
- }
- if (execOptions && child.stderr) {
- child.stderr.on('data', (chunk) => {
- if (execOptions.listeners && execOptions.listeners.stderr) {
- execOptions.listeners.stderr(chunk);
- }
- process.stdout.write(chunk);
- });
- }
- child.on('error', (error) => {
- core.debug(`${error}`);
- // Wait one second to get still some output.
- setTimeout(() => {
- reject(error);
- child.removeAllListeners();
- }, 1000);
- });
- child.on('exit', (exitCode) => {
- core.debug(`Exit code '${exitCode}' received from command '${commandPath}'`);
- // Do not resolve yet, wait for the close event.
- });
- child.on('close', (exitCode) => {
- core.debug(`STDIO streams have closed for command '${commandPath}'`);
- child.removeAllListeners();
- resolve(exitCode);
- });
- });
- });
+const EventEmitter = (__nccwpck_require__(5673).EventEmitter)
+const inherits = (__nccwpck_require__(7261).inherits)
+
+function SBMH (needle) {
+ if (typeof needle === 'string') {
+ needle = Buffer.from(needle)
+ }
+
+ if (!Buffer.isBuffer(needle)) {
+ throw new TypeError('The needle has to be a String or a Buffer.')
+ }
+
+ const needleLength = needle.length
+
+ if (needleLength === 0) {
+ throw new Error('The needle cannot be an empty String/Buffer.')
+ }
+
+ if (needleLength > 256) {
+ throw new Error('The needle cannot have a length bigger than 256.')
+ }
+
+ this.maxMatches = Infinity
+ this.matches = 0
+
+ this._occ = new Array(256)
+ .fill(needleLength) // Initialize occurrence table.
+ this._lookbehind_size = 0
+ this._needle = needle
+ this._bufpos = 0
+
+ this._lookbehind = Buffer.alloc(needleLength)
+
+ // Populate occurrence table with analysis of the needle,
+ // ignoring last letter.
+ for (var i = 0; i < needleLength - 1; ++i) { // eslint-disable-line no-var
+ this._occ[needle[i]] = needleLength - 1 - i
+ }
}
-class ActionToolRunner {
- constructor(path) {
- this.path = path;
- this.arguments = [];
- }
- _argStringToArray(text) {
- return this.__argStringToArray(text);
+inherits(SBMH, EventEmitter)
+
+SBMH.prototype.reset = function () {
+ this._lookbehind_size = 0
+ this.matches = 0
+ this._bufpos = 0
+}
+
+SBMH.prototype.push = function (chunk, pos) {
+ if (!Buffer.isBuffer(chunk)) {
+ chunk = Buffer.from(chunk, 'binary')
+ }
+ const chlen = chunk.length
+ this._bufpos = pos || 0
+ let r
+ while (r !== chlen && this.matches < this.maxMatches) { r = this._sbmh_feed(chunk) }
+ return r
+}
+
+SBMH.prototype._sbmh_feed = function (data) {
+ const len = data.length
+ const needle = this._needle
+ const needleLength = needle.length
+ const lastNeedleChar = needle[needleLength - 1]
+
+ // Positive: points to a position in `data`
+ // pos == 3 points to data[3]
+ // Negative: points to a position in the lookbehind buffer
+ // pos == -2 points to lookbehind[lookbehind_size - 2]
+ let pos = -this._lookbehind_size
+ let ch
+
+ if (pos < 0) {
+ // Lookbehind buffer is not empty. Perform Boyer-Moore-Horspool
+ // search with character lookup code that considers both the
+ // lookbehind buffer and the current round's haystack data.
+ //
+ // Loop until
+ // there is a match.
+ // or until
+ // we've moved past the position that requires the
+ // lookbehind buffer. In this case we switch to the
+ // optimized loop.
+ // or until
+ // the character to look at lies outside the haystack.
+ while (pos < 0 && pos <= len - needleLength) {
+ ch = this._sbmh_lookup_char(data, pos + needleLength - 1)
+
+ if (
+ ch === lastNeedleChar &&
+ this._sbmh_memcmp(data, pos, needleLength - 1)
+ ) {
+ this._lookbehind_size = 0
+ ++this.matches
+ this.emit('info', true)
+
+ return (this._bufpos = pos + needleLength)
+ }
+ pos += this._occ[ch]
}
- exec(options) {
- return exec(this.path, this.arguments, options);
+
+ // No match.
+
+ if (pos < 0) {
+ // There's too few data for Boyer-Moore-Horspool to run,
+ // so let's use a different algorithm to skip as much as
+ // we can.
+ // Forward pos until
+ // the trailing part of lookbehind + data
+ // looks like the beginning of the needle
+ // or until
+ // pos == 0
+ while (pos < 0 && !this._sbmh_memcmp(data, pos, len - pos)) { ++pos }
}
- line(val) {
- this.arguments = this.arguments.concat(toolrunner.argStringToArray(val));
+
+ if (pos >= 0) {
+ // Discard lookbehind buffer.
+ this.emit('info', false, this._lookbehind, 0, this._lookbehind_size)
+ this._lookbehind_size = 0
+ } else {
+ // Cut off part of the lookbehind buffer that has
+ // been processed and append the entire haystack
+ // into it.
+ const bytesToCutOff = this._lookbehind_size + pos
+ if (bytesToCutOff > 0) {
+ // The cut off data is guaranteed not to contain the needle.
+ this.emit('info', false, this._lookbehind, 0, bytesToCutOff)
+ }
+
+ this._lookbehind.copy(this._lookbehind, 0, bytesToCutOff,
+ this._lookbehind_size - bytesToCutOff)
+ this._lookbehind_size -= bytesToCutOff
+
+ data.copy(this._lookbehind, this._lookbehind_size)
+ this._lookbehind_size += len
+
+ this._bufpos = len
+ return len
}
- arg(val) {
- if (val instanceof Array) {
- this.arguments = this.arguments.concat(val);
- }
- else if (typeof (val) === 'string') {
- this.arguments = this.arguments.concat(val.trim());
+ }
+
+ pos += (pos >= 0) * this._bufpos
+
+ // Lookbehind buffer is now empty. We only need to check if the
+ // needle is in the haystack.
+ if (data.indexOf(needle, pos) !== -1) {
+ pos = data.indexOf(needle, pos)
+ ++this.matches
+ if (pos > 0) { this.emit('info', true, data, this._bufpos, pos) } else { this.emit('info', true) }
+
+ return (this._bufpos = pos + needleLength)
+ } else {
+ pos = len - needleLength
+ }
+
+ // There was no match. If there's trailing haystack data that we cannot
+ // match yet using the Boyer-Moore-Horspool algorithm (because the trailing
+ // data is less than the needle size) then match using a modified
+ // algorithm that starts matching from the beginning instead of the end.
+ // Whatever trailing data is left after running this algorithm is added to
+ // the lookbehind buffer.
+ while (
+ pos < len &&
+ (
+ data[pos] !== needle[0] ||
+ (
+ (Buffer.compare(
+ data.subarray(pos, pos + len - pos),
+ needle.subarray(0, len - pos)
+ ) !== 0)
+ )
+ )
+ ) {
+ ++pos
+ }
+ if (pos < len) {
+ data.copy(this._lookbehind, 0, pos, pos + (len - pos))
+ this._lookbehind_size = len - pos
+ }
+
+ // Everything until pos is guaranteed not to contain needle data.
+ if (pos > 0) { this.emit('info', false, data, this._bufpos, pos < len ? pos : len) }
+
+ this._bufpos = len
+ return len
+}
+
+SBMH.prototype._sbmh_lookup_char = function (data, pos) {
+ return (pos < 0)
+ ? this._lookbehind[this._lookbehind_size + pos]
+ : data[pos]
+}
+
+SBMH.prototype._sbmh_memcmp = function (data, pos, len) {
+ for (var i = 0; i < len; ++i) { // eslint-disable-line no-var
+ if (this._sbmh_lookup_char(data, pos + i) !== this._needle[i]) { return false }
+ }
+ return true
+}
+
+module.exports = SBMH
+
+
+/***/ }),
+
+/***/ 3438:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+const WritableStream = (__nccwpck_require__(4492).Writable)
+const { inherits } = __nccwpck_require__(7261)
+const Dicer = __nccwpck_require__(2856)
+
+const MultipartParser = __nccwpck_require__(415)
+const UrlencodedParser = __nccwpck_require__(6780)
+const parseParams = __nccwpck_require__(4426)
+
+function Busboy (opts) {
+ if (!(this instanceof Busboy)) { return new Busboy(opts) }
+
+ if (typeof opts !== 'object') {
+ throw new TypeError('Busboy expected an options-Object.')
+ }
+ if (typeof opts.headers !== 'object') {
+ throw new TypeError('Busboy expected an options-Object with headers-attribute.')
+ }
+ if (typeof opts.headers['content-type'] !== 'string') {
+ throw new TypeError('Missing Content-Type-header.')
+ }
+
+ const {
+ headers,
+ ...streamOptions
+ } = opts
+
+ this.opts = {
+ autoDestroy: false,
+ ...streamOptions
+ }
+ WritableStream.call(this, this.opts)
+
+ this._done = false
+ this._parser = this.getParserByHeaders(headers)
+ this._finished = false
+}
+inherits(Busboy, WritableStream)
+
+Busboy.prototype.emit = function (ev) {
+ if (ev === 'finish') {
+ if (!this._done) {
+ this._parser?.end()
+ return
+ } else if (this._finished) {
+ return
+ }
+ this._finished = true
+ }
+ WritableStream.prototype.emit.apply(this, arguments)
+}
+
+Busboy.prototype.getParserByHeaders = function (headers) {
+ const parsed = parseParams(headers['content-type'])
+
+ const cfg = {
+ defCharset: this.opts.defCharset,
+ fileHwm: this.opts.fileHwm,
+ headers,
+ highWaterMark: this.opts.highWaterMark,
+ isPartAFile: this.opts.isPartAFile,
+ limits: this.opts.limits,
+ parsedConType: parsed,
+ preservePath: this.opts.preservePath
+ }
+
+ if (MultipartParser.detect.test(parsed[0])) {
+ return new MultipartParser(this, cfg)
+ }
+ if (UrlencodedParser.detect.test(parsed[0])) {
+ return new UrlencodedParser(this, cfg)
+ }
+ throw new Error('Unsupported Content-Type.')
+}
+
+Busboy.prototype._write = function (chunk, encoding, cb) {
+ this._parser.write(chunk, cb)
+}
+
+module.exports = Busboy
+module.exports["default"] = Busboy
+module.exports.Busboy = Busboy
+
+module.exports.Dicer = Dicer
+
+
+/***/ }),
+
+/***/ 415:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+// TODO:
+// * support 1 nested multipart level
+// (see second multipart example here:
+// http://www.w3.org/TR/html401/interact/forms.html#didx-multipartform-data)
+// * support limits.fieldNameSize
+// -- this will require modifications to utils.parseParams
+
+const { Readable } = __nccwpck_require__(4492)
+const { inherits } = __nccwpck_require__(7261)
+
+const Dicer = __nccwpck_require__(2856)
+
+const parseParams = __nccwpck_require__(4426)
+const decodeText = __nccwpck_require__(9136)
+const basename = __nccwpck_require__(496)
+const getLimit = __nccwpck_require__(9692)
+
+const RE_BOUNDARY = /^boundary$/i
+const RE_FIELD = /^form-data$/i
+const RE_CHARSET = /^charset$/i
+const RE_FILENAME = /^filename$/i
+const RE_NAME = /^name$/i
+
+Multipart.detect = /^multipart\/form-data/i
+function Multipart (boy, cfg) {
+ let i
+ let len
+ const self = this
+ let boundary
+ const limits = cfg.limits
+ const isPartAFile = cfg.isPartAFile || ((fieldName, contentType, fileName) => (contentType === 'application/octet-stream' || fileName !== undefined))
+ const parsedConType = cfg.parsedConType || []
+ const defCharset = cfg.defCharset || 'utf8'
+ const preservePath = cfg.preservePath
+ const fileOpts = { highWaterMark: cfg.fileHwm }
+
+ for (i = 0, len = parsedConType.length; i < len; ++i) {
+ if (Array.isArray(parsedConType[i]) &&
+ RE_BOUNDARY.test(parsedConType[i][0])) {
+ boundary = parsedConType[i][1]
+ break
+ }
+ }
+
+ function checkFinished () {
+ if (nends === 0 && finished && !boy._done) {
+ finished = false
+ self.end()
+ }
+ }
+
+ if (typeof boundary !== 'string') { throw new Error('Multipart: Boundary not found') }
+
+ const fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024)
+ const fileSizeLimit = getLimit(limits, 'fileSize', Infinity)
+ const filesLimit = getLimit(limits, 'files', Infinity)
+ const fieldsLimit = getLimit(limits, 'fields', Infinity)
+ const partsLimit = getLimit(limits, 'parts', Infinity)
+ const headerPairsLimit = getLimit(limits, 'headerPairs', 2000)
+ const headerSizeLimit = getLimit(limits, 'headerSize', 80 * 1024)
+
+ let nfiles = 0
+ let nfields = 0
+ let nends = 0
+ let curFile
+ let curField
+ let finished = false
+
+ this._needDrain = false
+ this._pause = false
+ this._cb = undefined
+ this._nparts = 0
+ this._boy = boy
+
+ const parserCfg = {
+ boundary,
+ maxHeaderPairs: headerPairsLimit,
+ maxHeaderSize: headerSizeLimit,
+ partHwm: fileOpts.highWaterMark,
+ highWaterMark: cfg.highWaterMark
+ }
+
+ this.parser = new Dicer(parserCfg)
+ this.parser.on('drain', function () {
+ self._needDrain = false
+ if (self._cb && !self._pause) {
+ const cb = self._cb
+ self._cb = undefined
+ cb()
+ }
+ }).on('part', function onPart (part) {
+ if (++self._nparts > partsLimit) {
+ self.parser.removeListener('part', onPart)
+ self.parser.on('part', skipPart)
+ boy.hitPartsLimit = true
+ boy.emit('partsLimit')
+ return skipPart(part)
+ }
+
+ // hack because streams2 _always_ doesn't emit 'end' until nextTick, so let
+ // us emit 'end' early since we know the part has ended if we are already
+ // seeing the next part
+ if (curField) {
+ const field = curField
+ field.emit('end')
+ field.removeAllListeners('end')
+ }
+
+ part.on('header', function (header) {
+ let contype
+ let fieldname
+ let parsed
+ let charset
+ let encoding
+ let filename
+ let nsize = 0
+
+ if (header['content-type']) {
+ parsed = parseParams(header['content-type'][0])
+ if (parsed[0]) {
+ contype = parsed[0].toLowerCase()
+ for (i = 0, len = parsed.length; i < len; ++i) {
+ if (RE_CHARSET.test(parsed[i][0])) {
+ charset = parsed[i][1].toLowerCase()
+ break
+ }
+ }
+ }
+ }
+
+ if (contype === undefined) { contype = 'text/plain' }
+ if (charset === undefined) { charset = defCharset }
+
+ if (header['content-disposition']) {
+ parsed = parseParams(header['content-disposition'][0])
+ if (!RE_FIELD.test(parsed[0])) { return skipPart(part) }
+ for (i = 0, len = parsed.length; i < len; ++i) {
+ if (RE_NAME.test(parsed[i][0])) {
+ fieldname = parsed[i][1]
+ } else if (RE_FILENAME.test(parsed[i][0])) {
+ filename = parsed[i][1]
+ if (!preservePath) { filename = basename(filename) }
+ }
+ }
+ } else { return skipPart(part) }
+
+ if (header['content-transfer-encoding']) { encoding = header['content-transfer-encoding'][0].toLowerCase() } else { encoding = '7bit' }
+
+ let onData,
+ onEnd
+
+ if (isPartAFile(fieldname, contype, filename)) {
+ // file/binary field
+ if (nfiles === filesLimit) {
+ if (!boy.hitFilesLimit) {
+ boy.hitFilesLimit = true
+ boy.emit('filesLimit')
+ }
+ return skipPart(part)
+ }
+
+ ++nfiles
+
+ if (!boy._events.file) {
+ self.parser._ignore()
+ return
+ }
+
+ ++nends
+ const file = new FileStream(fileOpts)
+ curFile = file
+ file.on('end', function () {
+ --nends
+ self._pause = false
+ checkFinished()
+ if (self._cb && !self._needDrain) {
+ const cb = self._cb
+ self._cb = undefined
+ cb()
+ }
+ })
+ file._read = function (n) {
+ if (!self._pause) { return }
+ self._pause = false
+ if (self._cb && !self._needDrain) {
+ const cb = self._cb
+ self._cb = undefined
+ cb()
+ }
+ }
+ boy.emit('file', fieldname, file, filename, encoding, contype)
+
+ onData = function (data) {
+ if ((nsize += data.length) > fileSizeLimit) {
+ const extralen = fileSizeLimit - nsize + data.length
+ if (extralen > 0) { file.push(data.slice(0, extralen)) }
+ file.truncated = true
+ file.bytesRead = fileSizeLimit
+ part.removeAllListeners('data')
+ file.emit('limit')
+ return
+ } else if (!file.push(data)) { self._pause = true }
+
+ file.bytesRead = nsize
+ }
+
+ onEnd = function () {
+ curFile = undefined
+ file.push(null)
+ }
+ } else {
+ // non-file field
+ if (nfields === fieldsLimit) {
+ if (!boy.hitFieldsLimit) {
+ boy.hitFieldsLimit = true
+ boy.emit('fieldsLimit')
+ }
+ return skipPart(part)
+ }
+
+ ++nfields
+ ++nends
+ let buffer = ''
+ let truncated = false
+ curField = part
+
+ onData = function (data) {
+ if ((nsize += data.length) > fieldSizeLimit) {
+ const extralen = (fieldSizeLimit - (nsize - data.length))
+ buffer += data.toString('binary', 0, extralen)
+ truncated = true
+ part.removeAllListeners('data')
+ } else { buffer += data.toString('binary') }
+ }
+
+ onEnd = function () {
+ curField = undefined
+ if (buffer.length) { buffer = decodeText(buffer, 'binary', charset) }
+ boy.emit('field', fieldname, buffer, false, truncated, encoding, contype)
+ --nends
+ checkFinished()
+ }
+ }
+
+ /* As of node@2efe4ab761666 (v0.10.29+/v0.11.14+), busboy had become
+ broken. Streams2/streams3 is a huge black box of confusion, but
+ somehow overriding the sync state seems to fix things again (and still
+ seems to work for previous node versions).
+ */
+ part._readableState.sync = false
+
+ part.on('data', onData)
+ part.on('end', onEnd)
+ }).on('error', function (err) {
+ if (curFile) { curFile.emit('error', err) }
+ })
+ }).on('error', function (err) {
+ boy.emit('error', err)
+ }).on('finish', function () {
+ finished = true
+ checkFinished()
+ })
+}
+
+Multipart.prototype.write = function (chunk, cb) {
+ const r = this.parser.write(chunk)
+ if (r && !this._pause) {
+ cb()
+ } else {
+ this._needDrain = !r
+ this._cb = cb
+ }
+}
+
+Multipart.prototype.end = function () {
+ const self = this
+
+ if (self.parser.writable) {
+ self.parser.end()
+ } else if (!self._boy._done) {
+ process.nextTick(function () {
+ self._boy._done = true
+ self._boy.emit('finish')
+ })
+ }
+}
+
+function skipPart (part) {
+ part.resume()
+}
+
+function FileStream (opts) {
+ Readable.call(this, opts)
+
+ this.bytesRead = 0
+
+ this.truncated = false
+}
+
+inherits(FileStream, Readable)
+
+FileStream.prototype._read = function (n) {}
+
+module.exports = Multipart
+
+
+/***/ }),
+
+/***/ 6780:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+const Decoder = __nccwpck_require__(9730)
+const decodeText = __nccwpck_require__(9136)
+const getLimit = __nccwpck_require__(9692)
+
+const RE_CHARSET = /^charset$/i
+
+UrlEncoded.detect = /^application\/x-www-form-urlencoded/i
+function UrlEncoded (boy, cfg) {
+ const limits = cfg.limits
+ const parsedConType = cfg.parsedConType
+ this.boy = boy
+
+ this.fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024)
+ this.fieldNameSizeLimit = getLimit(limits, 'fieldNameSize', 100)
+ this.fieldsLimit = getLimit(limits, 'fields', Infinity)
+
+ let charset
+ for (var i = 0, len = parsedConType.length; i < len; ++i) { // eslint-disable-line no-var
+ if (Array.isArray(parsedConType[i]) &&
+ RE_CHARSET.test(parsedConType[i][0])) {
+ charset = parsedConType[i][1].toLowerCase()
+ break
+ }
+ }
+
+ if (charset === undefined) { charset = cfg.defCharset || 'utf8' }
+
+ this.decoder = new Decoder()
+ this.charset = charset
+ this._fields = 0
+ this._state = 'key'
+ this._checkingBytes = true
+ this._bytesKey = 0
+ this._bytesVal = 0
+ this._key = ''
+ this._val = ''
+ this._keyTrunc = false
+ this._valTrunc = false
+ this._hitLimit = false
+}
+
+UrlEncoded.prototype.write = function (data, cb) {
+ if (this._fields === this.fieldsLimit) {
+ if (!this.boy.hitFieldsLimit) {
+ this.boy.hitFieldsLimit = true
+ this.boy.emit('fieldsLimit')
+ }
+ return cb()
+ }
+
+ let idxeq; let idxamp; let i; let p = 0; const len = data.length
+
+ while (p < len) {
+ if (this._state === 'key') {
+ idxeq = idxamp = undefined
+ for (i = p; i < len; ++i) {
+ if (!this._checkingBytes) { ++p }
+ if (data[i] === 0x3D/* = */) {
+ idxeq = i
+ break
+ } else if (data[i] === 0x26/* & */) {
+ idxamp = i
+ break
+ }
+ if (this._checkingBytes && this._bytesKey === this.fieldNameSizeLimit) {
+ this._hitLimit = true
+ break
+ } else if (this._checkingBytes) { ++this._bytesKey }
+ }
+
+ if (idxeq !== undefined) {
+ // key with assignment
+ if (idxeq > p) { this._key += this.decoder.write(data.toString('binary', p, idxeq)) }
+ this._state = 'val'
+
+ this._hitLimit = false
+ this._checkingBytes = true
+ this._val = ''
+ this._bytesVal = 0
+ this._valTrunc = false
+ this.decoder.reset()
+
+ p = idxeq + 1
+ } else if (idxamp !== undefined) {
+ // key with no assignment
+ ++this._fields
+ let key; const keyTrunc = this._keyTrunc
+ if (idxamp > p) { key = (this._key += this.decoder.write(data.toString('binary', p, idxamp))) } else { key = this._key }
+
+ this._hitLimit = false
+ this._checkingBytes = true
+ this._key = ''
+ this._bytesKey = 0
+ this._keyTrunc = false
+ this.decoder.reset()
+
+ if (key.length) {
+ this.boy.emit('field', decodeText(key, 'binary', this.charset),
+ '',
+ keyTrunc,
+ false)
+ }
+
+ p = idxamp + 1
+ if (this._fields === this.fieldsLimit) { return cb() }
+ } else if (this._hitLimit) {
+ // we may not have hit the actual limit if there are encoded bytes...
+ if (i > p) { this._key += this.decoder.write(data.toString('binary', p, i)) }
+ p = i
+ if ((this._bytesKey = this._key.length) === this.fieldNameSizeLimit) {
+ // yep, we actually did hit the limit
+ this._checkingBytes = false
+ this._keyTrunc = true
+ }
+ } else {
+ if (p < len) { this._key += this.decoder.write(data.toString('binary', p)) }
+ p = len
+ }
+ } else {
+ idxamp = undefined
+ for (i = p; i < len; ++i) {
+ if (!this._checkingBytes) { ++p }
+ if (data[i] === 0x26/* & */) {
+ idxamp = i
+ break
+ }
+ if (this._checkingBytes && this._bytesVal === this.fieldSizeLimit) {
+ this._hitLimit = true
+ break
+ } else if (this._checkingBytes) { ++this._bytesVal }
+ }
+
+ if (idxamp !== undefined) {
+ ++this._fields
+ if (idxamp > p) { this._val += this.decoder.write(data.toString('binary', p, idxamp)) }
+ this.boy.emit('field', decodeText(this._key, 'binary', this.charset),
+ decodeText(this._val, 'binary', this.charset),
+ this._keyTrunc,
+ this._valTrunc)
+ this._state = 'key'
+
+ this._hitLimit = false
+ this._checkingBytes = true
+ this._key = ''
+ this._bytesKey = 0
+ this._keyTrunc = false
+ this.decoder.reset()
+
+ p = idxamp + 1
+ if (this._fields === this.fieldsLimit) { return cb() }
+ } else if (this._hitLimit) {
+ // we may not have hit the actual limit if there are encoded bytes...
+ if (i > p) { this._val += this.decoder.write(data.toString('binary', p, i)) }
+ p = i
+ if ((this._val === '' && this.fieldSizeLimit === 0) ||
+ (this._bytesVal = this._val.length) === this.fieldSizeLimit) {
+ // yep, we actually did hit the limit
+ this._checkingBytes = false
+ this._valTrunc = true
+ }
+ } else {
+ if (p < len) { this._val += this.decoder.write(data.toString('binary', p)) }
+ p = len
+ }
+ }
+ }
+ cb()
+}
+
+UrlEncoded.prototype.end = function () {
+ if (this.boy._done) { return }
+
+ if (this._state === 'key' && this._key.length > 0) {
+ this.boy.emit('field', decodeText(this._key, 'binary', this.charset),
+ '',
+ this._keyTrunc,
+ false)
+ } else if (this._state === 'val') {
+ this.boy.emit('field', decodeText(this._key, 'binary', this.charset),
+ decodeText(this._val, 'binary', this.charset),
+ this._keyTrunc,
+ this._valTrunc)
+ }
+ this.boy._done = true
+ this.boy.emit('finish')
+}
+
+module.exports = UrlEncoded
+
+
+/***/ }),
+
+/***/ 9730:
+/***/ ((module) => {
+
+"use strict";
+
+
+const RE_PLUS = /\+/g
+
+const HEX = [
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,
+ 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
+]
+
+function Decoder () {
+ this.buffer = undefined
+}
+Decoder.prototype.write = function (str) {
+ // Replace '+' with ' ' before decoding
+ str = str.replace(RE_PLUS, ' ')
+ let res = ''
+ let i = 0; let p = 0; const len = str.length
+ for (; i < len; ++i) {
+ if (this.buffer !== undefined) {
+ if (!HEX[str.charCodeAt(i)]) {
+ res += '%' + this.buffer
+ this.buffer = undefined
+ --i // retry character
+ } else {
+ this.buffer += str[i]
+ ++p
+ if (this.buffer.length === 2) {
+ res += String.fromCharCode(parseInt(this.buffer, 16))
+ this.buffer = undefined
+ }
+ }
+ } else if (str[i] === '%') {
+ if (i > p) {
+ res += str.substring(p, i)
+ p = i
+ }
+ this.buffer = ''
+ ++p
+ }
+ }
+ if (p < len && this.buffer === undefined) { res += str.substring(p) }
+ return res
+}
+Decoder.prototype.reset = function () {
+ this.buffer = undefined
+}
+
+module.exports = Decoder
+
+
+/***/ }),
+
+/***/ 496:
+/***/ ((module) => {
+
+"use strict";
+
+
+module.exports = function basename (path) {
+ if (typeof path !== 'string') { return '' }
+ for (var i = path.length - 1; i >= 0; --i) { // eslint-disable-line no-var
+ switch (path.charCodeAt(i)) {
+ case 0x2F: // '/'
+ case 0x5C: // '\'
+ path = path.slice(i + 1)
+ return (path === '..' || path === '.' ? '' : path)
+ }
+ }
+ return (path === '..' || path === '.' ? '' : path)
+}
+
+
+/***/ }),
+
+/***/ 9136:
+/***/ ((module) => {
+
+"use strict";
+
+
+// Node has always utf-8
+const utf8Decoder = new TextDecoder('utf-8')
+const textDecoders = new Map([
+ ['utf-8', utf8Decoder],
+ ['utf8', utf8Decoder]
+])
+
+function decodeText (text, textEncoding, destEncoding) {
+ if (text) {
+ if (textDecoders.has(destEncoding)) {
+ try {
+ return textDecoders.get(destEncoding).decode(Buffer.from(text, textEncoding))
+ } catch (e) { }
+ } else {
+ try {
+ textDecoders.set(destEncoding, new TextDecoder(destEncoding))
+ return textDecoders.get(destEncoding).decode(Buffer.from(text, textEncoding))
+ } catch (e) { }
+ }
+ }
+ return text
+}
+
+module.exports = decodeText
+
+
+/***/ }),
+
+/***/ 9692:
+/***/ ((module) => {
+
+"use strict";
+
+
+module.exports = function getLimit (limits, name, defaultLimit) {
+ if (
+ !limits ||
+ limits[name] === undefined ||
+ limits[name] === null
+ ) { return defaultLimit }
+
+ if (
+ typeof limits[name] !== 'number' ||
+ isNaN(limits[name])
+ ) { throw new TypeError('Limit ' + name + ' is not a valid number') }
+
+ return limits[name]
+}
+
+
+/***/ }),
+
+/***/ 4426:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+const decodeText = __nccwpck_require__(9136)
+
+const RE_ENCODED = /%([a-fA-F0-9]{2})/g
+
+function encodedReplacer (match, byte) {
+ return String.fromCharCode(parseInt(byte, 16))
+}
+
+function parseParams (str) {
+ const res = []
+ let state = 'key'
+ let charset = ''
+ let inquote = false
+ let escaping = false
+ let p = 0
+ let tmp = ''
+
+ for (var i = 0, len = str.length; i < len; ++i) { // eslint-disable-line no-var
+ const char = str[i]
+ if (char === '\\' && inquote) {
+ if (escaping) { escaping = false } else {
+ escaping = true
+ continue
+ }
+ } else if (char === '"') {
+ if (!escaping) {
+ if (inquote) {
+ inquote = false
+ state = 'key'
+ } else { inquote = true }
+ continue
+ } else { escaping = false }
+ } else {
+ if (escaping && inquote) { tmp += '\\' }
+ escaping = false
+ if ((state === 'charset' || state === 'lang') && char === "'") {
+ if (state === 'charset') {
+ state = 'lang'
+ charset = tmp.substring(1)
+ } else { state = 'value' }
+ tmp = ''
+ continue
+ } else if (state === 'key' &&
+ (char === '*' || char === '=') &&
+ res.length) {
+ if (char === '*') { state = 'charset' } else { state = 'value' }
+ res[p] = [tmp, undefined]
+ tmp = ''
+ continue
+ } else if (!inquote && char === ';') {
+ state = 'key'
+ if (charset) {
+ if (tmp.length) {
+ tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer),
+ 'binary',
+ charset)
+ }
+ charset = ''
+ } else if (tmp.length) {
+ tmp = decodeText(tmp, 'binary', 'utf8')
+ }
+ if (res[p] === undefined) { res[p] = tmp } else { res[p][1] = tmp }
+ tmp = ''
+ ++p
+ continue
+ } else if (!inquote && (char === ' ' || char === '\t')) { continue }
+ }
+ tmp += char
+ }
+ if (charset && tmp.length) {
+ tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer),
+ 'binary',
+ charset)
+ } else if (tmp) {
+ tmp = decodeText(tmp, 'binary', 'utf8')
+ }
+
+ if (res[p] === undefined) {
+ if (tmp) { res[p] = tmp }
+ } else { res[p][1] = tmp }
+
+ return res
+}
+
+module.exports = parseParams
+
+
+/***/ }),
+
+/***/ 7447:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+
+"use strict";
+
+// Copyright (c) 2019-2020-2021-2022-2023 Luca Cappa
+// Released under the term specified in file LICENSE.txt
+// SPDX short identifier: MIT
+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ var desc = Object.getOwnPropertyDescriptor(m, k);
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+ desc = { enumerable: true, get: function() { return m[k]; } };
+ }
+ Object.defineProperty(o, k2, desc);
+}) : (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ o[k2] = m[k];
+}));
+var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
+}) : function(o, v) {
+ o["default"] = v;
+});
+var __importStar = (this && this.__importStar) || function (mod) {
+ if (mod && mod.__esModule) return mod;
+ var result = {};
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
+ __setModuleDefault(result, mod);
+ return result;
+};
+var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.ActionLib = exports.ActionToolRunner = void 0;
+const utils = __importStar(__nccwpck_require__(2365));
+const core = __importStar(__nccwpck_require__(2186));
+const corecommand = __importStar(__nccwpck_require__(7351));
+const toolrunner = __importStar(__nccwpck_require__(8159));
+const actionglob = __importStar(__nccwpck_require__(8090));
+const ioutil = __importStar(__nccwpck_require__(1962));
+const io = __importStar(__nccwpck_require__(7436));
+const fs = __importStar(__nccwpck_require__(7147));
+const path = __importStar(__nccwpck_require__(1017));
+const cp = __importStar(__nccwpck_require__(2081));
+function escapeCmdCommand(command) {
+ command = command.trim();
+ if (!/^".*"$/.test(command))
+ command = `"${command}"`;
+ return command;
+}
+function escapeShArgument(argument) {
+ // escape all blanks: blank -> \blank
+ return argument.replace(/ /g, '\\ ');
+}
+function escapeCmdExeArgument(argument) {
+ // \" -> \\"
+ argument = argument.replace(/(\\*)"/g, '$1$1\\"');
+ // \$ -> \\$
+ argument = argument.replace(/(\\*)$/g, '$1$1');
+ // All other backslashes occur literally.
+ // Quote the whole thing:
+ argument = `"${argument}"`;
+ // Prefix with caret ^ any character to be escaped, as in:
+ // http://www.robvanderwoude.com/escapechars.php
+ // Do not escape %, let variable be passed in as is.
+ const metaCharsRegExp = /([()\][!^"`<>&|;, *?])/g;
+ argument = argument.replace(metaCharsRegExp, '^$1');
+ return argument;
+}
+/**
+ * Run a command with arguments in a shell.
+ * Note: -G Ninja or -GNinja? The former works witha shell, the second does not work without a shell.
+ * e.spawnSync('cmake', ['-GNinja', '.'], {shell:false, stdio:'inherit', cwd:'/Users/git_repos/cmake-task-tests/'}) -> Configuring done.
+ * e.spawnSync('cmake', ['-G Ninja', '.'], {shell:false, stdio:'inherit', cwd:'/Users/git_repos/cmake-task-tests/'}) -> CMake Error: Could not create named generator Ninja
+ * e.spawnSync('cmake', ['-G Ninja', '.'], {shell:true, stdio:'inherit', cwd:'/Users/git_repos/cmake-task-tests/'}) -> -- Configuring done
+ * e.spawnSync('cmake', ['-GNinja', '.'], {shell:true, stdio:'inherit', cwd:'/Users/git_repos/cmake-task-tests/'}) -> -- Configuring done
+ * Hence the caller of this function is always using no spaces in between arguments.
+ * Exception is arbitrary text coming from the user, which will hit this problem when not using a shell.
+ *
+ * Other corner cases:
+ * e.spawnSync('cmake', ['-GUnix Makefiles', '.'], {shell:true, stdio:'inherit', cwd:'/Users/git_repos/cmake-task-tests/'}) -> CMake Error: Could not create named generator Unix
+ * e.spawnSync('cmake', ['-GUnix\ Makefiles', '.'], {shell:false, stdio:'inherit', cwd:'/Users/git_repos/cmake-task-tests/'}) -> -- Configuring done
+ > e.spawnSync('cmake', ['-GUnix Makefiles', '.'], {shell:false, stdio:'inherit', cwd:'/Users/git_repos/cmake-task-tests/'}) -> -- Configuring done
+ e.spawnSync('cmake', ['-G Unix Makefiles', '.'], {shell:false, stdio:'inherit', cwd:'/Users/git_repos/cmake-task-tests/'}) -> CMake Error: Could not create named generator Unix Makefiles
+ * @static
+ * @param {string} commandPath
+ * @param {string[]} args
+ * @param {baselib.ExecOptions} [execOptions]
+ * @returns {Promise}
+ * @memberof ActionLib
+ */
+function exec(commandPath, args, execOptions) {
+ var _a;
+ return __awaiter(this, void 0, void 0, function* () {
+ core.debug(`exec(${commandPath}, ${JSON.stringify(args)}, {${execOptions === null || execOptions === void 0 ? void 0 : execOptions.cwd}})<<`);
+ let useShell = false;
+ if (process.env.INPUT_USESHELL === 'true')
+ useShell = true;
+ else if (process.env.INPUT_USESHELL === 'false') {
+ useShell = false;
+ }
+ else if (process.env.INPUT_USESHELL) {
+ useShell = process.env.INPUT_USESHELL;
+ }
+ const opts = {
+ shell: useShell,
+ windowsVerbatimArguments: false,
+ cwd: execOptions === null || execOptions === void 0 ? void 0 : execOptions.cwd,
+ env: execOptions === null || execOptions === void 0 ? void 0 : execOptions.env,
+ stdio: "pipe",
+ };
+ let args2 = args;
+ if ((typeof useShell === 'string' && useShell.includes('cmd')) ||
+ (process.platform === 'win32' && typeof useShell === 'boolean' && useShell === true)) {
+ args2 = [];
+ args.map((arg) => args2.push(escapeCmdExeArgument(arg)));
+ // When using a shell, the command must be enclosed by quotes to handle blanks correctly.
+ commandPath = escapeCmdCommand(commandPath);
+ }
+ else if (((typeof useShell === 'string' && !useShell.includes('cmd')) ||
+ (process.platform !== 'win32' && typeof useShell === 'boolean' && useShell === true))) {
+ args2 = [];
+ args.map((arg) => args2.push(escapeShArgument(arg)));
+ // When using a Unix shell, blanks needs to be escaped in the command as well.
+ commandPath = escapeShArgument(commandPath);
+ }
+ args = args2;
+ core.info(`Running command '${commandPath}' with args '${args}' in current directory '${opts === null || opts === void 0 ? void 0 : opts.cwd}'.`);
+ core.debug(`cp.spawn("${commandPath}", ${JSON.stringify(args)}, {cwd=${opts === null || opts === void 0 ? void 0 : opts.cwd}, shell=${opts === null || opts === void 0 ? void 0 : opts.shell}, path=${JSON.stringify((_a = opts === null || opts === void 0 ? void 0 : opts.env) === null || _a === void 0 ? void 0 : _a.PATH)}})`);
+ return new Promise((resolve, reject) => {
+ const child = cp.spawn(`${commandPath}`, args, opts);
+ if (execOptions && child.stdout) {
+ child.stdout.on('data', (chunk) => {
+ if (execOptions.listeners && execOptions.listeners.stdout) {
+ execOptions.listeners.stdout(chunk);
+ }
+ process.stdout.write(chunk);
+ });
+ }
+ if (execOptions && child.stderr) {
+ child.stderr.on('data', (chunk) => {
+ if (execOptions.listeners && execOptions.listeners.stderr) {
+ execOptions.listeners.stderr(chunk);
+ }
+ process.stdout.write(chunk);
+ });
+ }
+ child.on('error', (error) => {
+ core.debug(`${error}`);
+ // Wait one second to get still some output.
+ setTimeout(() => {
+ reject(error);
+ child.removeAllListeners();
+ }, 1000);
+ });
+ child.on('exit', (exitCode) => {
+ core.debug(`Exit code '${exitCode}' received from command '${commandPath}'`);
+ // Do not resolve yet, wait for the close event.
+ });
+ child.on('close', (exitCode) => {
+ core.debug(`STDIO streams have closed for command '${commandPath}'`);
+ child.removeAllListeners();
+ resolve(exitCode);
+ });
+ });
+ });
+}
+class ActionToolRunner {
+ constructor(path) {
+ this.path = path;
+ this.arguments = [];
+ }
+ getName() {
+ return this.path;
+ }
+ _argStringToArray(text) {
+ return this.__argStringToArray(text);
+ }
+ exec(options) {
+ return exec(this.path, this.arguments, options);
+ }
+ line(val) {
+ this.arguments = this.arguments.concat(toolrunner.argStringToArray(val));
+ }
+ arg(val) {
+ if (val instanceof Array) {
+ this.arguments = this.arguments.concat(val);
+ }
+ else if (typeof (val) === 'string') {
+ this.arguments = this.arguments.concat(val.trim());
}
}
execSync(options) {
@@ -42284,7 +44267,7 @@ class ActionLib {
corecommand.issueCommand('remove-matcher', { owner: owner }, "");
}
hashFiles(fileGlob, options) {
- return actionglob.hashFiles(fileGlob, options);
+ return actionglob.hashFiles(fileGlob, undefined, options);
}
addPath(path) {
core.addPath(path);
@@ -42302,7 +44285,11 @@ exports.ActionLib = ActionLib;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
+ var desc = Object.getOwnPropertyDescriptor(m, k);
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+ desc = { enumerable: true, get: function() { return m[k]; } };
+ }
+ Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
@@ -42321,12 +44308,16 @@ __exportStar(__nccwpck_require__(7447), exports);
"use strict";
-// Copyright (c) 2019-2020-2021-2022 Luca Cappa
+// Copyright (c) 2019-2020-2021-2022-2023 Luca Cappa
// Released under the term specified in file LICENSE.txt
// SPDX short identifier: MIT
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
+ var desc = Object.getOwnPropertyDescriptor(m, k);
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+ desc = { enumerable: true, get: function() { return m[k]; } };
+ }
+ Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
@@ -42354,11 +44345,11 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.setEnvVarIfUndefined = exports.replaceFromEnvVar = exports.createKeySet = exports.dumpFile = exports.LogFileCollector = exports.dumpError = exports.Matcher = exports.BaseUtilLib = void 0;
-const fs = __importStar(__nccwpck_require__(5747));
-const os = __importStar(__nccwpck_require__(2087));
-const path = __importStar(__nccwpck_require__(5622));
+const fs = __importStar(__nccwpck_require__(7147));
+const os = __importStar(__nccwpck_require__(2037));
+const path = __importStar(__nccwpck_require__(1017));
const del = __importStar(__nccwpck_require__(3325));
-const perf_hooks_1 = __nccwpck_require__(630);
+const perf_hooks_1 = __nccwpck_require__(4074);
const fastglob = __importStar(__nccwpck_require__(693));
class BaseUtilLib {
constructor(baseLib) {
@@ -42402,8 +44393,8 @@ class BaseUtilLib {
}
finally {
this.baseLib.debug(`isVcpkgSubmodule()>> --> ${isSubmodule}`);
- return isSubmodule;
}
+ return isSubmodule;
});
}
throwIfErrorCode(errorCode) {
@@ -42488,12 +44479,12 @@ class BaseUtilLib {
}
return null;
}
- // Force 'name' env variable to have value of 'value'.
+ // Set both the environment variable and the workflow variable with the same name.
+ // The workflow variable might be re-used in subsequent steps.
setEnvVar(name, value) {
- // Set variable both as env var and as step variable, which might be re-used in subseqeunt steps.
process.env[name] = value;
this.baseLib.setVariable(name, value);
- this.baseLib.debug(`Set variable and the env variable '${name}' to value '${value}'.`);
+ this.baseLib.debug(`Set env ariable and the workflow variable named '${name}' to value '${value}'.`);
}
trimString(value) {
var _a;
@@ -42509,7 +44500,7 @@ class BaseUtilLib {
}
finally {
this.baseLib.endOperation();
- this.baseLib.info(`⏱ elapsed: ${((perf_hooks_1.performance.now() - startTime) / 1000.).toFixed(3)} seconds`);
+ this.baseLib.info(`⏱ elapsed: ${((perf_hooks_1.performance.now() - startTime) / 1000.0).toFixed(3)} seconds`);
}
return result;
});
@@ -42523,7 +44514,7 @@ class BaseUtilLib {
}
finally {
this.baseLib.endOperation();
- this.baseLib.info(`⏱ elapsed: ${((perf_hooks_1.performance.now() - startTime) / 1000.).toFixed(3)} seconds`);
+ this.baseLib.info(`⏱ elapsed: ${((perf_hooks_1.performance.now() - startTime) / 1000).toFixed(3)} seconds`);
}
return result;
}
@@ -42567,7 +44558,7 @@ class BaseUtilLib {
*/
static normalizePath(aPath) {
aPath = path.normalize(aPath);
- if (/[\\\/]$/.test(aPath) && aPath.length > 1)
+ if (/[\\/]$/.test(aPath) && aPath.length > 1)
aPath = aPath.slice(0, -1);
return aPath;
}
@@ -42791,7 +44782,11 @@ exports.setEnvVarIfUndefined = setEnvVarIfUndefined;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
+ var desc = Object.getOwnPropertyDescriptor(m, k);
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+ desc = { enumerable: true, get: function() { return m[k]; } };
+ }
+ Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
@@ -42825,6 +44820,10 @@ async function FastGlob(source, options) {
// https://github.com/typescript-eslint/typescript-eslint/issues/60
// eslint-disable-next-line no-redeclare
(function (FastGlob) {
+ FastGlob.glob = FastGlob;
+ FastGlob.globSync = sync;
+ FastGlob.globStream = stream;
+ FastGlob.async = FastGlob;
function sync(source, options) {
assertPatternsInput(source);
const works = getWorks(source, sync_1.default, options);
@@ -42860,6 +44859,37 @@ async function FastGlob(source, options) {
return utils.path.escape(source);
}
FastGlob.escapePath = escapePath;
+ function convertPathToPattern(source) {
+ assertPatternsInput(source);
+ return utils.path.convertPathToPattern(source);
+ }
+ FastGlob.convertPathToPattern = convertPathToPattern;
+ let posix;
+ (function (posix) {
+ function escapePath(source) {
+ assertPatternsInput(source);
+ return utils.path.escapePosixPath(source);
+ }
+ posix.escapePath = escapePath;
+ function convertPathToPattern(source) {
+ assertPatternsInput(source);
+ return utils.path.convertPosixPathToPattern(source);
+ }
+ posix.convertPathToPattern = convertPathToPattern;
+ })(posix = FastGlob.posix || (FastGlob.posix = {}));
+ let win32;
+ (function (win32) {
+ function escapePath(source) {
+ assertPatternsInput(source);
+ return utils.path.escapeWindowsPath(source);
+ }
+ win32.escapePath = escapePath;
+ function convertPathToPattern(source) {
+ assertPatternsInput(source);
+ return utils.path.convertWindowsPathToPattern(source);
+ }
+ win32.convertPathToPattern = convertPathToPattern;
+ })(win32 = FastGlob.win32 || (FastGlob.win32 = {}));
})(FastGlob || (FastGlob = {}));
function getWorks(source, _Provider, options) {
const patterns = [].concat(source);
@@ -42888,9 +44918,11 @@ module.exports = FastGlob;
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.convertPatternGroupToTask = exports.convertPatternGroupsToTasks = exports.groupPatternsByBaseDirectory = exports.getNegativePatternsAsPositive = exports.getPositivePatterns = exports.convertPatternsToTasks = exports.generate = void 0;
const utils = __nccwpck_require__(1352);
-function generate(patterns, settings) {
+function generate(input, settings) {
+ const patterns = processPatterns(input, settings);
+ const ignore = processPatterns(settings.ignore, settings);
const positivePatterns = getPositivePatterns(patterns);
- const negativePatterns = getNegativePatternsAsPositive(patterns, settings.ignore);
+ const negativePatterns = getNegativePatternsAsPositive(patterns, ignore);
const staticPatterns = positivePatterns.filter((pattern) => utils.pattern.isStaticPattern(pattern, settings));
const dynamicPatterns = positivePatterns.filter((pattern) => utils.pattern.isDynamicPattern(pattern, settings));
const staticTasks = convertPatternsToTasks(staticPatterns, negativePatterns, /* dynamic */ false);
@@ -42898,6 +44930,34 @@ function generate(patterns, settings) {
return staticTasks.concat(dynamicTasks);
}
exports.generate = generate;
+function processPatterns(input, settings) {
+ let patterns = input;
+ /**
+ * The original pattern like `{,*,**,a/*}` can lead to problems checking the depth when matching entry
+ * and some problems with the micromatch package (see fast-glob issues: #365, #394).
+ *
+ * To solve this problem, we expand all patterns containing brace expansion. This can lead to a slight slowdown
+ * in matching in the case of a large set of patterns after expansion.
+ */
+ if (settings.braceExpansion) {
+ patterns = utils.pattern.expandPatternsWithBraceExpansion(patterns);
+ }
+ /**
+ * If the `baseNameMatch` option is enabled, we must add globstar to patterns, so that they can be used
+ * at any nesting level.
+ *
+ * We do this here, because otherwise we have to complicate the filtering logic. For example, we need to change
+ * the pattern in the filter before creating a regular expression. There is no need to change the patterns
+ * in the application. Only on the input.
+ */
+ if (settings.baseNameMatch) {
+ patterns = patterns.map((pattern) => pattern.includes('/') ? pattern : `**/${pattern}`);
+ }
+ /**
+ * This method also removes duplicate slashes that may have been in the pattern or formed as a result of expansion.
+ */
+ return patterns.map((pattern) => utils.pattern.removeDuplicateSlashes(pattern));
+}
/**
* Returns tasks grouped by basic pattern directories.
*
@@ -42974,23 +45034,18 @@ exports.convertPatternGroupToTask = convertPatternGroupToTask;
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
-const stream_1 = __nccwpck_require__(5496);
+const async_1 = __nccwpck_require__(9790);
const provider_1 = __nccwpck_require__(2277);
class ProviderAsync extends provider_1.default {
constructor() {
super(...arguments);
- this._reader = new stream_1.default(this._settings);
+ this._reader = new async_1.default(this._settings);
}
- read(task) {
+ async read(task) {
const root = this._getRootDirectory(task);
const options = this._getReaderOptions(task);
- const entries = [];
- return new Promise((resolve, reject) => {
- const stream = this.api(root, task, options);
- stream.once('error', reject);
- stream.on('data', (entry) => entries.push(options.transform(entry)));
- stream.once('end', () => resolve(entries));
- });
+ const entries = await this.api(root, task, options);
+ return entries.map((entry) => options.transform(entry));
}
api(root, task, options) {
if (task.dynamic) {
@@ -42999,7 +45054,7 @@ class ProviderAsync extends provider_1.default {
return this._reader.static(task.patterns, options);
}
}
-exports.default = ProviderAsync;
+exports["default"] = ProviderAsync;
/***/ }),
@@ -43069,7 +45124,7 @@ class DeepFilter {
return !utils.pattern.matchAny(entryPath, patternsRe);
}
}
-exports.default = DeepFilter;
+exports["default"] = DeepFilter;
/***/ }),
@@ -43089,31 +45144,32 @@ class EntryFilter {
}
getFilter(positive, negative) {
const positiveRe = utils.pattern.convertPatternsToRe(positive, this._micromatchOptions);
- const negativeRe = utils.pattern.convertPatternsToRe(negative, this._micromatchOptions);
+ const negativeRe = utils.pattern.convertPatternsToRe(negative, Object.assign(Object.assign({}, this._micromatchOptions), { dot: true }));
return (entry) => this._filter(entry, positiveRe, negativeRe);
}
_filter(entry, positiveRe, negativeRe) {
- if (this._settings.unique && this._isDuplicateEntry(entry)) {
+ const filepath = utils.path.removeLeadingDotSegment(entry.path);
+ if (this._settings.unique && this._isDuplicateEntry(filepath)) {
return false;
}
if (this._onlyFileFilter(entry) || this._onlyDirectoryFilter(entry)) {
return false;
}
- if (this._isSkippedByAbsoluteNegativePatterns(entry.path, negativeRe)) {
+ if (this._isSkippedByAbsoluteNegativePatterns(filepath, negativeRe)) {
return false;
}
- const filepath = this._settings.baseNameMatch ? entry.name : entry.path;
- const isMatched = this._isMatchToPatterns(filepath, positiveRe) && !this._isMatchToPatterns(entry.path, negativeRe);
+ const isDirectory = entry.dirent.isDirectory();
+ const isMatched = this._isMatchToPatterns(filepath, positiveRe, isDirectory) && !this._isMatchToPatterns(filepath, negativeRe, isDirectory);
if (this._settings.unique && isMatched) {
- this._createIndexRecord(entry);
+ this._createIndexRecord(filepath);
}
return isMatched;
}
- _isDuplicateEntry(entry) {
- return this.index.has(entry.path);
+ _isDuplicateEntry(filepath) {
+ return this.index.has(filepath);
}
- _createIndexRecord(entry) {
- this.index.set(entry.path, undefined);
+ _createIndexRecord(filepath) {
+ this.index.set(filepath, undefined);
}
_onlyFileFilter(entry) {
return this._settings.onlyFiles && !entry.dirent.isFile();
@@ -43128,12 +45184,18 @@ class EntryFilter {
const fullpath = utils.path.makeAbsolute(this._settings.cwd, entryPath);
return utils.pattern.matchAny(fullpath, patternsRe);
}
- _isMatchToPatterns(entryPath, patternsRe) {
- const filepath = utils.path.removeLeadingDotSegment(entryPath);
- return utils.pattern.matchAny(filepath, patternsRe);
+ _isMatchToPatterns(filepath, patternsRe, isDirectory) {
+ // Trying to match files and directories by patterns.
+ const isMatched = utils.pattern.matchAny(filepath, patternsRe);
+ // A pattern with a trailling slash can be used for directory matching.
+ // To apply such pattern, we need to add a tralling slash to the path.
+ if (!isMatched && isDirectory) {
+ return utils.pattern.matchAny(filepath + '/', patternsRe);
+ }
+ return isMatched;
}
}
-exports.default = EntryFilter;
+exports["default"] = EntryFilter;
/***/ }),
@@ -43156,7 +45218,7 @@ class ErrorFilter {
return utils.errno.isEnoentCodeError(error) || this._settings.suppressErrors;
}
}
-exports.default = ErrorFilter;
+exports["default"] = ErrorFilter;
/***/ }),
@@ -43177,12 +45239,7 @@ class Matcher {
this._fillStorage();
}
_fillStorage() {
- /**
- * The original pattern may include `{,*,**,a/*}`, which will lead to problems with matching (unresolved level).
- * So, before expand patterns with brace expansion into separated patterns.
- */
- const patterns = utils.pattern.expandPatternsWithBraceExpansion(this._patterns);
- for (const pattern of patterns) {
+ for (const pattern of this._patterns) {
const segments = this._getPatternSegments(pattern);
const sections = this._splitSegmentsIntoSections(segments);
this._storage.push({
@@ -43214,7 +45271,7 @@ class Matcher {
return utils.array.splitWhen(segments, (segment) => segment.dynamic && utils.pattern.hasGlobStar(segment.pattern));
}
}
-exports.default = Matcher;
+exports["default"] = Matcher;
/***/ }),
@@ -43260,7 +45317,7 @@ class PartialMatcher extends matcher_1.default {
return false;
}
}
-exports.default = PartialMatcher;
+exports["default"] = PartialMatcher;
/***/ }),
@@ -43271,7 +45328,7 @@ exports.default = PartialMatcher;
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
-const path = __nccwpck_require__(5622);
+const path = __nccwpck_require__(1017);
const deep_1 = __nccwpck_require__(2296);
const entry_1 = __nccwpck_require__(4425);
const error_1 = __nccwpck_require__(3354);
@@ -43316,7 +45373,7 @@ class Provider {
};
}
}
-exports.default = Provider;
+exports["default"] = Provider;
/***/ }),
@@ -43327,7 +45384,7 @@ exports.default = Provider;
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
-const stream_1 = __nccwpck_require__(2413);
+const stream_1 = __nccwpck_require__(2781);
const stream_2 = __nccwpck_require__(5496);
const provider_1 = __nccwpck_require__(2277);
class ProviderStream extends provider_1.default {
@@ -43355,7 +45412,7 @@ class ProviderStream extends provider_1.default {
return this._reader.static(task.patterns, options);
}
}
-exports.default = ProviderStream;
+exports["default"] = ProviderStream;
/***/ }),
@@ -43366,7 +45423,7 @@ exports.default = ProviderStream;
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
-const sync_1 = __nccwpck_require__(5873);
+const sync_1 = __nccwpck_require__(7211);
const provider_1 = __nccwpck_require__(2277);
class ProviderSync extends provider_1.default {
constructor() {
@@ -43386,7 +45443,7 @@ class ProviderSync extends provider_1.default {
return this._reader.static(task.patterns, options);
}
}
-exports.default = ProviderSync;
+exports["default"] = ProviderSync;
/***/ }),
@@ -43420,7 +45477,50 @@ class EntryTransformer {
return Object.assign(Object.assign({}, entry), { path: filepath });
}
}
-exports.default = EntryTransformer;
+exports["default"] = EntryTransformer;
+
+
+/***/ }),
+
+/***/ 9790:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+const fsWalk = __nccwpck_require__(6026);
+const reader_1 = __nccwpck_require__(5948);
+const stream_1 = __nccwpck_require__(5496);
+class ReaderAsync extends reader_1.default {
+ constructor() {
+ super(...arguments);
+ this._walkAsync = fsWalk.walk;
+ this._readerStream = new stream_1.default(this._settings);
+ }
+ dynamic(root, options) {
+ return new Promise((resolve, reject) => {
+ this._walkAsync(root, options, (error, entries) => {
+ if (error === null) {
+ resolve(entries);
+ }
+ else {
+ reject(error);
+ }
+ });
+ });
+ }
+ async static(patterns, options) {
+ const entries = [];
+ const stream = this._readerStream.static(patterns, options);
+ // After #235, replace it with an asynchronous iterator.
+ return new Promise((resolve, reject) => {
+ stream.once('error', reject);
+ stream.on('data', (entry) => entries.push(entry));
+ stream.once('end', () => resolve(entries));
+ });
+ }
+}
+exports["default"] = ReaderAsync;
/***/ }),
@@ -43431,7 +45531,7 @@ exports.default = EntryTransformer;
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
-const path = __nccwpck_require__(5622);
+const path = __nccwpck_require__(1017);
const fsStat = __nccwpck_require__(109);
const utils = __nccwpck_require__(1352);
class Reader {
@@ -43461,7 +45561,7 @@ class Reader {
return !utils.errno.isEnoentCodeError(error) && !this._settings.suppressErrors;
}
}
-exports.default = Reader;
+exports["default"] = Reader;
/***/ }),
@@ -43472,7 +45572,7 @@ exports.default = Reader;
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
-const stream_1 = __nccwpck_require__(2413);
+const stream_1 = __nccwpck_require__(2781);
const fsStat = __nccwpck_require__(109);
const fsWalk = __nccwpck_require__(6026);
const reader_1 = __nccwpck_require__(5948);
@@ -43524,12 +45624,12 @@ class ReaderStream extends reader_1.default {
});
}
}
-exports.default = ReaderStream;
+exports["default"] = ReaderStream;
/***/ }),
-/***/ 5873:
+/***/ 7211:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
@@ -43575,7 +45675,7 @@ class ReaderSync extends reader_1.default {
return this._statSync(filepath, this._fsStatSettings);
}
}
-exports.default = ReaderSync;
+exports["default"] = ReaderSync;
/***/ }),
@@ -43587,8 +45687,8 @@ exports.default = ReaderSync;
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.DEFAULT_FILE_SYSTEM_ADAPTER = void 0;
-const fs = __nccwpck_require__(5747);
-const os = __nccwpck_require__(2087);
+const fs = __nccwpck_require__(7147);
+const os = __nccwpck_require__(2037);
/**
* The `os.cpus` method can return zero. We expect the number of cores to be greater than zero.
* https://github.com/nodejs/node/blob/7faeddf23a98c53896f8b574a6e66589e8fb1eb8/lib/os.js#L106-L107
@@ -43632,6 +45732,8 @@ class Settings {
if (this.stats) {
this.objectMode = true;
}
+ // Remove the cast to the array in the next major (#404).
+ this.ignore = [].concat(this.ignore);
}
_getValue(option, value) {
return option === undefined ? value : option;
@@ -43640,7 +45742,7 @@ class Settings {
return Object.assign(Object.assign({}, exports.DEFAULT_FILE_SYSTEM_ADAPTER), methods);
}
}
-exports.default = Settings;
+exports["default"] = Settings;
/***/ }),
@@ -43748,10 +45850,29 @@ exports.string = string;
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.removeLeadingDotSegment = exports.escape = exports.makeAbsolute = exports.unixify = void 0;
-const path = __nccwpck_require__(5622);
+exports.convertPosixPathToPattern = exports.convertWindowsPathToPattern = exports.convertPathToPattern = exports.escapePosixPath = exports.escapeWindowsPath = exports.escape = exports.removeLeadingDotSegment = exports.makeAbsolute = exports.unixify = void 0;
+const os = __nccwpck_require__(2037);
+const path = __nccwpck_require__(1017);
+const IS_WINDOWS_PLATFORM = os.platform() === 'win32';
const LEADING_DOT_SEGMENT_CHARACTERS_COUNT = 2; // ./ or .\\
-const UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()*?[\]{|}]|^!|[!+@](?=\())/g;
+/**
+ * All non-escaped special characters.
+ * Posix: ()*?[\]{|}, !+@ before (, ! at the beginning, \\ before non-special characters.
+ * Windows: (){}, !+@ before (, ! at the beginning.
+ */
+const POSIX_UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()*?[\]{|}]|^!|[!+@](?=\()|\\(?![!()*+?@[\]{|}]))/g;
+const WINDOWS_UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([(){}]|^!|[!+@](?=\())/g;
+/**
+ * The device path (\\.\ or \\?\).
+ * https://learn.microsoft.com/en-us/dotnet/standard/io/file-path-formats#dos-device-paths
+ */
+const DOS_DEVICE_PATH_RE = /^\\\\([.?])/;
+/**
+ * All backslashes except those escaping special characters.
+ * Windows: !()+@{}
+ * https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file#naming-conventions
+ */
+const WINDOWS_BACKSLASHES_RE = /\\(?![!()+@{}])/g;
/**
* Designed to work only with simple paths: `dir\\file`.
*/
@@ -43763,10 +45884,6 @@ function makeAbsolute(cwd, filepath) {
return path.resolve(cwd, filepath);
}
exports.makeAbsolute = makeAbsolute;
-function escape(pattern) {
- return pattern.replace(UNESCAPED_GLOB_SYMBOLS_RE, '\\$2');
-}
-exports.escape = escape;
function removeLeadingDotSegment(entry) {
// We do not use `startsWith` because this is 10x slower than current implementation for some cases.
// eslint-disable-next-line @typescript-eslint/prefer-string-starts-ends-with
@@ -43779,6 +45896,26 @@ function removeLeadingDotSegment(entry) {
return entry;
}
exports.removeLeadingDotSegment = removeLeadingDotSegment;
+exports.escape = IS_WINDOWS_PLATFORM ? escapeWindowsPath : escapePosixPath;
+function escapeWindowsPath(pattern) {
+ return pattern.replace(WINDOWS_UNESCAPED_GLOB_SYMBOLS_RE, '\\$2');
+}
+exports.escapeWindowsPath = escapeWindowsPath;
+function escapePosixPath(pattern) {
+ return pattern.replace(POSIX_UNESCAPED_GLOB_SYMBOLS_RE, '\\$2');
+}
+exports.escapePosixPath = escapePosixPath;
+exports.convertPathToPattern = IS_WINDOWS_PLATFORM ? convertWindowsPathToPattern : convertPosixPathToPattern;
+function convertWindowsPathToPattern(filepath) {
+ return escapeWindowsPath(filepath)
+ .replace(DOS_DEVICE_PATH_RE, '//$1')
+ .replace(WINDOWS_BACKSLASHES_RE, '/');
+}
+exports.convertWindowsPathToPattern = convertWindowsPathToPattern;
+function convertPosixPathToPattern(filepath) {
+ return escapePosixPath(filepath);
+}
+exports.convertPosixPathToPattern = convertPosixPathToPattern;
/***/ }),
@@ -43789,17 +45926,22 @@ exports.removeLeadingDotSegment = removeLeadingDotSegment;
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.matchAny = exports.convertPatternsToRe = exports.makeRe = exports.getPatternParts = exports.expandBraceExpansion = exports.expandPatternsWithBraceExpansion = exports.isAffectDepthOfReadingPattern = exports.endsWithSlashGlobStar = exports.hasGlobStar = exports.getBaseDirectory = exports.isPatternRelatedToParentDirectory = exports.getPatternsOutsideCurrentDirectory = exports.getPatternsInsideCurrentDirectory = exports.getPositivePatterns = exports.getNegativePatterns = exports.isPositivePattern = exports.isNegativePattern = exports.convertToNegativePattern = exports.convertToPositivePattern = exports.isDynamicPattern = exports.isStaticPattern = void 0;
-const path = __nccwpck_require__(5622);
-const globParent = __nccwpck_require__(4655);
+exports.removeDuplicateSlashes = exports.matchAny = exports.convertPatternsToRe = exports.makeRe = exports.getPatternParts = exports.expandBraceExpansion = exports.expandPatternsWithBraceExpansion = exports.isAffectDepthOfReadingPattern = exports.endsWithSlashGlobStar = exports.hasGlobStar = exports.getBaseDirectory = exports.isPatternRelatedToParentDirectory = exports.getPatternsOutsideCurrentDirectory = exports.getPatternsInsideCurrentDirectory = exports.getPositivePatterns = exports.getNegativePatterns = exports.isPositivePattern = exports.isNegativePattern = exports.convertToNegativePattern = exports.convertToPositivePattern = exports.isDynamicPattern = exports.isStaticPattern = void 0;
+const path = __nccwpck_require__(1017);
+const globParent = __nccwpck_require__(2604);
const micromatch = __nccwpck_require__(6228);
const GLOBSTAR = '**';
const ESCAPE_SYMBOL = '\\';
const COMMON_GLOB_SYMBOLS_RE = /[*?]|^!/;
-const REGEX_CHARACTER_CLASS_SYMBOLS_RE = /\[.*]/;
-const REGEX_GROUP_SYMBOLS_RE = /(?:^|[^!*+?@])\(.*\|.*\)/;
-const GLOB_EXTENSION_SYMBOLS_RE = /[!*+?@]\(.*\)/;
-const BRACE_EXPANSIONS_SYMBOLS_RE = /{.*(?:,|\.\.).*}/;
+const REGEX_CHARACTER_CLASS_SYMBOLS_RE = /\[[^[]*]/;
+const REGEX_GROUP_SYMBOLS_RE = /(?:^|[^!*+?@])\([^(]*\|[^|]*\)/;
+const GLOB_EXTENSION_SYMBOLS_RE = /[!*+?@]\([^(]*\)/;
+const BRACE_EXPANSION_SEPARATORS_RE = /,|\.\./;
+/**
+ * Matches a sequence of two or more consecutive slashes, excluding the first two slashes at the beginning of the string.
+ * The latter is due to the presence of the device path at the beginning of the UNC path.
+ */
+const DOUBLE_SLASH_RE = /(?!^)\/{2,}/g;
function isStaticPattern(pattern, options = {}) {
return !isDynamicPattern(pattern, options);
}
@@ -43826,12 +45968,24 @@ function isDynamicPattern(pattern, options = {}) {
if (options.extglob !== false && GLOB_EXTENSION_SYMBOLS_RE.test(pattern)) {
return true;
}
- if (options.braceExpansion !== false && BRACE_EXPANSIONS_SYMBOLS_RE.test(pattern)) {
+ if (options.braceExpansion !== false && hasBraceExpansion(pattern)) {
return true;
}
return false;
}
exports.isDynamicPattern = isDynamicPattern;
+function hasBraceExpansion(pattern) {
+ const openingBraceIndex = pattern.indexOf('{');
+ if (openingBraceIndex === -1) {
+ return false;
+ }
+ const closingBraceIndex = pattern.indexOf('}', openingBraceIndex + 1);
+ if (closingBraceIndex === -1) {
+ return false;
+ }
+ const braceContent = pattern.slice(openingBraceIndex, closingBraceIndex);
+ return BRACE_EXPANSION_SEPARATORS_RE.test(braceContent);
+}
function convertToPositivePattern(pattern) {
return isNegativePattern(pattern) ? pattern.slice(1) : pattern;
}
@@ -43906,10 +46060,16 @@ function expandPatternsWithBraceExpansion(patterns) {
}
exports.expandPatternsWithBraceExpansion = expandPatternsWithBraceExpansion;
function expandBraceExpansion(pattern) {
- return micromatch.braces(pattern, {
- expand: true,
- nodupes: true
- });
+ const patterns = micromatch.braces(pattern, { expand: true, nodupes: true });
+ /**
+ * Sort the patterns by length so that the same depth patterns are processed side by side.
+ * `a/{b,}/{c,}/*` – `['a///*', 'a/b//*', 'a//c/*', 'a/b/c/*']`
+ */
+ patterns.sort((a, b) => a.length - b.length);
+ /**
+ * Micromatch can return an empty string in the case of patterns like `{a,}`.
+ */
+ return patterns.filter((pattern) => pattern !== '');
}
exports.expandBraceExpansion = expandBraceExpansion;
function getPatternParts(pattern, options) {
@@ -43944,6 +46104,14 @@ function matchAny(entry, patternsRe) {
return patternsRe.some((patternRe) => patternRe.test(entry));
}
exports.matchAny = matchAny;
+/**
+ * This package only works with forward slashes as a path separator.
+ * Because of this, we cannot use the standard `path.normalize` method, because on Windows platform it will use of backslashes.
+ */
+function removeDuplicateSlashes(pattern) {
+ return pattern.replace(DOUBLE_SLASH_RE, '/');
+}
+exports.removeDuplicateSlashes = removeDuplicateSlashes;
/***/ }),
@@ -43990,6 +46158,56 @@ function isEmpty(input) {
exports.isEmpty = isEmpty;
+/***/ }),
+
+/***/ 2604:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+var isGlob = __nccwpck_require__(4466);
+var pathPosixDirname = (__nccwpck_require__(1017).posix.dirname);
+var isWin32 = (__nccwpck_require__(2037).platform)() === 'win32';
+
+var slash = '/';
+var backslash = /\\/g;
+var enclosure = /[\{\[].*[\}\]]$/;
+var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/;
+var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g;
+
+/**
+ * @param {string} str
+ * @param {Object} opts
+ * @param {boolean} [opts.flipBackslashes=true]
+ * @returns {string}
+ */
+module.exports = function globParent(str, opts) {
+ var options = Object.assign({ flipBackslashes: true }, opts);
+
+ // flip windows path separators
+ if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) {
+ str = str.replace(backslash, slash);
+ }
+
+ // special case for strings ending in enclosure containing path separator
+ if (enclosure.test(str)) {
+ str += slash;
+ }
+
+ // preserves full path in case of trailing path separator
+ str += 'a';
+
+ // remove path parts that are globby
+ do {
+ str = pathPosixDirname(str);
+ } while (isGlob(str) || globby.test(str));
+
+ // remove escape chars and return result
+ return str.replace(escaped, '$1');
+};
+
+
/***/ }),
/***/ 4393:
@@ -43999,7 +46217,11 @@ exports.isEmpty = isEmpty;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
+ var desc = Object.getOwnPropertyDescriptor(m, k);
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+ desc = { enumerable: true, get: function() { return m[k]; } };
+ }
+ Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
@@ -44008,14 +46230,14 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
-__exportStar(__nccwpck_require__(4408), exports);
+__exportStar(__nccwpck_require__(772), exports);
__exportStar(__nccwpck_require__(2914), exports);
__exportStar(__nccwpck_require__(6188), exports);
//# sourceMappingURL=index.js.map
/***/ }),
-/***/ 4408:
+/***/ 772:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
@@ -44049,7 +46271,11 @@ exports.ACTIONS_RUNTIME_TOKEN = `ACTIONS_RUNTIME_TOKEN`;
// SPDX short identifier: MIT
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
+ var desc = Object.getOwnPropertyDescriptor(m, k);
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+ desc = { enumerable: true, get: function() { return m[k]; } };
+ }
+ Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
@@ -44077,27 +46303,12 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.VcpkgRunner = void 0;
-const path = __importStar(__nccwpck_require__(5622));
-const globals = __importStar(__nccwpck_require__(4408));
+const path = __importStar(__nccwpck_require__(1017));
+const globals = __importStar(__nccwpck_require__(772));
const vcpkgutils = __importStar(__nccwpck_require__(6188));
const baseutillib = __importStar(__nccwpck_require__(2365));
-const using_statement_1 = __nccwpck_require__(1861);
+const using_statement_1 = __nccwpck_require__(153);
class VcpkgRunner {
- /**
- * @description Used only in tests.
- */
- constructor(baseUtils, vcpkgDestPath, vcpkgUrl, vcpkgGitCommitId, doRunVcpkgInstall, doNotUpdateVcpkg, runVcpkgInstallPath, pathToLastBuiltCommitId, options = {}, vcpkgInstallCmd) {
- this.baseUtils = baseUtils;
- this.vcpkgDestPath = vcpkgDestPath;
- this.vcpkgUrl = vcpkgUrl;
- this.vcpkgGitCommitId = vcpkgGitCommitId;
- this.doRunVcpkgInstall = doRunVcpkgInstall;
- this.doNotUpdateVcpkg = doNotUpdateVcpkg;
- this.runVcpkgInstallPath = runVcpkgInstallPath;
- this.pathToLastBuiltCommitId = pathToLastBuiltCommitId;
- this.options = options;
- this.vcpkgInstallCmd = vcpkgInstallCmd;
- }
/**
* @description Used only in tests.
*/
@@ -44144,9 +46355,24 @@ class VcpkgRunner {
yield vcpkgRunner.run();
});
}
+ /**
+ * @description Used only in tests.
+ */
+ constructor(baseUtils, vcpkgDestPath, vcpkgUrl, vcpkgGitCommitId, doRunVcpkgInstall, doNotUpdateVcpkg, runVcpkgInstallPath, pathToLastBuiltCommitId, options = {}, vcpkgInstallCmd) {
+ this.baseUtils = baseUtils;
+ this.vcpkgDestPath = vcpkgDestPath;
+ this.vcpkgUrl = vcpkgUrl;
+ this.vcpkgGitCommitId = vcpkgGitCommitId;
+ this.doRunVcpkgInstall = doRunVcpkgInstall;
+ this.doNotUpdateVcpkg = doNotUpdateVcpkg;
+ this.runVcpkgInstallPath = runVcpkgInstallPath;
+ this.pathToLastBuiltCommitId = pathToLastBuiltCommitId;
+ this.options = options;
+ this.vcpkgInstallCmd = vcpkgInstallCmd;
+ }
run() {
return __awaiter(this, void 0, void 0, function* () {
- yield using_statement_1.using(baseutillib.Matcher.createMatcher('all', this.baseUtils.baseLib, __dirname), () => __awaiter(this, void 0, void 0, function* () { return this.runImpl(); }));
+ yield (0, using_statement_1.using)(baseutillib.Matcher.createMatcher('all', this.baseUtils.baseLib, __dirname), () => __awaiter(this, void 0, void 0, function* () { return this.runImpl(); }));
});
}
runImpl() {
@@ -44455,7 +46681,11 @@ VcpkgRunner.VCPKG_FORCE_SYSTEM_BINARIES = "VCPKG_FORCE_SYSTEM_BINARIES";
// SPDX short identifier: MIT
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
+ var desc = Object.getOwnPropertyDescriptor(m, k);
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+ desc = { enumerable: true, get: function() { return m[k]; } };
+ }
+ Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
@@ -44483,7 +46713,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getDefaultVcpkgCacheDirectory = exports.getDefaultVcpkgInstallDirectory = exports.getDefaultVcpkgDirectory = exports.getOrdinaryCachedPaths = void 0;
-const path = __importStar(__nccwpck_require__(5622));
+const path = __importStar(__nccwpck_require__(1017));
/**
*
* @param vcpkgRootDir The VCPKG_ROOT directory.
@@ -44533,7 +46763,7 @@ function fwSlash(p) {
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0;
-const fs = __nccwpck_require__(5747);
+const fs = __nccwpck_require__(7147);
exports.FILE_SYSTEM_ADAPTER = {
lstat: fs.lstat,
stat: fs.stat,
@@ -44813,7 +47043,7 @@ exports.readdir = readdir;
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
-const path = __nccwpck_require__(5622);
+const path = __nccwpck_require__(1017);
const fsStat = __nccwpck_require__(109);
const fs = __nccwpck_require__(3803);
class Settings {
@@ -44834,7 +47064,7 @@ class Settings {
return option !== null && option !== void 0 ? option : value;
}
}
-exports.default = Settings;
+exports["default"] = Settings;
/***/ }),
@@ -44886,7 +47116,7 @@ exports.fs = fs;
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0;
-const fs = __nccwpck_require__(5747);
+const fs = __nccwpck_require__(7147);
exports.FILE_SYSTEM_ADAPTER = {
lstat: fs.lstat,
stat: fs.stat,
@@ -45032,7 +47262,7 @@ class Settings {
return option !== null && option !== void 0 ? option : value;
}
}
-exports.default = Settings;
+exports["default"] = Settings;
/***/ }),
@@ -45106,7 +47336,7 @@ class AsyncProvider {
this._reader.read();
}
}
-exports.default = AsyncProvider;
+exports["default"] = AsyncProvider;
function callFailureCallback(callback, error) {
callback(error);
}
@@ -45123,7 +47353,7 @@ function callSuccessCallback(callback, entries) {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
-const stream_1 = __nccwpck_require__(2413);
+const stream_1 = __nccwpck_require__(2781);
const async_1 = __nccwpck_require__(5732);
class StreamProvider {
constructor(_root, _settings) {
@@ -45154,7 +47384,7 @@ class StreamProvider {
return this._stream;
}
}
-exports.default = StreamProvider;
+exports["default"] = StreamProvider;
/***/ }),
@@ -45176,7 +47406,7 @@ class SyncProvider {
return this._reader.read();
}
}
-exports.default = SyncProvider;
+exports["default"] = SyncProvider;
/***/ }),
@@ -45187,7 +47417,7 @@ exports.default = SyncProvider;
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
-const events_1 = __nccwpck_require__(8614);
+const events_1 = __nccwpck_require__(2361);
const fsScandir = __nccwpck_require__(5667);
const fastq = __nccwpck_require__(7340);
const common = __nccwpck_require__(7988);
@@ -45281,7 +47511,7 @@ class AsyncReader extends reader_1.default {
this._emitter.emit('entry', entry);
}
}
-exports.default = AsyncReader;
+exports["default"] = AsyncReader;
/***/ }),
@@ -45339,7 +47569,7 @@ class Reader {
this._root = common.replacePathSegmentSeparator(_root, _settings.pathSegmentSeparator);
}
}
-exports.default = Reader;
+exports["default"] = Reader;
/***/ }),
@@ -45406,7 +47636,7 @@ class SyncReader extends reader_1.default {
this._storage.push(entry);
}
}
-exports.default = SyncReader;
+exports["default"] = SyncReader;
/***/ }),
@@ -45417,7 +47647,7 @@ exports.default = SyncReader;
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
-const path = __nccwpck_require__(5622);
+const path = __nccwpck_require__(1017);
const fsScandir = __nccwpck_require__(5667);
class Settings {
constructor(_options = {}) {
@@ -45440,13 +47670,13 @@ class Settings {
return option !== null && option !== void 0 ? option : value;
}
}
-exports.default = Settings;
+exports["default"] = Settings;
/***/ }),
/***/ 7171:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
@@ -45465,46 +47695,40 @@ exports.default = Settings;
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var __spreadArray = (this && this.__spreadArray) || function (to, from) {
- for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
- to[j] = from[i];
- return to;
-};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ContextAPI = void 0;
-var NoopContextManager_1 = __nccwpck_require__(4118);
-var global_utils_1 = __nccwpck_require__(5135);
-var diag_1 = __nccwpck_require__(1877);
-var API_NAME = 'context';
-var NOOP_CONTEXT_MANAGER = new NoopContextManager_1.NoopContextManager();
+const NoopContextManager_1 = __nccwpck_require__(4118);
+const global_utils_1 = __nccwpck_require__(5135);
+const diag_1 = __nccwpck_require__(1877);
+const API_NAME = 'context';
+const NOOP_CONTEXT_MANAGER = new NoopContextManager_1.NoopContextManager();
/**
* Singleton object which represents the entry point to the OpenTelemetry Context API
*/
-var ContextAPI = /** @class */ (function () {
+class ContextAPI {
/** Empty private constructor prevents end users from constructing a new instance of the API */
- function ContextAPI() {
- }
+ constructor() { }
/** Get the singleton instance of the Context API */
- ContextAPI.getInstance = function () {
+ static getInstance() {
if (!this._instance) {
this._instance = new ContextAPI();
}
return this._instance;
- };
+ }
/**
* Set the current context manager.
*
* @returns true if the context manager was successfully registered, else false
*/
- ContextAPI.prototype.setGlobalContextManager = function (contextManager) {
- return global_utils_1.registerGlobal(API_NAME, contextManager, diag_1.DiagAPI.instance());
- };
+ setGlobalContextManager(contextManager) {
+ return (0, global_utils_1.registerGlobal)(API_NAME, contextManager, diag_1.DiagAPI.instance());
+ }
/**
* Get the currently active context
*/
- ContextAPI.prototype.active = function () {
+ active() {
return this._getContextManager().active();
- };
+ }
/**
* Execute a function with an active context
*
@@ -45513,33 +47737,27 @@ var ContextAPI = /** @class */ (function () {
* @param thisArg optional receiver to be used for calling fn
* @param args optional arguments forwarded to fn
*/
- ContextAPI.prototype.with = function (context, fn, thisArg) {
- var _a;
- var args = [];
- for (var _i = 3; _i < arguments.length; _i++) {
- args[_i - 3] = arguments[_i];
- }
- return (_a = this._getContextManager()).with.apply(_a, __spreadArray([context, fn, thisArg], args));
- };
+ with(context, fn, thisArg, ...args) {
+ return this._getContextManager().with(context, fn, thisArg, ...args);
+ }
/**
* Bind a context to a target function or event emitter
*
* @param context context to bind to the event emitter or function. Defaults to the currently active context
* @param target function or event emitter to bind
*/
- ContextAPI.prototype.bind = function (context, target) {
+ bind(context, target) {
return this._getContextManager().bind(context, target);
- };
- ContextAPI.prototype._getContextManager = function () {
- return global_utils_1.getGlobal(API_NAME) || NOOP_CONTEXT_MANAGER;
- };
+ }
+ _getContextManager() {
+ return (0, global_utils_1.getGlobal)(API_NAME) || NOOP_CONTEXT_MANAGER;
+ }
/** Disable and remove the global context manager */
- ContextAPI.prototype.disable = function () {
+ disable() {
this._getContextManager().disable();
- global_utils_1.unregisterGlobal(API_NAME, diag_1.DiagAPI.instance());
- };
- return ContextAPI;
-}());
+ (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance());
+ }
+}
exports.ContextAPI = ContextAPI;
//# sourceMappingURL=context.js.map
@@ -45567,62 +47785,63 @@ exports.ContextAPI = ContextAPI;
*/
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.DiagAPI = void 0;
-var ComponentLogger_1 = __nccwpck_require__(7978);
-var logLevelLogger_1 = __nccwpck_require__(9639);
-var types_1 = __nccwpck_require__(8077);
-var global_utils_1 = __nccwpck_require__(5135);
-var API_NAME = 'diag';
+const ComponentLogger_1 = __nccwpck_require__(7978);
+const logLevelLogger_1 = __nccwpck_require__(9639);
+const types_1 = __nccwpck_require__(8077);
+const global_utils_1 = __nccwpck_require__(5135);
+const API_NAME = 'diag';
/**
* Singleton object which represents the entry point to the OpenTelemetry internal
* diagnostic API
*/
-var DiagAPI = /** @class */ (function () {
+class DiagAPI {
/**
* Private internal constructor
* @private
*/
- function DiagAPI() {
+ constructor() {
function _logProxy(funcName) {
- return function () {
- var args = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- args[_i] = arguments[_i];
- }
- var logger = global_utils_1.getGlobal('diag');
+ return function (...args) {
+ const logger = (0, global_utils_1.getGlobal)('diag');
// shortcut if logger not set
if (!logger)
return;
- return logger[funcName].apply(logger, args);
+ return logger[funcName](...args);
};
}
// Using self local variable for minification purposes as 'this' cannot be minified
- var self = this;
+ const self = this;
// DiagAPI specific functions
- self.setLogger = function (logger, logLevel) {
- var _a, _b;
- if (logLevel === void 0) { logLevel = types_1.DiagLogLevel.INFO; }
+ const setLogger = (logger, optionsOrLogLevel = { logLevel: types_1.DiagLogLevel.INFO }) => {
+ var _a, _b, _c;
if (logger === self) {
// There isn't much we can do here.
// Logging to the console might break the user application.
// Try to log to self. If a logger was previously registered it will receive the log.
- var err = new Error('Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation');
+ const err = new Error('Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation');
self.error((_a = err.stack) !== null && _a !== void 0 ? _a : err.message);
return false;
}
- var oldLogger = global_utils_1.getGlobal('diag');
- var newLogger = logLevelLogger_1.createLogLevelDiagLogger(logLevel, logger);
+ if (typeof optionsOrLogLevel === 'number') {
+ optionsOrLogLevel = {
+ logLevel: optionsOrLogLevel,
+ };
+ }
+ const oldLogger = (0, global_utils_1.getGlobal)('diag');
+ const newLogger = (0, logLevelLogger_1.createLogLevelDiagLogger)((_b = optionsOrLogLevel.logLevel) !== null && _b !== void 0 ? _b : types_1.DiagLogLevel.INFO, logger);
// There already is an logger registered. We'll let it know before overwriting it.
- if (oldLogger) {
- var stack = (_b = new Error().stack) !== null && _b !== void 0 ? _b : '';
- oldLogger.warn("Current logger will be overwritten from " + stack);
- newLogger.warn("Current logger will overwrite one already registered from " + stack);
+ if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) {
+ const stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : '';
+ oldLogger.warn(`Current logger will be overwritten from ${stack}`);
+ newLogger.warn(`Current logger will overwrite one already registered from ${stack}`);
}
- return global_utils_1.registerGlobal('diag', newLogger, self, true);
+ return (0, global_utils_1.registerGlobal)('diag', newLogger, self, true);
};
- self.disable = function () {
- global_utils_1.unregisterGlobal(API_NAME, self);
+ self.setLogger = setLogger;
+ self.disable = () => {
+ (0, global_utils_1.unregisterGlobal)(API_NAME, self);
};
- self.createComponentLogger = function (options) {
+ self.createComponentLogger = (options) => {
return new ComponentLogger_1.DiagComponentLogger(options);
};
self.verbose = _logProxy('verbose');
@@ -45632,19 +47851,86 @@ var DiagAPI = /** @class */ (function () {
self.error = _logProxy('error');
}
/** Get the singleton instance of the DiagAPI API */
- DiagAPI.instance = function () {
+ static instance() {
if (!this._instance) {
this._instance = new DiagAPI();
}
return this._instance;
- };
- return DiagAPI;
-}());
+ }
+}
exports.DiagAPI = DiagAPI;
//# sourceMappingURL=diag.js.map
/***/ }),
+/***/ 7696:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+/*
+ * Copyright The OpenTelemetry Authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.MetricsAPI = void 0;
+const NoopMeterProvider_1 = __nccwpck_require__(2647);
+const global_utils_1 = __nccwpck_require__(5135);
+const diag_1 = __nccwpck_require__(1877);
+const API_NAME = 'metrics';
+/**
+ * Singleton object which represents the entry point to the OpenTelemetry Metrics API
+ */
+class MetricsAPI {
+ /** Empty private constructor prevents end users from constructing a new instance of the API */
+ constructor() { }
+ /** Get the singleton instance of the Metrics API */
+ static getInstance() {
+ if (!this._instance) {
+ this._instance = new MetricsAPI();
+ }
+ return this._instance;
+ }
+ /**
+ * Set the current global meter provider.
+ * Returns true if the meter provider was successfully registered, else false.
+ */
+ setGlobalMeterProvider(provider) {
+ return (0, global_utils_1.registerGlobal)(API_NAME, provider, diag_1.DiagAPI.instance());
+ }
+ /**
+ * Returns the global meter provider.
+ */
+ getMeterProvider() {
+ return (0, global_utils_1.getGlobal)(API_NAME) || NoopMeterProvider_1.NOOP_METER_PROVIDER;
+ }
+ /**
+ * Returns a meter from the global meter provider.
+ */
+ getMeter(name, version, options) {
+ return this.getMeterProvider().getMeter(name, version, options);
+ }
+ /** Remove the global meter provider */
+ disable() {
+ (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance());
+ }
+}
+exports.MetricsAPI = MetricsAPI;
+//# sourceMappingURL=metrics.js.map
+
+/***/ }),
+
/***/ 9909:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
@@ -45667,40 +47953,41 @@ exports.DiagAPI = DiagAPI;
*/
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.PropagationAPI = void 0;
-var global_utils_1 = __nccwpck_require__(5135);
-var NoopTextMapPropagator_1 = __nccwpck_require__(2368);
-var TextMapPropagator_1 = __nccwpck_require__(865);
-var context_helpers_1 = __nccwpck_require__(7682);
-var utils_1 = __nccwpck_require__(8136);
-var diag_1 = __nccwpck_require__(1877);
-var API_NAME = 'propagation';
-var NOOP_TEXT_MAP_PROPAGATOR = new NoopTextMapPropagator_1.NoopTextMapPropagator();
+const global_utils_1 = __nccwpck_require__(5135);
+const NoopTextMapPropagator_1 = __nccwpck_require__(2368);
+const TextMapPropagator_1 = __nccwpck_require__(865);
+const context_helpers_1 = __nccwpck_require__(7682);
+const utils_1 = __nccwpck_require__(8136);
+const diag_1 = __nccwpck_require__(1877);
+const API_NAME = 'propagation';
+const NOOP_TEXT_MAP_PROPAGATOR = new NoopTextMapPropagator_1.NoopTextMapPropagator();
/**
* Singleton object which represents the entry point to the OpenTelemetry Propagation API
*/
-var PropagationAPI = /** @class */ (function () {
+class PropagationAPI {
/** Empty private constructor prevents end users from constructing a new instance of the API */
- function PropagationAPI() {
+ constructor() {
this.createBaggage = utils_1.createBaggage;
this.getBaggage = context_helpers_1.getBaggage;
+ this.getActiveBaggage = context_helpers_1.getActiveBaggage;
this.setBaggage = context_helpers_1.setBaggage;
this.deleteBaggage = context_helpers_1.deleteBaggage;
}
/** Get the singleton instance of the Propagator API */
- PropagationAPI.getInstance = function () {
+ static getInstance() {
if (!this._instance) {
this._instance = new PropagationAPI();
}
return this._instance;
- };
+ }
/**
* Set the current propagator.
*
* @returns true if the propagator was successfully registered, else false
*/
- PropagationAPI.prototype.setGlobalPropagator = function (propagator) {
- return global_utils_1.registerGlobal(API_NAME, propagator, diag_1.DiagAPI.instance());
- };
+ setGlobalPropagator(propagator) {
+ return (0, global_utils_1.registerGlobal)(API_NAME, propagator, diag_1.DiagAPI.instance());
+ }
/**
* Inject context into a carrier to be propagated inter-process
*
@@ -45708,10 +47995,9 @@ var PropagationAPI = /** @class */ (function () {
* @param carrier carrier to inject context into
* @param setter Function used to set values on the carrier
*/
- PropagationAPI.prototype.inject = function (context, carrier, setter) {
- if (setter === void 0) { setter = TextMapPropagator_1.defaultTextMapSetter; }
+ inject(context, carrier, setter = TextMapPropagator_1.defaultTextMapSetter) {
return this._getGlobalPropagator().inject(context, carrier, setter);
- };
+ }
/**
* Extract context from a carrier
*
@@ -45719,25 +48005,23 @@ var PropagationAPI = /** @class */ (function () {
* @param carrier Carrier to extract context from
* @param getter Function used to extract keys from a carrier
*/
- PropagationAPI.prototype.extract = function (context, carrier, getter) {
- if (getter === void 0) { getter = TextMapPropagator_1.defaultTextMapGetter; }
+ extract(context, carrier, getter = TextMapPropagator_1.defaultTextMapGetter) {
return this._getGlobalPropagator().extract(context, carrier, getter);
- };
+ }
/**
* Return a list of all fields which may be used by the propagator.
*/
- PropagationAPI.prototype.fields = function () {
+ fields() {
return this._getGlobalPropagator().fields();
- };
+ }
/** Remove the global propagator */
- PropagationAPI.prototype.disable = function () {
- global_utils_1.unregisterGlobal(API_NAME, diag_1.DiagAPI.instance());
- };
- PropagationAPI.prototype._getGlobalPropagator = function () {
- return global_utils_1.getGlobal(API_NAME) || NOOP_TEXT_MAP_PROPAGATOR;
- };
- return PropagationAPI;
-}());
+ disable() {
+ (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance());
+ }
+ _getGlobalPropagator() {
+ return (0, global_utils_1.getGlobal)(API_NAME) || NOOP_TEXT_MAP_PROPAGATOR;
+ }
+}
exports.PropagationAPI = PropagationAPI;
//# sourceMappingURL=propagation.js.map
@@ -45765,65 +48049,65 @@ exports.PropagationAPI = PropagationAPI;
*/
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.TraceAPI = void 0;
-var global_utils_1 = __nccwpck_require__(5135);
-var ProxyTracerProvider_1 = __nccwpck_require__(2285);
-var spancontext_utils_1 = __nccwpck_require__(9745);
-var context_utils_1 = __nccwpck_require__(3326);
-var diag_1 = __nccwpck_require__(1877);
-var API_NAME = 'trace';
+const global_utils_1 = __nccwpck_require__(5135);
+const ProxyTracerProvider_1 = __nccwpck_require__(2285);
+const spancontext_utils_1 = __nccwpck_require__(9745);
+const context_utils_1 = __nccwpck_require__(3326);
+const diag_1 = __nccwpck_require__(1877);
+const API_NAME = 'trace';
/**
* Singleton object which represents the entry point to the OpenTelemetry Tracing API
*/
-var TraceAPI = /** @class */ (function () {
+class TraceAPI {
/** Empty private constructor prevents end users from constructing a new instance of the API */
- function TraceAPI() {
+ constructor() {
this._proxyTracerProvider = new ProxyTracerProvider_1.ProxyTracerProvider();
this.wrapSpanContext = spancontext_utils_1.wrapSpanContext;
this.isSpanContextValid = spancontext_utils_1.isSpanContextValid;
this.deleteSpan = context_utils_1.deleteSpan;
this.getSpan = context_utils_1.getSpan;
+ this.getActiveSpan = context_utils_1.getActiveSpan;
this.getSpanContext = context_utils_1.getSpanContext;
this.setSpan = context_utils_1.setSpan;
this.setSpanContext = context_utils_1.setSpanContext;
}
/** Get the singleton instance of the Trace API */
- TraceAPI.getInstance = function () {
+ static getInstance() {
if (!this._instance) {
this._instance = new TraceAPI();
}
return this._instance;
- };
+ }
/**
* Set the current global tracer.
*
* @returns true if the tracer provider was successfully registered, else false
*/
- TraceAPI.prototype.setGlobalTracerProvider = function (provider) {
- var success = global_utils_1.registerGlobal(API_NAME, this._proxyTracerProvider, diag_1.DiagAPI.instance());
+ setGlobalTracerProvider(provider) {
+ const success = (0, global_utils_1.registerGlobal)(API_NAME, this._proxyTracerProvider, diag_1.DiagAPI.instance());
if (success) {
this._proxyTracerProvider.setDelegate(provider);
}
return success;
- };
+ }
/**
* Returns the global tracer provider.
*/
- TraceAPI.prototype.getTracerProvider = function () {
- return global_utils_1.getGlobal(API_NAME) || this._proxyTracerProvider;
- };
+ getTracerProvider() {
+ return (0, global_utils_1.getGlobal)(API_NAME) || this._proxyTracerProvider;
+ }
/**
* Returns a tracer from the global tracer provider.
*/
- TraceAPI.prototype.getTracer = function (name, version) {
+ getTracer(name, version) {
return this.getTracerProvider().getTracer(name, version);
- };
+ }
/** Remove the global tracer provider */
- TraceAPI.prototype.disable = function () {
- global_utils_1.unregisterGlobal(API_NAME, diag_1.DiagAPI.instance());
+ disable() {
+ (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance());
this._proxyTracerProvider = new ProxyTracerProvider_1.ProxyTracerProvider();
- };
- return TraceAPI;
-}());
+ }
+}
exports.TraceAPI = TraceAPI;
//# sourceMappingURL=trace.js.map
@@ -45850,12 +48134,13 @@ exports.TraceAPI = TraceAPI;
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.deleteBaggage = exports.setBaggage = exports.getBaggage = void 0;
-var context_1 = __nccwpck_require__(8242);
+exports.deleteBaggage = exports.setBaggage = exports.getActiveBaggage = exports.getBaggage = void 0;
+const context_1 = __nccwpck_require__(7171);
+const context_2 = __nccwpck_require__(8242);
/**
* Baggage key
*/
-var BAGGAGE_KEY = context_1.createContextKey('OpenTelemetry Baggage Key');
+const BAGGAGE_KEY = (0, context_2.createContextKey)('OpenTelemetry Baggage Key');
/**
* Retrieve the current baggage from the given context
*
@@ -45866,6 +48151,15 @@ function getBaggage(context) {
return context.getValue(BAGGAGE_KEY) || undefined;
}
exports.getBaggage = getBaggage;
+/**
+ * Retrieve the current baggage from the active/current context
+ *
+ * @returns {Baggage} Extracted baggage from the context
+ */
+function getActiveBaggage() {
+ return getBaggage(context_1.ContextAPI.getInstance().active());
+}
+exports.getActiveBaggage = getActiveBaggage;
/**
* Store a baggage in the given context
*
@@ -45911,50 +48205,41 @@ exports.deleteBaggage = deleteBaggage;
*/
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.BaggageImpl = void 0;
-var BaggageImpl = /** @class */ (function () {
- function BaggageImpl(entries) {
+class BaggageImpl {
+ constructor(entries) {
this._entries = entries ? new Map(entries) : new Map();
}
- BaggageImpl.prototype.getEntry = function (key) {
- var entry = this._entries.get(key);
+ getEntry(key) {
+ const entry = this._entries.get(key);
if (!entry) {
return undefined;
}
return Object.assign({}, entry);
- };
- BaggageImpl.prototype.getAllEntries = function () {
- return Array.from(this._entries.entries()).map(function (_a) {
- var k = _a[0], v = _a[1];
- return [k, v];
- });
- };
- BaggageImpl.prototype.setEntry = function (key, entry) {
- var newBaggage = new BaggageImpl(this._entries);
+ }
+ getAllEntries() {
+ return Array.from(this._entries.entries()).map(([k, v]) => [k, v]);
+ }
+ setEntry(key, entry) {
+ const newBaggage = new BaggageImpl(this._entries);
newBaggage._entries.set(key, entry);
return newBaggage;
- };
- BaggageImpl.prototype.removeEntry = function (key) {
- var newBaggage = new BaggageImpl(this._entries);
+ }
+ removeEntry(key) {
+ const newBaggage = new BaggageImpl(this._entries);
newBaggage._entries.delete(key);
return newBaggage;
- };
- BaggageImpl.prototype.removeEntries = function () {
- var keys = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- keys[_i] = arguments[_i];
- }
- var newBaggage = new BaggageImpl(this._entries);
- for (var _a = 0, keys_1 = keys; _a < keys_1.length; _a++) {
- var key = keys_1[_a];
+ }
+ removeEntries(...keys) {
+ const newBaggage = new BaggageImpl(this._entries);
+ for (const key of keys) {
newBaggage._entries.delete(key);
}
return newBaggage;
- };
- BaggageImpl.prototype.clear = function () {
+ }
+ clear() {
return new BaggageImpl();
- };
- return BaggageImpl;
-}());
+ }
+}
exports.BaggageImpl = BaggageImpl;
//# sourceMappingURL=baggage-impl.js.map
@@ -45990,31 +48275,6 @@ exports.baggageEntryMetadataSymbol = Symbol('BaggageEntryMetadata');
/***/ }),
-/***/ 1508:
-/***/ ((__unused_webpack_module, exports) => {
-
-"use strict";
-
-/*
- * Copyright The OpenTelemetry Authors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-//# sourceMappingURL=types.js.map
-
-/***/ }),
-
/***/ 8136:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
@@ -46037,17 +48297,16 @@ Object.defineProperty(exports, "__esModule", ({ value: true }));
*/
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.baggageEntryMetadataFromString = exports.createBaggage = void 0;
-var diag_1 = __nccwpck_require__(1877);
-var baggage_impl_1 = __nccwpck_require__(4811);
-var symbol_1 = __nccwpck_require__(3542);
-var diag = diag_1.DiagAPI.instance();
+const diag_1 = __nccwpck_require__(1877);
+const baggage_impl_1 = __nccwpck_require__(4811);
+const symbol_1 = __nccwpck_require__(3542);
+const diag = diag_1.DiagAPI.instance();
/**
* Create a new Baggage with optional entries
*
* @param entries An array of baggage entries the new baggage should contain
*/
-function createBaggage(entries) {
- if (entries === void 0) { entries = {}; }
+function createBaggage(entries = {}) {
return new baggage_impl_1.BaggageImpl(new Map(Object.entries(entries)));
}
exports.createBaggage = createBaggage;
@@ -46059,12 +48318,12 @@ exports.createBaggage = createBaggage;
*/
function baggageEntryMetadataFromString(str) {
if (typeof str !== 'string') {
- diag.error("Cannot create baggage metadata from unknown type: " + typeof str);
+ diag.error(`Cannot create baggage metadata from unknown type: ${typeof str}`);
str = '';
}
return {
__TYPE__: symbol_1.baggageEntryMetadataSymbol,
- toString: function () {
+ toString() {
return str;
},
};
@@ -46074,33 +48333,8 @@ exports.baggageEntryMetadataFromString = baggageEntryMetadataFromString;
/***/ }),
-/***/ 1109:
-/***/ ((__unused_webpack_module, exports) => {
-
-"use strict";
-
-/*
- * Copyright The OpenTelemetry Authors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-//# sourceMappingURL=Attributes.js.map
-
-/***/ }),
-
-/***/ 4447:
-/***/ ((__unused_webpack_module, exports) => {
+/***/ 7393:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
@@ -46120,22 +48354,18 @@ Object.defineProperty(exports, "__esModule", ({ value: true }));
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", ({ value: true }));
-//# sourceMappingURL=Exception.js.map
-
-/***/ }),
-
-/***/ 2358:
-/***/ ((__unused_webpack_module, exports) => {
-
-"use strict";
-
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-//# sourceMappingURL=Time.js.map
+exports.context = void 0;
+// Split module-level variable definition into separate files to allow
+// tree-shaking on each api instance.
+const context_1 = __nccwpck_require__(7171);
+/** Entrypoint for context API */
+exports.context = context_1.ContextAPI.getInstance();
+//# sourceMappingURL=context-api.js.map
/***/ }),
/***/ 4118:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
@@ -46154,38 +48384,26 @@ Object.defineProperty(exports, "__esModule", ({ value: true }));
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var __spreadArray = (this && this.__spreadArray) || function (to, from) {
- for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
- to[j] = from[i];
- return to;
-};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.NoopContextManager = void 0;
-var context_1 = __nccwpck_require__(8242);
-var NoopContextManager = /** @class */ (function () {
- function NoopContextManager() {
- }
- NoopContextManager.prototype.active = function () {
+const context_1 = __nccwpck_require__(8242);
+class NoopContextManager {
+ active() {
return context_1.ROOT_CONTEXT;
- };
- NoopContextManager.prototype.with = function (_context, fn, thisArg) {
- var args = [];
- for (var _i = 3; _i < arguments.length; _i++) {
- args[_i - 3] = arguments[_i];
- }
- return fn.call.apply(fn, __spreadArray([thisArg], args));
- };
- NoopContextManager.prototype.bind = function (_context, target) {
+ }
+ with(_context, fn, thisArg, ...args) {
+ return fn.call(thisArg, ...args);
+ }
+ bind(_context, target) {
return target;
- };
- NoopContextManager.prototype.enable = function () {
+ }
+ enable() {
return this;
- };
- NoopContextManager.prototype.disable = function () {
+ }
+ disable() {
return this;
- };
- return NoopContextManager;
-}());
+ }
+}
exports.NoopContextManager = NoopContextManager;
//# sourceMappingURL=NoopContextManager.js.map
@@ -46224,38 +48442,37 @@ function createContextKey(description) {
return Symbol.for(description);
}
exports.createContextKey = createContextKey;
-var BaseContext = /** @class */ (function () {
+class BaseContext {
/**
* Construct a new context which inherits values from an optional parent context.
*
* @param parentContext a context from which to inherit values
*/
- function BaseContext(parentContext) {
+ constructor(parentContext) {
// for minification
- var self = this;
+ const self = this;
self._currentContext = parentContext ? new Map(parentContext) : new Map();
- self.getValue = function (key) { return self._currentContext.get(key); };
- self.setValue = function (key, value) {
- var context = new BaseContext(self._currentContext);
+ self.getValue = (key) => self._currentContext.get(key);
+ self.setValue = (key, value) => {
+ const context = new BaseContext(self._currentContext);
context._currentContext.set(key, value);
return context;
};
- self.deleteValue = function (key) {
- var context = new BaseContext(self._currentContext);
+ self.deleteValue = (key) => {
+ const context = new BaseContext(self._currentContext);
context._currentContext.delete(key);
return context;
};
}
- return BaseContext;
-}());
+}
/** The root context is used as the default parent context when there is no active context */
exports.ROOT_CONTEXT = new BaseContext();
//# sourceMappingURL=context.js.map
/***/ }),
-/***/ 6504:
-/***/ ((__unused_webpack_module, exports) => {
+/***/ 9721:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
@@ -46275,7 +48492,18 @@ exports.ROOT_CONTEXT = new BaseContext();
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", ({ value: true }));
-//# sourceMappingURL=types.js.map
+exports.diag = void 0;
+// Split module-level variable definition into separate files to allow
+// tree-shaking on each api instance.
+const diag_1 = __nccwpck_require__(1877);
+/**
+ * Entrypoint for Diag API.
+ * Defines Diagnostic handler used for internal diagnostic logging operations.
+ * The default provides a Noop DiagLogger implementation which may be changed via the
+ * diag.setLogger(logger: DiagLogger) function.
+ */
+exports.diag = diag_1.DiagAPI.instance();
+//# sourceMappingURL=diag-api.js.map
/***/ }),
@@ -46301,7 +48529,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true }));
*/
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.DiagComponentLogger = void 0;
-var global_utils_1 = __nccwpck_require__(5135);
+const global_utils_1 = __nccwpck_require__(5135);
/**
* Component Logger which is meant to be used as part of any component which
* will add automatically additional namespace in front of the log message.
@@ -46311,56 +48539,35 @@ var global_utils_1 = __nccwpck_require__(5135);
* cLogger.debug('test');
* // @opentelemetry/instrumentation-http test
*/
-var DiagComponentLogger = /** @class */ (function () {
- function DiagComponentLogger(props) {
+class DiagComponentLogger {
+ constructor(props) {
this._namespace = props.namespace || 'DiagComponentLogger';
}
- DiagComponentLogger.prototype.debug = function () {
- var args = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- args[_i] = arguments[_i];
- }
+ debug(...args) {
return logProxy('debug', this._namespace, args);
- };
- DiagComponentLogger.prototype.error = function () {
- var args = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- args[_i] = arguments[_i];
- }
+ }
+ error(...args) {
return logProxy('error', this._namespace, args);
- };
- DiagComponentLogger.prototype.info = function () {
- var args = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- args[_i] = arguments[_i];
- }
+ }
+ info(...args) {
return logProxy('info', this._namespace, args);
- };
- DiagComponentLogger.prototype.warn = function () {
- var args = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- args[_i] = arguments[_i];
- }
+ }
+ warn(...args) {
return logProxy('warn', this._namespace, args);
- };
- DiagComponentLogger.prototype.verbose = function () {
- var args = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- args[_i] = arguments[_i];
- }
+ }
+ verbose(...args) {
return logProxy('verbose', this._namespace, args);
- };
- return DiagComponentLogger;
-}());
+ }
+}
exports.DiagComponentLogger = DiagComponentLogger;
function logProxy(funcName, namespace, args) {
- var logger = global_utils_1.getGlobal('diag');
+ const logger = (0, global_utils_1.getGlobal)('diag');
// shortcut if logger not set
if (!logger) {
return;
}
args.unshift(namespace);
- return logger[funcName].apply(logger, args);
+ return logger[funcName](...args);
}
//# sourceMappingURL=ComponentLogger.js.map
@@ -46388,7 +48595,7 @@ function logProxy(funcName, namespace, args) {
*/
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.DiagConsoleLogger = void 0;
-var consoleMap = [
+const consoleMap = [
{ n: 'error', c: 'error' },
{ n: 'warn', c: 'warn' },
{ n: 'info', c: 'info' },
@@ -46400,18 +48607,14 @@ var consoleMap = [
* If you want to limit the amount of logging to a specific level or lower use the
* {@link createLogLevelDiagLogger}
*/
-var DiagConsoleLogger = /** @class */ (function () {
- function DiagConsoleLogger() {
+class DiagConsoleLogger {
+ constructor() {
function _consoleFunc(funcName) {
- return function () {
- var args = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- args[_i] = arguments[_i];
- }
+ return function (...args) {
if (console) {
// Some environments only expose the console when the F12 developer console is open
// eslint-disable-next-line no-console
- var theFunc = console[funcName];
+ let theFunc = console[funcName];
if (typeof theFunc !== 'function') {
// Not all environments support all functions
// eslint-disable-next-line no-console
@@ -46424,54 +48627,16 @@ var DiagConsoleLogger = /** @class */ (function () {
}
};
}
- for (var i = 0; i < consoleMap.length; i++) {
+ for (let i = 0; i < consoleMap.length; i++) {
this[consoleMap[i].n] = _consoleFunc(consoleMap[i].c);
}
}
- return DiagConsoleLogger;
-}());
+}
exports.DiagConsoleLogger = DiagConsoleLogger;
//# sourceMappingURL=consoleLogger.js.map
/***/ }),
-/***/ 1634:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
-
-"use strict";
-
-/*
- * Copyright The OpenTelemetry Authors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
-}) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
-}));
-var __exportStar = (this && this.__exportStar) || function(m, exports) {
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-__exportStar(__nccwpck_require__(3041), exports);
-__exportStar(__nccwpck_require__(8077), exports);
-//# sourceMappingURL=index.js.map
-
-/***/ }),
-
/***/ 9639:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
@@ -46494,7 +48659,7 @@ __exportStar(__nccwpck_require__(8077), exports);
*/
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.createLogLevelDiagLogger = void 0;
-var types_1 = __nccwpck_require__(8077);
+const types_1 = __nccwpck_require__(8077);
function createLogLevelDiagLogger(maxLevel, logger) {
if (maxLevel < types_1.DiagLogLevel.NONE) {
maxLevel = types_1.DiagLogLevel.NONE;
@@ -46505,7 +48670,7 @@ function createLogLevelDiagLogger(maxLevel, logger) {
// In case the logger is null or undefined
logger = logger || {};
function _filterFunc(funcName, theLevel) {
- var theFunc = logger[funcName];
+ const theFunc = logger[funcName];
if (typeof theFunc === 'function' && maxLevel >= theLevel) {
return theFunc.bind(logger);
}
@@ -46576,7 +48741,7 @@ var DiagLogLevel;
/***/ }),
/***/ 5163:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
@@ -46595,44 +48760,42 @@ var DiagLogLevel;
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
-}) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
-}));
-var __exportStar = (this && this.__exportStar) || function(m, exports) {
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
-};
Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.diag = exports.propagation = exports.trace = exports.context = exports.INVALID_SPAN_CONTEXT = exports.INVALID_TRACEID = exports.INVALID_SPANID = exports.isValidSpanId = exports.isValidTraceId = exports.isSpanContextValid = exports.createTraceState = exports.baggageEntryMetadataFromString = void 0;
-__exportStar(__nccwpck_require__(1508), exports);
+exports.trace = exports.propagation = exports.metrics = exports.diag = exports.context = exports.INVALID_SPAN_CONTEXT = exports.INVALID_TRACEID = exports.INVALID_SPANID = exports.isValidSpanId = exports.isValidTraceId = exports.isSpanContextValid = exports.createTraceState = exports.TraceFlags = exports.SpanStatusCode = exports.SpanKind = exports.SamplingDecision = exports.ProxyTracerProvider = exports.ProxyTracer = exports.defaultTextMapSetter = exports.defaultTextMapGetter = exports.ValueType = exports.createNoopMeter = exports.DiagLogLevel = exports.DiagConsoleLogger = exports.ROOT_CONTEXT = exports.createContextKey = exports.baggageEntryMetadataFromString = void 0;
var utils_1 = __nccwpck_require__(8136);
Object.defineProperty(exports, "baggageEntryMetadataFromString", ({ enumerable: true, get: function () { return utils_1.baggageEntryMetadataFromString; } }));
-__exportStar(__nccwpck_require__(4447), exports);
-__exportStar(__nccwpck_require__(2358), exports);
-__exportStar(__nccwpck_require__(1109), exports);
-__exportStar(__nccwpck_require__(1634), exports);
-__exportStar(__nccwpck_require__(865), exports);
-__exportStar(__nccwpck_require__(7492), exports);
-__exportStar(__nccwpck_require__(4023), exports);
-__exportStar(__nccwpck_require__(3503), exports);
-__exportStar(__nccwpck_require__(2285), exports);
-__exportStar(__nccwpck_require__(9671), exports);
-__exportStar(__nccwpck_require__(3209), exports);
-__exportStar(__nccwpck_require__(5769), exports);
-__exportStar(__nccwpck_require__(1424), exports);
-__exportStar(__nccwpck_require__(4416), exports);
-__exportStar(__nccwpck_require__(955), exports);
-__exportStar(__nccwpck_require__(8845), exports);
-__exportStar(__nccwpck_require__(6905), exports);
-__exportStar(__nccwpck_require__(8384), exports);
+// Context APIs
+var context_1 = __nccwpck_require__(8242);
+Object.defineProperty(exports, "createContextKey", ({ enumerable: true, get: function () { return context_1.createContextKey; } }));
+Object.defineProperty(exports, "ROOT_CONTEXT", ({ enumerable: true, get: function () { return context_1.ROOT_CONTEXT; } }));
+// Diag APIs
+var consoleLogger_1 = __nccwpck_require__(3041);
+Object.defineProperty(exports, "DiagConsoleLogger", ({ enumerable: true, get: function () { return consoleLogger_1.DiagConsoleLogger; } }));
+var types_1 = __nccwpck_require__(8077);
+Object.defineProperty(exports, "DiagLogLevel", ({ enumerable: true, get: function () { return types_1.DiagLogLevel; } }));
+// Metrics APIs
+var NoopMeter_1 = __nccwpck_require__(4837);
+Object.defineProperty(exports, "createNoopMeter", ({ enumerable: true, get: function () { return NoopMeter_1.createNoopMeter; } }));
+var Metric_1 = __nccwpck_require__(9999);
+Object.defineProperty(exports, "ValueType", ({ enumerable: true, get: function () { return Metric_1.ValueType; } }));
+// Propagation APIs
+var TextMapPropagator_1 = __nccwpck_require__(865);
+Object.defineProperty(exports, "defaultTextMapGetter", ({ enumerable: true, get: function () { return TextMapPropagator_1.defaultTextMapGetter; } }));
+Object.defineProperty(exports, "defaultTextMapSetter", ({ enumerable: true, get: function () { return TextMapPropagator_1.defaultTextMapSetter; } }));
+var ProxyTracer_1 = __nccwpck_require__(3503);
+Object.defineProperty(exports, "ProxyTracer", ({ enumerable: true, get: function () { return ProxyTracer_1.ProxyTracer; } }));
+var ProxyTracerProvider_1 = __nccwpck_require__(2285);
+Object.defineProperty(exports, "ProxyTracerProvider", ({ enumerable: true, get: function () { return ProxyTracerProvider_1.ProxyTracerProvider; } }));
+var SamplingResult_1 = __nccwpck_require__(3209);
+Object.defineProperty(exports, "SamplingDecision", ({ enumerable: true, get: function () { return SamplingResult_1.SamplingDecision; } }));
+var span_kind_1 = __nccwpck_require__(1424);
+Object.defineProperty(exports, "SpanKind", ({ enumerable: true, get: function () { return span_kind_1.SpanKind; } }));
+var status_1 = __nccwpck_require__(8845);
+Object.defineProperty(exports, "SpanStatusCode", ({ enumerable: true, get: function () { return status_1.SpanStatusCode; } }));
+var trace_flags_1 = __nccwpck_require__(6905);
+Object.defineProperty(exports, "TraceFlags", ({ enumerable: true, get: function () { return trace_flags_1.TraceFlags; } }));
var utils_2 = __nccwpck_require__(2615);
Object.defineProperty(exports, "createTraceState", ({ enumerable: true, get: function () { return utils_2.createTraceState; } }));
-__exportStar(__nccwpck_require__(891), exports);
-__exportStar(__nccwpck_require__(3168), exports);
-__exportStar(__nccwpck_require__(1823), exports);
var spancontext_utils_1 = __nccwpck_require__(9745);
Object.defineProperty(exports, "isSpanContextValid", ({ enumerable: true, get: function () { return spancontext_utils_1.isSpanContextValid; } }));
Object.defineProperty(exports, "isValidTraceId", ({ enumerable: true, get: function () { return spancontext_utils_1.isValidTraceId; } }));
@@ -46641,30 +48804,25 @@ var invalid_span_constants_1 = __nccwpck_require__(1760);
Object.defineProperty(exports, "INVALID_SPANID", ({ enumerable: true, get: function () { return invalid_span_constants_1.INVALID_SPANID; } }));
Object.defineProperty(exports, "INVALID_TRACEID", ({ enumerable: true, get: function () { return invalid_span_constants_1.INVALID_TRACEID; } }));
Object.defineProperty(exports, "INVALID_SPAN_CONTEXT", ({ enumerable: true, get: function () { return invalid_span_constants_1.INVALID_SPAN_CONTEXT; } }));
-__exportStar(__nccwpck_require__(8242), exports);
-__exportStar(__nccwpck_require__(6504), exports);
-var context_1 = __nccwpck_require__(7171);
-/** Entrypoint for context API */
-exports.context = context_1.ContextAPI.getInstance();
-var trace_1 = __nccwpck_require__(1539);
-/** Entrypoint for trace API */
-exports.trace = trace_1.TraceAPI.getInstance();
-var propagation_1 = __nccwpck_require__(9909);
-/** Entrypoint for propagation API */
-exports.propagation = propagation_1.PropagationAPI.getInstance();
-var diag_1 = __nccwpck_require__(1877);
-/**
- * Entrypoint for Diag API.
- * Defines Diagnostic handler used for internal diagnostic logging operations.
- * The default provides a Noop DiagLogger implementation which may be changed via the
- * diag.setLogger(logger: DiagLogger) function.
- */
-exports.diag = diag_1.DiagAPI.instance();
-exports.default = {
- trace: exports.trace,
- context: exports.context,
- propagation: exports.propagation,
- diag: exports.diag,
+// Split module-level variable definition into separate files to allow
+// tree-shaking on each api instance.
+const context_api_1 = __nccwpck_require__(7393);
+Object.defineProperty(exports, "context", ({ enumerable: true, get: function () { return context_api_1.context; } }));
+const diag_api_1 = __nccwpck_require__(9721);
+Object.defineProperty(exports, "diag", ({ enumerable: true, get: function () { return diag_api_1.diag; } }));
+const metrics_api_1 = __nccwpck_require__(2601);
+Object.defineProperty(exports, "metrics", ({ enumerable: true, get: function () { return metrics_api_1.metrics; } }));
+const propagation_api_1 = __nccwpck_require__(7591);
+Object.defineProperty(exports, "propagation", ({ enumerable: true, get: function () { return propagation_api_1.propagation; } }));
+const trace_api_1 = __nccwpck_require__(8989);
+Object.defineProperty(exports, "trace", ({ enumerable: true, get: function () { return trace_api_1.trace; } }));
+// Default export.
+exports["default"] = {
+ context: context_api_1.context,
+ diag: diag_api_1.diag,
+ metrics: metrics_api_1.metrics,
+ propagation: propagation_api_1.propagation,
+ trace: trace_api_1.trace,
};
//# sourceMappingURL=index.js.map
@@ -46692,47 +48850,46 @@ exports.default = {
*/
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.unregisterGlobal = exports.getGlobal = exports.registerGlobal = void 0;
-var platform_1 = __nccwpck_require__(9957);
-var version_1 = __nccwpck_require__(8996);
-var semver_1 = __nccwpck_require__(1522);
-var major = version_1.VERSION.split('.')[0];
-var GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for("opentelemetry.js.api." + major);
-var _global = platform_1._globalThis;
-function registerGlobal(type, instance, diag, allowOverride) {
+const platform_1 = __nccwpck_require__(9957);
+const version_1 = __nccwpck_require__(8996);
+const semver_1 = __nccwpck_require__(1522);
+const major = version_1.VERSION.split('.')[0];
+const GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for(`opentelemetry.js.api.${major}`);
+const _global = platform_1._globalThis;
+function registerGlobal(type, instance, diag, allowOverride = false) {
var _a;
- if (allowOverride === void 0) { allowOverride = false; }
- var api = (_global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a !== void 0 ? _a : {
+ const api = (_global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a !== void 0 ? _a : {
version: version_1.VERSION,
});
if (!allowOverride && api[type]) {
// already registered an API of this type
- var err = new Error("@opentelemetry/api: Attempted duplicate registration of API: " + type);
+ const err = new Error(`@opentelemetry/api: Attempted duplicate registration of API: ${type}`);
diag.error(err.stack || err.message);
return false;
}
if (api.version !== version_1.VERSION) {
// All registered APIs must be of the same version exactly
- var err = new Error('@opentelemetry/api: All API registration versions must match');
+ const err = new Error(`@opentelemetry/api: Registration of version v${api.version} for ${type} does not match previously registered API v${version_1.VERSION}`);
diag.error(err.stack || err.message);
return false;
}
api[type] = instance;
- diag.debug("@opentelemetry/api: Registered a global for " + type + " v" + version_1.VERSION + ".");
+ diag.debug(`@opentelemetry/api: Registered a global for ${type} v${version_1.VERSION}.`);
return true;
}
exports.registerGlobal = registerGlobal;
function getGlobal(type) {
var _a, _b;
- var globalVersion = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a === void 0 ? void 0 : _a.version;
- if (!globalVersion || !semver_1.isCompatible(globalVersion)) {
+ const globalVersion = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a === void 0 ? void 0 : _a.version;
+ if (!globalVersion || !(0, semver_1.isCompatible)(globalVersion)) {
return;
}
return (_b = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b === void 0 ? void 0 : _b[type];
}
exports.getGlobal = getGlobal;
function unregisterGlobal(type, diag) {
- diag.debug("@opentelemetry/api: Unregistering a global for " + type + " v" + version_1.VERSION + ".");
- var api = _global[GLOBAL_OPENTELEMETRY_API_KEY];
+ diag.debug(`@opentelemetry/api: Unregistering a global for ${type} v${version_1.VERSION}.`);
+ const api = _global[GLOBAL_OPENTELEMETRY_API_KEY];
if (api) {
delete api[type];
}
@@ -46764,8 +48921,8 @@ exports.unregisterGlobal = unregisterGlobal;
*/
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.isCompatible = exports._makeCompatibilityCheck = void 0;
-var version_1 = __nccwpck_require__(8996);
-var re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;
+const version_1 = __nccwpck_require__(8996);
+const re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;
/**
* Create a function to test an API version to see if it is compatible with the provided ownVersion.
*
@@ -46783,14 +48940,14 @@ var re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;
* @param ownVersion version which should be checked against
*/
function _makeCompatibilityCheck(ownVersion) {
- var acceptedVersions = new Set([ownVersion]);
- var rejectedVersions = new Set();
- var myVersionMatch = ownVersion.match(re);
+ const acceptedVersions = new Set([ownVersion]);
+ const rejectedVersions = new Set();
+ const myVersionMatch = ownVersion.match(re);
if (!myVersionMatch) {
// we cannot guarantee compatibility so we always return noop
- return function () { return false; };
+ return () => false;
}
- var ownVersionParsed = {
+ const ownVersionParsed = {
major: +myVersionMatch[1],
minor: +myVersionMatch[2],
patch: +myVersionMatch[3],
@@ -46817,13 +48974,13 @@ function _makeCompatibilityCheck(ownVersion) {
if (rejectedVersions.has(globalVersion)) {
return false;
}
- var globalVersionMatch = globalVersion.match(re);
+ const globalVersionMatch = globalVersion.match(re);
if (!globalVersionMatch) {
// cannot parse other version
// we cannot guarantee compatibility so we always noop
return _reject(globalVersion);
}
- var globalVersionParsed = {
+ const globalVersionParsed = {
major: +globalVersionMatch[1],
minor: +globalVersionMatch[2],
patch: +globalVersionMatch[3],
@@ -46871,8 +49028,8 @@ exports.isCompatible = _makeCompatibilityCheck(version_1.VERSION);
/***/ }),
-/***/ 9957:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+/***/ 2601:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
@@ -46891,23 +49048,18 @@ exports.isCompatible = _makeCompatibilityCheck(version_1.VERSION);
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
-}) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
-}));
-var __exportStar = (this && this.__exportStar) || function(m, exports) {
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
-};
Object.defineProperty(exports, "__esModule", ({ value: true }));
-__exportStar(__nccwpck_require__(7200), exports);
-//# sourceMappingURL=index.js.map
+exports.metrics = void 0;
+// Split module-level variable definition into separate files to allow
+// tree-shaking on each api instance.
+const metrics_1 = __nccwpck_require__(7696);
+/** Entrypoint for metrics API */
+exports.metrics = metrics_1.MetricsAPI.getInstance();
+//# sourceMappingURL=metrics-api.js.map
/***/ }),
-/***/ 9406:
+/***/ 9999:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
@@ -46928,15 +49080,244 @@ __exportStar(__nccwpck_require__(7200), exports);
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports._globalThis = void 0;
-/** only globals that common to node and browsers are allowed */
-// eslint-disable-next-line node/no-unsupported-features/es-builtins
-exports._globalThis = typeof globalThis === 'object' ? globalThis : global;
-//# sourceMappingURL=globalThis.js.map
+exports.ValueType = void 0;
+/** The Type of value. It describes how the data is reported. */
+var ValueType;
+(function (ValueType) {
+ ValueType[ValueType["INT"] = 0] = "INT";
+ ValueType[ValueType["DOUBLE"] = 1] = "DOUBLE";
+})(ValueType = exports.ValueType || (exports.ValueType = {}));
+//# sourceMappingURL=Metric.js.map
/***/ }),
-/***/ 7200:
+/***/ 4837:
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+/*
+ * Copyright The OpenTelemetry Authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.createNoopMeter = exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC = exports.NOOP_OBSERVABLE_GAUGE_METRIC = exports.NOOP_OBSERVABLE_COUNTER_METRIC = exports.NOOP_UP_DOWN_COUNTER_METRIC = exports.NOOP_HISTOGRAM_METRIC = exports.NOOP_COUNTER_METRIC = exports.NOOP_METER = exports.NoopObservableUpDownCounterMetric = exports.NoopObservableGaugeMetric = exports.NoopObservableCounterMetric = exports.NoopObservableMetric = exports.NoopHistogramMetric = exports.NoopUpDownCounterMetric = exports.NoopCounterMetric = exports.NoopMetric = exports.NoopMeter = void 0;
+/**
+ * NoopMeter is a noop implementation of the {@link Meter} interface. It reuses
+ * constant NoopMetrics for all of its methods.
+ */
+class NoopMeter {
+ constructor() { }
+ /**
+ * @see {@link Meter.createHistogram}
+ */
+ createHistogram(_name, _options) {
+ return exports.NOOP_HISTOGRAM_METRIC;
+ }
+ /**
+ * @see {@link Meter.createCounter}
+ */
+ createCounter(_name, _options) {
+ return exports.NOOP_COUNTER_METRIC;
+ }
+ /**
+ * @see {@link Meter.createUpDownCounter}
+ */
+ createUpDownCounter(_name, _options) {
+ return exports.NOOP_UP_DOWN_COUNTER_METRIC;
+ }
+ /**
+ * @see {@link Meter.createObservableGauge}
+ */
+ createObservableGauge(_name, _options) {
+ return exports.NOOP_OBSERVABLE_GAUGE_METRIC;
+ }
+ /**
+ * @see {@link Meter.createObservableCounter}
+ */
+ createObservableCounter(_name, _options) {
+ return exports.NOOP_OBSERVABLE_COUNTER_METRIC;
+ }
+ /**
+ * @see {@link Meter.createObservableUpDownCounter}
+ */
+ createObservableUpDownCounter(_name, _options) {
+ return exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC;
+ }
+ /**
+ * @see {@link Meter.addBatchObservableCallback}
+ */
+ addBatchObservableCallback(_callback, _observables) { }
+ /**
+ * @see {@link Meter.removeBatchObservableCallback}
+ */
+ removeBatchObservableCallback(_callback) { }
+}
+exports.NoopMeter = NoopMeter;
+class NoopMetric {
+}
+exports.NoopMetric = NoopMetric;
+class NoopCounterMetric extends NoopMetric {
+ add(_value, _attributes) { }
+}
+exports.NoopCounterMetric = NoopCounterMetric;
+class NoopUpDownCounterMetric extends NoopMetric {
+ add(_value, _attributes) { }
+}
+exports.NoopUpDownCounterMetric = NoopUpDownCounterMetric;
+class NoopHistogramMetric extends NoopMetric {
+ record(_value, _attributes) { }
+}
+exports.NoopHistogramMetric = NoopHistogramMetric;
+class NoopObservableMetric {
+ addCallback(_callback) { }
+ removeCallback(_callback) { }
+}
+exports.NoopObservableMetric = NoopObservableMetric;
+class NoopObservableCounterMetric extends NoopObservableMetric {
+}
+exports.NoopObservableCounterMetric = NoopObservableCounterMetric;
+class NoopObservableGaugeMetric extends NoopObservableMetric {
+}
+exports.NoopObservableGaugeMetric = NoopObservableGaugeMetric;
+class NoopObservableUpDownCounterMetric extends NoopObservableMetric {
+}
+exports.NoopObservableUpDownCounterMetric = NoopObservableUpDownCounterMetric;
+exports.NOOP_METER = new NoopMeter();
+// Synchronous instruments
+exports.NOOP_COUNTER_METRIC = new NoopCounterMetric();
+exports.NOOP_HISTOGRAM_METRIC = new NoopHistogramMetric();
+exports.NOOP_UP_DOWN_COUNTER_METRIC = new NoopUpDownCounterMetric();
+// Asynchronous instruments
+exports.NOOP_OBSERVABLE_COUNTER_METRIC = new NoopObservableCounterMetric();
+exports.NOOP_OBSERVABLE_GAUGE_METRIC = new NoopObservableGaugeMetric();
+exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC = new NoopObservableUpDownCounterMetric();
+/**
+ * Create a no-op Meter
+ */
+function createNoopMeter() {
+ return exports.NOOP_METER;
+}
+exports.createNoopMeter = createNoopMeter;
+//# sourceMappingURL=NoopMeter.js.map
+
+/***/ }),
+
+/***/ 2647:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+/*
+ * Copyright The OpenTelemetry Authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.NOOP_METER_PROVIDER = exports.NoopMeterProvider = void 0;
+const NoopMeter_1 = __nccwpck_require__(4837);
+/**
+ * An implementation of the {@link MeterProvider} which returns an impotent Meter
+ * for all calls to `getMeter`
+ */
+class NoopMeterProvider {
+ getMeter(_name, _version, _options) {
+ return NoopMeter_1.NOOP_METER;
+ }
+}
+exports.NoopMeterProvider = NoopMeterProvider;
+exports.NOOP_METER_PROVIDER = new NoopMeterProvider();
+//# sourceMappingURL=NoopMeterProvider.js.map
+
+/***/ }),
+
+/***/ 9957:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+
+"use strict";
+
+/*
+ * Copyright The OpenTelemetry Authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
+}) : (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ o[k2] = m[k];
+}));
+var __exportStar = (this && this.__exportStar) || function(m, exports) {
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
+};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+__exportStar(__nccwpck_require__(7200), exports);
+//# sourceMappingURL=index.js.map
+
+/***/ }),
+
+/***/ 9406:
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+/*
+ * Copyright The OpenTelemetry Authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports._globalThis = void 0;
+/** only globals that common to node and browsers are allowed */
+// eslint-disable-next-line node/no-unsupported-features/es-builtins
+exports._globalThis = typeof globalThis === 'object' ? globalThis : global;
+//# sourceMappingURL=globalThis.js.map
+
+/***/ }),
+
+/***/ 7200:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
@@ -46972,6 +49353,37 @@ __exportStar(__nccwpck_require__(9406), exports);
/***/ }),
+/***/ 7591:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+/*
+ * Copyright The OpenTelemetry Authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.propagation = void 0;
+// Split module-level variable definition into separate files to allow
+// tree-shaking on each api instance.
+const propagation_1 = __nccwpck_require__(9909);
+/** Entrypoint for propagation API */
+exports.propagation = propagation_1.PropagationAPI.getInstance();
+//# sourceMappingURL=propagation-api.js.map
+
+/***/ }),
+
/***/ 2368:
/***/ ((__unused_webpack_module, exports) => {
@@ -46997,20 +49409,17 @@ exports.NoopTextMapPropagator = void 0;
/**
* No-op implementations of {@link TextMapPropagator}.
*/
-var NoopTextMapPropagator = /** @class */ (function () {
- function NoopTextMapPropagator() {
- }
+class NoopTextMapPropagator {
/** Noop inject function does nothing */
- NoopTextMapPropagator.prototype.inject = function (_context, _carrier) { };
+ inject(_context, _carrier) { }
/** Noop extract function does nothing and returns the input context */
- NoopTextMapPropagator.prototype.extract = function (context, _carrier) {
+ extract(context, _carrier) {
return context;
- };
- NoopTextMapPropagator.prototype.fields = function () {
+ }
+ fields() {
return [];
- };
- return NoopTextMapPropagator;
-}());
+ }
+}
exports.NoopTextMapPropagator = NoopTextMapPropagator;
//# sourceMappingURL=NoopTextMapPropagator.js.map
@@ -47039,13 +49448,13 @@ exports.NoopTextMapPropagator = NoopTextMapPropagator;
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.defaultTextMapSetter = exports.defaultTextMapGetter = void 0;
exports.defaultTextMapGetter = {
- get: function (carrier, key) {
+ get(carrier, key) {
if (carrier == null) {
return undefined;
}
return carrier[key];
},
- keys: function (carrier) {
+ keys(carrier) {
if (carrier == null) {
return [];
}
@@ -47053,7 +49462,7 @@ exports.defaultTextMapGetter = {
},
};
exports.defaultTextMapSetter = {
- set: function (carrier, key, value) {
+ set(carrier, key, value) {
if (carrier == null) {
return;
}
@@ -47064,6 +49473,37 @@ exports.defaultTextMapSetter = {
/***/ }),
+/***/ 8989:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+/*
+ * Copyright The OpenTelemetry Authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.trace = void 0;
+// Split module-level variable definition into separate files to allow
+// tree-shaking on each api instance.
+const trace_1 = __nccwpck_require__(1539);
+/** Entrypoint for trace API */
+exports.trace = trace_1.TraceAPI.getInstance();
+//# sourceMappingURL=trace-api.js.map
+
+/***/ }),
+
/***/ 1462:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
@@ -47086,51 +49526,49 @@ exports.defaultTextMapSetter = {
*/
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.NonRecordingSpan = void 0;
-var invalid_span_constants_1 = __nccwpck_require__(1760);
+const invalid_span_constants_1 = __nccwpck_require__(1760);
/**
* The NonRecordingSpan is the default {@link Span} that is used when no Span
* implementation is available. All operations are no-op including context
* propagation.
*/
-var NonRecordingSpan = /** @class */ (function () {
- function NonRecordingSpan(_spanContext) {
- if (_spanContext === void 0) { _spanContext = invalid_span_constants_1.INVALID_SPAN_CONTEXT; }
+class NonRecordingSpan {
+ constructor(_spanContext = invalid_span_constants_1.INVALID_SPAN_CONTEXT) {
this._spanContext = _spanContext;
}
// Returns a SpanContext.
- NonRecordingSpan.prototype.spanContext = function () {
+ spanContext() {
return this._spanContext;
- };
+ }
// By default does nothing
- NonRecordingSpan.prototype.setAttribute = function (_key, _value) {
+ setAttribute(_key, _value) {
return this;
- };
+ }
// By default does nothing
- NonRecordingSpan.prototype.setAttributes = function (_attributes) {
+ setAttributes(_attributes) {
return this;
- };
+ }
// By default does nothing
- NonRecordingSpan.prototype.addEvent = function (_name, _attributes) {
+ addEvent(_name, _attributes) {
return this;
- };
+ }
// By default does nothing
- NonRecordingSpan.prototype.setStatus = function (_status) {
+ setStatus(_status) {
return this;
- };
+ }
// By default does nothing
- NonRecordingSpan.prototype.updateName = function (_name) {
+ updateName(_name) {
return this;
- };
+ }
// By default does nothing
- NonRecordingSpan.prototype.end = function (_endTime) { };
+ end(_endTime) { }
// isRecording always returns false for NonRecordingSpan.
- NonRecordingSpan.prototype.isRecording = function () {
+ isRecording() {
return false;
- };
+ }
// By default does nothing
- NonRecordingSpan.prototype.recordException = function (_exception, _time) { };
- return NonRecordingSpan;
-}());
+ recordException(_exception, _time) { }
+}
exports.NonRecordingSpan = NonRecordingSpan;
//# sourceMappingURL=NonRecordingSpan.js.map
@@ -47158,36 +49596,34 @@ exports.NonRecordingSpan = NonRecordingSpan;
*/
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.NoopTracer = void 0;
-var context_1 = __nccwpck_require__(7171);
-var context_utils_1 = __nccwpck_require__(3326);
-var NonRecordingSpan_1 = __nccwpck_require__(1462);
-var spancontext_utils_1 = __nccwpck_require__(9745);
-var context = context_1.ContextAPI.getInstance();
+const context_1 = __nccwpck_require__(7171);
+const context_utils_1 = __nccwpck_require__(3326);
+const NonRecordingSpan_1 = __nccwpck_require__(1462);
+const spancontext_utils_1 = __nccwpck_require__(9745);
+const contextApi = context_1.ContextAPI.getInstance();
/**
* No-op implementations of {@link Tracer}.
*/
-var NoopTracer = /** @class */ (function () {
- function NoopTracer() {
- }
+class NoopTracer {
// startSpan starts a noop span.
- NoopTracer.prototype.startSpan = function (name, options, context) {
- var root = Boolean(options === null || options === void 0 ? void 0 : options.root);
+ startSpan(name, options, context = contextApi.active()) {
+ const root = Boolean(options === null || options === void 0 ? void 0 : options.root);
if (root) {
return new NonRecordingSpan_1.NonRecordingSpan();
}
- var parentFromContext = context && context_utils_1.getSpanContext(context);
+ const parentFromContext = context && (0, context_utils_1.getSpanContext)(context);
if (isSpanContext(parentFromContext) &&
- spancontext_utils_1.isSpanContextValid(parentFromContext)) {
+ (0, spancontext_utils_1.isSpanContextValid)(parentFromContext)) {
return new NonRecordingSpan_1.NonRecordingSpan(parentFromContext);
}
else {
return new NonRecordingSpan_1.NonRecordingSpan();
}
- };
- NoopTracer.prototype.startActiveSpan = function (name, arg2, arg3, arg4) {
- var opts;
- var ctx;
- var fn;
+ }
+ startActiveSpan(name, arg2, arg3, arg4) {
+ let opts;
+ let ctx;
+ let fn;
if (arguments.length < 2) {
return;
}
@@ -47203,13 +49639,12 @@ var NoopTracer = /** @class */ (function () {
ctx = arg3;
fn = arg4;
}
- var parentContext = ctx !== null && ctx !== void 0 ? ctx : context.active();
- var span = this.startSpan(name, opts, parentContext);
- var contextWithSpanSet = context_utils_1.setSpan(parentContext, span);
- return context.with(contextWithSpanSet, fn, undefined, span);
- };
- return NoopTracer;
-}());
+ const parentContext = ctx !== null && ctx !== void 0 ? ctx : contextApi.active();
+ const span = this.startSpan(name, opts, parentContext);
+ const contextWithSpanSet = (0, context_utils_1.setSpan)(parentContext, span);
+ return contextApi.with(contextWithSpanSet, fn, undefined, span);
+ }
+}
exports.NoopTracer = NoopTracer;
function isSpanContext(spanContext) {
return (typeof spanContext === 'object' &&
@@ -47243,21 +49678,18 @@ function isSpanContext(spanContext) {
*/
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.NoopTracerProvider = void 0;
-var NoopTracer_1 = __nccwpck_require__(7606);
+const NoopTracer_1 = __nccwpck_require__(7606);
/**
* An implementation of the {@link TracerProvider} which returns an impotent
* Tracer for all calls to `getTracer`.
*
* All operations are no-op.
*/
-var NoopTracerProvider = /** @class */ (function () {
- function NoopTracerProvider() {
- }
- NoopTracerProvider.prototype.getTracer = function (_name, _version, _options) {
+class NoopTracerProvider {
+ getTracer(_name, _version, _options) {
return new NoopTracer_1.NoopTracer();
- };
- return NoopTracerProvider;
-}());
+ }
+}
exports.NoopTracerProvider = NoopTracerProvider;
//# sourceMappingURL=NoopTracerProvider.js.map
@@ -47285,42 +49717,41 @@ exports.NoopTracerProvider = NoopTracerProvider;
*/
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ProxyTracer = void 0;
-var NoopTracer_1 = __nccwpck_require__(7606);
-var NOOP_TRACER = new NoopTracer_1.NoopTracer();
+const NoopTracer_1 = __nccwpck_require__(7606);
+const NOOP_TRACER = new NoopTracer_1.NoopTracer();
/**
* Proxy tracer provided by the proxy tracer provider
*/
-var ProxyTracer = /** @class */ (function () {
- function ProxyTracer(_provider, name, version, options) {
+class ProxyTracer {
+ constructor(_provider, name, version, options) {
this._provider = _provider;
this.name = name;
this.version = version;
this.options = options;
}
- ProxyTracer.prototype.startSpan = function (name, options, context) {
+ startSpan(name, options, context) {
return this._getTracer().startSpan(name, options, context);
- };
- ProxyTracer.prototype.startActiveSpan = function (_name, _options, _context, _fn) {
- var tracer = this._getTracer();
+ }
+ startActiveSpan(_name, _options, _context, _fn) {
+ const tracer = this._getTracer();
return Reflect.apply(tracer.startActiveSpan, tracer, arguments);
- };
+ }
/**
* Try to get a tracer from the proxy tracer provider.
* If the proxy tracer provider has no delegate, return a noop tracer.
*/
- ProxyTracer.prototype._getTracer = function () {
+ _getTracer() {
if (this._delegate) {
return this._delegate;
}
- var tracer = this._provider.getDelegateTracer(this.name, this.version, this.options);
+ const tracer = this._provider.getDelegateTracer(this.name, this.version, this.options);
if (!tracer) {
return NOOP_TRACER;
}
this._delegate = tracer;
return this._delegate;
- };
- return ProxyTracer;
-}());
+ }
+}
exports.ProxyTracer = ProxyTracer;
//# sourceMappingURL=ProxyTracer.js.map
@@ -47348,9 +49779,9 @@ exports.ProxyTracer = ProxyTracer;
*/
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ProxyTracerProvider = void 0;
-var ProxyTracer_1 = __nccwpck_require__(3503);
-var NoopTracerProvider_1 = __nccwpck_require__(3259);
-var NOOP_TRACER_PROVIDER = new NoopTracerProvider_1.NoopTracerProvider();
+const ProxyTracer_1 = __nccwpck_require__(3503);
+const NoopTracerProvider_1 = __nccwpck_require__(3259);
+const NOOP_TRACER_PROVIDER = new NoopTracerProvider_1.NoopTracerProvider();
/**
* Tracer provider which provides {@link ProxyTracer}s.
*
@@ -47359,62 +49790,34 @@ var NOOP_TRACER_PROVIDER = new NoopTracerProvider_1.NoopTracerProvider();
* When a delegate is set after tracers have already been provided,
* all tracers already provided will use the provided delegate implementation.
*/
-var ProxyTracerProvider = /** @class */ (function () {
- function ProxyTracerProvider() {
- }
+class ProxyTracerProvider {
/**
* Get a {@link ProxyTracer}
*/
- ProxyTracerProvider.prototype.getTracer = function (name, version, options) {
+ getTracer(name, version, options) {
var _a;
return ((_a = this.getDelegateTracer(name, version, options)) !== null && _a !== void 0 ? _a : new ProxyTracer_1.ProxyTracer(this, name, version, options));
- };
- ProxyTracerProvider.prototype.getDelegate = function () {
+ }
+ getDelegate() {
var _a;
return (_a = this._delegate) !== null && _a !== void 0 ? _a : NOOP_TRACER_PROVIDER;
- };
+ }
/**
* Set the delegate tracer provider
*/
- ProxyTracerProvider.prototype.setDelegate = function (delegate) {
+ setDelegate(delegate) {
this._delegate = delegate;
- };
- ProxyTracerProvider.prototype.getDelegateTracer = function (name, version, options) {
+ }
+ getDelegateTracer(name, version, options) {
var _a;
return (_a = this._delegate) === null || _a === void 0 ? void 0 : _a.getTracer(name, version, options);
- };
- return ProxyTracerProvider;
-}());
+ }
+}
exports.ProxyTracerProvider = ProxyTracerProvider;
//# sourceMappingURL=ProxyTracerProvider.js.map
/***/ }),
-/***/ 9671:
-/***/ ((__unused_webpack_module, exports) => {
-
-"use strict";
-
-/*
- * Copyright The OpenTelemetry Authors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-//# sourceMappingURL=Sampler.js.map
-
-/***/ }),
-
/***/ 3209:
/***/ ((__unused_webpack_module, exports) => {
@@ -47438,6 +49841,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true }));
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.SamplingDecision = void 0;
/**
+ * @deprecated use the one declared in @opentelemetry/sdk-trace-base instead.
* A sampling decision that determines how a {@link Span} will be recorded
* and collected.
*/
@@ -47463,56 +49867,6 @@ var SamplingDecision;
/***/ }),
-/***/ 955:
-/***/ ((__unused_webpack_module, exports) => {
-
-"use strict";
-
-/*
- * Copyright The OpenTelemetry Authors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-//# sourceMappingURL=SpanOptions.js.map
-
-/***/ }),
-
-/***/ 7492:
-/***/ ((__unused_webpack_module, exports) => {
-
-"use strict";
-
-/*
- * Copyright The OpenTelemetry Authors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-//# sourceMappingURL=attributes.js.map
-
-/***/ }),
-
/***/ 3326:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
@@ -47534,13 +49888,14 @@ Object.defineProperty(exports, "__esModule", ({ value: true }));
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.getSpanContext = exports.setSpanContext = exports.deleteSpan = exports.setSpan = exports.getSpan = void 0;
-var context_1 = __nccwpck_require__(8242);
-var NonRecordingSpan_1 = __nccwpck_require__(1462);
+exports.getSpanContext = exports.setSpanContext = exports.deleteSpan = exports.setSpan = exports.getActiveSpan = exports.getSpan = void 0;
+const context_1 = __nccwpck_require__(8242);
+const NonRecordingSpan_1 = __nccwpck_require__(1462);
+const context_2 = __nccwpck_require__(7171);
/**
* span key
*/
-var SPAN_KEY = context_1.createContextKey('OpenTelemetry Context Key SPAN');
+const SPAN_KEY = (0, context_1.createContextKey)('OpenTelemetry Context Key SPAN');
/**
* Return the span if one exists
*
@@ -47550,6 +49905,13 @@ function getSpan(context) {
return context.getValue(SPAN_KEY) || undefined;
}
exports.getSpan = getSpan;
+/**
+ * Gets the span from the current context, if one exists.
+ */
+function getActiveSpan() {
+ return getSpan(context_2.ContextAPI.getInstance().active());
+}
+exports.getActiveSpan = getActiveSpan;
/**
* Set the span on a context
*
@@ -47616,11 +49978,11 @@ exports.getSpanContext = getSpanContext;
*/
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.TraceStateImpl = void 0;
-var tracestate_validators_1 = __nccwpck_require__(4864);
-var MAX_TRACE_STATE_ITEMS = 32;
-var MAX_TRACE_STATE_LEN = 512;
-var LIST_MEMBERS_SEPARATOR = ',';
-var LIST_MEMBER_KEY_VALUE_SPLITTER = '=';
+const tracestate_validators_1 = __nccwpck_require__(4864);
+const MAX_TRACE_STATE_ITEMS = 32;
+const MAX_TRACE_STATE_LEN = 512;
+const LIST_MEMBERS_SEPARATOR = ',';
+const LIST_MEMBER_KEY_VALUE_SPLITTER = '=';
/**
* TraceState must be a class and not a simple object type because of the spec
* requirement (https://www.w3.org/TR/trace-context/#tracestate-field).
@@ -47630,52 +49992,51 @@ var LIST_MEMBER_KEY_VALUE_SPLITTER = '=';
* - The value of any key can be updated. Modified keys MUST be moved to the
* beginning of the list.
*/
-var TraceStateImpl = /** @class */ (function () {
- function TraceStateImpl(rawTraceState) {
+class TraceStateImpl {
+ constructor(rawTraceState) {
this._internalState = new Map();
if (rawTraceState)
this._parse(rawTraceState);
}
- TraceStateImpl.prototype.set = function (key, value) {
+ set(key, value) {
// TODO: Benchmark the different approaches(map vs list) and
// use the faster one.
- var traceState = this._clone();
+ const traceState = this._clone();
if (traceState._internalState.has(key)) {
traceState._internalState.delete(key);
}
traceState._internalState.set(key, value);
return traceState;
- };
- TraceStateImpl.prototype.unset = function (key) {
- var traceState = this._clone();
+ }
+ unset(key) {
+ const traceState = this._clone();
traceState._internalState.delete(key);
return traceState;
- };
- TraceStateImpl.prototype.get = function (key) {
+ }
+ get(key) {
return this._internalState.get(key);
- };
- TraceStateImpl.prototype.serialize = function () {
- var _this = this;
+ }
+ serialize() {
return this._keys()
- .reduce(function (agg, key) {
- agg.push(key + LIST_MEMBER_KEY_VALUE_SPLITTER + _this.get(key));
+ .reduce((agg, key) => {
+ agg.push(key + LIST_MEMBER_KEY_VALUE_SPLITTER + this.get(key));
return agg;
}, [])
.join(LIST_MEMBERS_SEPARATOR);
- };
- TraceStateImpl.prototype._parse = function (rawTraceState) {
+ }
+ _parse(rawTraceState) {
if (rawTraceState.length > MAX_TRACE_STATE_LEN)
return;
this._internalState = rawTraceState
.split(LIST_MEMBERS_SEPARATOR)
.reverse() // Store in reverse so new keys (.set(...)) will be placed at the beginning
- .reduce(function (agg, part) {
- var listMember = part.trim(); // Optional Whitespace (OWS) handling
- var i = listMember.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER);
+ .reduce((agg, part) => {
+ const listMember = part.trim(); // Optional Whitespace (OWS) handling
+ const i = listMember.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER);
if (i !== -1) {
- var key = listMember.slice(0, i);
- var value = listMember.slice(i + 1, part.length);
- if (tracestate_validators_1.validateKey(key) && tracestate_validators_1.validateValue(value)) {
+ const key = listMember.slice(0, i);
+ const value = listMember.slice(i + 1, part.length);
+ if ((0, tracestate_validators_1.validateKey)(key) && (0, tracestate_validators_1.validateValue)(value)) {
agg.set(key, value);
}
else {
@@ -47690,17 +50051,16 @@ var TraceStateImpl = /** @class */ (function () {
.reverse() // Use reverse same as original tracestate parse chain
.slice(0, MAX_TRACE_STATE_ITEMS));
}
- };
- TraceStateImpl.prototype._keys = function () {
+ }
+ _keys() {
return Array.from(this._internalState.keys()).reverse();
- };
- TraceStateImpl.prototype._clone = function () {
- var traceState = new TraceStateImpl();
+ }
+ _clone() {
+ const traceState = new TraceStateImpl();
traceState._internalState = new Map(this._internalState);
return traceState;
- };
- return TraceStateImpl;
-}());
+ }
+}
exports.TraceStateImpl = TraceStateImpl;
//# sourceMappingURL=tracestate-impl.js.map
@@ -47728,12 +50088,12 @@ exports.TraceStateImpl = TraceStateImpl;
*/
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.validateValue = exports.validateKey = void 0;
-var VALID_KEY_CHAR_RANGE = '[_0-9a-z-*/]';
-var VALID_KEY = "[a-z]" + VALID_KEY_CHAR_RANGE + "{0,255}";
-var VALID_VENDOR_KEY = "[a-z0-9]" + VALID_KEY_CHAR_RANGE + "{0,240}@[a-z]" + VALID_KEY_CHAR_RANGE + "{0,13}";
-var VALID_KEY_REGEX = new RegExp("^(?:" + VALID_KEY + "|" + VALID_VENDOR_KEY + ")$");
-var VALID_VALUE_BASE_REGEX = /^[ -~]{0,255}[!-~]$/;
-var INVALID_VALUE_COMMA_EQUAL_REGEX = /,|=/;
+const VALID_KEY_CHAR_RANGE = '[_0-9a-z-*/]';
+const VALID_KEY = `[a-z]${VALID_KEY_CHAR_RANGE}{0,255}`;
+const VALID_VENDOR_KEY = `[a-z0-9]${VALID_KEY_CHAR_RANGE}{0,240}@[a-z]${VALID_KEY_CHAR_RANGE}{0,13}`;
+const VALID_KEY_REGEX = new RegExp(`^(?:${VALID_KEY}|${VALID_VENDOR_KEY})$`);
+const VALID_VALUE_BASE_REGEX = /^[ -~]{0,255}[!-~]$/;
+const INVALID_VALUE_COMMA_EQUAL_REGEX = /,|=/;
/**
* Key is opaque string up to 256 characters printable. It MUST begin with a
* lowercase letter, and can only contain lowercase letters a-z, digits 0-9,
@@ -47781,7 +50141,7 @@ exports.validateValue = validateValue;
*/
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.createTraceState = void 0;
-var tracestate_impl_1 = __nccwpck_require__(2110);
+const tracestate_impl_1 = __nccwpck_require__(2110);
function createTraceState(rawTraceState) {
return new tracestate_impl_1.TraceStateImpl(rawTraceState);
}
@@ -47812,7 +50172,7 @@ exports.createTraceState = createTraceState;
*/
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.INVALID_SPAN_CONTEXT = exports.INVALID_TRACEID = exports.INVALID_SPANID = void 0;
-var trace_flags_1 = __nccwpck_require__(6905);
+const trace_flags_1 = __nccwpck_require__(6905);
exports.INVALID_SPANID = '0000000000000000';
exports.INVALID_TRACEID = '00000000000000000000000000000000';
exports.INVALID_SPAN_CONTEXT = {
@@ -47824,81 +50184,6 @@ exports.INVALID_SPAN_CONTEXT = {
/***/ }),
-/***/ 4023:
-/***/ ((__unused_webpack_module, exports) => {
-
-"use strict";
-
-/*
- * Copyright The OpenTelemetry Authors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-//# sourceMappingURL=link.js.map
-
-/***/ }),
-
-/***/ 4416:
-/***/ ((__unused_webpack_module, exports) => {
-
-"use strict";
-
-/*
- * Copyright The OpenTelemetry Authors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-//# sourceMappingURL=span.js.map
-
-/***/ }),
-
-/***/ 5769:
-/***/ ((__unused_webpack_module, exports) => {
-
-"use strict";
-
-/*
- * Copyright The OpenTelemetry Authors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-//# sourceMappingURL=span_context.js.map
-
-/***/ }),
-
/***/ 1424:
/***/ ((__unused_webpack_module, exports) => {
@@ -47974,10 +50259,10 @@ exports.wrapSpanContext = exports.isSpanContextValid = exports.isValidSpanId = e
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-var invalid_span_constants_1 = __nccwpck_require__(1760);
-var NonRecordingSpan_1 = __nccwpck_require__(1462);
-var VALID_TRACEID_REGEX = /^([0-9a-f]{32})$/i;
-var VALID_SPANID_REGEX = /^[0-9a-f]{16}$/i;
+const invalid_span_constants_1 = __nccwpck_require__(1760);
+const NonRecordingSpan_1 = __nccwpck_require__(1462);
+const VALID_TRACEID_REGEX = /^([0-9a-f]{32})$/i;
+const VALID_SPANID_REGEX = /^[0-9a-f]{16}$/i;
function isValidTraceId(traceId) {
return VALID_TRACEID_REGEX.test(traceId) && traceId !== invalid_span_constants_1.INVALID_TRACEID;
}
@@ -48071,106 +50356,6 @@ var TraceFlags;
/***/ }),
-/***/ 8384:
-/***/ ((__unused_webpack_module, exports) => {
-
-"use strict";
-
-/*
- * Copyright The OpenTelemetry Authors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-//# sourceMappingURL=trace_state.js.map
-
-/***/ }),
-
-/***/ 3168:
-/***/ ((__unused_webpack_module, exports) => {
-
-"use strict";
-
-/*
- * Copyright The OpenTelemetry Authors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-//# sourceMappingURL=tracer.js.map
-
-/***/ }),
-
-/***/ 1823:
-/***/ ((__unused_webpack_module, exports) => {
-
-"use strict";
-
-/*
- * Copyright The OpenTelemetry Authors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-//# sourceMappingURL=tracer_options.js.map
-
-/***/ }),
-
-/***/ 891:
-/***/ ((__unused_webpack_module, exports) => {
-
-"use strict";
-
-/*
- * Copyright The OpenTelemetry Authors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-//# sourceMappingURL=tracer_provider.js.map
-
-/***/ }),
-
/***/ 8996:
/***/ ((__unused_webpack_module, exports) => {
@@ -48194,7 +50379,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true }));
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.VERSION = void 0;
// this is autogenerated file, see scripts/version-update.js
-exports.VERSION = '1.1.0';
+exports.VERSION = '1.6.0';
//# sourceMappingURL=version.js.map
/***/ }),
@@ -48986,1392 +51171,1718 @@ function expand(str, isTop) {
/***/ }),
-/***/ 7972:
+/***/ 610:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
-const os = __nccwpck_require__(2087);
-
-const extractPathRegex = /\s+at.*(?:\(|\s)(.*)\)?/;
-const pathRegex = /^(?:(?:(?:node|(?:internal\/[\w/]*|.*node_modules\/(?:babel-polyfill|pirates)\/.*)?\w+)\.js:\d+:\d+)|native)/;
-const homeDir = typeof os.homedir === 'undefined' ? '' : os.homedir();
-
-module.exports = (stack, options) => {
- options = Object.assign({pretty: false}, options);
- return stack.replace(/\\/g, '/')
- .split('\n')
- .filter(line => {
- const pathMatches = line.match(extractPathRegex);
- if (pathMatches === null || !pathMatches[1]) {
- return true;
- }
+const stringify = __nccwpck_require__(8750);
+const compile = __nccwpck_require__(9434);
+const expand = __nccwpck_require__(5873);
+const parse = __nccwpck_require__(6477);
- const match = pathMatches[1];
+/**
+ * Expand the given pattern or create a regex-compatible string.
+ *
+ * ```js
+ * const braces = require('braces');
+ * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)']
+ * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c']
+ * ```
+ * @param {String} `str`
+ * @param {Object} `options`
+ * @return {String}
+ * @api public
+ */
- // Electron
- if (
- match.includes('.app/Contents/Resources/electron.asar') ||
- match.includes('.app/Contents/Resources/default_app.asar')
- ) {
- return false;
- }
+const braces = (input, options = {}) => {
+ let output = [];
- return !pathRegex.test(match);
- })
- .filter(line => line.trim() !== '')
- .map(line => {
- if (options.pretty) {
- return line.replace(extractPathRegex, (m, p1) => m.replace(p1, p1.replace(homeDir, '~')));
- }
+ if (Array.isArray(input)) {
+ for (let pattern of input) {
+ let result = braces.create(pattern, options);
+ if (Array.isArray(result)) {
+ output.push(...result);
+ } else {
+ output.push(result);
+ }
+ }
+ } else {
+ output = [].concat(braces.create(input, options));
+ }
- return line;
- })
- .join('\n');
+ if (options && options.expand === true && options.nodupes === true) {
+ output = [...new Set(output)];
+ }
+ return output;
};
+/**
+ * Parse the given `str` with the given `options`.
+ *
+ * ```js
+ * // braces.parse(pattern, [, options]);
+ * const ast = braces.parse('a/{b,c}/d');
+ * console.log(ast);
+ * ```
+ * @param {String} pattern Brace pattern to parse
+ * @param {Object} options
+ * @return {Object} Returns an AST
+ * @api public
+ */
-/***/ }),
-
-/***/ 5443:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-var util = __nccwpck_require__(1669);
-var Stream = __nccwpck_require__(2413).Stream;
-var DelayedStream = __nccwpck_require__(8611);
-
-module.exports = CombinedStream;
-function CombinedStream() {
- this.writable = false;
- this.readable = true;
- this.dataSize = 0;
- this.maxDataSize = 2 * 1024 * 1024;
- this.pauseStreams = true;
-
- this._released = false;
- this._streams = [];
- this._currentStream = null;
- this._insideLoop = false;
- this._pendingNext = false;
-}
-util.inherits(CombinedStream, Stream);
+braces.parse = (input, options = {}) => parse(input, options);
-CombinedStream.create = function(options) {
- var combinedStream = new this();
+/**
+ * Creates a braces string from an AST, or an AST node.
+ *
+ * ```js
+ * const braces = require('braces');
+ * let ast = braces.parse('foo/{a,b}/bar');
+ * console.log(stringify(ast.nodes[2])); //=> '{a,b}'
+ * ```
+ * @param {String} `input` Brace pattern or AST.
+ * @param {Object} `options`
+ * @return {Array} Returns an array of expanded values.
+ * @api public
+ */
- options = options || {};
- for (var option in options) {
- combinedStream[option] = options[option];
+braces.stringify = (input, options = {}) => {
+ if (typeof input === 'string') {
+ return stringify(braces.parse(input, options), options);
}
-
- return combinedStream;
-};
-
-CombinedStream.isStreamLike = function(stream) {
- return (typeof stream !== 'function')
- && (typeof stream !== 'string')
- && (typeof stream !== 'boolean')
- && (typeof stream !== 'number')
- && (!Buffer.isBuffer(stream));
+ return stringify(input, options);
};
-CombinedStream.prototype.append = function(stream) {
- var isStreamLike = CombinedStream.isStreamLike(stream);
-
- if (isStreamLike) {
- if (!(stream instanceof DelayedStream)) {
- var newStream = DelayedStream.create(stream, {
- maxDataSize: Infinity,
- pauseStream: this.pauseStreams,
- });
- stream.on('data', this._checkDataSize.bind(this));
- stream = newStream;
- }
-
- this._handleErrors(stream);
+/**
+ * Compiles a brace pattern into a regex-compatible, optimized string.
+ * This method is called by the main [braces](#braces) function by default.
+ *
+ * ```js
+ * const braces = require('braces');
+ * console.log(braces.compile('a/{b,c}/d'));
+ * //=> ['a/(b|c)/d']
+ * ```
+ * @param {String} `input` Brace pattern or AST.
+ * @param {Object} `options`
+ * @return {Array} Returns an array of expanded values.
+ * @api public
+ */
- if (this.pauseStreams) {
- stream.pause();
- }
+braces.compile = (input, options = {}) => {
+ if (typeof input === 'string') {
+ input = braces.parse(input, options);
}
-
- this._streams.push(stream);
- return this;
-};
-
-CombinedStream.prototype.pipe = function(dest, options) {
- Stream.prototype.pipe.call(this, dest, options);
- this.resume();
- return dest;
+ return compile(input, options);
};
-CombinedStream.prototype._getNext = function() {
- this._currentStream = null;
-
- if (this._insideLoop) {
- this._pendingNext = true;
- return; // defer call
- }
+/**
+ * Expands a brace pattern into an array. This method is called by the
+ * main [braces](#braces) function when `options.expand` is true. Before
+ * using this method it's recommended that you read the [performance notes](#performance))
+ * and advantages of using [.compile](#compile) instead.
+ *
+ * ```js
+ * const braces = require('braces');
+ * console.log(braces.expand('a/{b,c}/d'));
+ * //=> ['a/b/d', 'a/c/d'];
+ * ```
+ * @param {String} `pattern` Brace pattern
+ * @param {Object} `options`
+ * @return {Array} Returns an array of expanded values.
+ * @api public
+ */
- this._insideLoop = true;
- try {
- do {
- this._pendingNext = false;
- this._realGetNext();
- } while (this._pendingNext);
- } finally {
- this._insideLoop = false;
+braces.expand = (input, options = {}) => {
+ if (typeof input === 'string') {
+ input = braces.parse(input, options);
}
-};
-
-CombinedStream.prototype._realGetNext = function() {
- var stream = this._streams.shift();
+ let result = expand(input, options);
- if (typeof stream == 'undefined') {
- this.end();
- return;
+ // filter out empty strings if specified
+ if (options.noempty === true) {
+ result = result.filter(Boolean);
}
- if (typeof stream !== 'function') {
- this._pipeNext(stream);
- return;
+ // filter out duplicates if specified
+ if (options.nodupes === true) {
+ result = [...new Set(result)];
}
- var getStream = stream;
- getStream(function(stream) {
- var isStreamLike = CombinedStream.isStreamLike(stream);
- if (isStreamLike) {
- stream.on('data', this._checkDataSize.bind(this));
- this._handleErrors(stream);
- }
-
- this._pipeNext(stream);
- }.bind(this));
+ return result;
};
-CombinedStream.prototype._pipeNext = function(stream) {
- this._currentStream = stream;
+/**
+ * Processes a brace pattern and returns either an expanded array
+ * (if `options.expand` is true), a highly optimized regex-compatible string.
+ * This method is called by the main [braces](#braces) function.
+ *
+ * ```js
+ * const braces = require('braces');
+ * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}'))
+ * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)'
+ * ```
+ * @param {String} `pattern` Brace pattern
+ * @param {Object} `options`
+ * @return {Array} Returns an array of expanded values.
+ * @api public
+ */
- var isStreamLike = CombinedStream.isStreamLike(stream);
- if (isStreamLike) {
- stream.on('end', this._getNext.bind(this));
- stream.pipe(this, {end: false});
- return;
+braces.create = (input, options = {}) => {
+ if (input === '' || input.length < 3) {
+ return [input];
}
- var value = stream;
- this.write(value);
- this._getNext();
-};
-
-CombinedStream.prototype._handleErrors = function(stream) {
- var self = this;
- stream.on('error', function(err) {
- self._emitError(err);
- });
-};
-
-CombinedStream.prototype.write = function(data) {
- this.emit('data', data);
+ return options.expand !== true
+ ? braces.compile(input, options)
+ : braces.expand(input, options);
};
-CombinedStream.prototype.pause = function() {
- if (!this.pauseStreams) {
- return;
- }
-
- if(this.pauseStreams && this._currentStream && typeof(this._currentStream.pause) == 'function') this._currentStream.pause();
- this.emit('pause');
-};
+/**
+ * Expose "braces"
+ */
-CombinedStream.prototype.resume = function() {
- if (!this._released) {
- this._released = true;
- this.writable = true;
- this._getNext();
- }
+module.exports = braces;
- if(this.pauseStreams && this._currentStream && typeof(this._currentStream.resume) == 'function') this._currentStream.resume();
- this.emit('resume');
-};
-CombinedStream.prototype.end = function() {
- this._reset();
- this.emit('end');
-};
+/***/ }),
-CombinedStream.prototype.destroy = function() {
- this._reset();
- this.emit('close');
-};
+/***/ 9434:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-CombinedStream.prototype._reset = function() {
- this.writable = false;
- this._streams = [];
- this._currentStream = null;
-};
+"use strict";
-CombinedStream.prototype._checkDataSize = function() {
- this._updateDataSize();
- if (this.dataSize <= this.maxDataSize) {
- return;
- }
- var message =
- 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.';
- this._emitError(new Error(message));
-};
+const fill = __nccwpck_require__(6330);
+const utils = __nccwpck_require__(5207);
-CombinedStream.prototype._updateDataSize = function() {
- this.dataSize = 0;
+const compile = (ast, options = {}) => {
+ let walk = (node, parent = {}) => {
+ let invalidBlock = utils.isInvalidBrace(parent);
+ let invalidNode = node.invalid === true && options.escapeInvalid === true;
+ let invalid = invalidBlock === true || invalidNode === true;
+ let prefix = options.escapeInvalid === true ? '\\' : '';
+ let output = '';
- var self = this;
- this._streams.forEach(function(stream) {
- if (!stream.dataSize) {
- return;
+ if (node.isOpen === true) {
+ return prefix + node.value;
+ }
+ if (node.isClose === true) {
+ return prefix + node.value;
}
- self.dataSize += stream.dataSize;
- });
+ if (node.type === 'open') {
+ return invalid ? (prefix + node.value) : '(';
+ }
- if (this._currentStream && this._currentStream.dataSize) {
- this.dataSize += this._currentStream.dataSize;
- }
-};
+ if (node.type === 'close') {
+ return invalid ? (prefix + node.value) : ')';
+ }
-CombinedStream.prototype._emitError = function(err) {
- this._reset();
- this.emit('error', err);
-};
+ if (node.type === 'comma') {
+ return node.prev.type === 'comma' ? '' : (invalid ? node.value : '|');
+ }
+ if (node.value) {
+ return node.value;
+ }
-/***/ }),
+ if (node.nodes && node.ranges > 0) {
+ let args = utils.reduce(node.nodes);
+ let range = fill(...args, { ...options, wrap: false, toRegex: true });
-/***/ 6891:
-/***/ ((module) => {
+ if (range.length !== 0) {
+ return args.length > 1 && range.length > 1 ? `(${range})` : range;
+ }
+ }
-module.exports = function (xs, fn) {
- var res = [];
- for (var i = 0; i < xs.length; i++) {
- var x = fn(xs[i], i);
- if (isArray(x)) res.push.apply(res, x);
- else res.push(x);
+ if (node.nodes) {
+ for (let child of node.nodes) {
+ output += walk(child, node);
+ }
}
- return res;
-};
+ return output;
+ };
-var isArray = Array.isArray || function (xs) {
- return Object.prototype.toString.call(xs) === '[object Array]';
+ return walk(ast);
};
+module.exports = compile;
+
/***/ }),
-/***/ 3325:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+/***/ 8774:
+/***/ ((module) => {
"use strict";
-const {promisify} = __nccwpck_require__(1669);
-const path = __nccwpck_require__(5622);
-const globby = __nccwpck_require__(3477);
-const isGlob = __nccwpck_require__(4466);
-const slash = __nccwpck_require__(4111);
-const gracefulFs = __nccwpck_require__(7758);
-const isPathCwd = __nccwpck_require__(8885);
-const isPathInside = __nccwpck_require__(628);
-const rimraf = __nccwpck_require__(4959);
-const pMap = __nccwpck_require__(1855);
-const rimrafP = promisify(rimraf);
+module.exports = {
+ MAX_LENGTH: 1024 * 64,
-const rimrafOptions = {
- glob: false,
- unlink: gracefulFs.unlink,
- unlinkSync: gracefulFs.unlinkSync,
- chmod: gracefulFs.chmod,
- chmodSync: gracefulFs.chmodSync,
- stat: gracefulFs.stat,
- statSync: gracefulFs.statSync,
- lstat: gracefulFs.lstat,
- lstatSync: gracefulFs.lstatSync,
- rmdir: gracefulFs.rmdir,
- rmdirSync: gracefulFs.rmdirSync,
- readdir: gracefulFs.readdir,
- readdirSync: gracefulFs.readdirSync
-};
-
-function safeCheck(file, cwd) {
- if (isPathCwd(file)) {
- throw new Error('Cannot delete the current working directory. Can be overridden with the `force` option.');
- }
-
- if (!isPathInside(file, cwd)) {
- throw new Error('Cannot delete files/directories outside the current working directory. Can be overridden with the `force` option.');
- }
-}
+ // Digits
+ CHAR_0: '0', /* 0 */
+ CHAR_9: '9', /* 9 */
-function normalizePatterns(patterns) {
- patterns = Array.isArray(patterns) ? patterns : [patterns];
+ // Alphabet chars.
+ CHAR_UPPERCASE_A: 'A', /* A */
+ CHAR_LOWERCASE_A: 'a', /* a */
+ CHAR_UPPERCASE_Z: 'Z', /* Z */
+ CHAR_LOWERCASE_Z: 'z', /* z */
- patterns = patterns.map(pattern => {
- if (process.platform === 'win32' && isGlob(pattern) === false) {
- return slash(pattern);
- }
+ CHAR_LEFT_PARENTHESES: '(', /* ( */
+ CHAR_RIGHT_PARENTHESES: ')', /* ) */
- return pattern;
- });
+ CHAR_ASTERISK: '*', /* * */
- return patterns;
-}
+ // Non-alphabetic chars.
+ CHAR_AMPERSAND: '&', /* & */
+ CHAR_AT: '@', /* @ */
+ CHAR_BACKSLASH: '\\', /* \ */
+ CHAR_BACKTICK: '`', /* ` */
+ CHAR_CARRIAGE_RETURN: '\r', /* \r */
+ CHAR_CIRCUMFLEX_ACCENT: '^', /* ^ */
+ CHAR_COLON: ':', /* : */
+ CHAR_COMMA: ',', /* , */
+ CHAR_DOLLAR: '$', /* . */
+ CHAR_DOT: '.', /* . */
+ CHAR_DOUBLE_QUOTE: '"', /* " */
+ CHAR_EQUAL: '=', /* = */
+ CHAR_EXCLAMATION_MARK: '!', /* ! */
+ CHAR_FORM_FEED: '\f', /* \f */
+ CHAR_FORWARD_SLASH: '/', /* / */
+ CHAR_HASH: '#', /* # */
+ CHAR_HYPHEN_MINUS: '-', /* - */
+ CHAR_LEFT_ANGLE_BRACKET: '<', /* < */
+ CHAR_LEFT_CURLY_BRACE: '{', /* { */
+ CHAR_LEFT_SQUARE_BRACKET: '[', /* [ */
+ CHAR_LINE_FEED: '\n', /* \n */
+ CHAR_NO_BREAK_SPACE: '\u00A0', /* \u00A0 */
+ CHAR_PERCENT: '%', /* % */
+ CHAR_PLUS: '+', /* + */
+ CHAR_QUESTION_MARK: '?', /* ? */
+ CHAR_RIGHT_ANGLE_BRACKET: '>', /* > */
+ CHAR_RIGHT_CURLY_BRACE: '}', /* } */
+ CHAR_RIGHT_SQUARE_BRACKET: ']', /* ] */
+ CHAR_SEMICOLON: ';', /* ; */
+ CHAR_SINGLE_QUOTE: '\'', /* ' */
+ CHAR_SPACE: ' ', /* */
+ CHAR_TAB: '\t', /* \t */
+ CHAR_UNDERSCORE: '_', /* _ */
+ CHAR_VERTICAL_LINE: '|', /* | */
+ CHAR_ZERO_WIDTH_NOBREAK_SPACE: '\uFEFF' /* \uFEFF */
+};
-module.exports = async (patterns, {force, dryRun, cwd = process.cwd(), ...options} = {}) => {
- options = {
- expandDirectories: false,
- onlyFiles: false,
- followSymbolicLinks: false,
- cwd,
- ...options
- };
- patterns = normalizePatterns(patterns);
+/***/ }),
- const files = (await globby(patterns, options))
- .sort((a, b) => b.localeCompare(a));
+/***/ 5873:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- const mapper = async file => {
- file = path.resolve(cwd, file);
+"use strict";
- if (!force) {
- safeCheck(file, cwd);
- }
- if (!dryRun) {
- await rimrafP(file, rimrafOptions);
- }
+const fill = __nccwpck_require__(6330);
+const stringify = __nccwpck_require__(8750);
+const utils = __nccwpck_require__(5207);
- return file;
- };
+const append = (queue = '', stash = '', enclose = false) => {
+ let result = [];
- const removedFiles = await pMap(files, mapper, options);
+ queue = [].concat(queue);
+ stash = [].concat(stash);
- removedFiles.sort((a, b) => a.localeCompare(b));
+ if (!stash.length) return queue;
+ if (!queue.length) {
+ return enclose ? utils.flatten(stash).map(ele => `{${ele}}`) : stash;
+ }
- return removedFiles;
+ for (let item of queue) {
+ if (Array.isArray(item)) {
+ for (let value of item) {
+ result.push(append(value, stash, enclose));
+ }
+ } else {
+ for (let ele of stash) {
+ if (enclose === true && typeof ele === 'string') ele = `{${ele}}`;
+ result.push(Array.isArray(ele) ? append(item, ele, enclose) : (item + ele));
+ }
+ }
+ }
+ return utils.flatten(result);
};
-module.exports.sync = (patterns, {force, dryRun, cwd = process.cwd(), ...options} = {}) => {
- options = {
- expandDirectories: false,
- onlyFiles: false,
- followSymbolicLinks: false,
- cwd,
- ...options
- };
+const expand = (ast, options = {}) => {
+ let rangeLimit = options.rangeLimit === void 0 ? 1000 : options.rangeLimit;
- patterns = normalizePatterns(patterns);
+ let walk = (node, parent = {}) => {
+ node.queue = [];
- const files = globby.sync(patterns, options)
- .sort((a, b) => b.localeCompare(a));
+ let p = parent;
+ let q = parent.queue;
- const removedFiles = files.map(file => {
- file = path.resolve(cwd, file);
+ while (p.type !== 'brace' && p.type !== 'root' && p.parent) {
+ p = p.parent;
+ q = p.queue;
+ }
- if (!force) {
- safeCheck(file, cwd);
- }
+ if (node.invalid || node.dollar) {
+ q.push(append(q.pop(), stringify(node, options)));
+ return;
+ }
- if (!dryRun) {
- rimraf.sync(file, rimrafOptions);
- }
+ if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) {
+ q.push(append(q.pop(), ['{}']));
+ return;
+ }
- return file;
- });
+ if (node.nodes && node.ranges > 0) {
+ let args = utils.reduce(node.nodes);
- removedFiles.sort((a, b) => a.localeCompare(b));
+ if (utils.exceedsLimit(...args, options.step, rangeLimit)) {
+ throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.');
+ }
- return removedFiles;
-};
+ let range = fill(...args, options);
+ if (range.length === 0) {
+ range = stringify(node, options);
+ }
+ q.push(append(q.pop(), range));
+ node.nodes = [];
+ return;
+ }
-/***/ }),
+ let enclose = utils.encloseBrace(node);
+ let queue = node.queue;
+ let block = node;
-/***/ 7895:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ while (block.type !== 'brace' && block.type !== 'root' && block.parent) {
+ block = block.parent;
+ queue = block.queue;
+ }
-"use strict";
+ for (let i = 0; i < node.nodes.length; i++) {
+ let child = node.nodes[i];
-const {promisify} = __nccwpck_require__(1669);
-const fs = __nccwpck_require__(5747);
-const path = __nccwpck_require__(5622);
-const fastGlob = __nccwpck_require__(3664);
-const gitIgnore = __nccwpck_require__(1865);
-const slash = __nccwpck_require__(4111);
+ if (child.type === 'comma' && node.type === 'brace') {
+ if (i === 1) queue.push('');
+ queue.push('');
+ continue;
+ }
-const DEFAULT_IGNORE = [
- '**/node_modules/**',
- '**/flow-typed/**',
- '**/coverage/**',
- '**/.git'
-];
+ if (child.type === 'close') {
+ q.push(append(q.pop(), queue, enclose));
+ continue;
+ }
-const readFileP = promisify(fs.readFile);
+ if (child.value && child.type !== 'open') {
+ queue.push(append(queue.pop(), child.value));
+ continue;
+ }
-const mapGitIgnorePatternTo = base => ignore => {
- if (ignore.startsWith('!')) {
- return '!' + path.posix.join(base, ignore.slice(1));
- }
+ if (child.nodes) {
+ walk(child, node);
+ }
+ }
- return path.posix.join(base, ignore);
+ return queue;
+ };
+
+ return utils.flatten(walk(ast));
};
-const parseGitIgnore = (content, options) => {
- const base = slash(path.relative(options.cwd, path.dirname(options.fileName)));
+module.exports = expand;
- return content
- .split(/\r?\n/)
- .filter(Boolean)
- .filter(line => !line.startsWith('#'))
- .map(mapGitIgnorePatternTo(base));
-};
-const reduceIgnore = files => {
- return files.reduce((ignores, file) => {
- ignores.add(parseGitIgnore(file.content, {
- cwd: file.cwd,
- fileName: file.filePath
- }));
- return ignores;
- }, gitIgnore());
-};
+/***/ }),
-const ensureAbsolutePathForCwd = (cwd, p) => {
- if (path.isAbsolute(p)) {
- if (p.startsWith(cwd)) {
- return p;
- }
+/***/ 6477:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- throw new Error(`Path ${p} is not in cwd ${cwd}`);
- }
+"use strict";
- return path.join(cwd, p);
-};
-const getIsIgnoredPredecate = (ignores, cwd) => {
- return p => ignores.ignores(slash(path.relative(cwd, ensureAbsolutePathForCwd(cwd, p))));
-};
+const stringify = __nccwpck_require__(8750);
-const getFile = async (file, cwd) => {
- const filePath = path.join(cwd, file);
- const content = await readFileP(filePath, 'utf8');
+/**
+ * Constants
+ */
- return {
- cwd,
- filePath,
- content
- };
-};
+const {
+ MAX_LENGTH,
+ CHAR_BACKSLASH, /* \ */
+ CHAR_BACKTICK, /* ` */
+ CHAR_COMMA, /* , */
+ CHAR_DOT, /* . */
+ CHAR_LEFT_PARENTHESES, /* ( */
+ CHAR_RIGHT_PARENTHESES, /* ) */
+ CHAR_LEFT_CURLY_BRACE, /* { */
+ CHAR_RIGHT_CURLY_BRACE, /* } */
+ CHAR_LEFT_SQUARE_BRACKET, /* [ */
+ CHAR_RIGHT_SQUARE_BRACKET, /* ] */
+ CHAR_DOUBLE_QUOTE, /* " */
+ CHAR_SINGLE_QUOTE, /* ' */
+ CHAR_NO_BREAK_SPACE,
+ CHAR_ZERO_WIDTH_NOBREAK_SPACE
+} = __nccwpck_require__(8774);
-const getFileSync = (file, cwd) => {
- const filePath = path.join(cwd, file);
- const content = fs.readFileSync(filePath, 'utf8');
+/**
+ * parse
+ */
- return {
- cwd,
- filePath,
- content
- };
-};
+const parse = (input, options = {}) => {
+ if (typeof input !== 'string') {
+ throw new TypeError('Expected a string');
+ }
-const normalizeOptions = ({
- ignore = [],
- cwd = slash(process.cwd())
-} = {}) => {
- return {ignore, cwd};
-};
+ let opts = options || {};
+ let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
+ if (input.length > max) {
+ throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`);
+ }
-module.exports = async options => {
- options = normalizeOptions(options);
+ let ast = { type: 'root', input, nodes: [] };
+ let stack = [ast];
+ let block = ast;
+ let prev = ast;
+ let brackets = 0;
+ let length = input.length;
+ let index = 0;
+ let depth = 0;
+ let value;
+ let memo = {};
- const paths = await fastGlob('**/.gitignore', {
- ignore: DEFAULT_IGNORE.concat(options.ignore),
- cwd: options.cwd
- });
+ /**
+ * Helpers
+ */
- const files = await Promise.all(paths.map(file => getFile(file, options.cwd)));
- const ignores = reduceIgnore(files);
+ const advance = () => input[index++];
+ const push = node => {
+ if (node.type === 'text' && prev.type === 'dot') {
+ prev.type = 'text';
+ }
- return getIsIgnoredPredecate(ignores, options.cwd);
-};
+ if (prev && prev.type === 'text' && node.type === 'text') {
+ prev.value += node.value;
+ return;
+ }
-module.exports.sync = options => {
- options = normalizeOptions(options);
+ block.nodes.push(node);
+ node.parent = block;
+ node.prev = prev;
+ prev = node;
+ return node;
+ };
- const paths = fastGlob.sync('**/.gitignore', {
- ignore: DEFAULT_IGNORE.concat(options.ignore),
- cwd: options.cwd
- });
+ push({ type: 'bos' });
- const files = paths.map(file => getFileSync(file, options.cwd));
- const ignores = reduceIgnore(files);
+ while (index < length) {
+ block = stack[stack.length - 1];
+ value = advance();
- return getIsIgnoredPredecate(ignores, options.cwd);
-};
+ /**
+ * Invalid chars
+ */
+ if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) {
+ continue;
+ }
-/***/ }),
+ /**
+ * Escaped chars
+ */
-/***/ 3477:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ if (value === CHAR_BACKSLASH) {
+ push({ type: 'text', value: (options.keepEscaping ? value : '') + advance() });
+ continue;
+ }
-"use strict";
+ /**
+ * Right square bracket (literal): ']'
+ */
-const fs = __nccwpck_require__(5747);
-const arrayUnion = __nccwpck_require__(9600);
-const merge2 = __nccwpck_require__(2578);
-const glob = __nccwpck_require__(1957);
-const fastGlob = __nccwpck_require__(3664);
-const dirGlob = __nccwpck_require__(2738);
-const gitignore = __nccwpck_require__(7895);
-const {FilterStream, UniqueStream} = __nccwpck_require__(308);
+ if (value === CHAR_RIGHT_SQUARE_BRACKET) {
+ push({ type: 'text', value: '\\' + value });
+ continue;
+ }
-const DEFAULT_FILTER = () => false;
+ /**
+ * Left square bracket: '['
+ */
-const isNegative = pattern => pattern[0] === '!';
+ if (value === CHAR_LEFT_SQUARE_BRACKET) {
+ brackets++;
-const assertPatternsInput = patterns => {
- if (!patterns.every(pattern => typeof pattern === 'string')) {
- throw new TypeError('Patterns must be a string or an array of strings');
- }
-};
+ let closed = true;
+ let next;
-const checkCwdOption = (options = {}) => {
- if (!options.cwd) {
- return;
- }
+ while (index < length && (next = advance())) {
+ value += next;
- let stat;
- try {
- stat = fs.statSync(options.cwd);
- } catch (_) {
- return;
- }
+ if (next === CHAR_LEFT_SQUARE_BRACKET) {
+ brackets++;
+ continue;
+ }
- if (!stat.isDirectory()) {
- throw new Error('The `cwd` option must be a path to a directory');
- }
-};
+ if (next === CHAR_BACKSLASH) {
+ value += advance();
+ continue;
+ }
-const getPathString = p => p.stats instanceof fs.Stats ? p.path : p;
+ if (next === CHAR_RIGHT_SQUARE_BRACKET) {
+ brackets--;
-const generateGlobTasks = (patterns, taskOptions) => {
- patterns = arrayUnion([].concat(patterns));
- assertPatternsInput(patterns);
- checkCwdOption(taskOptions);
+ if (brackets === 0) {
+ break;
+ }
+ }
+ }
- const globTasks = [];
+ push({ type: 'text', value });
+ continue;
+ }
- taskOptions = {
- ignore: [],
- expandDirectories: true,
- ...taskOptions
- };
+ /**
+ * Parentheses
+ */
- for (const [index, pattern] of patterns.entries()) {
- if (isNegative(pattern)) {
- continue;
- }
+ if (value === CHAR_LEFT_PARENTHESES) {
+ block = push({ type: 'paren', nodes: [] });
+ stack.push(block);
+ push({ type: 'text', value });
+ continue;
+ }
- const ignore = patterns
- .slice(index)
- .filter(isNegative)
- .map(pattern => pattern.slice(1));
+ if (value === CHAR_RIGHT_PARENTHESES) {
+ if (block.type !== 'paren') {
+ push({ type: 'text', value });
+ continue;
+ }
+ block = stack.pop();
+ push({ type: 'text', value });
+ block = stack[stack.length - 1];
+ continue;
+ }
- const options = {
- ...taskOptions,
- ignore: taskOptions.ignore.concat(ignore)
- };
+ /**
+ * Quotes: '|"|`
+ */
- globTasks.push({pattern, options});
- }
+ if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) {
+ let open = value;
+ let next;
- return globTasks;
-};
+ if (options.keepQuotes !== true) {
+ value = '';
+ }
-const globDirs = (task, fn) => {
- let options = {};
- if (task.options.cwd) {
- options.cwd = task.options.cwd;
- }
+ while (index < length && (next = advance())) {
+ if (next === CHAR_BACKSLASH) {
+ value += next + advance();
+ continue;
+ }
- if (Array.isArray(task.options.expandDirectories)) {
- options = {
- ...options,
- files: task.options.expandDirectories
- };
- } else if (typeof task.options.expandDirectories === 'object') {
- options = {
- ...options,
- ...task.options.expandDirectories
- };
- }
+ if (next === open) {
+ if (options.keepQuotes === true) value += next;
+ break;
+ }
- return fn(task.pattern, options);
-};
+ value += next;
+ }
-const getPattern = (task, fn) => task.options.expandDirectories ? globDirs(task, fn) : [task.pattern];
+ push({ type: 'text', value });
+ continue;
+ }
-const getFilterSync = options => {
- return options && options.gitignore ?
- gitignore.sync({cwd: options.cwd, ignore: options.ignore}) :
- DEFAULT_FILTER;
-};
+ /**
+ * Left curly brace: '{'
+ */
-const globToTask = task => glob => {
- const {options} = task;
- if (options.ignore && Array.isArray(options.ignore) && options.expandDirectories) {
- options.ignore = dirGlob.sync(options.ignore);
- }
+ if (value === CHAR_LEFT_CURLY_BRACE) {
+ depth++;
- return {
- pattern: glob,
- options
- };
-};
+ let dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true;
+ let brace = {
+ type: 'brace',
+ open: true,
+ close: false,
+ dollar,
+ depth,
+ commas: 0,
+ ranges: 0,
+ nodes: []
+ };
-module.exports = async (patterns, options) => {
- const globTasks = generateGlobTasks(patterns, options);
+ block = push(brace);
+ stack.push(block);
+ push({ type: 'open', value });
+ continue;
+ }
- const getFilter = async () => {
- return options && options.gitignore ?
- gitignore({cwd: options.cwd, ignore: options.ignore}) :
- DEFAULT_FILTER;
- };
+ /**
+ * Right curly brace: '}'
+ */
- const getTasks = async () => {
- const tasks = await Promise.all(globTasks.map(async task => {
- const globs = await getPattern(task, dirGlob);
- return Promise.all(globs.map(globToTask(task)));
- }));
+ if (value === CHAR_RIGHT_CURLY_BRACE) {
+ if (block.type !== 'brace') {
+ push({ type: 'text', value });
+ continue;
+ }
- return arrayUnion(...tasks);
- };
+ let type = 'close';
+ block = stack.pop();
+ block.close = true;
- const [filter, tasks] = await Promise.all([getFilter(), getTasks()]);
- const paths = await Promise.all(tasks.map(task => fastGlob(task.pattern, task.options)));
+ push({ type, value });
+ depth--;
- return arrayUnion(...paths).filter(path_ => !filter(getPathString(path_)));
-};
+ block = stack[stack.length - 1];
+ continue;
+ }
-module.exports.sync = (patterns, options) => {
- const globTasks = generateGlobTasks(patterns, options);
+ /**
+ * Comma: ','
+ */
- const tasks = globTasks.reduce((tasks, task) => {
- const newTask = getPattern(task, dirGlob.sync).map(globToTask(task));
- return tasks.concat(newTask);
- }, []);
+ if (value === CHAR_COMMA && depth > 0) {
+ if (block.ranges > 0) {
+ block.ranges = 0;
+ let open = block.nodes.shift();
+ block.nodes = [open, { type: 'text', value: stringify(block) }];
+ }
- const filter = getFilterSync(options);
+ push({ type: 'comma', value });
+ block.commas++;
+ continue;
+ }
- return tasks.reduce(
- (matches, task) => arrayUnion(matches, fastGlob.sync(task.pattern, task.options)),
- []
- ).filter(path_ => !filter(path_));
-};
+ /**
+ * Dot: '.'
+ */
-module.exports.stream = (patterns, options) => {
- const globTasks = generateGlobTasks(patterns, options);
+ if (value === CHAR_DOT && depth > 0 && block.commas === 0) {
+ let siblings = block.nodes;
- const tasks = globTasks.reduce((tasks, task) => {
- const newTask = getPattern(task, dirGlob.sync).map(globToTask(task));
- return tasks.concat(newTask);
- }, []);
+ if (depth === 0 || siblings.length === 0) {
+ push({ type: 'text', value });
+ continue;
+ }
- const filter = getFilterSync(options);
- const filterStream = new FilterStream(p => !filter(p));
- const uniqueStream = new UniqueStream();
+ if (prev.type === 'dot') {
+ block.range = [];
+ prev.value += value;
+ prev.type = 'range';
- return merge2(tasks.map(task => fastGlob.stream(task.pattern, task.options)))
- .pipe(filterStream)
- .pipe(uniqueStream);
-};
+ if (block.nodes.length !== 3 && block.nodes.length !== 5) {
+ block.invalid = true;
+ block.ranges = 0;
+ prev.type = 'text';
+ continue;
+ }
-module.exports.generateGlobTasks = generateGlobTasks;
+ block.ranges++;
+ block.args = [];
+ continue;
+ }
-module.exports.hasMagic = (patterns, options) => []
- .concat(patterns)
- .some(pattern => glob.hasMagic(pattern, options));
+ if (prev.type === 'range') {
+ siblings.pop();
-module.exports.gitignore = gitignore;
+ let before = siblings[siblings.length - 1];
+ before.value += prev.value + value;
+ prev = before;
+ block.ranges--;
+ continue;
+ }
+
+ push({ type: 'dot', value });
+ continue;
+ }
+
+ /**
+ * Text
+ */
+
+ push({ type: 'text', value });
+ }
+
+ // Mark imbalanced braces and brackets as invalid
+ do {
+ block = stack.pop();
+
+ if (block.type !== 'root') {
+ block.nodes.forEach(node => {
+ if (!node.nodes) {
+ if (node.type === 'open') node.isOpen = true;
+ if (node.type === 'close') node.isClose = true;
+ if (!node.nodes) node.type = 'text';
+ node.invalid = true;
+ }
+ });
+
+ // get the location of the block on parent.nodes (block's siblings)
+ let parent = stack[stack.length - 1];
+ let index = parent.nodes.indexOf(block);
+ // replace the (invalid) block with it's nodes
+ parent.nodes.splice(index, 1, ...block.nodes);
+ }
+ } while (stack.length > 0);
+
+ push({ type: 'eos' });
+ return ast;
+};
+
+module.exports = parse;
/***/ }),
-/***/ 308:
+/***/ 8750:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
-const {Transform} = __nccwpck_require__(2413);
-
-class ObjectTransform extends Transform {
- constructor() {
- super({
- objectMode: true
- });
- }
-}
-
-class FilterStream extends ObjectTransform {
- constructor(filter) {
- super();
- this._filter = filter;
- }
- _transform(data, encoding, callback) {
- if (this._filter(data)) {
- this.push(data);
- }
+const utils = __nccwpck_require__(5207);
- callback();
- }
-}
+module.exports = (ast, options = {}) => {
+ let stringify = (node, parent = {}) => {
+ let invalidBlock = options.escapeInvalid && utils.isInvalidBrace(parent);
+ let invalidNode = node.invalid === true && options.escapeInvalid === true;
+ let output = '';
-class UniqueStream extends ObjectTransform {
- constructor() {
- super();
- this._pushed = new Set();
- }
+ if (node.value) {
+ if ((invalidBlock || invalidNode) && utils.isOpenOrClose(node)) {
+ return '\\' + node.value;
+ }
+ return node.value;
+ }
- _transform(data, encoding, callback) {
- if (!this._pushed.has(data)) {
- this.push(data);
- this._pushed.add(data);
- }
+ if (node.value) {
+ return node.value;
+ }
- callback();
- }
-}
+ if (node.nodes) {
+ for (let child of node.nodes) {
+ output += stringify(child);
+ }
+ }
+ return output;
+ };
-module.exports = {
- FilterStream,
- UniqueStream
+ return stringify(ast);
};
+
/***/ }),
-/***/ 1865:
-/***/ ((module) => {
+/***/ 5207:
+/***/ ((__unused_webpack_module, exports) => {
-// A simple implementation of make-array
-function makeArray (subject) {
- return Array.isArray(subject)
- ? subject
- : [subject]
-}
+"use strict";
-const EMPTY = ''
-const SPACE = ' '
-const ESCAPE = '\\'
-const REGEX_TEST_BLANK_LINE = /^\s+$/
-const REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/
-const REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/
-const REGEX_SPLITALL_CRLF = /\r?\n/g
-// /foo,
-// ./foo,
-// ../foo,
-// .
-// ..
-const REGEX_TEST_INVALID_PATH = /^\.*\/|^\.+$/
-const SLASH = '/'
-const KEY_IGNORE = typeof Symbol !== 'undefined'
- ? Symbol.for('node-ignore')
- /* istanbul ignore next */
- : 'node-ignore'
+exports.isInteger = num => {
+ if (typeof num === 'number') {
+ return Number.isInteger(num);
+ }
+ if (typeof num === 'string' && num.trim() !== '') {
+ return Number.isInteger(Number(num));
+ }
+ return false;
+};
-const define = (object, key, value) =>
- Object.defineProperty(object, key, {value})
+/**
+ * Find a node of the given type
+ */
-const REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g
+exports.find = (node, type) => node.nodes.find(node => node.type === type);
-// Sanitize the range of a regular expression
-// The cases are complicated, see test cases for details
-const sanitizeRange = range => range.replace(
- REGEX_REGEXP_RANGE,
- (match, from, to) => from.charCodeAt(0) <= to.charCodeAt(0)
- ? match
- // Invalid range (out of order) which is ok for gitignore rules but
- // fatal for JavaScript regular expression, so eliminate it.
- : EMPTY
-)
+/**
+ * Find a node of the given type
+ */
-// See fixtures #59
-const cleanRangeBackSlash = slashes => {
- const {length} = slashes
- return slashes.slice(0, length - length % 2)
-}
+exports.exceedsLimit = (min, max, step = 1, limit) => {
+ if (limit === false) return false;
+ if (!exports.isInteger(min) || !exports.isInteger(max)) return false;
+ return ((Number(max) - Number(min)) / Number(step)) >= limit;
+};
-// > If the pattern ends with a slash,
-// > it is removed for the purpose of the following description,
-// > but it would only find a match with a directory.
-// > In other words, foo/ will match a directory foo and paths underneath it,
-// > but will not match a regular file or a symbolic link foo
-// > (this is consistent with the way how pathspec works in general in Git).
-// '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`'
-// -> ignore-rules will not deal with it, because it costs extra `fs.stat` call
-// you could use option `mark: true` with `glob`
+/**
+ * Escape the given node with '\\' before node.value
+ */
-// '`foo/`' should not continue with the '`..`'
-const REPLACERS = [
+exports.escapeNode = (block, n = 0, type) => {
+ let node = block.nodes[n];
+ if (!node) return;
- // > Trailing spaces are ignored unless they are quoted with backslash ("\")
- [
- // (a\ ) -> (a )
- // (a ) -> (a)
- // (a \ ) -> (a )
- /\\?\s+$/,
- match => match.indexOf('\\') === 0
- ? SPACE
- : EMPTY
- ],
+ if ((type && node.type === type) || node.type === 'open' || node.type === 'close') {
+ if (node.escaped !== true) {
+ node.value = '\\' + node.value;
+ node.escaped = true;
+ }
+ }
+};
- // replace (\ ) with ' '
- [
- /\\\s/g,
- () => SPACE
- ],
+/**
+ * Returns true if the given brace node should be enclosed in literal braces
+ */
- // Escape metacharacters
- // which is written down by users but means special for regular expressions.
+exports.encloseBrace = node => {
+ if (node.type !== 'brace') return false;
+ if ((node.commas >> 0 + node.ranges >> 0) === 0) {
+ node.invalid = true;
+ return true;
+ }
+ return false;
+};
- // > There are 12 characters with special meanings:
- // > - the backslash \,
- // > - the caret ^,
- // > - the dollar sign $,
- // > - the period or dot .,
- // > - the vertical bar or pipe symbol |,
- // > - the question mark ?,
- // > - the asterisk or star *,
- // > - the plus sign +,
- // > - the opening parenthesis (,
- // > - the closing parenthesis ),
- // > - and the opening square bracket [,
- // > - the opening curly brace {,
- // > These special characters are often called "metacharacters".
- [
- /[\\$.|*+(){^]/g,
- match => `\\${match}`
- ],
+/**
+ * Returns true if a brace node is invalid.
+ */
- [
- // > a question mark (?) matches a single character
- /(?!\\)\?/g,
- () => '[^/]'
- ],
+exports.isInvalidBrace = block => {
+ if (block.type !== 'brace') return false;
+ if (block.invalid === true || block.dollar) return true;
+ if ((block.commas >> 0 + block.ranges >> 0) === 0) {
+ block.invalid = true;
+ return true;
+ }
+ if (block.open !== true || block.close !== true) {
+ block.invalid = true;
+ return true;
+ }
+ return false;
+};
- // leading slash
- [
+/**
+ * Returns true if a node is an open or close node
+ */
- // > A leading slash matches the beginning of the pathname.
- // > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c".
- // A leading slash matches the beginning of the pathname
- /^\//,
- () => '^'
- ],
+exports.isOpenOrClose = node => {
+ if (node.type === 'open' || node.type === 'close') {
+ return true;
+ }
+ return node.open === true || node.close === true;
+};
- // replace special metacharacter slash after the leading slash
- [
- /\//g,
- () => '\\/'
- ],
+/**
+ * Reduce an array of text nodes.
+ */
- [
- // > A leading "**" followed by a slash means match in all directories.
- // > For example, "**/foo" matches file or directory "foo" anywhere,
- // > the same as pattern "foo".
- // > "**/foo/bar" matches file or directory "bar" anywhere that is directly
- // > under directory "foo".
- // Notice that the '*'s have been replaced as '\\*'
- /^\^*\\\*\\\*\\\//,
+exports.reduce = nodes => nodes.reduce((acc, node) => {
+ if (node.type === 'text') acc.push(node.value);
+ if (node.type === 'range') node.type = 'text';
+ return acc;
+}, []);
- // '**/foo' <-> 'foo'
- () => '^(?:.*\\/)?'
- ],
+/**
+ * Flatten an array
+ */
- // starting
- [
- // there will be no leading '/'
- // (which has been replaced by section "leading slash")
- // If starts with '**', adding a '^' to the regular expression also works
- /^(?=[^^])/,
- function startingReplacer () {
- // If has a slash `/` at the beginning or middle
- return !/\/(?!$)/.test(this)
- // > Prior to 2.22.1
- // > If the pattern does not contain a slash /,
- // > Git treats it as a shell glob pattern
- // Actually, if there is only a trailing slash,
- // git also treats it as a shell glob pattern
+exports.flatten = (...args) => {
+ const result = [];
+ const flat = arr => {
+ for (let i = 0; i < arr.length; i++) {
+ let ele = arr[i];
+ Array.isArray(ele) ? flat(ele, result) : ele !== void 0 && result.push(ele);
+ }
+ return result;
+ };
+ flat(args);
+ return result;
+};
- // After 2.22.1 (compatible but clearer)
- // > If there is a separator at the beginning or middle (or both)
- // > of the pattern, then the pattern is relative to the directory
- // > level of the particular .gitignore file itself.
- // > Otherwise the pattern may also match at any level below
- // > the .gitignore level.
- ? '(?:^|\\/)'
- // > Otherwise, Git treats the pattern as a shell glob suitable for
- // > consumption by fnmatch(3)
- : '^'
- }
- ],
+/***/ }),
- // two globstars
- [
- // Use lookahead assertions so that we could match more than one `'/**'`
- /\\\/\\\*\\\*(?=\\\/|$)/g,
+/***/ 7972:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // Zero, one or several directories
- // should not use '*', or it will be replaced by the next replacer
+"use strict";
- // Check if it is not the last `'/**'`
- (_, index, str) => index + 6 < str.length
+const os = __nccwpck_require__(2037);
- // case: /**/
- // > A slash followed by two consecutive asterisks then a slash matches
- // > zero or more directories.
- // > For example, "a/**/b" matches "a/b", "a/x/b", "a/x/y/b" and so on.
- // '/**/'
- ? '(?:\\/[^\\/]+)*'
+const extractPathRegex = /\s+at.*(?:\(|\s)(.*)\)?/;
+const pathRegex = /^(?:(?:(?:node|(?:internal\/[\w/]*|.*node_modules\/(?:babel-polyfill|pirates)\/.*)?\w+)\.js:\d+:\d+)|native)/;
+const homeDir = typeof os.homedir === 'undefined' ? '' : os.homedir();
- // case: /**
- // > A trailing `"/**"` matches everything inside.
+module.exports = (stack, options) => {
+ options = Object.assign({pretty: false}, options);
- // #21: everything inside but it should not include the current folder
- : '\\/.+'
- ],
+ return stack.replace(/\\/g, '/')
+ .split('\n')
+ .filter(line => {
+ const pathMatches = line.match(extractPathRegex);
+ if (pathMatches === null || !pathMatches[1]) {
+ return true;
+ }
- // intermediate wildcards
- [
- // Never replace escaped '*'
- // ignore rule '\*' will match the path '*'
+ const match = pathMatches[1];
- // 'abc.*/' -> go
- // 'abc.*' -> skip this rule
- /(^|[^\\]+)\\\*(?=.+)/g,
+ // Electron
+ if (
+ match.includes('.app/Contents/Resources/electron.asar') ||
+ match.includes('.app/Contents/Resources/default_app.asar')
+ ) {
+ return false;
+ }
- // '*.js' matches '.js'
- // '*.js' doesn't match 'abc'
- (_, p1) => `${p1}[^\\/]*`
- ],
+ return !pathRegex.test(match);
+ })
+ .filter(line => line.trim() !== '')
+ .map(line => {
+ if (options.pretty) {
+ return line.replace(extractPathRegex, (m, p1) => m.replace(p1, p1.replace(homeDir, '~')));
+ }
- [
- // unescape, revert step 3 except for back slash
- // For example, if a user escape a '\\*',
- // after step 3, the result will be '\\\\\\*'
- /\\\\\\(?=[$.|*+(){^])/g,
- () => ESCAPE
- ],
+ return line;
+ })
+ .join('\n');
+};
- [
- // '\\\\' -> '\\'
- /\\\\/g,
- () => ESCAPE
- ],
- [
- // > The range notation, e.g. [a-zA-Z],
- // > can be used to match one of the characters in a range.
+/***/ }),
- // `\` is escaped by step 3
- /(\\)?\[([^\]/]*?)(\\*)($|\])/g,
- (match, leadEscape, range, endEscape, close) => leadEscape === ESCAPE
- // '\\[bar]' -> '\\\\[bar\\]'
- ? `\\[${range}${cleanRangeBackSlash(endEscape)}${close}`
- : close === ']'
- ? endEscape.length % 2 === 0
- // A normal case, and it is a range notation
- // '[bar]'
- // '[bar\\\\]'
- ? `[${sanitizeRange(range)}${endEscape}]`
- // Invalid range notaton
- // '[bar\\]' -> '[bar\\\\]'
- : '[]'
- : '[]'
- ],
+/***/ 5443:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // ending
- [
- // 'js' will not match 'js.'
- // 'ab' will not match 'abc'
- /(?:[^*])$/,
+var util = __nccwpck_require__(3837);
+var Stream = (__nccwpck_require__(2781).Stream);
+var DelayedStream = __nccwpck_require__(8611);
- // WTF!
- // https://git-scm.com/docs/gitignore
- // changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1)
- // which re-fixes #24, #38
+module.exports = CombinedStream;
+function CombinedStream() {
+ this.writable = false;
+ this.readable = true;
+ this.dataSize = 0;
+ this.maxDataSize = 2 * 1024 * 1024;
+ this.pauseStreams = true;
- // > If there is a separator at the end of the pattern then the pattern
- // > will only match directories, otherwise the pattern can match both
- // > files and directories.
+ this._released = false;
+ this._streams = [];
+ this._currentStream = null;
+ this._insideLoop = false;
+ this._pendingNext = false;
+}
+util.inherits(CombinedStream, Stream);
- // 'js*' will not match 'a.js'
- // 'js/' will not match 'a.js'
- // 'js' will match 'a.js' and 'a.js/'
- match => /\/$/.test(match)
- // foo/ will not match 'foo'
- ? `${match}$`
- // foo matches 'foo' and 'foo/'
- : `${match}(?=$|\\/$)`
- ],
+CombinedStream.create = function(options) {
+ var combinedStream = new this();
- // trailing wildcard
- [
- /(\^|\\\/)?\\\*$/,
- (_, p1) => {
- const prefix = p1
- // '\^':
- // '/*' does not match EMPTY
- // '/*' does not match everything
+ options = options || {};
+ for (var option in options) {
+ combinedStream[option] = options[option];
+ }
- // '\\\/':
- // 'abc/*' does not match 'abc/'
- ? `${p1}[^/]+`
+ return combinedStream;
+};
- // 'a*' matches 'a'
- // 'a*' matches 'aa'
- : '[^/]*'
+CombinedStream.isStreamLike = function(stream) {
+ return (typeof stream !== 'function')
+ && (typeof stream !== 'string')
+ && (typeof stream !== 'boolean')
+ && (typeof stream !== 'number')
+ && (!Buffer.isBuffer(stream));
+};
- return `${prefix}(?=$|\\/$)`
+CombinedStream.prototype.append = function(stream) {
+ var isStreamLike = CombinedStream.isStreamLike(stream);
+
+ if (isStreamLike) {
+ if (!(stream instanceof DelayedStream)) {
+ var newStream = DelayedStream.create(stream, {
+ maxDataSize: Infinity,
+ pauseStream: this.pauseStreams,
+ });
+ stream.on('data', this._checkDataSize.bind(this));
+ stream = newStream;
}
- ],
-]
-// A simple cache, because an ignore rule only has only one certain meaning
-const regexCache = Object.create(null)
+ this._handleErrors(stream);
-// @param {pattern}
-const makeRegex = (pattern, negative, ignorecase) => {
- const r = regexCache[pattern]
- if (r) {
- return r
+ if (this.pauseStreams) {
+ stream.pause();
+ }
}
- // const replacers = negative
- // ? NEGATIVE_REPLACERS
- // : POSITIVE_REPLACERS
+ this._streams.push(stream);
+ return this;
+};
- const source = REPLACERS.reduce(
- (prev, current) => prev.replace(current[0], current[1].bind(pattern)),
- pattern
- )
+CombinedStream.prototype.pipe = function(dest, options) {
+ Stream.prototype.pipe.call(this, dest, options);
+ this.resume();
+ return dest;
+};
- return regexCache[pattern] = ignorecase
- ? new RegExp(source, 'i')
- : new RegExp(source)
-}
+CombinedStream.prototype._getNext = function() {
+ this._currentStream = null;
-const isString = subject => typeof subject === 'string'
+ if (this._insideLoop) {
+ this._pendingNext = true;
+ return; // defer call
+ }
-// > A blank line matches no files, so it can serve as a separator for readability.
-const checkPattern = pattern => pattern
- && isString(pattern)
- && !REGEX_TEST_BLANK_LINE.test(pattern)
+ this._insideLoop = true;
+ try {
+ do {
+ this._pendingNext = false;
+ this._realGetNext();
+ } while (this._pendingNext);
+ } finally {
+ this._insideLoop = false;
+ }
+};
- // > A line starting with # serves as a comment.
- && pattern.indexOf('#') !== 0
+CombinedStream.prototype._realGetNext = function() {
+ var stream = this._streams.shift();
-const splitPattern = pattern => pattern.split(REGEX_SPLITALL_CRLF)
-class IgnoreRule {
- constructor (
- origin,
- pattern,
- negative,
- regex
- ) {
- this.origin = origin
- this.pattern = pattern
- this.negative = negative
- this.regex = regex
+ if (typeof stream == 'undefined') {
+ this.end();
+ return;
}
-}
-
-const createRule = (pattern, ignorecase) => {
- const origin = pattern
- let negative = false
- // > An optional prefix "!" which negates the pattern;
- if (pattern.indexOf('!') === 0) {
- negative = true
- pattern = pattern.substr(1)
+ if (typeof stream !== 'function') {
+ this._pipeNext(stream);
+ return;
}
- pattern = pattern
- // > Put a backslash ("\") in front of the first "!" for patterns that
- // > begin with a literal "!", for example, `"\!important!.txt"`.
- .replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, '!')
- // > Put a backslash ("\") in front of the first hash for patterns that
- // > begin with a hash.
- .replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, '#')
-
- const regex = makeRegex(pattern, negative, ignorecase)
+ var getStream = stream;
+ getStream(function(stream) {
+ var isStreamLike = CombinedStream.isStreamLike(stream);
+ if (isStreamLike) {
+ stream.on('data', this._checkDataSize.bind(this));
+ this._handleErrors(stream);
+ }
- return new IgnoreRule(
- origin,
- pattern,
- negative,
- regex
- )
-}
+ this._pipeNext(stream);
+ }.bind(this));
+};
-const throwError = (message, Ctor) => {
- throw new Ctor(message)
-}
+CombinedStream.prototype._pipeNext = function(stream) {
+ this._currentStream = stream;
-const checkPath = (path, originalPath, doThrow) => {
- if (!isString(path)) {
- return doThrow(
- `path must be a string, but got \`${originalPath}\``,
- TypeError
- )
+ var isStreamLike = CombinedStream.isStreamLike(stream);
+ if (isStreamLike) {
+ stream.on('end', this._getNext.bind(this));
+ stream.pipe(this, {end: false});
+ return;
}
- // We don't know if we should ignore EMPTY, so throw
- if (!path) {
- return doThrow(`path must not be empty`, TypeError)
- }
+ var value = stream;
+ this.write(value);
+ this._getNext();
+};
- // Check if it is a relative path
- if (checkPath.isNotRelative(path)) {
- const r = '`path.relative()`d'
- return doThrow(
- `path should be a ${r} string, but got "${originalPath}"`,
- RangeError
- )
- }
+CombinedStream.prototype._handleErrors = function(stream) {
+ var self = this;
+ stream.on('error', function(err) {
+ self._emitError(err);
+ });
+};
- return true
-}
+CombinedStream.prototype.write = function(data) {
+ this.emit('data', data);
+};
-const isNotRelative = path => REGEX_TEST_INVALID_PATH.test(path)
+CombinedStream.prototype.pause = function() {
+ if (!this.pauseStreams) {
+ return;
+ }
-checkPath.isNotRelative = isNotRelative
-checkPath.convert = p => p
+ if(this.pauseStreams && this._currentStream && typeof(this._currentStream.pause) == 'function') this._currentStream.pause();
+ this.emit('pause');
+};
-class Ignore {
- constructor ({
- ignorecase = true
- } = {}) {
- this._rules = []
- this._ignorecase = ignorecase
- define(this, KEY_IGNORE, true)
- this._initCache()
+CombinedStream.prototype.resume = function() {
+ if (!this._released) {
+ this._released = true;
+ this.writable = true;
+ this._getNext();
}
- _initCache () {
- this._ignoreCache = Object.create(null)
- this._testCache = Object.create(null)
- }
+ if(this.pauseStreams && this._currentStream && typeof(this._currentStream.resume) == 'function') this._currentStream.resume();
+ this.emit('resume');
+};
- _addPattern (pattern) {
- // #32
- if (pattern && pattern[KEY_IGNORE]) {
- this._rules = this._rules.concat(pattern._rules)
- this._added = true
- return
- }
+CombinedStream.prototype.end = function() {
+ this._reset();
+ this.emit('end');
+};
- if (checkPattern(pattern)) {
- const rule = createRule(pattern, this._ignorecase)
- this._added = true
- this._rules.push(rule)
- }
+CombinedStream.prototype.destroy = function() {
+ this._reset();
+ this.emit('close');
+};
+
+CombinedStream.prototype._reset = function() {
+ this.writable = false;
+ this._streams = [];
+ this._currentStream = null;
+};
+
+CombinedStream.prototype._checkDataSize = function() {
+ this._updateDataSize();
+ if (this.dataSize <= this.maxDataSize) {
+ return;
}
- // @param {Array | string | Ignore} pattern
- add (pattern) {
- this._added = false
+ var message =
+ 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.';
+ this._emitError(new Error(message));
+};
- makeArray(
- isString(pattern)
- ? splitPattern(pattern)
- : pattern
- ).forEach(this._addPattern, this)
+CombinedStream.prototype._updateDataSize = function() {
+ this.dataSize = 0;
- // Some rules have just added to the ignore,
- // making the behavior changed.
- if (this._added) {
- this._initCache()
+ var self = this;
+ this._streams.forEach(function(stream) {
+ if (!stream.dataSize) {
+ return;
}
- return this
- }
+ self.dataSize += stream.dataSize;
+ });
- // legacy
- addPattern (pattern) {
- return this.add(pattern)
+ if (this._currentStream && this._currentStream.dataSize) {
+ this.dataSize += this._currentStream.dataSize;
}
+};
- // | ignored : unignored
- // negative | 0:0 | 0:1 | 1:0 | 1:1
- // -------- | ------- | ------- | ------- | --------
- // 0 | TEST | TEST | SKIP | X
- // 1 | TESTIF | SKIP | TEST | X
+CombinedStream.prototype._emitError = function(err) {
+ this._reset();
+ this.emit('error', err);
+};
- // - SKIP: always skip
- // - TEST: always test
- // - TESTIF: only test if checkUnignored
- // - X: that never happen
- // @param {boolean} whether should check if the path is unignored,
- // setting `checkUnignored` to `false` could reduce additional
- // path matching.
+/***/ }),
- // @returns {TestResult} true if a file is ignored
- _testOne (path, checkUnignored) {
- let ignored = false
- let unignored = false
+/***/ 6891:
+/***/ ((module) => {
- this._rules.forEach(rule => {
- const {negative} = rule
- if (
- unignored === negative && ignored !== unignored
- || negative && !ignored && !unignored && !checkUnignored
- ) {
- return
- }
+module.exports = function (xs, fn) {
+ var res = [];
+ for (var i = 0; i < xs.length; i++) {
+ var x = fn(xs[i], i);
+ if (isArray(x)) res.push.apply(res, x);
+ else res.push(x);
+ }
+ return res;
+};
- const matched = rule.regex.test(path)
+var isArray = Array.isArray || function (xs) {
+ return Object.prototype.toString.call(xs) === '[object Array]';
+};
- if (matched) {
- ignored = !negative
- unignored = negative
- }
- })
- return {
- ignored,
- unignored
- }
- }
+/***/ }),
- // @returns {TestResult}
- _test (originalPath, cache, checkUnignored, slices) {
- const path = originalPath
- // Supports nullable path
- && checkPath.convert(originalPath)
+/***/ 3325:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- checkPath(path, originalPath, throwError)
+"use strict";
- return this._t(path, cache, checkUnignored, slices)
- }
+const {promisify} = __nccwpck_require__(3837);
+const path = __nccwpck_require__(1017);
+const globby = __nccwpck_require__(3477);
+const isGlob = __nccwpck_require__(4466);
+const slash = __nccwpck_require__(4111);
+const gracefulFs = __nccwpck_require__(7758);
+const isPathCwd = __nccwpck_require__(8885);
+const isPathInside = __nccwpck_require__(628);
+const rimraf = __nccwpck_require__(4959);
+const pMap = __nccwpck_require__(1855);
- _t (path, cache, checkUnignored, slices) {
- if (path in cache) {
- return cache[path]
- }
+const rimrafP = promisify(rimraf);
- if (!slices) {
- // path/to/a.js
- // ['path', 'to', 'a.js']
- slices = path.split(SLASH)
- }
+const rimrafOptions = {
+ glob: false,
+ unlink: gracefulFs.unlink,
+ unlinkSync: gracefulFs.unlinkSync,
+ chmod: gracefulFs.chmod,
+ chmodSync: gracefulFs.chmodSync,
+ stat: gracefulFs.stat,
+ statSync: gracefulFs.statSync,
+ lstat: gracefulFs.lstat,
+ lstatSync: gracefulFs.lstatSync,
+ rmdir: gracefulFs.rmdir,
+ rmdirSync: gracefulFs.rmdirSync,
+ readdir: gracefulFs.readdir,
+ readdirSync: gracefulFs.readdirSync
+};
- slices.pop()
+function safeCheck(file, cwd) {
+ if (isPathCwd(file)) {
+ throw new Error('Cannot delete the current working directory. Can be overridden with the `force` option.');
+ }
- // If the path has no parent directory, just test it
- if (!slices.length) {
- return cache[path] = this._testOne(path, checkUnignored)
- }
+ if (!isPathInside(file, cwd)) {
+ throw new Error('Cannot delete files/directories outside the current working directory. Can be overridden with the `force` option.');
+ }
+}
- const parent = this._t(
- slices.join(SLASH) + SLASH,
- cache,
- checkUnignored,
- slices
- )
+function normalizePatterns(patterns) {
+ patterns = Array.isArray(patterns) ? patterns : [patterns];
- // If the path contains a parent directory, check the parent first
- return cache[path] = parent.ignored
- // > It is not possible to re-include a file if a parent directory of
- // > that file is excluded.
- ? parent
- : this._testOne(path, checkUnignored)
- }
+ patterns = patterns.map(pattern => {
+ if (process.platform === 'win32' && isGlob(pattern) === false) {
+ return slash(pattern);
+ }
- ignores (path) {
- return this._test(path, this._ignoreCache, false).ignored
- }
+ return pattern;
+ });
- createFilter () {
- return path => !this.ignores(path)
- }
+ return patterns;
+}
- filter (paths) {
- return makeArray(paths).filter(this.createFilter())
- }
+module.exports = async (patterns, {force, dryRun, cwd = process.cwd(), ...options} = {}) => {
+ options = {
+ expandDirectories: false,
+ onlyFiles: false,
+ followSymbolicLinks: false,
+ cwd,
+ ...options
+ };
- // @returns {TestResult}
- test (path) {
- return this._test(path, this._testCache, true)
- }
-}
+ patterns = normalizePatterns(patterns);
-const factory = options => new Ignore(options)
+ const files = (await globby(patterns, options))
+ .sort((a, b) => b.localeCompare(a));
-const returnFalse = () => false
+ const mapper = async file => {
+ file = path.resolve(cwd, file);
-const isPathValid = path =>
- checkPath(path && checkPath.convert(path), path, returnFalse)
+ if (!force) {
+ safeCheck(file, cwd);
+ }
-factory.isPathValid = isPathValid
+ if (!dryRun) {
+ await rimrafP(file, rimrafOptions);
+ }
-// Fixes typescript
-factory.default = factory
+ return file;
+ };
-module.exports = factory
+ const removedFiles = await pMap(files, mapper, options);
-// Windows
-// --------------------------------------------------------------
-/* istanbul ignore if */
-if (
- // Detect `process` so that it can run in browsers.
- typeof process !== 'undefined'
- && (
- process.env && process.env.IGNORE_TEST_WIN32
- || process.platform === 'win32'
- )
-) {
- /* eslint no-control-regex: "off" */
- const makePosix = str => /^\\\\\?\\/.test(str)
- || /["<>|\u0000-\u001F]+/u.test(str)
- ? str
- : str.replace(/\\/g, '/')
+ removedFiles.sort((a, b) => a.localeCompare(b));
- checkPath.convert = makePosix
+ return removedFiles;
+};
- // 'C:\\foo' <- 'C:\\foo' has been converted to 'C:/'
- // 'd:\\foo'
- const REGIX_IS_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i
- checkPath.isNotRelative = path =>
- REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path)
- || isNotRelative(path)
+module.exports.sync = (patterns, {force, dryRun, cwd = process.cwd(), ...options} = {}) => {
+ options = {
+ expandDirectories: false,
+ onlyFiles: false,
+ followSymbolicLinks: false,
+ cwd,
+ ...options
+ };
+
+ patterns = normalizePatterns(patterns);
+
+ const files = globby.sync(patterns, options)
+ .sort((a, b) => b.localeCompare(a));
+
+ const removedFiles = files.map(file => {
+ file = path.resolve(cwd, file);
+
+ if (!force) {
+ safeCheck(file, cwd);
+ }
+
+ if (!dryRun) {
+ rimraf.sync(file, rimrafOptions);
+ }
+
+ return file;
+ });
+
+ removedFiles.sort((a, b) => a.localeCompare(b));
+
+ return removedFiles;
+};
+
+
+/***/ }),
+
+/***/ 7895:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+
+const {promisify} = __nccwpck_require__(3837);
+const fs = __nccwpck_require__(7147);
+const path = __nccwpck_require__(1017);
+const fastGlob = __nccwpck_require__(3664);
+const gitIgnore = __nccwpck_require__(4777);
+const slash = __nccwpck_require__(4111);
+
+const DEFAULT_IGNORE = [
+ '**/node_modules/**',
+ '**/flow-typed/**',
+ '**/coverage/**',
+ '**/.git'
+];
+
+const readFileP = promisify(fs.readFile);
+
+const mapGitIgnorePatternTo = base => ignore => {
+ if (ignore.startsWith('!')) {
+ return '!' + path.posix.join(base, ignore.slice(1));
+ }
+
+ return path.posix.join(base, ignore);
+};
+
+const parseGitIgnore = (content, options) => {
+ const base = slash(path.relative(options.cwd, path.dirname(options.fileName)));
+
+ return content
+ .split(/\r?\n/)
+ .filter(Boolean)
+ .filter(line => !line.startsWith('#'))
+ .map(mapGitIgnorePatternTo(base));
+};
+
+const reduceIgnore = files => {
+ return files.reduce((ignores, file) => {
+ ignores.add(parseGitIgnore(file.content, {
+ cwd: file.cwd,
+ fileName: file.filePath
+ }));
+ return ignores;
+ }, gitIgnore());
+};
+
+const ensureAbsolutePathForCwd = (cwd, p) => {
+ if (path.isAbsolute(p)) {
+ if (p.startsWith(cwd)) {
+ return p;
+ }
+
+ throw new Error(`Path ${p} is not in cwd ${cwd}`);
+ }
+
+ return path.join(cwd, p);
+};
+
+const getIsIgnoredPredecate = (ignores, cwd) => {
+ return p => ignores.ignores(slash(path.relative(cwd, ensureAbsolutePathForCwd(cwd, p))));
+};
+
+const getFile = async (file, cwd) => {
+ const filePath = path.join(cwd, file);
+ const content = await readFileP(filePath, 'utf8');
+
+ return {
+ cwd,
+ filePath,
+ content
+ };
+};
+
+const getFileSync = (file, cwd) => {
+ const filePath = path.join(cwd, file);
+ const content = fs.readFileSync(filePath, 'utf8');
+
+ return {
+ cwd,
+ filePath,
+ content
+ };
+};
+
+const normalizeOptions = ({
+ ignore = [],
+ cwd = slash(process.cwd())
+} = {}) => {
+ return {ignore, cwd};
+};
+
+module.exports = async options => {
+ options = normalizeOptions(options);
+
+ const paths = await fastGlob('**/.gitignore', {
+ ignore: DEFAULT_IGNORE.concat(options.ignore),
+ cwd: options.cwd
+ });
+
+ const files = await Promise.all(paths.map(file => getFile(file, options.cwd)));
+ const ignores = reduceIgnore(files);
+
+ return getIsIgnoredPredecate(ignores, options.cwd);
+};
+
+module.exports.sync = options => {
+ options = normalizeOptions(options);
+
+ const paths = fastGlob.sync('**/.gitignore', {
+ ignore: DEFAULT_IGNORE.concat(options.ignore),
+ cwd: options.cwd
+ });
+
+ const files = paths.map(file => getFileSync(file, options.cwd));
+ const ignores = reduceIgnore(files);
+
+ return getIsIgnoredPredecate(ignores, options.cwd);
+};
+
+
+/***/ }),
+
+/***/ 3477:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+
+const fs = __nccwpck_require__(7147);
+const arrayUnion = __nccwpck_require__(9600);
+const merge2 = __nccwpck_require__(2578);
+const glob = __nccwpck_require__(1957);
+const fastGlob = __nccwpck_require__(3664);
+const dirGlob = __nccwpck_require__(2738);
+const gitignore = __nccwpck_require__(7895);
+const {FilterStream, UniqueStream} = __nccwpck_require__(308);
+
+const DEFAULT_FILTER = () => false;
+
+const isNegative = pattern => pattern[0] === '!';
+
+const assertPatternsInput = patterns => {
+ if (!patterns.every(pattern => typeof pattern === 'string')) {
+ throw new TypeError('Patterns must be a string or an array of strings');
+ }
+};
+
+const checkCwdOption = (options = {}) => {
+ if (!options.cwd) {
+ return;
+ }
+
+ let stat;
+ try {
+ stat = fs.statSync(options.cwd);
+ } catch (_) {
+ return;
+ }
+
+ if (!stat.isDirectory()) {
+ throw new Error('The `cwd` option must be a path to a directory');
+ }
+};
+
+const getPathString = p => p.stats instanceof fs.Stats ? p.path : p;
+
+const generateGlobTasks = (patterns, taskOptions) => {
+ patterns = arrayUnion([].concat(patterns));
+ assertPatternsInput(patterns);
+ checkCwdOption(taskOptions);
+
+ const globTasks = [];
+
+ taskOptions = {
+ ignore: [],
+ expandDirectories: true,
+ ...taskOptions
+ };
+
+ for (const [index, pattern] of patterns.entries()) {
+ if (isNegative(pattern)) {
+ continue;
+ }
+
+ const ignore = patterns
+ .slice(index)
+ .filter(isNegative)
+ .map(pattern => pattern.slice(1));
+
+ const options = {
+ ...taskOptions,
+ ignore: taskOptions.ignore.concat(ignore)
+ };
+
+ globTasks.push({pattern, options});
+ }
+
+ return globTasks;
+};
+
+const globDirs = (task, fn) => {
+ let options = {};
+ if (task.options.cwd) {
+ options.cwd = task.options.cwd;
+ }
+
+ if (Array.isArray(task.options.expandDirectories)) {
+ options = {
+ ...options,
+ files: task.options.expandDirectories
+ };
+ } else if (typeof task.options.expandDirectories === 'object') {
+ options = {
+ ...options,
+ ...task.options.expandDirectories
+ };
+ }
+
+ return fn(task.pattern, options);
+};
+
+const getPattern = (task, fn) => task.options.expandDirectories ? globDirs(task, fn) : [task.pattern];
+
+const getFilterSync = options => {
+ return options && options.gitignore ?
+ gitignore.sync({cwd: options.cwd, ignore: options.ignore}) :
+ DEFAULT_FILTER;
+};
+
+const globToTask = task => glob => {
+ const {options} = task;
+ if (options.ignore && Array.isArray(options.ignore) && options.expandDirectories) {
+ options.ignore = dirGlob.sync(options.ignore);
+ }
+
+ return {
+ pattern: glob,
+ options
+ };
+};
+
+module.exports = async (patterns, options) => {
+ const globTasks = generateGlobTasks(patterns, options);
+
+ const getFilter = async () => {
+ return options && options.gitignore ?
+ gitignore({cwd: options.cwd, ignore: options.ignore}) :
+ DEFAULT_FILTER;
+ };
+
+ const getTasks = async () => {
+ const tasks = await Promise.all(globTasks.map(async task => {
+ const globs = await getPattern(task, dirGlob);
+ return Promise.all(globs.map(globToTask(task)));
+ }));
+
+ return arrayUnion(...tasks);
+ };
+
+ const [filter, tasks] = await Promise.all([getFilter(), getTasks()]);
+ const paths = await Promise.all(tasks.map(task => fastGlob(task.pattern, task.options)));
+
+ return arrayUnion(...paths).filter(path_ => !filter(getPathString(path_)));
+};
+
+module.exports.sync = (patterns, options) => {
+ const globTasks = generateGlobTasks(patterns, options);
+
+ const tasks = globTasks.reduce((tasks, task) => {
+ const newTask = getPattern(task, dirGlob.sync).map(globToTask(task));
+ return tasks.concat(newTask);
+ }, []);
+
+ const filter = getFilterSync(options);
+
+ return tasks.reduce(
+ (matches, task) => arrayUnion(matches, fastGlob.sync(task.pattern, task.options)),
+ []
+ ).filter(path_ => !filter(path_));
+};
+
+module.exports.stream = (patterns, options) => {
+ const globTasks = generateGlobTasks(patterns, options);
+
+ const tasks = globTasks.reduce((tasks, task) => {
+ const newTask = getPattern(task, dirGlob.sync).map(globToTask(task));
+ return tasks.concat(newTask);
+ }, []);
+
+ const filter = getFilterSync(options);
+ const filterStream = new FilterStream(p => !filter(p));
+ const uniqueStream = new UniqueStream();
+
+ return merge2(tasks.map(task => fastGlob.stream(task.pattern, task.options)))
+ .pipe(filterStream)
+ .pipe(uniqueStream);
+};
+
+module.exports.generateGlobTasks = generateGlobTasks;
+
+module.exports.hasMagic = (patterns, options) => []
+ .concat(patterns)
+ .some(pattern => glob.hasMagic(pattern, options));
+
+module.exports.gitignore = gitignore;
+
+
+/***/ }),
+
+/***/ 308:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+
+const {Transform} = __nccwpck_require__(2781);
+
+class ObjectTransform extends Transform {
+ constructor() {
+ super({
+ objectMode: true
+ });
+ }
+}
+
+class FilterStream extends ObjectTransform {
+ constructor(filter) {
+ super();
+ this._filter = filter;
+ }
+
+ _transform(data, encoding, callback) {
+ if (this._filter(data)) {
+ this.push(data);
+ }
+
+ callback();
+ }
}
+class UniqueStream extends ObjectTransform {
+ constructor() {
+ super();
+ this._pushed = new Set();
+ }
+
+ _transform(data, encoding, callback) {
+ if (!this._pushed.has(data)) {
+ this.push(data);
+ this._pushed.add(data);
+ }
+
+ callback();
+ }
+}
+
+module.exports = {
+ FilterStream,
+ UniqueStream
+};
+
/***/ }),
/***/ 8611:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-var Stream = __nccwpck_require__(2413).Stream;
-var util = __nccwpck_require__(1669);
+var Stream = (__nccwpck_require__(2781).Stream);
+var util = __nccwpck_require__(3837);
module.exports = DelayedStream;
function DelayedStream() {
@@ -50486,7 +52997,7 @@ DelayedStream.prototype._checkIfMaxDataSizeExceeded = function() {
"use strict";
-const path = __nccwpck_require__(5622);
+const path = __nccwpck_require__(1017);
const pathType = __nccwpck_require__(3433);
const getExtensions = extensions => extensions.length > 1 ? `{${extensions.join(',')}}` : extensions[0];
@@ -50564,52 +53075,102 @@ module.exports.sync = (input, options) => {
/***/ }),
-/***/ 3664:
+/***/ 4460:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
-
-const taskManager = __nccwpck_require__(2708);
-const patternManager = __nccwpck_require__(8306);
-const async_1 = __nccwpck_require__(5679);
-const stream_1 = __nccwpck_require__(4630);
-const sync_1 = __nccwpck_require__(2405);
-const settings_1 = __nccwpck_require__(952);
-const utils = __nccwpck_require__(5444);
-async function FastGlob(source, options) {
- assertPatternsInput(source);
- const works = getWorks(source, async_1.default, options);
- const result = await Promise.all(works);
- return utils.array.flatten(result);
-}
-// https://github.com/typescript-eslint/typescript-eslint/issues/60
-// eslint-disable-next-line no-redeclare
-(function (FastGlob) {
- function sync(source, options) {
- assertPatternsInput(source);
- const works = getWorks(source, sync_1.default, options);
- return utils.array.flatten(works);
- }
- FastGlob.sync = sync;
- function stream(source, options) {
- assertPatternsInput(source);
- const works = getWorks(source, stream_1.default, options);
- /**
- * The stream returned by the provider cannot work with an asynchronous iterator.
- * To support asynchronous iterators, regardless of the number of tasks, we always multiplex streams.
- * This affects performance (+25%). I don't see best solution right now.
- */
- return utils.stream.merge(works);
- }
- FastGlob.stream = stream;
- function generateTasks(source, options) {
- assertPatternsInput(source);
- const patterns = patternManager.transform([].concat(source));
- const settings = new settings_1.default(options);
- return taskManager.generate(patterns, settings);
- }
- FastGlob.generateTasks = generateTasks;
- function isDynamicPattern(source, options) {
+
+
+var isGlob = __nccwpck_require__(4466);
+var pathPosixDirname = (__nccwpck_require__(1017).posix.dirname);
+var isWin32 = (__nccwpck_require__(2037).platform)() === 'win32';
+
+var slash = '/';
+var backslash = /\\/g;
+var enclosure = /[\{\[].*[\}\]]$/;
+var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/;
+var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g;
+
+/**
+ * @param {string} str
+ * @param {Object} opts
+ * @param {boolean} [opts.flipBackslashes=true]
+ * @returns {string}
+ */
+module.exports = function globParent(str, opts) {
+ var options = Object.assign({ flipBackslashes: true }, opts);
+
+ // flip windows path separators
+ if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) {
+ str = str.replace(backslash, slash);
+ }
+
+ // special case for strings ending in enclosure containing path separator
+ if (enclosure.test(str)) {
+ str += slash;
+ }
+
+ // preserves full path in case of trailing path separator
+ str += 'a';
+
+ // remove path parts that are globby
+ do {
+ str = pathPosixDirname(str);
+ } while (isGlob(str) || globby.test(str));
+
+ // remove escape chars and return result
+ return str.replace(escaped, '$1');
+};
+
+
+/***/ }),
+
+/***/ 3664:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+
+const taskManager = __nccwpck_require__(2708);
+const patternManager = __nccwpck_require__(8306);
+const async_1 = __nccwpck_require__(5679);
+const stream_1 = __nccwpck_require__(4630);
+const sync_1 = __nccwpck_require__(2405);
+const settings_1 = __nccwpck_require__(952);
+const utils = __nccwpck_require__(5444);
+async function FastGlob(source, options) {
+ assertPatternsInput(source);
+ const works = getWorks(source, async_1.default, options);
+ const result = await Promise.all(works);
+ return utils.array.flatten(result);
+}
+// https://github.com/typescript-eslint/typescript-eslint/issues/60
+// eslint-disable-next-line no-redeclare
+(function (FastGlob) {
+ function sync(source, options) {
+ assertPatternsInput(source);
+ const works = getWorks(source, sync_1.default, options);
+ return utils.array.flatten(works);
+ }
+ FastGlob.sync = sync;
+ function stream(source, options) {
+ assertPatternsInput(source);
+ const works = getWorks(source, stream_1.default, options);
+ /**
+ * The stream returned by the provider cannot work with an asynchronous iterator.
+ * To support asynchronous iterators, regardless of the number of tasks, we always multiplex streams.
+ * This affects performance (+25%). I don't see best solution right now.
+ */
+ return utils.stream.merge(works);
+ }
+ FastGlob.stream = stream;
+ function generateTasks(source, options) {
+ assertPatternsInput(source);
+ const patterns = patternManager.transform([].concat(source));
+ const settings = new settings_1.default(options);
+ return taskManager.generate(patterns, settings);
+ }
+ FastGlob.generateTasks = generateTasks;
+ function isDynamicPattern(source, options) {
assertPatternsInput(source);
const settings = new settings_1.default(options);
return utils.pattern.isDynamicPattern(source, settings);
@@ -50783,7 +53344,7 @@ class ProviderAsync extends provider_1.default {
return this._reader.static(task.patterns, options);
}
}
-exports.default = ProviderAsync;
+exports["default"] = ProviderAsync;
/***/ }),
@@ -50853,7 +53414,7 @@ class DeepFilter {
return !utils.pattern.matchAny(entryPath, patternsRe);
}
}
-exports.default = DeepFilter;
+exports["default"] = DeepFilter;
/***/ }),
@@ -50925,7 +53486,7 @@ class EntryFilter {
return isMatched;
}
}
-exports.default = EntryFilter;
+exports["default"] = EntryFilter;
/***/ }),
@@ -50948,7 +53509,7 @@ class ErrorFilter {
return utils.errno.isEnoentCodeError(error) || this._settings.suppressErrors;
}
}
-exports.default = ErrorFilter;
+exports["default"] = ErrorFilter;
/***/ }),
@@ -51006,7 +53567,7 @@ class Matcher {
return utils.array.splitWhen(segments, (segment) => segment.dynamic && utils.pattern.hasGlobStar(segment.pattern));
}
}
-exports.default = Matcher;
+exports["default"] = Matcher;
/***/ }),
@@ -51052,7 +53613,7 @@ class PartialMatcher extends matcher_1.default {
return false;
}
}
-exports.default = PartialMatcher;
+exports["default"] = PartialMatcher;
/***/ }),
@@ -51063,7 +53624,7 @@ exports.default = PartialMatcher;
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
-const path = __nccwpck_require__(5622);
+const path = __nccwpck_require__(1017);
const deep_1 = __nccwpck_require__(6983);
const entry_1 = __nccwpck_require__(1343);
const error_1 = __nccwpck_require__(6654);
@@ -51108,7 +53669,7 @@ class Provider {
};
}
}
-exports.default = Provider;
+exports["default"] = Provider;
/***/ }),
@@ -51119,7 +53680,7 @@ exports.default = Provider;
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
-const stream_1 = __nccwpck_require__(2413);
+const stream_1 = __nccwpck_require__(2781);
const stream_2 = __nccwpck_require__(2083);
const provider_1 = __nccwpck_require__(257);
class ProviderStream extends provider_1.default {
@@ -51147,7 +53708,7 @@ class ProviderStream extends provider_1.default {
return this._reader.static(task.patterns, options);
}
}
-exports.default = ProviderStream;
+exports["default"] = ProviderStream;
/***/ }),
@@ -51178,7 +53739,7 @@ class ProviderSync extends provider_1.default {
return this._reader.static(task.patterns, options);
}
}
-exports.default = ProviderSync;
+exports["default"] = ProviderSync;
/***/ }),
@@ -51212,7 +53773,7 @@ class EntryTransformer {
return Object.assign(Object.assign({}, entry), { path: filepath });
}
}
-exports.default = EntryTransformer;
+exports["default"] = EntryTransformer;
/***/ }),
@@ -51255,7 +53816,7 @@ class ReaderAsync extends reader_1.default {
});
}
}
-exports.default = ReaderAsync;
+exports["default"] = ReaderAsync;
/***/ }),
@@ -51266,7 +53827,7 @@ exports.default = ReaderAsync;
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
-const path = __nccwpck_require__(5622);
+const path = __nccwpck_require__(1017);
const fsStat = __nccwpck_require__(109);
const utils = __nccwpck_require__(5444);
class Reader {
@@ -51296,7 +53857,7 @@ class Reader {
return !utils.errno.isEnoentCodeError(error) && !this._settings.suppressErrors;
}
}
-exports.default = Reader;
+exports["default"] = Reader;
/***/ }),
@@ -51307,7 +53868,7 @@ exports.default = Reader;
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
-const stream_1 = __nccwpck_require__(2413);
+const stream_1 = __nccwpck_require__(2781);
const fsStat = __nccwpck_require__(109);
const fsWalk = __nccwpck_require__(6026);
const reader_1 = __nccwpck_require__(5582);
@@ -51359,7 +53920,7 @@ class ReaderStream extends reader_1.default {
});
}
}
-exports.default = ReaderStream;
+exports["default"] = ReaderStream;
/***/ }),
@@ -51410,7 +53971,7 @@ class ReaderSync extends reader_1.default {
return this._statSync(filepath, this._fsStatSettings);
}
}
-exports.default = ReaderSync;
+exports["default"] = ReaderSync;
/***/ }),
@@ -51422,8 +53983,8 @@ exports.default = ReaderSync;
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.DEFAULT_FILE_SYSTEM_ADAPTER = void 0;
-const fs = __nccwpck_require__(5747);
-const os = __nccwpck_require__(2087);
+const fs = __nccwpck_require__(7147);
+const os = __nccwpck_require__(2037);
/**
* The `os.cpus` method can return zero. We expect the number of cores to be greater than zero.
* https://github.com/nodejs/node/blob/7faeddf23a98c53896f8b574a6e66589e8fb1eb8/lib/os.js#L106-L107
@@ -51475,7 +54036,7 @@ class Settings {
return Object.assign(Object.assign({}, exports.DEFAULT_FILE_SYSTEM_ADAPTER), methods);
}
}
-exports.default = Settings;
+exports["default"] = Settings;
/***/ }),
@@ -51584,7 +54145,7 @@ exports.string = string;
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.removeLeadingDotSegment = exports.escape = exports.makeAbsolute = exports.unixify = void 0;
-const path = __nccwpck_require__(5622);
+const path = __nccwpck_require__(1017);
const LEADING_DOT_SEGMENT_CHARACTERS_COUNT = 2; // ./ or .\\
const UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()*?[\]{|}]|^!|[!+@](?=\())/g;
/**
@@ -51625,8 +54186,8 @@ exports.removeLeadingDotSegment = removeLeadingDotSegment;
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.matchAny = exports.convertPatternsToRe = exports.makeRe = exports.getPatternParts = exports.expandBraceExpansion = exports.expandPatternsWithBraceExpansion = exports.isAffectDepthOfReadingPattern = exports.endsWithSlashGlobStar = exports.hasGlobStar = exports.getBaseDirectory = exports.isPatternRelatedToParentDirectory = exports.getPatternsOutsideCurrentDirectory = exports.getPatternsInsideCurrentDirectory = exports.getPositivePatterns = exports.getNegativePatterns = exports.isPositivePattern = exports.isNegativePattern = exports.convertToNegativePattern = exports.convertToPositivePattern = exports.isDynamicPattern = exports.isStaticPattern = void 0;
-const path = __nccwpck_require__(5622);
-const globParent = __nccwpck_require__(4655);
+const path = __nccwpck_require__(1017);
+const globParent = __nccwpck_require__(4460);
const micromatch = __nccwpck_require__(6228);
const GLOBSTAR = '**';
const ESCAPE_SYMBOL = '\\';
@@ -52068,6 +54629,7 @@ function queueAsPromised (context, worker, concurrency) {
queue.push = push
queue.unshift = unshift
+ queue.drained = drained
return queue
@@ -52108,12 +54670,288 @@ function queueAsPromised (context, worker, concurrency) {
return p
}
+
+ function drained () {
+ if (queue.idle()) {
+ return new Promise(function (resolve) {
+ resolve()
+ })
+ }
+
+ var previousDrain = queue.drain
+
+ var p = new Promise(function (resolve) {
+ queue.drain = function () {
+ previousDrain()
+ resolve()
+ }
+ })
+
+ return p
+ }
}
module.exports = fastqueue
module.exports.promise = queueAsPromised
+/***/ }),
+
+/***/ 6330:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+/*!
+ * fill-range
+ *
+ * Copyright (c) 2014-present, Jon Schlinkert.
+ * Licensed under the MIT License.
+ */
+
+
+
+const util = __nccwpck_require__(3837);
+const toRegexRange = __nccwpck_require__(1861);
+
+const isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
+
+const transform = toNumber => {
+ return value => toNumber === true ? Number(value) : String(value);
+};
+
+const isValidValue = value => {
+ return typeof value === 'number' || (typeof value === 'string' && value !== '');
+};
+
+const isNumber = num => Number.isInteger(+num);
+
+const zeros = input => {
+ let value = `${input}`;
+ let index = -1;
+ if (value[0] === '-') value = value.slice(1);
+ if (value === '0') return false;
+ while (value[++index] === '0');
+ return index > 0;
+};
+
+const stringify = (start, end, options) => {
+ if (typeof start === 'string' || typeof end === 'string') {
+ return true;
+ }
+ return options.stringify === true;
+};
+
+const pad = (input, maxLength, toNumber) => {
+ if (maxLength > 0) {
+ let dash = input[0] === '-' ? '-' : '';
+ if (dash) input = input.slice(1);
+ input = (dash + input.padStart(dash ? maxLength - 1 : maxLength, '0'));
+ }
+ if (toNumber === false) {
+ return String(input);
+ }
+ return input;
+};
+
+const toMaxLen = (input, maxLength) => {
+ let negative = input[0] === '-' ? '-' : '';
+ if (negative) {
+ input = input.slice(1);
+ maxLength--;
+ }
+ while (input.length < maxLength) input = '0' + input;
+ return negative ? ('-' + input) : input;
+};
+
+const toSequence = (parts, options) => {
+ parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
+ parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
+
+ let prefix = options.capture ? '' : '?:';
+ let positives = '';
+ let negatives = '';
+ let result;
+
+ if (parts.positives.length) {
+ positives = parts.positives.join('|');
+ }
+
+ if (parts.negatives.length) {
+ negatives = `-(${prefix}${parts.negatives.join('|')})`;
+ }
+
+ if (positives && negatives) {
+ result = `${positives}|${negatives}`;
+ } else {
+ result = positives || negatives;
+ }
+
+ if (options.wrap) {
+ return `(${prefix}${result})`;
+ }
+
+ return result;
+};
+
+const toRange = (a, b, isNumbers, options) => {
+ if (isNumbers) {
+ return toRegexRange(a, b, { wrap: false, ...options });
+ }
+
+ let start = String.fromCharCode(a);
+ if (a === b) return start;
+
+ let stop = String.fromCharCode(b);
+ return `[${start}-${stop}]`;
+};
+
+const toRegex = (start, end, options) => {
+ if (Array.isArray(start)) {
+ let wrap = options.wrap === true;
+ let prefix = options.capture ? '' : '?:';
+ return wrap ? `(${prefix}${start.join('|')})` : start.join('|');
+ }
+ return toRegexRange(start, end, options);
+};
+
+const rangeError = (...args) => {
+ return new RangeError('Invalid range arguments: ' + util.inspect(...args));
+};
+
+const invalidRange = (start, end, options) => {
+ if (options.strictRanges === true) throw rangeError([start, end]);
+ return [];
+};
+
+const invalidStep = (step, options) => {
+ if (options.strictRanges === true) {
+ throw new TypeError(`Expected step "${step}" to be a number`);
+ }
+ return [];
+};
+
+const fillNumbers = (start, end, step = 1, options = {}) => {
+ let a = Number(start);
+ let b = Number(end);
+
+ if (!Number.isInteger(a) || !Number.isInteger(b)) {
+ if (options.strictRanges === true) throw rangeError([start, end]);
+ return [];
+ }
+
+ // fix negative zero
+ if (a === 0) a = 0;
+ if (b === 0) b = 0;
+
+ let descending = a > b;
+ let startString = String(start);
+ let endString = String(end);
+ let stepString = String(step);
+ step = Math.max(Math.abs(step), 1);
+
+ let padded = zeros(startString) || zeros(endString) || zeros(stepString);
+ let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0;
+ let toNumber = padded === false && stringify(start, end, options) === false;
+ let format = options.transform || transform(toNumber);
+
+ if (options.toRegex && step === 1) {
+ return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options);
+ }
+
+ let parts = { negatives: [], positives: [] };
+ let push = num => parts[num < 0 ? 'negatives' : 'positives'].push(Math.abs(num));
+ let range = [];
+ let index = 0;
+
+ while (descending ? a >= b : a <= b) {
+ if (options.toRegex === true && step > 1) {
+ push(a);
+ } else {
+ range.push(pad(format(a, index), maxLen, toNumber));
+ }
+ a = descending ? a - step : a + step;
+ index++;
+ }
+
+ if (options.toRegex === true) {
+ return step > 1
+ ? toSequence(parts, options)
+ : toRegex(range, null, { wrap: false, ...options });
+ }
+
+ return range;
+};
+
+const fillLetters = (start, end, step = 1, options = {}) => {
+ if ((!isNumber(start) && start.length > 1) || (!isNumber(end) && end.length > 1)) {
+ return invalidRange(start, end, options);
+ }
+
+
+ let format = options.transform || (val => String.fromCharCode(val));
+ let a = `${start}`.charCodeAt(0);
+ let b = `${end}`.charCodeAt(0);
+
+ let descending = a > b;
+ let min = Math.min(a, b);
+ let max = Math.max(a, b);
+
+ if (options.toRegex && step === 1) {
+ return toRange(min, max, false, options);
+ }
+
+ let range = [];
+ let index = 0;
+
+ while (descending ? a >= b : a <= b) {
+ range.push(format(a, index));
+ a = descending ? a - step : a + step;
+ index++;
+ }
+
+ if (options.toRegex === true) {
+ return toRegex(range, null, { wrap: false, options });
+ }
+
+ return range;
+};
+
+const fill = (start, end, step, options = {}) => {
+ if (end == null && isValidValue(start)) {
+ return [start];
+ }
+
+ if (!isValidValue(start) || !isValidValue(end)) {
+ return invalidRange(start, end, options);
+ }
+
+ if (typeof step === 'function') {
+ return fill(start, end, 1, { transform: step });
+ }
+
+ if (isObject(step)) {
+ return fill(start, end, 0, step);
+ }
+
+ let opts = { ...options };
+ if (opts.capture === true) opts.wrap = true;
+ step = step || opts.step || 1;
+
+ if (!isNumber(step)) {
+ if (step != null && !isObject(step)) return invalidStep(step, opts);
+ return fill(start, end, 1, step);
+ }
+
+ if (isNumber(start) && isNumber(end)) {
+ return fillNumbers(start, end, step, opts);
+ }
+
+ return fillLetters(start, end, Math.max(Math.abs(step), 1), opts);
+};
+
+module.exports = fill;
+
+
/***/ }),
/***/ 6863:
@@ -52126,7 +54964,7 @@ realpath.realpathSync = realpathSync
realpath.monkeypatch = monkeypatch
realpath.unmonkeypatch = unmonkeypatch
-var fs = __nccwpck_require__(5747)
+var fs = __nccwpck_require__(7147)
var origRealpath = fs.realpath
var origRealpathSync = fs.realpathSync
@@ -52213,9 +55051,9 @@ function unmonkeypatch () {
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
-var pathModule = __nccwpck_require__(5622);
+var pathModule = __nccwpck_require__(1017);
var isWindows = process.platform === 'win32';
-var fs = __nccwpck_require__(5747);
+var fs = __nccwpck_require__(7147);
// JavaScript implementation of realpath, ported from node pre-v6
@@ -52497,56 +55335,6 @@ exports.realpath = function realpath(p, cache, cb) {
};
-/***/ }),
-
-/***/ 4655:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
-
-
-var isGlob = __nccwpck_require__(4466);
-var pathPosixDirname = __nccwpck_require__(5622).posix.dirname;
-var isWin32 = __nccwpck_require__(2087).platform() === 'win32';
-
-var slash = '/';
-var backslash = /\\/g;
-var enclosure = /[\{\[].*[\}\]]$/;
-var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/;
-var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g;
-
-/**
- * @param {string} str
- * @param {Object} opts
- * @param {boolean} [opts.flipBackslashes=true]
- * @returns {string}
- */
-module.exports = function globParent(str, opts) {
- var options = Object.assign({ flipBackslashes: true }, opts);
-
- // flip windows path separators
- if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) {
- str = str.replace(backslash, slash);
- }
-
- // special case for strings ending in enclosure containing path separator
- if (enclosure.test(str)) {
- str += slash;
- }
-
- // preserves full path in case of trailing path separator
- str += 'a';
-
- // remove path parts that are globby
- do {
- str = pathPosixDirname(str);
- } while (isGlob(str) || globby.test(str));
-
- // remove escape chars and return result
- return str.replace(escaped, '$1');
-};
-
-
/***/ }),
/***/ 7625:
@@ -52564,7 +55352,8 @@ function ownProp (obj, field) {
return Object.prototype.hasOwnProperty.call(obj, field)
}
-var path = __nccwpck_require__(5622)
+var fs = __nccwpck_require__(7147)
+var path = __nccwpck_require__(1017)
var minimatch = __nccwpck_require__(3973)
var isAbsolute = __nccwpck_require__(8714)
var Minimatch = minimatch.Minimatch
@@ -52629,6 +55418,7 @@ function setopts (self, pattern, options) {
self.stat = !!options.stat
self.noprocess = !!options.noprocess
self.absolute = !!options.absolute
+ self.fs = options.fs || fs
self.maxLength = options.maxLength || Infinity
self.cache = options.cache || Object.create(null)
@@ -52662,6 +55452,8 @@ function setopts (self, pattern, options) {
// Note that they are not supported in Glob itself anyway.
options.nonegate = true
options.nocomment = true
+ // always treat \ in patterns as escapes, not path separators
+ options.allowWindowsEscape = false
self.minimatch = new Minimatch(pattern, options)
self.options = self.minimatch.options
@@ -52835,21 +55627,20 @@ function childrenIgnored (self, path) {
module.exports = glob
-var fs = __nccwpck_require__(5747)
var rp = __nccwpck_require__(6863)
var minimatch = __nccwpck_require__(3973)
var Minimatch = minimatch.Minimatch
var inherits = __nccwpck_require__(4124)
-var EE = __nccwpck_require__(8614).EventEmitter
-var path = __nccwpck_require__(5622)
-var assert = __nccwpck_require__(2357)
+var EE = (__nccwpck_require__(2361).EventEmitter)
+var path = __nccwpck_require__(1017)
+var assert = __nccwpck_require__(9491)
var isAbsolute = __nccwpck_require__(8714)
var globSync = __nccwpck_require__(9010)
var common = __nccwpck_require__(7625)
var setopts = common.setopts
var ownProp = common.ownProp
var inflight = __nccwpck_require__(2492)
-var util = __nccwpck_require__(1669)
+var util = __nccwpck_require__(3837)
var childrenIgnored = common.childrenIgnored
var isIgnored = common.isIgnored
@@ -53138,7 +55929,10 @@ Glob.prototype._process = function (pattern, index, inGlobStar, cb) {
var read
if (prefix === null)
read = '.'
- else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) {
+ else if (isAbsolute(prefix) ||
+ isAbsolute(pattern.map(function (p) {
+ return typeof p === 'string' ? p : '[*]'
+ }).join('/'))) {
if (!prefix || !isAbsolute(prefix))
prefix = '/' + prefix
read = prefix
@@ -53296,7 +56090,7 @@ Glob.prototype._readdirInGlobStar = function (abs, cb) {
var lstatcb = inflight(lstatkey, lstatcb_)
if (lstatcb)
- fs.lstat(abs, lstatcb)
+ self.fs.lstat(abs, lstatcb)
function lstatcb_ (er, lstat) {
if (er && er.code === 'ENOENT')
@@ -53337,7 +56131,7 @@ Glob.prototype._readdir = function (abs, inGlobStar, cb) {
}
var self = this
- fs.readdir(abs, readdirCb(this, abs, cb))
+ self.fs.readdir(abs, readdirCb(this, abs, cb))
}
function readdirCb (self, abs, cb) {
@@ -53541,13 +56335,13 @@ Glob.prototype._stat = function (f, cb) {
var self = this
var statcb = inflight('stat\0' + abs, lstatcb_)
if (statcb)
- fs.lstat(abs, statcb)
+ self.fs.lstat(abs, statcb)
function lstatcb_ (er, lstat) {
if (lstat && lstat.isSymbolicLink()) {
// If it's a symlink, then treat it as the target, unless
// the target does not exist, then treat it as a file.
- return fs.stat(abs, function (er, stat) {
+ return self.fs.stat(abs, function (er, stat) {
if (er)
self._stat2(f, abs, null, lstat, cb)
else
@@ -53591,14 +56385,13 @@ Glob.prototype._stat2 = function (f, abs, er, stat, cb) {
module.exports = globSync
globSync.GlobSync = GlobSync
-var fs = __nccwpck_require__(5747)
var rp = __nccwpck_require__(6863)
var minimatch = __nccwpck_require__(3973)
var Minimatch = minimatch.Minimatch
-var Glob = __nccwpck_require__(1957).Glob
-var util = __nccwpck_require__(1669)
-var path = __nccwpck_require__(5622)
-var assert = __nccwpck_require__(2357)
+var Glob = (__nccwpck_require__(1957).Glob)
+var util = __nccwpck_require__(3837)
+var path = __nccwpck_require__(1017)
+var assert = __nccwpck_require__(9491)
var isAbsolute = __nccwpck_require__(8714)
var common = __nccwpck_require__(7625)
var setopts = common.setopts
@@ -53639,7 +56432,7 @@ function GlobSync (pattern, options) {
}
GlobSync.prototype._finish = function () {
- assert(this instanceof GlobSync)
+ assert.ok(this instanceof GlobSync)
if (this.realpath) {
var self = this
this.matches.forEach(function (matchset, index) {
@@ -53663,7 +56456,7 @@ GlobSync.prototype._finish = function () {
GlobSync.prototype._process = function (pattern, index, inGlobStar) {
- assert(this instanceof GlobSync)
+ assert.ok(this instanceof GlobSync)
// Get the first [n] parts of pattern that are all strings.
var n = 0
@@ -53700,7 +56493,10 @@ GlobSync.prototype._process = function (pattern, index, inGlobStar) {
var read
if (prefix === null)
read = '.'
- else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) {
+ else if (isAbsolute(prefix) ||
+ isAbsolute(pattern.map(function (p) {
+ return typeof p === 'string' ? p : '[*]'
+ }).join('/'))) {
if (!prefix || !isAbsolute(prefix))
prefix = '/' + prefix
read = prefix
@@ -53836,7 +56632,7 @@ GlobSync.prototype._readdirInGlobStar = function (abs) {
var lstat
var stat
try {
- lstat = fs.lstatSync(abs)
+ lstat = this.fs.lstatSync(abs)
} catch (er) {
if (er.code === 'ENOENT') {
// lstat failed, doesn't exist
@@ -53873,7 +56669,7 @@ GlobSync.prototype._readdir = function (abs, inGlobStar) {
}
try {
- return this._readdirEntries(abs, fs.readdirSync(abs))
+ return this._readdirEntries(abs, this.fs.readdirSync(abs))
} catch (er) {
this._readdirError(abs, er)
return null
@@ -54032,7 +56828,7 @@ GlobSync.prototype._stat = function (f) {
if (!stat) {
var lstat
try {
- lstat = fs.lstatSync(abs)
+ lstat = this.fs.lstatSync(abs)
} catch (er) {
if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
this.statCache[abs] = false
@@ -54042,7 +56838,7 @@ GlobSync.prototype._stat = function (f) {
if (lstat && lstat.isSymbolicLink()) {
try {
- stat = fs.statSync(abs)
+ stat = this.fs.statSync(abs)
} catch (er) {
stat = lstat
}
@@ -54110,12 +56906,12 @@ function clone (obj) {
/***/ 7758:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-var fs = __nccwpck_require__(5747)
+var fs = __nccwpck_require__(7147)
var polyfills = __nccwpck_require__(263)
var legacy = __nccwpck_require__(3086)
var clone = __nccwpck_require__(7356)
-var util = __nccwpck_require__(1669)
+var util = __nccwpck_require__(3837)
/* istanbul ignore next - node 0.x polyfill */
var gracefulQueue
@@ -54196,7 +56992,7 @@ if (!fs[gracefulQueue]) {
if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) {
process.on('exit', function() {
debug(fs[gracefulQueue])
- __nccwpck_require__(2357).equal(fs[gracefulQueue].length, 0)
+ __nccwpck_require__(9491).equal(fs[gracefulQueue].length, 0)
})
}
}
@@ -54303,16 +57099,35 @@ function patch (fs) {
var fs$readdir = fs.readdir
fs.readdir = readdir
+ var noReaddirOptionVersions = /^v[0-5]\./
function readdir (path, options, cb) {
if (typeof options === 'function')
cb = options, options = null
+ var go$readdir = noReaddirOptionVersions.test(process.version)
+ ? function go$readdir (path, options, cb, startTime) {
+ return fs$readdir(path, fs$readdirCallback(
+ path, options, cb, startTime
+ ))
+ }
+ : function go$readdir (path, options, cb, startTime) {
+ return fs$readdir(path, options, fs$readdirCallback(
+ path, options, cb, startTime
+ ))
+ }
+
return go$readdir(path, options, cb)
- function go$readdir (path, options, cb, startTime) {
- return fs$readdir(path, options, function (err, files) {
+ function fs$readdirCallback (path, options, cb, startTime) {
+ return function (err, files) {
if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
- enqueue([go$readdir, [path, options, cb], err, startTime || Date.now(), Date.now()])
+ enqueue([
+ go$readdir,
+ [path, options, cb],
+ err,
+ startTime || Date.now(),
+ Date.now()
+ ])
else {
if (files && files.sort)
files.sort()
@@ -54320,7 +57135,7 @@ function patch (fs) {
if (typeof cb === 'function')
cb.call(this, err, files)
}
- })
+ }
}
}
@@ -54546,7 +57361,7 @@ function retry () {
/***/ 3086:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-var Stream = __nccwpck_require__(2413).Stream
+var Stream = (__nccwpck_require__(2781).Stream)
module.exports = legacy
@@ -54671,7 +57486,7 @@ function legacy (fs) {
/***/ 263:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-var constants = __nccwpck_require__(7619)
+var constants = __nccwpck_require__(2057)
var origCwd = process.cwd
var cwd = null
@@ -54744,13 +57559,13 @@ function patch (fs) {
fs.lstatSync = statFixSync(fs.lstatSync)
// if lchmod/lchown do not exist, then make them no-ops
- if (!fs.lchmod) {
+ if (fs.chmod && !fs.lchmod) {
fs.lchmod = function (path, mode, cb) {
if (cb) process.nextTick(cb)
}
fs.lchmodSync = function () {}
}
- if (!fs.lchown) {
+ if (fs.chown && !fs.lchown) {
fs.lchown = function (path, uid, gid, cb) {
if (cb) process.nextTick(cb)
}
@@ -54767,32 +57582,38 @@ function patch (fs) {
// CPU to a busy looping process, which can cause the program causing the lock
// contention to be starved of CPU by node, so the contention doesn't resolve.
if (platform === "win32") {
- fs.rename = (function (fs$rename) { return function (from, to, cb) {
- var start = Date.now()
- var backoff = 0;
- fs$rename(from, to, function CB (er) {
- if (er
- && (er.code === "EACCES" || er.code === "EPERM")
- && Date.now() - start < 60000) {
- setTimeout(function() {
- fs.stat(to, function (stater, st) {
- if (stater && stater.code === "ENOENT")
- fs$rename(from, to, CB);
- else
- cb(er)
- })
- }, backoff)
- if (backoff < 100)
- backoff += 10;
- return;
- }
- if (cb) cb(er)
- })
- }})(fs.rename)
+ fs.rename = typeof fs.rename !== 'function' ? fs.rename
+ : (function (fs$rename) {
+ function rename (from, to, cb) {
+ var start = Date.now()
+ var backoff = 0;
+ fs$rename(from, to, function CB (er) {
+ if (er
+ && (er.code === "EACCES" || er.code === "EPERM" || er.code === "EBUSY")
+ && Date.now() - start < 60000) {
+ setTimeout(function() {
+ fs.stat(to, function (stater, st) {
+ if (stater && stater.code === "ENOENT")
+ fs$rename(from, to, CB);
+ else
+ cb(er)
+ })
+ }, backoff)
+ if (backoff < 100)
+ backoff += 10;
+ return;
+ }
+ if (cb) cb(er)
+ })
+ }
+ if (Object.setPrototypeOf) Object.setPrototypeOf(rename, fs$rename)
+ return rename
+ })(fs.rename)
}
// if read() returns EAGAIN, then just try it again.
- fs.read = (function (fs$read) {
+ fs.read = typeof fs.read !== 'function' ? fs.read
+ : (function (fs$read) {
function read (fd, buffer, offset, length, position, callback_) {
var callback
if (callback_ && typeof callback_ === 'function') {
@@ -54813,7 +57634,8 @@ function patch (fs) {
return read
})(fs.read)
- fs.readSync = (function (fs$readSync) { return function (fd, buffer, offset, length, position) {
+ fs.readSync = typeof fs.readSync !== 'function' ? fs.readSync
+ : (function (fs$readSync) { return function (fd, buffer, offset, length, position) {
var eagCounter = 0
while (true) {
try {
@@ -54872,7 +57694,7 @@ function patch (fs) {
}
function patchLutimes (fs) {
- if (constants.hasOwnProperty("O_SYMLINK")) {
+ if (constants.hasOwnProperty("O_SYMLINK") && fs.futimes) {
fs.lutimes = function (path, at, mt, cb) {
fs.open(path, constants.O_SYMLINK, function (er, fd) {
if (er) {
@@ -54906,7 +57728,7 @@ function patch (fs) {
return ret
}
- } else {
+ } else if (fs.futimes) {
fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb) }
fs.lutimesSync = function () {}
}
@@ -54983,8 +57805,10 @@ function patch (fs) {
return function (target, options) {
var stats = options ? orig.call(fs, target, options)
: orig.call(fs, target)
- if (stats.uid < 0) stats.uid += 0x100000000
- if (stats.gid < 0) stats.gid += 0x100000000
+ if (stats) {
+ if (stats.uid < 0) stats.uid += 0x100000000
+ if (stats.gid < 0) stats.gid += 0x100000000
+ }
return stats;
}
}
@@ -55021,16517 +57845,35526 @@ function patch (fs) {
/***/ }),
-/***/ 8043:
+/***/ 4777:
/***/ ((module) => {
-"use strict";
+// A simple implementation of make-array
+function makeArray (subject) {
+ return Array.isArray(subject)
+ ? subject
+ : [subject]
+}
+const EMPTY = ''
+const SPACE = ' '
+const ESCAPE = '\\'
+const REGEX_TEST_BLANK_LINE = /^\s+$/
+const REGEX_INVALID_TRAILING_BACKSLASH = /(?:[^\\]|^)\\$/
+const REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/
+const REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/
+const REGEX_SPLITALL_CRLF = /\r?\n/g
+// /foo,
+// ./foo,
+// ../foo,
+// .
+// ..
+const REGEX_TEST_INVALID_PATH = /^\.*\/|^\.+$/
-module.exports = (string, count = 1, options) => {
- options = {
- indent: ' ',
- includeEmptyLines: false,
- ...options
- };
+const SLASH = '/'
- if (typeof string !== 'string') {
- throw new TypeError(
- `Expected \`input\` to be a \`string\`, got \`${typeof string}\``
- );
- }
+// Do not use ternary expression here, since "istanbul ignore next" is buggy
+let TMP_KEY_IGNORE = 'node-ignore'
+/* istanbul ignore else */
+if (typeof Symbol !== 'undefined') {
+ TMP_KEY_IGNORE = Symbol.for('node-ignore')
+}
+const KEY_IGNORE = TMP_KEY_IGNORE
- if (typeof count !== 'number') {
- throw new TypeError(
- `Expected \`count\` to be a \`number\`, got \`${typeof count}\``
- );
- }
+const define = (object, key, value) =>
+ Object.defineProperty(object, key, {value})
- if (typeof options.indent !== 'string') {
- throw new TypeError(
- `Expected \`options.indent\` to be a \`string\`, got \`${typeof options.indent}\``
- );
- }
+const REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g
- if (count === 0) {
- return string;
- }
+const RETURN_FALSE = () => false
- const regex = options.includeEmptyLines ? /^/gm : /^(?!\s*$)/gm;
+// Sanitize the range of a regular expression
+// The cases are complicated, see test cases for details
+const sanitizeRange = range => range.replace(
+ REGEX_REGEXP_RANGE,
+ (match, from, to) => from.charCodeAt(0) <= to.charCodeAt(0)
+ ? match
+ // Invalid range (out of order) which is ok for gitignore rules but
+ // fatal for JavaScript regular expression, so eliminate it.
+ : EMPTY
+)
- return string.replace(regex, options.indent.repeat(count));
-};
+// See fixtures #59
+const cleanRangeBackSlash = slashes => {
+ const {length} = slashes
+ return slashes.slice(0, length - length % 2)
+}
+// > If the pattern ends with a slash,
+// > it is removed for the purpose of the following description,
+// > but it would only find a match with a directory.
+// > In other words, foo/ will match a directory foo and paths underneath it,
+// > but will not match a regular file or a symbolic link foo
+// > (this is consistent with the way how pathspec works in general in Git).
+// '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`'
+// -> ignore-rules will not deal with it, because it costs extra `fs.stat` call
+// you could use option `mark: true` with `glob`
-/***/ }),
+// '`foo/`' should not continue with the '`..`'
+const REPLACERS = [
-/***/ 2492:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // > Trailing spaces are ignored unless they are quoted with backslash ("\")
+ [
+ // (a\ ) -> (a )
+ // (a ) -> (a)
+ // (a \ ) -> (a )
+ /\\?\s+$/,
+ match => match.indexOf('\\') === 0
+ ? SPACE
+ : EMPTY
+ ],
-var wrappy = __nccwpck_require__(2940)
-var reqs = Object.create(null)
-var once = __nccwpck_require__(1223)
+ // replace (\ ) with ' '
+ [
+ /\\\s/g,
+ () => SPACE
+ ],
-module.exports = wrappy(inflight)
+ // Escape metacharacters
+ // which is written down by users but means special for regular expressions.
-function inflight (key, cb) {
- if (reqs[key]) {
- reqs[key].push(cb)
- return null
- } else {
- reqs[key] = [cb]
- return makeres(key)
- }
-}
+ // > There are 12 characters with special meanings:
+ // > - the backslash \,
+ // > - the caret ^,
+ // > - the dollar sign $,
+ // > - the period or dot .,
+ // > - the vertical bar or pipe symbol |,
+ // > - the question mark ?,
+ // > - the asterisk or star *,
+ // > - the plus sign +,
+ // > - the opening parenthesis (,
+ // > - the closing parenthesis ),
+ // > - and the opening square bracket [,
+ // > - the opening curly brace {,
+ // > These special characters are often called "metacharacters".
+ [
+ /[\\$.|*+(){^]/g,
+ match => `\\${match}`
+ ],
-function makeres (key) {
- return once(function RES () {
- var cbs = reqs[key]
- var len = cbs.length
- var args = slice(arguments)
+ [
+ // > a question mark (?) matches a single character
+ /(?!\\)\?/g,
+ () => '[^/]'
+ ],
- // XXX It's somewhat ambiguous whether a new callback added in this
- // pass should be queued for later execution if something in the
- // list of callbacks throws, or if it should just be discarded.
- // However, it's such an edge case that it hardly matters, and either
- // choice is likely as surprising as the other.
- // As it happens, we do go ahead and schedule it for later execution.
- try {
- for (var i = 0; i < len; i++) {
- cbs[i].apply(null, args)
- }
- } finally {
- if (cbs.length > len) {
- // added more in the interim.
- // de-zalgo, just in case, but don't call again.
- cbs.splice(0, len)
- process.nextTick(function () {
- RES.apply(null, args)
- })
- } else {
- delete reqs[key]
- }
- }
- })
-}
+ // leading slash
+ [
-function slice (args) {
- var length = args.length
- var array = []
+ // > A leading slash matches the beginning of the pathname.
+ // > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c".
+ // A leading slash matches the beginning of the pathname
+ /^\//,
+ () => '^'
+ ],
- for (var i = 0; i < length; i++) array[i] = args[i]
- return array
-}
+ // replace special metacharacter slash after the leading slash
+ [
+ /\//g,
+ () => '\\/'
+ ],
+ [
+ // > A leading "**" followed by a slash means match in all directories.
+ // > For example, "**/foo" matches file or directory "foo" anywhere,
+ // > the same as pattern "foo".
+ // > "**/foo/bar" matches file or directory "bar" anywhere that is directly
+ // > under directory "foo".
+ // Notice that the '*'s have been replaced as '\\*'
+ /^\^*\\\*\\\*\\\//,
-/***/ }),
+ // '**/foo' <-> 'foo'
+ () => '^(?:.*\\/)?'
+ ],
-/***/ 4124:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // starting
+ [
+ // there will be no leading '/'
+ // (which has been replaced by section "leading slash")
+ // If starts with '**', adding a '^' to the regular expression also works
+ /^(?=[^^])/,
+ function startingReplacer () {
+ // If has a slash `/` at the beginning or middle
+ return !/\/(?!$)/.test(this)
+ // > Prior to 2.22.1
+ // > If the pattern does not contain a slash /,
+ // > Git treats it as a shell glob pattern
+ // Actually, if there is only a trailing slash,
+ // git also treats it as a shell glob pattern
-try {
- var util = __nccwpck_require__(1669);
- /* istanbul ignore next */
- if (typeof util.inherits !== 'function') throw '';
- module.exports = util.inherits;
-} catch (e) {
- /* istanbul ignore next */
- module.exports = __nccwpck_require__(8544);
-}
+ // After 2.22.1 (compatible but clearer)
+ // > If there is a separator at the beginning or middle (or both)
+ // > of the pattern, then the pattern is relative to the directory
+ // > level of the particular .gitignore file itself.
+ // > Otherwise the pattern may also match at any level below
+ // > the .gitignore level.
+ ? '(?:^|\\/)'
+ // > Otherwise, Git treats the pattern as a shell glob suitable for
+ // > consumption by fnmatch(3)
+ : '^'
+ }
+ ],
-/***/ }),
+ // two globstars
+ [
+ // Use lookahead assertions so that we could match more than one `'/**'`
+ /\\\/\\\*\\\*(?=\\\/|$)/g,
-/***/ 8544:
-/***/ ((module) => {
+ // Zero, one or several directories
+ // should not use '*', or it will be replaced by the next replacer
-if (typeof Object.create === 'function') {
- // implementation from standard node.js 'util' module
- module.exports = function inherits(ctor, superCtor) {
- if (superCtor) {
- ctor.super_ = superCtor
- ctor.prototype = Object.create(superCtor.prototype, {
- constructor: {
- value: ctor,
- enumerable: false,
- writable: true,
- configurable: true
- }
- })
- }
- };
-} else {
- // old school shim for old browsers
- module.exports = function inherits(ctor, superCtor) {
- if (superCtor) {
- ctor.super_ = superCtor
- var TempCtor = function () {}
- TempCtor.prototype = superCtor.prototype
- ctor.prototype = new TempCtor()
- ctor.prototype.constructor = ctor
- }
- }
-}
+ // Check if it is not the last `'/**'`
+ (_, index, str) => index + 6 < str.length
+ // case: /**/
+ // > A slash followed by two consecutive asterisks then a slash matches
+ // > zero or more directories.
+ // > For example, "a/**/b" matches "a/b", "a/x/b", "a/x/y/b" and so on.
+ // '/**/'
+ ? '(?:\\/[^\\/]+)*'
-/***/ }),
+ // case: /**
+ // > A trailing `"/**"` matches everything inside.
-/***/ 6435:
-/***/ ((module) => {
+ // #21: everything inside but it should not include the current folder
+ : '\\/.+'
+ ],
-/*!
- * is-extglob
- *
- * Copyright (c) 2014-2016, Jon Schlinkert.
- * Licensed under the MIT License.
- */
+ // normal intermediate wildcards
+ [
+ // Never replace escaped '*'
+ // ignore rule '\*' will match the path '*'
-module.exports = function isExtglob(str) {
- if (typeof str !== 'string' || str === '') {
- return false;
- }
+ // 'abc.*/' -> go
+ // 'abc.*' -> skip this rule,
+ // coz trailing single wildcard will be handed by [trailing wildcard]
+ /(^|[^\\]+)(\\\*)+(?=.+)/g,
- var match;
- while ((match = /(\\).|([@?!+*]\(.*\))/g.exec(str))) {
- if (match[2]) return true;
- str = str.slice(match.index + match[0].length);
- }
+ // '*.js' matches '.js'
+ // '*.js' doesn't match 'abc'
+ (_, p1, p2) => {
+ // 1.
+ // > An asterisk "*" matches anything except a slash.
+ // 2.
+ // > Other consecutive asterisks are considered regular asterisks
+ // > and will match according to the previous rules.
+ const unescaped = p2.replace(/\\\*/g, '[^\\/]*')
+ return p1 + unescaped
+ }
+ ],
- return false;
-};
+ [
+ // unescape, revert step 3 except for back slash
+ // For example, if a user escape a '\\*',
+ // after step 3, the result will be '\\\\\\*'
+ /\\\\\\(?=[$.|*+(){^])/g,
+ () => ESCAPE
+ ],
+ [
+ // '\\\\' -> '\\'
+ /\\\\/g,
+ () => ESCAPE
+ ],
-/***/ }),
+ [
+ // > The range notation, e.g. [a-zA-Z],
+ // > can be used to match one of the characters in a range.
-/***/ 4466:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // `\` is escaped by step 3
+ /(\\)?\[([^\]/]*?)(\\*)($|\])/g,
+ (match, leadEscape, range, endEscape, close) => leadEscape === ESCAPE
+ // '\\[bar]' -> '\\\\[bar\\]'
+ ? `\\[${range}${cleanRangeBackSlash(endEscape)}${close}`
+ : close === ']'
+ ? endEscape.length % 2 === 0
+ // A normal case, and it is a range notation
+ // '[bar]'
+ // '[bar\\\\]'
+ ? `[${sanitizeRange(range)}${endEscape}]`
+ // Invalid range notaton
+ // '[bar\\]' -> '[bar\\\\]'
+ : '[]'
+ : '[]'
+ ],
-/*!
- * is-glob
- *
- * Copyright (c) 2014-2017, Jon Schlinkert.
- * Released under the MIT License.
- */
+ // ending
+ [
+ // 'js' will not match 'js.'
+ // 'ab' will not match 'abc'
+ /(?:[^*])$/,
-var isExtglob = __nccwpck_require__(6435);
-var chars = { '{': '}', '(': ')', '[': ']'};
-var strictRegex = /\\(.)|(^!|\*|[\].+)]\?|\[[^\\\]]+\]|\{[^\\}]+\}|\(\?[:!=][^\\)]+\)|\([^|]+\|[^\\)]+\))/;
-var relaxedRegex = /\\(.)|(^!|[*?{}()[\]]|\(\?)/;
+ // WTF!
+ // https://git-scm.com/docs/gitignore
+ // changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1)
+ // which re-fixes #24, #38
-module.exports = function isGlob(str, options) {
- if (typeof str !== 'string' || str === '') {
- return false;
- }
+ // > If there is a separator at the end of the pattern then the pattern
+ // > will only match directories, otherwise the pattern can match both
+ // > files and directories.
- if (isExtglob(str)) {
- return true;
- }
+ // 'js*' will not match 'a.js'
+ // 'js/' will not match 'a.js'
+ // 'js' will match 'a.js' and 'a.js/'
+ match => /\/$/.test(match)
+ // foo/ will not match 'foo'
+ ? `${match}$`
+ // foo matches 'foo' and 'foo/'
+ : `${match}(?=$|\\/$)`
+ ],
- var regex = strictRegex;
- var match;
+ // trailing wildcard
+ [
+ /(\^|\\\/)?\\\*$/,
+ (_, p1) => {
+ const prefix = p1
+ // '\^':
+ // '/*' does not match EMPTY
+ // '/*' does not match everything
- // optionally relax regex
- if (options && options.strict === false) {
- regex = relaxedRegex;
- }
+ // '\\\/':
+ // 'abc/*' does not match 'abc/'
+ ? `${p1}[^/]+`
- while ((match = regex.exec(str))) {
- if (match[2]) return true;
- var idx = match.index + match[0].length;
+ // 'a*' matches 'a'
+ // 'a*' matches 'aa'
+ : '[^/]*'
- // if an open bracket/brace/paren is escaped,
- // set the index to the next closing character
- var open = match[1];
- var close = open ? chars[open] : null;
- if (open && close) {
- var n = str.indexOf(close, idx);
- if (n !== -1) {
- idx = n + 1;
- }
+ return `${prefix}(?=$|\\/$)`
}
+ ],
+]
- str = str.slice(idx);
- }
- return false;
-};
-
+// A simple cache, because an ignore rule only has only one certain meaning
+const regexCache = Object.create(null)
-/***/ }),
+// @param {pattern}
+const makeRegex = (pattern, ignoreCase) => {
+ let source = regexCache[pattern]
-/***/ 8885:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ if (!source) {
+ source = REPLACERS.reduce(
+ (prev, current) => prev.replace(current[0], current[1].bind(pattern)),
+ pattern
+ )
+ regexCache[pattern] = source
+ }
-"use strict";
+ return ignoreCase
+ ? new RegExp(source, 'i')
+ : new RegExp(source)
+}
-const path = __nccwpck_require__(5622);
+const isString = subject => typeof subject === 'string'
-module.exports = path_ => {
- let cwd = process.cwd();
+// > A blank line matches no files, so it can serve as a separator for readability.
+const checkPattern = pattern => pattern
+ && isString(pattern)
+ && !REGEX_TEST_BLANK_LINE.test(pattern)
+ && !REGEX_INVALID_TRAILING_BACKSLASH.test(pattern)
- path_ = path.resolve(path_);
+ // > A line starting with # serves as a comment.
+ && pattern.indexOf('#') !== 0
- if (process.platform === 'win32') {
- cwd = cwd.toLowerCase();
- path_ = path_.toLowerCase();
- }
+const splitPattern = pattern => pattern.split(REGEX_SPLITALL_CRLF)
- return path_ === cwd;
-};
+class IgnoreRule {
+ constructor (
+ origin,
+ pattern,
+ negative,
+ regex
+ ) {
+ this.origin = origin
+ this.pattern = pattern
+ this.negative = negative
+ this.regex = regex
+ }
+}
+const createRule = (pattern, ignoreCase) => {
+ const origin = pattern
+ let negative = false
-/***/ }),
+ // > An optional prefix "!" which negates the pattern;
+ if (pattern.indexOf('!') === 0) {
+ negative = true
+ pattern = pattern.substr(1)
+ }
-/***/ 628:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ pattern = pattern
+ // > Put a backslash ("\") in front of the first "!" for patterns that
+ // > begin with a literal "!", for example, `"\!important!.txt"`.
+ .replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, '!')
+ // > Put a backslash ("\") in front of the first hash for patterns that
+ // > begin with a hash.
+ .replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, '#')
-"use strict";
+ const regex = makeRegex(pattern, ignoreCase)
-const path = __nccwpck_require__(5622);
+ return new IgnoreRule(
+ origin,
+ pattern,
+ negative,
+ regex
+ )
+}
-module.exports = (childPath, parentPath) => {
- const relation = path.relative(parentPath, childPath);
- return Boolean(
- relation &&
- relation !== '..' &&
- !relation.startsWith(`..${path.sep}`) &&
- relation !== path.resolve(childPath)
- );
-};
+const throwError = (message, Ctor) => {
+ throw new Ctor(message)
+}
+const checkPath = (path, originalPath, doThrow) => {
+ if (!isString(path)) {
+ return doThrow(
+ `path must be a string, but got \`${originalPath}\``,
+ TypeError
+ )
+ }
-/***/ }),
+ // We don't know if we should ignore EMPTY, so throw
+ if (!path) {
+ return doThrow(`path must not be empty`, TypeError)
+ }
-/***/ 2578:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // Check if it is a relative path
+ if (checkPath.isNotRelative(path)) {
+ const r = '`path.relative()`d'
+ return doThrow(
+ `path should be a ${r} string, but got "${originalPath}"`,
+ RangeError
+ )
+ }
-"use strict";
+ return true
+}
-/*
- * merge2
- * https://github.com/teambition/merge2
- *
- * Copyright (c) 2014-2020 Teambition
- * Licensed under the MIT license.
- */
-const Stream = __nccwpck_require__(2413)
-const PassThrough = Stream.PassThrough
-const slice = Array.prototype.slice
+const isNotRelative = path => REGEX_TEST_INVALID_PATH.test(path)
-module.exports = merge2
+checkPath.isNotRelative = isNotRelative
+checkPath.convert = p => p
-function merge2 () {
- const streamsQueue = []
- const args = slice.call(arguments)
- let merging = false
- let options = args[args.length - 1]
+class Ignore {
+ constructor ({
+ ignorecase = true,
+ ignoreCase = ignorecase,
+ allowRelativePaths = false
+ } = {}) {
+ define(this, KEY_IGNORE, true)
- if (options && !Array.isArray(options) && options.pipe == null) {
- args.pop()
- } else {
- options = {}
+ this._rules = []
+ this._ignoreCase = ignoreCase
+ this._allowRelativePaths = allowRelativePaths
+ this._initCache()
}
- const doEnd = options.end !== false
- const doPipeError = options.pipeError === true
- if (options.objectMode == null) {
- options.objectMode = true
+ _initCache () {
+ this._ignoreCache = Object.create(null)
+ this._testCache = Object.create(null)
}
- if (options.highWaterMark == null) {
- options.highWaterMark = 64 * 1024
+
+ _addPattern (pattern) {
+ // #32
+ if (pattern && pattern[KEY_IGNORE]) {
+ this._rules = this._rules.concat(pattern._rules)
+ this._added = true
+ return
+ }
+
+ if (checkPattern(pattern)) {
+ const rule = createRule(pattern, this._ignoreCase)
+ this._added = true
+ this._rules.push(rule)
+ }
}
- const mergedStream = PassThrough(options)
- function addStream () {
- for (let i = 0, len = arguments.length; i < len; i++) {
- streamsQueue.push(pauseStreams(arguments[i], options))
+ // @param {Array | string | Ignore} pattern
+ add (pattern) {
+ this._added = false
+
+ makeArray(
+ isString(pattern)
+ ? splitPattern(pattern)
+ : pattern
+ ).forEach(this._addPattern, this)
+
+ // Some rules have just added to the ignore,
+ // making the behavior changed.
+ if (this._added) {
+ this._initCache()
}
- mergeStream()
+
return this
}
- function mergeStream () {
- if (merging) {
- return
- }
- merging = true
+ // legacy
+ addPattern (pattern) {
+ return this.add(pattern)
+ }
- let streams = streamsQueue.shift()
- if (!streams) {
- process.nextTick(endStream)
- return
- }
- if (!Array.isArray(streams)) {
- streams = [streams]
- }
+ // | ignored : unignored
+ // negative | 0:0 | 0:1 | 1:0 | 1:1
+ // -------- | ------- | ------- | ------- | --------
+ // 0 | TEST | TEST | SKIP | X
+ // 1 | TESTIF | SKIP | TEST | X
- let pipesCount = streams.length + 1
+ // - SKIP: always skip
+ // - TEST: always test
+ // - TESTIF: only test if checkUnignored
+ // - X: that never happen
- function next () {
- if (--pipesCount > 0) {
- return
- }
- merging = false
- mergeStream()
- }
+ // @param {boolean} whether should check if the path is unignored,
+ // setting `checkUnignored` to `false` could reduce additional
+ // path matching.
- function pipe (stream) {
- function onend () {
- stream.removeListener('merge2UnpipeEnd', onend)
- stream.removeListener('end', onend)
- if (doPipeError) {
- stream.removeListener('error', onerror)
- }
- next()
- }
- function onerror (err) {
- mergedStream.emit('error', err)
- }
- // skip ended stream
- if (stream._readableState.endEmitted) {
- return next()
+ // @returns {TestResult} true if a file is ignored
+ _testOne (path, checkUnignored) {
+ let ignored = false
+ let unignored = false
+
+ this._rules.forEach(rule => {
+ const {negative} = rule
+ if (
+ unignored === negative && ignored !== unignored
+ || negative && !ignored && !unignored && !checkUnignored
+ ) {
+ return
}
- stream.on('merge2UnpipeEnd', onend)
- stream.on('end', onend)
+ const matched = rule.regex.test(path)
- if (doPipeError) {
- stream.on('error', onerror)
+ if (matched) {
+ ignored = !negative
+ unignored = negative
}
+ })
- stream.pipe(mergedStream, { end: false })
- // compatible for old stream
- stream.resume()
- }
-
- for (let i = 0; i < streams.length; i++) {
- pipe(streams[i])
+ return {
+ ignored,
+ unignored
}
-
- next()
}
- function endStream () {
- merging = false
- // emit 'queueDrain' when all streams merged.
- mergedStream.emit('queueDrain')
- if (doEnd) {
- mergedStream.end()
- }
- }
+ // @returns {TestResult}
+ _test (originalPath, cache, checkUnignored, slices) {
+ const path = originalPath
+ // Supports nullable path
+ && checkPath.convert(originalPath)
- mergedStream.setMaxListeners(0)
- mergedStream.add = addStream
- mergedStream.on('unpipe', function (stream) {
- stream.emit('merge2UnpipeEnd')
- })
+ checkPath(
+ path,
+ originalPath,
+ this._allowRelativePaths
+ ? RETURN_FALSE
+ : throwError
+ )
- if (args.length) {
- addStream.apply(null, args)
+ return this._t(path, cache, checkUnignored, slices)
}
- return mergedStream
-}
-// check and pause streams for pipe.
-function pauseStreams (streams, options) {
- if (!Array.isArray(streams)) {
- // Backwards-compat with old-style streams
- if (!streams._readableState && streams.pipe) {
- streams = streams.pipe(PassThrough(options))
+ _t (path, cache, checkUnignored, slices) {
+ if (path in cache) {
+ return cache[path]
}
- if (!streams._readableState || !streams.pause || !streams.pipe) {
- throw new Error('Only readable stream can be merged.')
+
+ if (!slices) {
+ // path/to/a.js
+ // ['path', 'to', 'a.js']
+ slices = path.split(SLASH)
}
- streams.pause()
- } else {
- for (let i = 0, len = streams.length; i < len; i++) {
- streams[i] = pauseStreams(streams[i], options)
+
+ slices.pop()
+
+ // If the path has no parent directory, just test it
+ if (!slices.length) {
+ return cache[path] = this._testOne(path, checkUnignored)
}
- }
- return streams
-}
+ const parent = this._t(
+ slices.join(SLASH) + SLASH,
+ cache,
+ checkUnignored,
+ slices
+ )
-/***/ }),
+ // If the path contains a parent directory, check the parent first
+ return cache[path] = parent.ignored
+ // > It is not possible to re-include a file if a parent directory of
+ // > that file is excluded.
+ ? parent
+ : this._testOne(path, checkUnignored)
+ }
-/***/ 6228:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ ignores (path) {
+ return this._test(path, this._ignoreCache, false).ignored
+ }
-"use strict";
+ createFilter () {
+ return path => !this.ignores(path)
+ }
+ filter (paths) {
+ return makeArray(paths).filter(this.createFilter())
+ }
-const util = __nccwpck_require__(1669);
-const braces = __nccwpck_require__(5371);
-const picomatch = __nccwpck_require__(8569);
-const utils = __nccwpck_require__(479);
-const isEmptyString = val => val === '' || val === './';
+ // @returns {TestResult}
+ test (path) {
+ return this._test(path, this._testCache, true)
+ }
+}
-/**
- * Returns an array of strings that match one or more glob patterns.
- *
- * ```js
- * const mm = require('micromatch');
- * // mm(list, patterns[, options]);
- *
- * console.log(mm(['a.js', 'a.txt'], ['*.js']));
- * //=> [ 'a.js' ]
- * ```
- * @param {String|Array} `list` List of strings to match.
- * @param {String|Array} `patterns` One or more glob patterns to use for matching.
- * @param {Object} `options` See available [options](#options)
- * @return {Array} Returns an array of matches
- * @summary false
- * @api public
- */
+const factory = options => new Ignore(options)
-const micromatch = (list, patterns, options) => {
- patterns = [].concat(patterns);
- list = [].concat(list);
+const isPathValid = path =>
+ checkPath(path && checkPath.convert(path), path, RETURN_FALSE)
- let omit = new Set();
- let keep = new Set();
- let items = new Set();
- let negatives = 0;
+factory.isPathValid = isPathValid
- let onResult = state => {
- items.add(state.output);
- if (options && options.onResult) {
- options.onResult(state);
- }
- };
+// Fixes typescript
+factory.default = factory
- for (let i = 0; i < patterns.length; i++) {
- let isMatch = picomatch(String(patterns[i]), { ...options, onResult }, true);
- let negated = isMatch.state.negated || isMatch.state.negatedExtglob;
- if (negated) negatives++;
+module.exports = factory
- for (let item of list) {
- let matched = isMatch(item, true);
+// Windows
+// --------------------------------------------------------------
+/* istanbul ignore if */
+if (
+ // Detect `process` so that it can run in browsers.
+ typeof process !== 'undefined'
+ && (
+ process.env && process.env.IGNORE_TEST_WIN32
+ || process.platform === 'win32'
+ )
+) {
+ /* eslint no-control-regex: "off" */
+ const makePosix = str => /^\\\\\?\\/.test(str)
+ || /["<>|\u0000-\u001F]+/u.test(str)
+ ? str
+ : str.replace(/\\/g, '/')
- let match = negated ? !matched.isMatch : matched.isMatch;
- if (!match) continue;
+ checkPath.convert = makePosix
- if (negated) {
- omit.add(matched.output);
- } else {
- omit.delete(matched.output);
- keep.add(matched.output);
- }
- }
- }
+ // 'C:\\foo' <- 'C:\\foo' has been converted to 'C:/'
+ // 'd:\\foo'
+ const REGIX_IS_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i
+ checkPath.isNotRelative = path =>
+ REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path)
+ || isNotRelative(path)
+}
- let result = negatives === patterns.length ? [...items] : [...keep];
- let matches = result.filter(item => !omit.has(item));
- if (options && matches.length === 0) {
- if (options.failglob === true) {
- throw new Error(`No matches found for "${patterns.join(', ')}"`);
- }
+/***/ }),
- if (options.nonull === true || options.nullglob === true) {
- return options.unescape ? patterns.map(p => p.replace(/\\/g, '')) : patterns;
- }
- }
+/***/ 8043:
+/***/ ((module) => {
- return matches;
-};
+"use strict";
-/**
- * Backwards compatibility
- */
-micromatch.match = micromatch;
+module.exports = (string, count = 1, options) => {
+ options = {
+ indent: ' ',
+ includeEmptyLines: false,
+ ...options
+ };
-/**
- * Returns a matcher function from the given glob `pattern` and `options`.
- * The returned function takes a string to match as its only argument and returns
- * true if the string is a match.
- *
- * ```js
- * const mm = require('micromatch');
- * // mm.matcher(pattern[, options]);
- *
- * const isMatch = mm.matcher('*.!(*a)');
- * console.log(isMatch('a.a')); //=> false
- * console.log(isMatch('a.b')); //=> true
- * ```
- * @param {String} `pattern` Glob pattern
- * @param {Object} `options`
- * @return {Function} Returns a matcher function.
- * @api public
- */
+ if (typeof string !== 'string') {
+ throw new TypeError(
+ `Expected \`input\` to be a \`string\`, got \`${typeof string}\``
+ );
+ }
-micromatch.matcher = (pattern, options) => picomatch(pattern, options);
+ if (typeof count !== 'number') {
+ throw new TypeError(
+ `Expected \`count\` to be a \`number\`, got \`${typeof count}\``
+ );
+ }
-/**
- * Returns true if **any** of the given glob `patterns` match the specified `string`.
- *
- * ```js
- * const mm = require('micromatch');
- * // mm.isMatch(string, patterns[, options]);
- *
- * console.log(mm.isMatch('a.a', ['b.*', '*.a'])); //=> true
- * console.log(mm.isMatch('a.a', 'b.*')); //=> false
- * ```
- * @param {String} `str` The string to test.
- * @param {String|Array} `patterns` One or more glob patterns to use for matching.
- * @param {Object} `[options]` See available [options](#options).
- * @return {Boolean} Returns true if any patterns match `str`
- * @api public
- */
+ if (typeof options.indent !== 'string') {
+ throw new TypeError(
+ `Expected \`options.indent\` to be a \`string\`, got \`${typeof options.indent}\``
+ );
+ }
-micromatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
+ if (count === 0) {
+ return string;
+ }
-/**
- * Backwards compatibility
- */
+ const regex = options.includeEmptyLines ? /^/gm : /^(?!\s*$)/gm;
-micromatch.any = micromatch.isMatch;
+ return string.replace(regex, options.indent.repeat(count));
+};
-/**
- * Returns a list of strings that _**do not match any**_ of the given `patterns`.
- *
- * ```js
- * const mm = require('micromatch');
- * // mm.not(list, patterns[, options]);
- *
- * console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a'));
- * //=> ['b.b', 'c.c']
- * ```
- * @param {Array} `list` Array of strings to match.
- * @param {String|Array} `patterns` One or more glob pattern to use for matching.
- * @param {Object} `options` See available [options](#options) for changing how matches are performed
- * @return {Array} Returns an array of strings that **do not match** the given patterns.
- * @api public
- */
-micromatch.not = (list, patterns, options = {}) => {
- patterns = [].concat(patterns).map(String);
- let result = new Set();
- let items = [];
+/***/ }),
- let onResult = state => {
- if (options.onResult) options.onResult(state);
- items.push(state.output);
- };
+/***/ 2492:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- let matches = micromatch(list, patterns, { ...options, onResult });
+var wrappy = __nccwpck_require__(2940)
+var reqs = Object.create(null)
+var once = __nccwpck_require__(1223)
- for (let item of items) {
- if (!matches.includes(item)) {
- result.add(item);
- }
+module.exports = wrappy(inflight)
+
+function inflight (key, cb) {
+ if (reqs[key]) {
+ reqs[key].push(cb)
+ return null
+ } else {
+ reqs[key] = [cb]
+ return makeres(key)
}
- return [...result];
-};
+}
-/**
- * Returns true if the given `string` contains the given pattern. Similar
- * to [.isMatch](#isMatch) but the pattern can match any part of the string.
- *
- * ```js
- * var mm = require('micromatch');
- * // mm.contains(string, pattern[, options]);
- *
- * console.log(mm.contains('aa/bb/cc', '*b'));
- * //=> true
- * console.log(mm.contains('aa/bb/cc', '*d'));
- * //=> false
- * ```
- * @param {String} `str` The string to match.
- * @param {String|Array} `patterns` Glob pattern to use for matching.
- * @param {Object} `options` See available [options](#options) for changing how matches are performed
- * @return {Boolean} Returns true if any of the patterns matches any part of `str`.
- * @api public
- */
+function makeres (key) {
+ return once(function RES () {
+ var cbs = reqs[key]
+ var len = cbs.length
+ var args = slice(arguments)
-micromatch.contains = (str, pattern, options) => {
- if (typeof str !== 'string') {
- throw new TypeError(`Expected a string: "${util.inspect(str)}"`);
- }
+ // XXX It's somewhat ambiguous whether a new callback added in this
+ // pass should be queued for later execution if something in the
+ // list of callbacks throws, or if it should just be discarded.
+ // However, it's such an edge case that it hardly matters, and either
+ // choice is likely as surprising as the other.
+ // As it happens, we do go ahead and schedule it for later execution.
+ try {
+ for (var i = 0; i < len; i++) {
+ cbs[i].apply(null, args)
+ }
+ } finally {
+ if (cbs.length > len) {
+ // added more in the interim.
+ // de-zalgo, just in case, but don't call again.
+ cbs.splice(0, len)
+ process.nextTick(function () {
+ RES.apply(null, args)
+ })
+ } else {
+ delete reqs[key]
+ }
+ }
+ })
+}
- if (Array.isArray(pattern)) {
- return pattern.some(p => micromatch.contains(str, p, options));
- }
+function slice (args) {
+ var length = args.length
+ var array = []
- if (typeof pattern === 'string') {
- if (isEmptyString(str) || isEmptyString(pattern)) {
- return false;
- }
+ for (var i = 0; i < length; i++) array[i] = args[i]
+ return array
+}
- if (str.includes(pattern) || (str.startsWith('./') && str.slice(2).includes(pattern))) {
- return true;
+
+/***/ }),
+
+/***/ 4124:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+try {
+ var util = __nccwpck_require__(3837);
+ /* istanbul ignore next */
+ if (typeof util.inherits !== 'function') throw '';
+ module.exports = util.inherits;
+} catch (e) {
+ /* istanbul ignore next */
+ module.exports = __nccwpck_require__(8544);
+}
+
+
+/***/ }),
+
+/***/ 8544:
+/***/ ((module) => {
+
+if (typeof Object.create === 'function') {
+ // implementation from standard node.js 'util' module
+ module.exports = function inherits(ctor, superCtor) {
+ if (superCtor) {
+ ctor.super_ = superCtor
+ ctor.prototype = Object.create(superCtor.prototype, {
+ constructor: {
+ value: ctor,
+ enumerable: false,
+ writable: true,
+ configurable: true
+ }
+ })
+ }
+ };
+} else {
+ // old school shim for old browsers
+ module.exports = function inherits(ctor, superCtor) {
+ if (superCtor) {
+ ctor.super_ = superCtor
+ var TempCtor = function () {}
+ TempCtor.prototype = superCtor.prototype
+ ctor.prototype = new TempCtor()
+ ctor.prototype.constructor = ctor
}
}
+}
- return micromatch.isMatch(str, pattern, { ...options, contains: true });
-};
-/**
- * Filter the keys of the given object with the given `glob` pattern
- * and `options`. Does not attempt to match nested keys. If you need this feature,
- * use [glob-object][] instead.
- *
- * ```js
- * const mm = require('micromatch');
- * // mm.matchKeys(object, patterns[, options]);
+/***/ }),
+
+/***/ 6435:
+/***/ ((module) => {
+
+/*!
+ * is-extglob
*
- * const obj = { aa: 'a', ab: 'b', ac: 'c' };
- * console.log(mm.matchKeys(obj, '*b'));
- * //=> { ab: 'b' }
- * ```
- * @param {Object} `object` The object with keys to filter.
- * @param {String|Array} `patterns` One or more glob patterns to use for matching.
- * @param {Object} `options` See available [options](#options) for changing how matches are performed
- * @return {Object} Returns an object with only keys that match the given patterns.
- * @api public
+ * Copyright (c) 2014-2016, Jon Schlinkert.
+ * Licensed under the MIT License.
*/
-micromatch.matchKeys = (obj, patterns, options) => {
- if (!utils.isObject(obj)) {
- throw new TypeError('Expected the first argument to be an object');
+module.exports = function isExtglob(str) {
+ if (typeof str !== 'string' || str === '') {
+ return false;
}
- let keys = micromatch(Object.keys(obj), patterns, options);
- let res = {};
- for (let key of keys) res[key] = obj[key];
- return res;
+
+ var match;
+ while ((match = /(\\).|([@?!+*]\(.*\))/g.exec(str))) {
+ if (match[2]) return true;
+ str = str.slice(match.index + match[0].length);
+ }
+
+ return false;
};
-/**
- * Returns true if some of the strings in the given `list` match any of the given glob `patterns`.
- *
- * ```js
- * const mm = require('micromatch');
- * // mm.some(list, patterns[, options]);
+
+/***/ }),
+
+/***/ 4466:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+/*!
+ * is-glob
*
- * console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
- * // true
- * console.log(mm.some(['foo.js'], ['*.js', '!foo.js']));
- * // false
- * ```
- * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found.
- * @param {String|Array} `patterns` One or more glob patterns to use for matching.
- * @param {Object} `options` See available [options](#options) for changing how matches are performed
- * @return {Boolean} Returns true if any `patterns` matches any of the strings in `list`
- * @api public
+ * Copyright (c) 2014-2017, Jon Schlinkert.
+ * Released under the MIT License.
*/
-micromatch.some = (list, patterns, options) => {
- let items = [].concat(list);
+var isExtglob = __nccwpck_require__(6435);
+var chars = { '{': '}', '(': ')', '[': ']'};
+var strictCheck = function(str) {
+ if (str[0] === '!') {
+ return true;
+ }
+ var index = 0;
+ var pipeIndex = -2;
+ var closeSquareIndex = -2;
+ var closeCurlyIndex = -2;
+ var closeParenIndex = -2;
+ var backSlashIndex = -2;
+ while (index < str.length) {
+ if (str[index] === '*') {
+ return true;
+ }
- for (let pattern of [].concat(patterns)) {
- let isMatch = picomatch(String(pattern), options);
- if (items.some(item => isMatch(item))) {
+ if (str[index + 1] === '?' && /[\].+)]/.test(str[index])) {
return true;
}
+
+ if (closeSquareIndex !== -1 && str[index] === '[' && str[index + 1] !== ']') {
+ if (closeSquareIndex < index) {
+ closeSquareIndex = str.indexOf(']', index);
+ }
+ if (closeSquareIndex > index) {
+ if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) {
+ return true;
+ }
+ backSlashIndex = str.indexOf('\\', index);
+ if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) {
+ return true;
+ }
+ }
+ }
+
+ if (closeCurlyIndex !== -1 && str[index] === '{' && str[index + 1] !== '}') {
+ closeCurlyIndex = str.indexOf('}', index);
+ if (closeCurlyIndex > index) {
+ backSlashIndex = str.indexOf('\\', index);
+ if (backSlashIndex === -1 || backSlashIndex > closeCurlyIndex) {
+ return true;
+ }
+ }
+ }
+
+ if (closeParenIndex !== -1 && str[index] === '(' && str[index + 1] === '?' && /[:!=]/.test(str[index + 2]) && str[index + 3] !== ')') {
+ closeParenIndex = str.indexOf(')', index);
+ if (closeParenIndex > index) {
+ backSlashIndex = str.indexOf('\\', index);
+ if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) {
+ return true;
+ }
+ }
+ }
+
+ if (pipeIndex !== -1 && str[index] === '(' && str[index + 1] !== '|') {
+ if (pipeIndex < index) {
+ pipeIndex = str.indexOf('|', index);
+ }
+ if (pipeIndex !== -1 && str[pipeIndex + 1] !== ')') {
+ closeParenIndex = str.indexOf(')', pipeIndex);
+ if (closeParenIndex > pipeIndex) {
+ backSlashIndex = str.indexOf('\\', pipeIndex);
+ if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) {
+ return true;
+ }
+ }
+ }
+ }
+
+ if (str[index] === '\\') {
+ var open = str[index + 1];
+ index += 2;
+ var close = chars[open];
+
+ if (close) {
+ var n = str.indexOf(close, index);
+ if (n !== -1) {
+ index = n + 1;
+ }
+ }
+
+ if (str[index] === '!') {
+ return true;
+ }
+ } else {
+ index++;
+ }
}
return false;
};
-/**
- * Returns true if every string in the given `list` matches
- * any of the given glob `patterns`.
- *
- * ```js
- * const mm = require('micromatch');
- * // mm.every(list, patterns[, options]);
- *
- * console.log(mm.every('foo.js', ['foo.js']));
- * // true
- * console.log(mm.every(['foo.js', 'bar.js'], ['*.js']));
- * // true
- * console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
- * // false
- * console.log(mm.every(['foo.js'], ['*.js', '!foo.js']));
- * // false
- * ```
- * @param {String|Array} `list` The string or array of strings to test.
- * @param {String|Array} `patterns` One or more glob patterns to use for matching.
- * @param {Object} `options` See available [options](#options) for changing how matches are performed
- * @return {Boolean} Returns true if all `patterns` matches all of the strings in `list`
- * @api public
- */
+var relaxedCheck = function(str) {
+ if (str[0] === '!') {
+ return true;
+ }
+ var index = 0;
+ while (index < str.length) {
+ if (/[*?{}()[\]]/.test(str[index])) {
+ return true;
+ }
-micromatch.every = (list, patterns, options) => {
- let items = [].concat(list);
+ if (str[index] === '\\') {
+ var open = str[index + 1];
+ index += 2;
+ var close = chars[open];
- for (let pattern of [].concat(patterns)) {
- let isMatch = picomatch(String(pattern), options);
- if (!items.every(item => isMatch(item))) {
- return false;
+ if (close) {
+ var n = str.indexOf(close, index);
+ if (n !== -1) {
+ index = n + 1;
+ }
+ }
+
+ if (str[index] === '!') {
+ return true;
+ }
+ } else {
+ index++;
}
}
- return true;
+ return false;
};
-/**
- * Returns true if **all** of the given `patterns` match
- * the specified string.
- *
- * ```js
- * const mm = require('micromatch');
- * // mm.all(string, patterns[, options]);
- *
- * console.log(mm.all('foo.js', ['foo.js']));
- * // true
- *
- * console.log(mm.all('foo.js', ['*.js', '!foo.js']));
- * // false
- *
- * console.log(mm.all('foo.js', ['*.js', 'foo.js']));
- * // true
- *
- * console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js']));
- * // true
- * ```
- * @param {String|Array} `str` The string to test.
- * @param {String|Array} `patterns` One or more glob patterns to use for matching.
- * @param {Object} `options` See available [options](#options) for changing how matches are performed
- * @return {Boolean} Returns true if any patterns match `str`
- * @api public
- */
-
-micromatch.all = (str, patterns, options) => {
- if (typeof str !== 'string') {
- throw new TypeError(`Expected a string: "${util.inspect(str)}"`);
+module.exports = function isGlob(str, options) {
+ if (typeof str !== 'string' || str === '') {
+ return false;
}
- return [].concat(patterns).every(p => picomatch(p, options)(str));
-};
-
-/**
- * Returns an array of matches captured by `pattern` in `string, or `null` if the pattern did not match.
- *
- * ```js
- * const mm = require('micromatch');
- * // mm.capture(pattern, string[, options]);
- *
- * console.log(mm.capture('test/*.js', 'test/foo.js'));
- * //=> ['foo']
- * console.log(mm.capture('test/*.js', 'foo/bar.css'));
- * //=> null
- * ```
- * @param {String} `glob` Glob pattern to use for matching.
- * @param {String} `input` String to match
- * @param {Object} `options` See available [options](#options) for changing how matches are performed
- * @return {Array|null} Returns an array of captures if the input matches the glob pattern, otherwise `null`.
- * @api public
- */
+ if (isExtglob(str)) {
+ return true;
+ }
-micromatch.capture = (glob, input, options) => {
- let posix = utils.isWindows(options);
- let regex = picomatch.makeRe(String(glob), { ...options, capture: true });
- let match = regex.exec(posix ? utils.toPosixSlashes(input) : input);
+ var check = strictCheck;
- if (match) {
- return match.slice(1).map(v => v === void 0 ? '' : v);
+ // optionally relax check
+ if (options && options.strict === false) {
+ check = relaxedCheck;
}
+
+ return check(str);
};
-/**
- * Create a regular expression from the given glob `pattern`.
- *
- * ```js
- * const mm = require('micromatch');
- * // mm.makeRe(pattern[, options]);
- *
- * console.log(mm.makeRe('*.js'));
- * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/
- * ```
- * @param {String} `pattern` A glob pattern to convert to regex.
- * @param {Object} `options`
- * @return {RegExp} Returns a regex created from the given pattern.
- * @api public
- */
-micromatch.makeRe = (...args) => picomatch.makeRe(...args);
+/***/ }),
-/**
- * Scan a glob pattern to separate the pattern into segments. Used
- * by the [split](#split) method.
+/***/ 5680:
+/***/ ((module) => {
+
+"use strict";
+/*!
+ * is-number
*
- * ```js
- * const mm = require('micromatch');
- * const state = mm.scan(pattern[, options]);
- * ```
- * @param {String} `pattern`
- * @param {Object} `options`
- * @return {Object} Returns an object with
- * @api public
+ * Copyright (c) 2014-present, Jon Schlinkert.
+ * Released under the MIT License.
*/
-micromatch.scan = (...args) => picomatch.scan(...args);
-/**
- * Parse a glob pattern to create the source string for a regular
- * expression.
- *
- * ```js
- * const mm = require('micromatch');
- * const state = mm(pattern[, options]);
- * ```
- * @param {String} `glob`
- * @param {Object} `options`
- * @return {Object} Returns an object with useful properties and output to be used as regex source string.
- * @api public
- */
-micromatch.parse = (patterns, options) => {
- let res = [];
- for (let pattern of [].concat(patterns || [])) {
- for (let str of braces(String(pattern), options)) {
- res.push(picomatch.parse(str, options));
- }
+module.exports = function(num) {
+ if (typeof num === 'number') {
+ return num - num === 0;
}
- return res;
+ if (typeof num === 'string' && num.trim() !== '') {
+ return Number.isFinite ? Number.isFinite(+num) : isFinite(+num);
+ }
+ return false;
};
-/**
- * Process the given brace `pattern`.
- *
- * ```js
- * const { braces } = require('micromatch');
- * console.log(braces('foo/{a,b,c}/bar'));
- * //=> [ 'foo/(a|b|c)/bar' ]
- *
- * console.log(braces('foo/{a,b,c}/bar', { expand: true }));
- * //=> [ 'foo/a/bar', 'foo/b/bar', 'foo/c/bar' ]
- * ```
- * @param {String} `pattern` String with brace pattern to process.
- * @param {Object} `options` Any [options](#options) to change how expansion is performed. See the [braces][] library for all available options.
- * @return {Array}
- * @api public
- */
-micromatch.braces = (pattern, options) => {
- if (typeof pattern !== 'string') throw new TypeError('Expected a string');
- if ((options && options.nobrace === true) || !/\{.*\}/.test(pattern)) {
- return [pattern];
- }
- return braces(pattern, options);
-};
+/***/ }),
-/**
- * Expand braces
- */
+/***/ 8885:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-micromatch.braceExpand = (pattern, options) => {
- if (typeof pattern !== 'string') throw new TypeError('Expected a string');
- return micromatch.braces(pattern, { ...options, expand: true });
-};
+"use strict";
-/**
- * Expose micromatch
- */
+const path = __nccwpck_require__(1017);
-module.exports = micromatch;
+module.exports = path_ => {
+ let cwd = process.cwd();
+
+ path_ = path.resolve(path_);
+
+ if (process.platform === 'win32') {
+ cwd = cwd.toLowerCase();
+ path_ = path_.toLowerCase();
+ }
+
+ return path_ === cwd;
+};
/***/ }),
-/***/ 5371:
+/***/ 628:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
+const path = __nccwpck_require__(1017);
-const stringify = __nccwpck_require__(470);
-const compile = __nccwpck_require__(9746);
-const expand = __nccwpck_require__(8926);
-const parse = __nccwpck_require__(6751);
+module.exports = (childPath, parentPath) => {
+ const relation = path.relative(parentPath, childPath);
+ return Boolean(
+ relation &&
+ relation !== '..' &&
+ !relation.startsWith(`..${path.sep}`) &&
+ relation !== path.resolve(childPath)
+ );
+};
-/**
- * Expand the given pattern or create a regex-compatible string.
- *
- * ```js
- * const braces = require('braces');
- * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)']
- * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c']
- * ```
- * @param {String} `str`
- * @param {Object} `options`
- * @return {String}
- * @api public
- */
-const braces = (input, options = {}) => {
- let output = [];
+/***/ }),
- if (Array.isArray(input)) {
- for (let pattern of input) {
- let result = braces.create(pattern, options);
- if (Array.isArray(result)) {
- output.push(...result);
- } else {
- output.push(result);
- }
- }
- } else {
- output = [].concat(braces.create(input, options));
- }
+/***/ 2578:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- if (options && options.expand === true && options.nodupes === true) {
- output = [...new Set(output)];
- }
- return output;
-};
+"use strict";
-/**
- * Parse the given `str` with the given `options`.
+/*
+ * merge2
+ * https://github.com/teambition/merge2
*
- * ```js
- * // braces.parse(pattern, [, options]);
- * const ast = braces.parse('a/{b,c}/d');
- * console.log(ast);
- * ```
- * @param {String} pattern Brace pattern to parse
- * @param {Object} options
- * @return {Object} Returns an AST
- * @api public
+ * Copyright (c) 2014-2020 Teambition
+ * Licensed under the MIT license.
*/
+const Stream = __nccwpck_require__(2781)
+const PassThrough = Stream.PassThrough
+const slice = Array.prototype.slice
-braces.parse = (input, options = {}) => parse(input, options);
+module.exports = merge2
-/**
- * Creates a braces string from an AST, or an AST node.
- *
- * ```js
- * const braces = require('braces');
- * let ast = braces.parse('foo/{a,b}/bar');
- * console.log(stringify(ast.nodes[2])); //=> '{a,b}'
- * ```
- * @param {String} `input` Brace pattern or AST.
- * @param {Object} `options`
- * @return {Array} Returns an array of expanded values.
- * @api public
- */
+function merge2 () {
+ const streamsQueue = []
+ const args = slice.call(arguments)
+ let merging = false
+ let options = args[args.length - 1]
-braces.stringify = (input, options = {}) => {
- if (typeof input === 'string') {
- return stringify(braces.parse(input, options), options);
+ if (options && !Array.isArray(options) && options.pipe == null) {
+ args.pop()
+ } else {
+ options = {}
}
- return stringify(input, options);
-};
-/**
- * Compiles a brace pattern into a regex-compatible, optimized string.
- * This method is called by the main [braces](#braces) function by default.
- *
- * ```js
- * const braces = require('braces');
- * console.log(braces.compile('a/{b,c}/d'));
- * //=> ['a/(b|c)/d']
- * ```
- * @param {String} `input` Brace pattern or AST.
- * @param {Object} `options`
- * @return {Array} Returns an array of expanded values.
- * @api public
- */
+ const doEnd = options.end !== false
+ const doPipeError = options.pipeError === true
+ if (options.objectMode == null) {
+ options.objectMode = true
+ }
+ if (options.highWaterMark == null) {
+ options.highWaterMark = 64 * 1024
+ }
+ const mergedStream = PassThrough(options)
-braces.compile = (input, options = {}) => {
- if (typeof input === 'string') {
- input = braces.parse(input, options);
+ function addStream () {
+ for (let i = 0, len = arguments.length; i < len; i++) {
+ streamsQueue.push(pauseStreams(arguments[i], options))
+ }
+ mergeStream()
+ return this
}
- return compile(input, options);
-};
-/**
- * Expands a brace pattern into an array. This method is called by the
- * main [braces](#braces) function when `options.expand` is true. Before
- * using this method it's recommended that you read the [performance notes](#performance))
- * and advantages of using [.compile](#compile) instead.
- *
- * ```js
- * const braces = require('braces');
- * console.log(braces.expand('a/{b,c}/d'));
- * //=> ['a/b/d', 'a/c/d'];
- * ```
- * @param {String} `pattern` Brace pattern
- * @param {Object} `options`
- * @return {Array} Returns an array of expanded values.
- * @api public
- */
+ function mergeStream () {
+ if (merging) {
+ return
+ }
+ merging = true
-braces.expand = (input, options = {}) => {
- if (typeof input === 'string') {
- input = braces.parse(input, options);
- }
+ let streams = streamsQueue.shift()
+ if (!streams) {
+ process.nextTick(endStream)
+ return
+ }
+ if (!Array.isArray(streams)) {
+ streams = [streams]
+ }
- let result = expand(input, options);
+ let pipesCount = streams.length + 1
- // filter out empty strings if specified
- if (options.noempty === true) {
- result = result.filter(Boolean);
- }
+ function next () {
+ if (--pipesCount > 0) {
+ return
+ }
+ merging = false
+ mergeStream()
+ }
- // filter out duplicates if specified
- if (options.nodupes === true) {
- result = [...new Set(result)];
- }
+ function pipe (stream) {
+ function onend () {
+ stream.removeListener('merge2UnpipeEnd', onend)
+ stream.removeListener('end', onend)
+ if (doPipeError) {
+ stream.removeListener('error', onerror)
+ }
+ next()
+ }
+ function onerror (err) {
+ mergedStream.emit('error', err)
+ }
+ // skip ended stream
+ if (stream._readableState.endEmitted) {
+ return next()
+ }
- return result;
-};
+ stream.on('merge2UnpipeEnd', onend)
+ stream.on('end', onend)
-/**
- * Processes a brace pattern and returns either an expanded array
- * (if `options.expand` is true), a highly optimized regex-compatible string.
- * This method is called by the main [braces](#braces) function.
- *
- * ```js
- * const braces = require('braces');
- * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}'))
- * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)'
- * ```
- * @param {String} `pattern` Brace pattern
- * @param {Object} `options`
- * @return {Array} Returns an array of expanded values.
- * @api public
- */
+ if (doPipeError) {
+ stream.on('error', onerror)
+ }
-braces.create = (input, options = {}) => {
- if (input === '' || input.length < 3) {
- return [input];
+ stream.pipe(mergedStream, { end: false })
+ // compatible for old stream
+ stream.resume()
+ }
+
+ for (let i = 0; i < streams.length; i++) {
+ pipe(streams[i])
+ }
+
+ next()
}
- return options.expand !== true
- ? braces.compile(input, options)
- : braces.expand(input, options);
-};
+ function endStream () {
+ merging = false
+ // emit 'queueDrain' when all streams merged.
+ mergedStream.emit('queueDrain')
+ if (doEnd) {
+ mergedStream.end()
+ }
+ }
-/**
- * Expose "braces"
- */
+ mergedStream.setMaxListeners(0)
+ mergedStream.add = addStream
+ mergedStream.on('unpipe', function (stream) {
+ stream.emit('merge2UnpipeEnd')
+ })
-module.exports = braces;
+ if (args.length) {
+ addStream.apply(null, args)
+ }
+ return mergedStream
+}
+
+// check and pause streams for pipe.
+function pauseStreams (streams, options) {
+ if (!Array.isArray(streams)) {
+ // Backwards-compat with old-style streams
+ if (!streams._readableState && streams.pipe) {
+ streams = streams.pipe(PassThrough(options))
+ }
+ if (!streams._readableState || !streams.pause || !streams.pipe) {
+ throw new Error('Only readable stream can be merged.')
+ }
+ streams.pause()
+ } else {
+ for (let i = 0, len = streams.length; i < len; i++) {
+ streams[i] = pauseStreams(streams[i], options)
+ }
+ }
+ return streams
+}
/***/ }),
-/***/ 9746:
+/***/ 6228:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
-const fill = __nccwpck_require__(4652);
-const utils = __nccwpck_require__(2081);
-
-const compile = (ast, options = {}) => {
- let walk = (node, parent = {}) => {
- let invalidBlock = utils.isInvalidBrace(parent);
- let invalidNode = node.invalid === true && options.escapeInvalid === true;
- let invalid = invalidBlock === true || invalidNode === true;
- let prefix = options.escapeInvalid === true ? '\\' : '';
- let output = '';
+const util = __nccwpck_require__(3837);
+const braces = __nccwpck_require__(610);
+const picomatch = __nccwpck_require__(8569);
+const utils = __nccwpck_require__(479);
+const isEmptyString = val => val === '' || val === './';
- if (node.isOpen === true) {
- return prefix + node.value;
- }
- if (node.isClose === true) {
- return prefix + node.value;
- }
+/**
+ * Returns an array of strings that match one or more glob patterns.
+ *
+ * ```js
+ * const mm = require('micromatch');
+ * // mm(list, patterns[, options]);
+ *
+ * console.log(mm(['a.js', 'a.txt'], ['*.js']));
+ * //=> [ 'a.js' ]
+ * ```
+ * @param {String|Array} `list` List of strings to match.
+ * @param {String|Array} `patterns` One or more glob patterns to use for matching.
+ * @param {Object} `options` See available [options](#options)
+ * @return {Array} Returns an array of matches
+ * @summary false
+ * @api public
+ */
- if (node.type === 'open') {
- return invalid ? (prefix + node.value) : '(';
- }
+const micromatch = (list, patterns, options) => {
+ patterns = [].concat(patterns);
+ list = [].concat(list);
- if (node.type === 'close') {
- return invalid ? (prefix + node.value) : ')';
- }
+ let omit = new Set();
+ let keep = new Set();
+ let items = new Set();
+ let negatives = 0;
- if (node.type === 'comma') {
- return node.prev.type === 'comma' ? '' : (invalid ? node.value : '|');
+ let onResult = state => {
+ items.add(state.output);
+ if (options && options.onResult) {
+ options.onResult(state);
}
+ };
- if (node.value) {
- return node.value;
- }
+ for (let i = 0; i < patterns.length; i++) {
+ let isMatch = picomatch(String(patterns[i]), { ...options, onResult }, true);
+ let negated = isMatch.state.negated || isMatch.state.negatedExtglob;
+ if (negated) negatives++;
- if (node.nodes && node.ranges > 0) {
- let args = utils.reduce(node.nodes);
- let range = fill(...args, { ...options, wrap: false, toRegex: true });
+ for (let item of list) {
+ let matched = isMatch(item, true);
- if (range.length !== 0) {
- return args.length > 1 && range.length > 1 ? `(${range})` : range;
- }
- }
+ let match = negated ? !matched.isMatch : matched.isMatch;
+ if (!match) continue;
- if (node.nodes) {
- for (let child of node.nodes) {
- output += walk(child, node);
+ if (negated) {
+ omit.add(matched.output);
+ } else {
+ omit.delete(matched.output);
+ keep.add(matched.output);
}
}
- return output;
- };
-
- return walk(ast);
-};
-
-module.exports = compile;
-
-
-/***/ }),
-
-/***/ 1756:
-/***/ ((module) => {
-
-"use strict";
+ }
+ let result = negatives === patterns.length ? [...items] : [...keep];
+ let matches = result.filter(item => !omit.has(item));
-module.exports = {
- MAX_LENGTH: 1024 * 64,
+ if (options && matches.length === 0) {
+ if (options.failglob === true) {
+ throw new Error(`No matches found for "${patterns.join(', ')}"`);
+ }
- // Digits
- CHAR_0: '0', /* 0 */
- CHAR_9: '9', /* 9 */
+ if (options.nonull === true || options.nullglob === true) {
+ return options.unescape ? patterns.map(p => p.replace(/\\/g, '')) : patterns;
+ }
+ }
- // Alphabet chars.
- CHAR_UPPERCASE_A: 'A', /* A */
- CHAR_LOWERCASE_A: 'a', /* a */
- CHAR_UPPERCASE_Z: 'Z', /* Z */
- CHAR_LOWERCASE_Z: 'z', /* z */
+ return matches;
+};
- CHAR_LEFT_PARENTHESES: '(', /* ( */
- CHAR_RIGHT_PARENTHESES: ')', /* ) */
+/**
+ * Backwards compatibility
+ */
- CHAR_ASTERISK: '*', /* * */
+micromatch.match = micromatch;
- // Non-alphabetic chars.
- CHAR_AMPERSAND: '&', /* & */
- CHAR_AT: '@', /* @ */
- CHAR_BACKSLASH: '\\', /* \ */
- CHAR_BACKTICK: '`', /* ` */
- CHAR_CARRIAGE_RETURN: '\r', /* \r */
- CHAR_CIRCUMFLEX_ACCENT: '^', /* ^ */
- CHAR_COLON: ':', /* : */
- CHAR_COMMA: ',', /* , */
- CHAR_DOLLAR: '$', /* . */
- CHAR_DOT: '.', /* . */
- CHAR_DOUBLE_QUOTE: '"', /* " */
- CHAR_EQUAL: '=', /* = */
- CHAR_EXCLAMATION_MARK: '!', /* ! */
- CHAR_FORM_FEED: '\f', /* \f */
- CHAR_FORWARD_SLASH: '/', /* / */
- CHAR_HASH: '#', /* # */
- CHAR_HYPHEN_MINUS: '-', /* - */
- CHAR_LEFT_ANGLE_BRACKET: '<', /* < */
- CHAR_LEFT_CURLY_BRACE: '{', /* { */
- CHAR_LEFT_SQUARE_BRACKET: '[', /* [ */
- CHAR_LINE_FEED: '\n', /* \n */
- CHAR_NO_BREAK_SPACE: '\u00A0', /* \u00A0 */
- CHAR_PERCENT: '%', /* % */
- CHAR_PLUS: '+', /* + */
- CHAR_QUESTION_MARK: '?', /* ? */
- CHAR_RIGHT_ANGLE_BRACKET: '>', /* > */
- CHAR_RIGHT_CURLY_BRACE: '}', /* } */
- CHAR_RIGHT_SQUARE_BRACKET: ']', /* ] */
- CHAR_SEMICOLON: ';', /* ; */
- CHAR_SINGLE_QUOTE: '\'', /* ' */
- CHAR_SPACE: ' ', /* */
- CHAR_TAB: '\t', /* \t */
- CHAR_UNDERSCORE: '_', /* _ */
- CHAR_VERTICAL_LINE: '|', /* | */
- CHAR_ZERO_WIDTH_NOBREAK_SPACE: '\uFEFF' /* \uFEFF */
-};
+/**
+ * Returns a matcher function from the given glob `pattern` and `options`.
+ * The returned function takes a string to match as its only argument and returns
+ * true if the string is a match.
+ *
+ * ```js
+ * const mm = require('micromatch');
+ * // mm.matcher(pattern[, options]);
+ *
+ * const isMatch = mm.matcher('*.!(*a)');
+ * console.log(isMatch('a.a')); //=> false
+ * console.log(isMatch('a.b')); //=> true
+ * ```
+ * @param {String} `pattern` Glob pattern
+ * @param {Object} `options`
+ * @return {Function} Returns a matcher function.
+ * @api public
+ */
+micromatch.matcher = (pattern, options) => picomatch(pattern, options);
-/***/ }),
+/**
+ * Returns true if **any** of the given glob `patterns` match the specified `string`.
+ *
+ * ```js
+ * const mm = require('micromatch');
+ * // mm.isMatch(string, patterns[, options]);
+ *
+ * console.log(mm.isMatch('a.a', ['b.*', '*.a'])); //=> true
+ * console.log(mm.isMatch('a.a', 'b.*')); //=> false
+ * ```
+ * @param {String} `str` The string to test.
+ * @param {String|Array} `patterns` One or more glob patterns to use for matching.
+ * @param {Object} `[options]` See available [options](#options).
+ * @return {Boolean} Returns true if any patterns match `str`
+ * @api public
+ */
-/***/ 8926:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+micromatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
-"use strict";
+/**
+ * Backwards compatibility
+ */
+micromatch.any = micromatch.isMatch;
-const fill = __nccwpck_require__(4652);
-const stringify = __nccwpck_require__(470);
-const utils = __nccwpck_require__(2081);
+/**
+ * Returns a list of strings that _**do not match any**_ of the given `patterns`.
+ *
+ * ```js
+ * const mm = require('micromatch');
+ * // mm.not(list, patterns[, options]);
+ *
+ * console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a'));
+ * //=> ['b.b', 'c.c']
+ * ```
+ * @param {Array} `list` Array of strings to match.
+ * @param {String|Array} `patterns` One or more glob pattern to use for matching.
+ * @param {Object} `options` See available [options](#options) for changing how matches are performed
+ * @return {Array} Returns an array of strings that **do not match** the given patterns.
+ * @api public
+ */
-const append = (queue = '', stash = '', enclose = false) => {
- let result = [];
+micromatch.not = (list, patterns, options = {}) => {
+ patterns = [].concat(patterns).map(String);
+ let result = new Set();
+ let items = [];
- queue = [].concat(queue);
- stash = [].concat(stash);
+ let onResult = state => {
+ if (options.onResult) options.onResult(state);
+ items.push(state.output);
+ };
- if (!stash.length) return queue;
- if (!queue.length) {
- return enclose ? utils.flatten(stash).map(ele => `{${ele}}`) : stash;
- }
+ let matches = new Set(micromatch(list, patterns, { ...options, onResult }));
- for (let item of queue) {
- if (Array.isArray(item)) {
- for (let value of item) {
- result.push(append(value, stash, enclose));
- }
- } else {
- for (let ele of stash) {
- if (enclose === true && typeof ele === 'string') ele = `{${ele}}`;
- result.push(Array.isArray(ele) ? append(item, ele, enclose) : (item + ele));
- }
+ for (let item of items) {
+ if (!matches.has(item)) {
+ result.add(item);
}
}
- return utils.flatten(result);
+ return [...result];
};
-const expand = (ast, options = {}) => {
- let rangeLimit = options.rangeLimit === void 0 ? 1000 : options.rangeLimit;
-
- let walk = (node, parent = {}) => {
- node.queue = [];
+/**
+ * Returns true if the given `string` contains the given pattern. Similar
+ * to [.isMatch](#isMatch) but the pattern can match any part of the string.
+ *
+ * ```js
+ * var mm = require('micromatch');
+ * // mm.contains(string, pattern[, options]);
+ *
+ * console.log(mm.contains('aa/bb/cc', '*b'));
+ * //=> true
+ * console.log(mm.contains('aa/bb/cc', '*d'));
+ * //=> false
+ * ```
+ * @param {String} `str` The string to match.
+ * @param {String|Array} `patterns` Glob pattern to use for matching.
+ * @param {Object} `options` See available [options](#options) for changing how matches are performed
+ * @return {Boolean} Returns true if any of the patterns matches any part of `str`.
+ * @api public
+ */
- let p = parent;
- let q = parent.queue;
+micromatch.contains = (str, pattern, options) => {
+ if (typeof str !== 'string') {
+ throw new TypeError(`Expected a string: "${util.inspect(str)}"`);
+ }
- while (p.type !== 'brace' && p.type !== 'root' && p.parent) {
- p = p.parent;
- q = p.queue;
- }
+ if (Array.isArray(pattern)) {
+ return pattern.some(p => micromatch.contains(str, p, options));
+ }
- if (node.invalid || node.dollar) {
- q.push(append(q.pop(), stringify(node, options)));
- return;
+ if (typeof pattern === 'string') {
+ if (isEmptyString(str) || isEmptyString(pattern)) {
+ return false;
}
- if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) {
- q.push(append(q.pop(), ['{}']));
- return;
+ if (str.includes(pattern) || (str.startsWith('./') && str.slice(2).includes(pattern))) {
+ return true;
}
+ }
- if (node.nodes && node.ranges > 0) {
- let args = utils.reduce(node.nodes);
+ return micromatch.isMatch(str, pattern, { ...options, contains: true });
+};
- if (utils.exceedsLimit(...args, options.step, rangeLimit)) {
- throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.');
- }
+/**
+ * Filter the keys of the given object with the given `glob` pattern
+ * and `options`. Does not attempt to match nested keys. If you need this feature,
+ * use [glob-object][] instead.
+ *
+ * ```js
+ * const mm = require('micromatch');
+ * // mm.matchKeys(object, patterns[, options]);
+ *
+ * const obj = { aa: 'a', ab: 'b', ac: 'c' };
+ * console.log(mm.matchKeys(obj, '*b'));
+ * //=> { ab: 'b' }
+ * ```
+ * @param {Object} `object` The object with keys to filter.
+ * @param {String|Array} `patterns` One or more glob patterns to use for matching.
+ * @param {Object} `options` See available [options](#options) for changing how matches are performed
+ * @return {Object} Returns an object with only keys that match the given patterns.
+ * @api public
+ */
- let range = fill(...args, options);
- if (range.length === 0) {
- range = stringify(node, options);
- }
+micromatch.matchKeys = (obj, patterns, options) => {
+ if (!utils.isObject(obj)) {
+ throw new TypeError('Expected the first argument to be an object');
+ }
+ let keys = micromatch(Object.keys(obj), patterns, options);
+ let res = {};
+ for (let key of keys) res[key] = obj[key];
+ return res;
+};
- q.push(append(q.pop(), range));
- node.nodes = [];
- return;
- }
+/**
+ * Returns true if some of the strings in the given `list` match any of the given glob `patterns`.
+ *
+ * ```js
+ * const mm = require('micromatch');
+ * // mm.some(list, patterns[, options]);
+ *
+ * console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
+ * // true
+ * console.log(mm.some(['foo.js'], ['*.js', '!foo.js']));
+ * // false
+ * ```
+ * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found.
+ * @param {String|Array} `patterns` One or more glob patterns to use for matching.
+ * @param {Object} `options` See available [options](#options) for changing how matches are performed
+ * @return {Boolean} Returns true if any `patterns` matches any of the strings in `list`
+ * @api public
+ */
- let enclose = utils.encloseBrace(node);
- let queue = node.queue;
- let block = node;
+micromatch.some = (list, patterns, options) => {
+ let items = [].concat(list);
- while (block.type !== 'brace' && block.type !== 'root' && block.parent) {
- block = block.parent;
- queue = block.queue;
+ for (let pattern of [].concat(patterns)) {
+ let isMatch = picomatch(String(pattern), options);
+ if (items.some(item => isMatch(item))) {
+ return true;
}
+ }
+ return false;
+};
- for (let i = 0; i < node.nodes.length; i++) {
- let child = node.nodes[i];
-
- if (child.type === 'comma' && node.type === 'brace') {
- if (i === 1) queue.push('');
- queue.push('');
- continue;
- }
-
- if (child.type === 'close') {
- q.push(append(q.pop(), queue, enclose));
- continue;
- }
+/**
+ * Returns true if every string in the given `list` matches
+ * any of the given glob `patterns`.
+ *
+ * ```js
+ * const mm = require('micromatch');
+ * // mm.every(list, patterns[, options]);
+ *
+ * console.log(mm.every('foo.js', ['foo.js']));
+ * // true
+ * console.log(mm.every(['foo.js', 'bar.js'], ['*.js']));
+ * // true
+ * console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
+ * // false
+ * console.log(mm.every(['foo.js'], ['*.js', '!foo.js']));
+ * // false
+ * ```
+ * @param {String|Array} `list` The string or array of strings to test.
+ * @param {String|Array} `patterns` One or more glob patterns to use for matching.
+ * @param {Object} `options` See available [options](#options) for changing how matches are performed
+ * @return {Boolean} Returns true if all `patterns` matches all of the strings in `list`
+ * @api public
+ */
- if (child.value && child.type !== 'open') {
- queue.push(append(queue.pop(), child.value));
- continue;
- }
+micromatch.every = (list, patterns, options) => {
+ let items = [].concat(list);
- if (child.nodes) {
- walk(child, node);
- }
+ for (let pattern of [].concat(patterns)) {
+ let isMatch = picomatch(String(pattern), options);
+ if (!items.every(item => isMatch(item))) {
+ return false;
}
+ }
+ return true;
+};
- return queue;
- };
+/**
+ * Returns true if **all** of the given `patterns` match
+ * the specified string.
+ *
+ * ```js
+ * const mm = require('micromatch');
+ * // mm.all(string, patterns[, options]);
+ *
+ * console.log(mm.all('foo.js', ['foo.js']));
+ * // true
+ *
+ * console.log(mm.all('foo.js', ['*.js', '!foo.js']));
+ * // false
+ *
+ * console.log(mm.all('foo.js', ['*.js', 'foo.js']));
+ * // true
+ *
+ * console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js']));
+ * // true
+ * ```
+ * @param {String|Array} `str` The string to test.
+ * @param {String|Array} `patterns` One or more glob patterns to use for matching.
+ * @param {Object} `options` See available [options](#options) for changing how matches are performed
+ * @return {Boolean} Returns true if any patterns match `str`
+ * @api public
+ */
- return utils.flatten(walk(ast));
+micromatch.all = (str, patterns, options) => {
+ if (typeof str !== 'string') {
+ throw new TypeError(`Expected a string: "${util.inspect(str)}"`);
+ }
+
+ return [].concat(patterns).every(p => picomatch(p, options)(str));
};
-module.exports = expand;
+/**
+ * Returns an array of matches captured by `pattern` in `string, or `null` if the pattern did not match.
+ *
+ * ```js
+ * const mm = require('micromatch');
+ * // mm.capture(pattern, string[, options]);
+ *
+ * console.log(mm.capture('test/*.js', 'test/foo.js'));
+ * //=> ['foo']
+ * console.log(mm.capture('test/*.js', 'foo/bar.css'));
+ * //=> null
+ * ```
+ * @param {String} `glob` Glob pattern to use for matching.
+ * @param {String} `input` String to match
+ * @param {Object} `options` See available [options](#options) for changing how matches are performed
+ * @return {Array|null} Returns an array of captures if the input matches the glob pattern, otherwise `null`.
+ * @api public
+ */
+micromatch.capture = (glob, input, options) => {
+ let posix = utils.isWindows(options);
+ let regex = picomatch.makeRe(String(glob), { ...options, capture: true });
+ let match = regex.exec(posix ? utils.toPosixSlashes(input) : input);
-/***/ }),
+ if (match) {
+ return match.slice(1).map(v => v === void 0 ? '' : v);
+ }
+};
-/***/ 6751:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+/**
+ * Create a regular expression from the given glob `pattern`.
+ *
+ * ```js
+ * const mm = require('micromatch');
+ * // mm.makeRe(pattern[, options]);
+ *
+ * console.log(mm.makeRe('*.js'));
+ * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/
+ * ```
+ * @param {String} `pattern` A glob pattern to convert to regex.
+ * @param {Object} `options`
+ * @return {RegExp} Returns a regex created from the given pattern.
+ * @api public
+ */
-"use strict";
+micromatch.makeRe = (...args) => picomatch.makeRe(...args);
+/**
+ * Scan a glob pattern to separate the pattern into segments. Used
+ * by the [split](#split) method.
+ *
+ * ```js
+ * const mm = require('micromatch');
+ * const state = mm.scan(pattern[, options]);
+ * ```
+ * @param {String} `pattern`
+ * @param {Object} `options`
+ * @return {Object} Returns an object with
+ * @api public
+ */
-const stringify = __nccwpck_require__(470);
+micromatch.scan = (...args) => picomatch.scan(...args);
/**
- * Constants
+ * Parse a glob pattern to create the source string for a regular
+ * expression.
+ *
+ * ```js
+ * const mm = require('micromatch');
+ * const state = mm.parse(pattern[, options]);
+ * ```
+ * @param {String} `glob`
+ * @param {Object} `options`
+ * @return {Object} Returns an object with useful properties and output to be used as regex source string.
+ * @api public
*/
-const {
- MAX_LENGTH,
- CHAR_BACKSLASH, /* \ */
- CHAR_BACKTICK, /* ` */
- CHAR_COMMA, /* , */
- CHAR_DOT, /* . */
- CHAR_LEFT_PARENTHESES, /* ( */
- CHAR_RIGHT_PARENTHESES, /* ) */
- CHAR_LEFT_CURLY_BRACE, /* { */
- CHAR_RIGHT_CURLY_BRACE, /* } */
- CHAR_LEFT_SQUARE_BRACKET, /* [ */
- CHAR_RIGHT_SQUARE_BRACKET, /* ] */
- CHAR_DOUBLE_QUOTE, /* " */
- CHAR_SINGLE_QUOTE, /* ' */
- CHAR_NO_BREAK_SPACE,
- CHAR_ZERO_WIDTH_NOBREAK_SPACE
-} = __nccwpck_require__(1756);
+micromatch.parse = (patterns, options) => {
+ let res = [];
+ for (let pattern of [].concat(patterns || [])) {
+ for (let str of braces(String(pattern), options)) {
+ res.push(picomatch.parse(str, options));
+ }
+ }
+ return res;
+};
/**
- * parse
+ * Process the given brace `pattern`.
+ *
+ * ```js
+ * const { braces } = require('micromatch');
+ * console.log(braces('foo/{a,b,c}/bar'));
+ * //=> [ 'foo/(a|b|c)/bar' ]
+ *
+ * console.log(braces('foo/{a,b,c}/bar', { expand: true }));
+ * //=> [ 'foo/a/bar', 'foo/b/bar', 'foo/c/bar' ]
+ * ```
+ * @param {String} `pattern` String with brace pattern to process.
+ * @param {Object} `options` Any [options](#options) to change how expansion is performed. See the [braces][] library for all available options.
+ * @return {Array}
+ * @api public
*/
-const parse = (input, options = {}) => {
- if (typeof input !== 'string') {
- throw new TypeError('Expected a string');
+micromatch.braces = (pattern, options) => {
+ if (typeof pattern !== 'string') throw new TypeError('Expected a string');
+ if ((options && options.nobrace === true) || !/\{.*\}/.test(pattern)) {
+ return [pattern];
}
+ return braces(pattern, options);
+};
- let opts = options || {};
- let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
- if (input.length > max) {
- throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`);
- }
+/**
+ * Expand braces
+ */
- let ast = { type: 'root', input, nodes: [] };
- let stack = [ast];
- let block = ast;
- let prev = ast;
- let brackets = 0;
- let length = input.length;
- let index = 0;
- let depth = 0;
- let value;
- let memo = {};
+micromatch.braceExpand = (pattern, options) => {
+ if (typeof pattern !== 'string') throw new TypeError('Expected a string');
+ return micromatch.braces(pattern, { ...options, expand: true });
+};
- /**
- * Helpers
- */
+/**
+ * Expose micromatch
+ */
- const advance = () => input[index++];
- const push = node => {
- if (node.type === 'text' && prev.type === 'dot') {
- prev.type = 'text';
- }
+module.exports = micromatch;
- if (prev && prev.type === 'text' && node.type === 'text') {
- prev.value += node.value;
- return;
- }
- block.nodes.push(node);
- node.parent = block;
- node.prev = prev;
- prev = node;
- return node;
- };
+/***/ }),
- push({ type: 'bos' });
+/***/ 7426:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- while (index < length) {
- block = stack[stack.length - 1];
- value = advance();
+/*!
+ * mime-db
+ * Copyright(c) 2014 Jonathan Ong
+ * Copyright(c) 2015-2022 Douglas Christopher Wilson
+ * MIT Licensed
+ */
- /**
- * Invalid chars
- */
+/**
+ * Module exports.
+ */
- if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) {
- continue;
- }
+module.exports = __nccwpck_require__(3765)
- /**
- * Escaped chars
- */
- if (value === CHAR_BACKSLASH) {
- push({ type: 'text', value: (options.keepEscaping ? value : '') + advance() });
- continue;
- }
+/***/ }),
- /**
- * Right square bracket (literal): ']'
- */
+/***/ 3583:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- if (value === CHAR_RIGHT_SQUARE_BRACKET) {
- push({ type: 'text', value: '\\' + value });
- continue;
- }
+"use strict";
+/*!
+ * mime-types
+ * Copyright(c) 2014 Jonathan Ong
+ * Copyright(c) 2015 Douglas Christopher Wilson
+ * MIT Licensed
+ */
- /**
- * Left square bracket: '['
- */
- if (value === CHAR_LEFT_SQUARE_BRACKET) {
- brackets++;
- let closed = true;
- let next;
+/**
+ * Module dependencies.
+ * @private
+ */
- while (index < length && (next = advance())) {
- value += next;
+var db = __nccwpck_require__(7426)
+var extname = (__nccwpck_require__(1017).extname)
- if (next === CHAR_LEFT_SQUARE_BRACKET) {
- brackets++;
- continue;
- }
+/**
+ * Module variables.
+ * @private
+ */
- if (next === CHAR_BACKSLASH) {
- value += advance();
- continue;
- }
+var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/
+var TEXT_TYPE_REGEXP = /^text\//i
- if (next === CHAR_RIGHT_SQUARE_BRACKET) {
- brackets--;
+/**
+ * Module exports.
+ * @public
+ */
- if (brackets === 0) {
- break;
- }
- }
- }
+exports.charset = charset
+exports.charsets = { lookup: charset }
+exports.contentType = contentType
+exports.extension = extension
+exports.extensions = Object.create(null)
+exports.lookup = lookup
+exports.types = Object.create(null)
- push({ type: 'text', value });
- continue;
- }
+// Populate the extensions/types maps
+populateMaps(exports.extensions, exports.types)
- /**
- * Parentheses
- */
+/**
+ * Get the default charset for a MIME type.
+ *
+ * @param {string} type
+ * @return {boolean|string}
+ */
- if (value === CHAR_LEFT_PARENTHESES) {
- block = push({ type: 'paren', nodes: [] });
- stack.push(block);
- push({ type: 'text', value });
- continue;
- }
+function charset (type) {
+ if (!type || typeof type !== 'string') {
+ return false
+ }
- if (value === CHAR_RIGHT_PARENTHESES) {
- if (block.type !== 'paren') {
- push({ type: 'text', value });
- continue;
- }
- block = stack.pop();
- push({ type: 'text', value });
- block = stack[stack.length - 1];
- continue;
- }
+ // TODO: use media-typer
+ var match = EXTRACT_TYPE_REGEXP.exec(type)
+ var mime = match && db[match[1].toLowerCase()]
- /**
- * Quotes: '|"|`
- */
+ if (mime && mime.charset) {
+ return mime.charset
+ }
- if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) {
- let open = value;
- let next;
+ // default text/* to utf-8
+ if (match && TEXT_TYPE_REGEXP.test(match[1])) {
+ return 'UTF-8'
+ }
- if (options.keepQuotes !== true) {
- value = '';
- }
+ return false
+}
- while (index < length && (next = advance())) {
- if (next === CHAR_BACKSLASH) {
- value += next + advance();
- continue;
- }
+/**
+ * Create a full Content-Type header given a MIME type or extension.
+ *
+ * @param {string} str
+ * @return {boolean|string}
+ */
- if (next === open) {
- if (options.keepQuotes === true) value += next;
- break;
- }
+function contentType (str) {
+ // TODO: should this even be in this module?
+ if (!str || typeof str !== 'string') {
+ return false
+ }
- value += next;
- }
+ var mime = str.indexOf('/') === -1
+ ? exports.lookup(str)
+ : str
- push({ type: 'text', value });
- continue;
- }
+ if (!mime) {
+ return false
+ }
- /**
- * Left curly brace: '{'
- */
+ // TODO: use content-type or other module
+ if (mime.indexOf('charset') === -1) {
+ var charset = exports.charset(mime)
+ if (charset) mime += '; charset=' + charset.toLowerCase()
+ }
- if (value === CHAR_LEFT_CURLY_BRACE) {
- depth++;
+ return mime
+}
- let dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true;
- let brace = {
- type: 'brace',
- open: true,
- close: false,
- dollar,
- depth,
- commas: 0,
- ranges: 0,
- nodes: []
- };
+/**
+ * Get the default extension for a MIME type.
+ *
+ * @param {string} type
+ * @return {boolean|string}
+ */
- block = push(brace);
- stack.push(block);
- push({ type: 'open', value });
- continue;
- }
+function extension (type) {
+ if (!type || typeof type !== 'string') {
+ return false
+ }
- /**
- * Right curly brace: '}'
- */
+ // TODO: use media-typer
+ var match = EXTRACT_TYPE_REGEXP.exec(type)
- if (value === CHAR_RIGHT_CURLY_BRACE) {
- if (block.type !== 'brace') {
- push({ type: 'text', value });
- continue;
- }
+ // get extensions
+ var exts = match && exports.extensions[match[1].toLowerCase()]
- let type = 'close';
- block = stack.pop();
- block.close = true;
+ if (!exts || !exts.length) {
+ return false
+ }
- push({ type, value });
- depth--;
+ return exts[0]
+}
- block = stack[stack.length - 1];
- continue;
- }
+/**
+ * Lookup the MIME type for a file path/extension.
+ *
+ * @param {string} path
+ * @return {boolean|string}
+ */
- /**
- * Comma: ','
- */
+function lookup (path) {
+ if (!path || typeof path !== 'string') {
+ return false
+ }
- if (value === CHAR_COMMA && depth > 0) {
- if (block.ranges > 0) {
- block.ranges = 0;
- let open = block.nodes.shift();
- block.nodes = [open, { type: 'text', value: stringify(block) }];
- }
+ // get the extension ("ext" or ".ext" or full path)
+ var extension = extname('x.' + path)
+ .toLowerCase()
+ .substr(1)
- push({ type: 'comma', value });
- block.commas++;
- continue;
- }
+ if (!extension) {
+ return false
+ }
- /**
- * Dot: '.'
- */
+ return exports.types[extension] || false
+}
- if (value === CHAR_DOT && depth > 0 && block.commas === 0) {
- let siblings = block.nodes;
+/**
+ * Populate the extensions and types maps.
+ * @private
+ */
- if (depth === 0 || siblings.length === 0) {
- push({ type: 'text', value });
- continue;
- }
+function populateMaps (extensions, types) {
+ // source preference (least -> most)
+ var preference = ['nginx', 'apache', undefined, 'iana']
- if (prev.type === 'dot') {
- block.range = [];
- prev.value += value;
- prev.type = 'range';
+ Object.keys(db).forEach(function forEachMimeType (type) {
+ var mime = db[type]
+ var exts = mime.extensions
- if (block.nodes.length !== 3 && block.nodes.length !== 5) {
- block.invalid = true;
- block.ranges = 0;
- prev.type = 'text';
- continue;
- }
+ if (!exts || !exts.length) {
+ return
+ }
- block.ranges++;
- block.args = [];
- continue;
- }
+ // mime -> extensions
+ extensions[type] = exts
- if (prev.type === 'range') {
- siblings.pop();
+ // extension -> mime
+ for (var i = 0; i < exts.length; i++) {
+ var extension = exts[i]
- let before = siblings[siblings.length - 1];
- before.value += prev.value + value;
- prev = before;
- block.ranges--;
- continue;
+ if (types[extension]) {
+ var from = preference.indexOf(db[types[extension]].source)
+ var to = preference.indexOf(mime.source)
+
+ if (types[extension] !== 'application/octet-stream' &&
+ (from > to || (from === to && types[extension].substr(0, 12) === 'application/'))) {
+ // skip the remapping
+ continue
+ }
}
- push({ type: 'dot', value });
- continue;
+ // set the extension -> mime
+ types[extension] = type
}
+ })
+}
- /**
- * Text
- */
-
- push({ type: 'text', value });
- }
- // Mark imbalanced braces and brackets as invalid
- do {
- block = stack.pop();
+/***/ }),
- if (block.type !== 'root') {
- block.nodes.forEach(node => {
- if (!node.nodes) {
- if (node.type === 'open') node.isOpen = true;
- if (node.type === 'close') node.isClose = true;
- if (!node.nodes) node.type = 'text';
- node.invalid = true;
- }
- });
+/***/ 3973:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // get the location of the block on parent.nodes (block's siblings)
- let parent = stack[stack.length - 1];
- let index = parent.nodes.indexOf(block);
- // replace the (invalid) block with it's nodes
- parent.nodes.splice(index, 1, ...block.nodes);
- }
- } while (stack.length > 0);
+module.exports = minimatch
+minimatch.Minimatch = Minimatch
- push({ type: 'eos' });
- return ast;
-};
+var path = (function () { try { return __nccwpck_require__(1017) } catch (e) {}}()) || {
+ sep: '/'
+}
+minimatch.sep = path.sep
-module.exports = parse;
+var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {}
+var expand = __nccwpck_require__(3717)
+var plTypes = {
+ '!': { open: '(?:(?!(?:', close: '))[^/]*?)'},
+ '?': { open: '(?:', close: ')?' },
+ '+': { open: '(?:', close: ')+' },
+ '*': { open: '(?:', close: ')*' },
+ '@': { open: '(?:', close: ')' }
+}
-/***/ }),
+// any single thing other than /
+// don't need to escape / when using new RegExp()
+var qmark = '[^/]'
-/***/ 470:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+// * => any number of characters
+var star = qmark + '*?'
-"use strict";
+// ** when dots are allowed. Anything goes, except .. and .
+// not (^ or / followed by one or two dots followed by $ or /),
+// followed by anything, any number of times.
+var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?'
+// not a ^ or / followed by a dot,
+// followed by anything, any number of times.
+var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?'
-const utils = __nccwpck_require__(2081);
+// characters that need to be escaped in RegExp.
+var reSpecials = charSet('().*{}+?[]^$\\!')
-module.exports = (ast, options = {}) => {
- let stringify = (node, parent = {}) => {
- let invalidBlock = options.escapeInvalid && utils.isInvalidBrace(parent);
- let invalidNode = node.invalid === true && options.escapeInvalid === true;
- let output = '';
+// "abc" -> { a:true, b:true, c:true }
+function charSet (s) {
+ return s.split('').reduce(function (set, c) {
+ set[c] = true
+ return set
+ }, {})
+}
- if (node.value) {
- if ((invalidBlock || invalidNode) && utils.isOpenOrClose(node)) {
- return '\\' + node.value;
- }
- return node.value;
- }
+// normalizes slashes.
+var slashSplit = /\/+/
- if (node.value) {
- return node.value;
- }
+minimatch.filter = filter
+function filter (pattern, options) {
+ options = options || {}
+ return function (p, i, list) {
+ return minimatch(p, pattern, options)
+ }
+}
- if (node.nodes) {
- for (let child of node.nodes) {
- output += stringify(child);
- }
- }
- return output;
- };
+function ext (a, b) {
+ b = b || {}
+ var t = {}
+ Object.keys(a).forEach(function (k) {
+ t[k] = a[k]
+ })
+ Object.keys(b).forEach(function (k) {
+ t[k] = b[k]
+ })
+ return t
+}
- return stringify(ast);
-};
+minimatch.defaults = function (def) {
+ if (!def || typeof def !== 'object' || !Object.keys(def).length) {
+ return minimatch
+ }
+ var orig = minimatch
+ var m = function minimatch (p, pattern, options) {
+ return orig(p, pattern, ext(def, options))
+ }
-/***/ }),
+ m.Minimatch = function Minimatch (pattern, options) {
+ return new orig.Minimatch(pattern, ext(def, options))
+ }
+ m.Minimatch.defaults = function defaults (options) {
+ return orig.defaults(ext(def, options)).Minimatch
+ }
-/***/ 2081:
-/***/ ((__unused_webpack_module, exports) => {
+ m.filter = function filter (pattern, options) {
+ return orig.filter(pattern, ext(def, options))
+ }
-"use strict";
+ m.defaults = function defaults (options) {
+ return orig.defaults(ext(def, options))
+ }
+ m.makeRe = function makeRe (pattern, options) {
+ return orig.makeRe(pattern, ext(def, options))
+ }
-exports.isInteger = num => {
- if (typeof num === 'number') {
- return Number.isInteger(num);
+ m.braceExpand = function braceExpand (pattern, options) {
+ return orig.braceExpand(pattern, ext(def, options))
}
- if (typeof num === 'string' && num.trim() !== '') {
- return Number.isInteger(Number(num));
+
+ m.match = function (list, pattern, options) {
+ return orig.match(list, pattern, ext(def, options))
}
- return false;
-};
-/**
- * Find a node of the given type
- */
+ return m
+}
-exports.find = (node, type) => node.nodes.find(node => node.type === type);
+Minimatch.defaults = function (def) {
+ return minimatch.defaults(def).Minimatch
+}
-/**
- * Find a node of the given type
- */
+function minimatch (p, pattern, options) {
+ assertValidPattern(pattern)
-exports.exceedsLimit = (min, max, step = 1, limit) => {
- if (limit === false) return false;
- if (!exports.isInteger(min) || !exports.isInteger(max)) return false;
- return ((Number(max) - Number(min)) / Number(step)) >= limit;
-};
+ if (!options) options = {}
-/**
- * Escape the given node with '\\' before node.value
- */
+ // shortcut: comments match nothing.
+ if (!options.nocomment && pattern.charAt(0) === '#') {
+ return false
+ }
-exports.escapeNode = (block, n = 0, type) => {
- let node = block.nodes[n];
- if (!node) return;
+ return new Minimatch(pattern, options).match(p)
+}
- if ((type && node.type === type) || node.type === 'open' || node.type === 'close') {
- if (node.escaped !== true) {
- node.value = '\\' + node.value;
- node.escaped = true;
- }
+function Minimatch (pattern, options) {
+ if (!(this instanceof Minimatch)) {
+ return new Minimatch(pattern, options)
}
-};
-/**
- * Returns true if the given brace node should be enclosed in literal braces
- */
+ assertValidPattern(pattern)
-exports.encloseBrace = node => {
- if (node.type !== 'brace') return false;
- if ((node.commas >> 0 + node.ranges >> 0) === 0) {
- node.invalid = true;
- return true;
- }
- return false;
-};
+ if (!options) options = {}
-/**
- * Returns true if a brace node is invalid.
- */
+ pattern = pattern.trim()
-exports.isInvalidBrace = block => {
- if (block.type !== 'brace') return false;
- if (block.invalid === true || block.dollar) return true;
- if ((block.commas >> 0 + block.ranges >> 0) === 0) {
- block.invalid = true;
- return true;
- }
- if (block.open !== true || block.close !== true) {
- block.invalid = true;
- return true;
+ // windows support: need to use /, not \
+ if (!options.allowWindowsEscape && path.sep !== '/') {
+ pattern = pattern.split(path.sep).join('/')
}
- return false;
-};
-/**
- * Returns true if a node is an open or close node
- */
+ this.options = options
+ this.set = []
+ this.pattern = pattern
+ this.regexp = null
+ this.negate = false
+ this.comment = false
+ this.empty = false
+ this.partial = !!options.partial
-exports.isOpenOrClose = node => {
- if (node.type === 'open' || node.type === 'close') {
- return true;
- }
- return node.open === true || node.close === true;
-};
+ // make the set of regexps etc.
+ this.make()
+}
-/**
- * Reduce an array of text nodes.
- */
+Minimatch.prototype.debug = function () {}
-exports.reduce = nodes => nodes.reduce((acc, node) => {
- if (node.type === 'text') acc.push(node.value);
- if (node.type === 'range') node.type = 'text';
- return acc;
-}, []);
+Minimatch.prototype.make = make
+function make () {
+ var pattern = this.pattern
+ var options = this.options
-/**
- * Flatten an array
- */
+ // empty patterns and comments match nothing.
+ if (!options.nocomment && pattern.charAt(0) === '#') {
+ this.comment = true
+ return
+ }
+ if (!pattern) {
+ this.empty = true
+ return
+ }
-exports.flatten = (...args) => {
- const result = [];
- const flat = arr => {
- for (let i = 0; i < arr.length; i++) {
- let ele = arr[i];
- Array.isArray(ele) ? flat(ele, result) : ele !== void 0 && result.push(ele);
- }
- return result;
- };
- flat(args);
- return result;
-};
+ // step 1: figure out negation, etc.
+ this.parseNegate()
+ // step 2: expand braces
+ var set = this.globSet = this.braceExpand()
-/***/ }),
+ if (options.debug) this.debug = function debug() { console.error.apply(console, arguments) }
-/***/ 4652:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ this.debug(this.pattern, set)
-"use strict";
-/*!
- * fill-range
- *
- * Copyright (c) 2014-present, Jon Schlinkert.
- * Licensed under the MIT License.
- */
+ // step 3: now we have a set, so turn each one into a series of path-portion
+ // matching patterns.
+ // These will be regexps, except in the case of "**", which is
+ // set to the GLOBSTAR object for globstar behavior,
+ // and will not contain any / characters
+ set = this.globParts = set.map(function (s) {
+ return s.split(slashSplit)
+ })
+ this.debug(this.pattern, set)
+ // glob --> regexps
+ set = set.map(function (s, si, set) {
+ return s.map(this.parse, this)
+ }, this)
-const util = __nccwpck_require__(1669);
-const toRegexRange = __nccwpck_require__(151);
+ this.debug(this.pattern, set)
-const isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
+ // filter out everything that didn't compile properly.
+ set = set.filter(function (s) {
+ return s.indexOf(false) === -1
+ })
-const transform = toNumber => {
- return value => toNumber === true ? Number(value) : String(value);
-};
+ this.debug(this.pattern, set)
-const isValidValue = value => {
- return typeof value === 'number' || (typeof value === 'string' && value !== '');
-};
+ this.set = set
+}
-const isNumber = num => Number.isInteger(+num);
+Minimatch.prototype.parseNegate = parseNegate
+function parseNegate () {
+ var pattern = this.pattern
+ var negate = false
+ var options = this.options
+ var negateOffset = 0
-const zeros = input => {
- let value = `${input}`;
- let index = -1;
- if (value[0] === '-') value = value.slice(1);
- if (value === '0') return false;
- while (value[++index] === '0');
- return index > 0;
-};
+ if (options.nonegate) return
-const stringify = (start, end, options) => {
- if (typeof start === 'string' || typeof end === 'string') {
- return true;
+ for (var i = 0, l = pattern.length
+ ; i < l && pattern.charAt(i) === '!'
+ ; i++) {
+ negate = !negate
+ negateOffset++
}
- return options.stringify === true;
-};
-const pad = (input, maxLength, toNumber) => {
- if (maxLength > 0) {
- let dash = input[0] === '-' ? '-' : '';
- if (dash) input = input.slice(1);
- input = (dash + input.padStart(dash ? maxLength - 1 : maxLength, '0'));
- }
- if (toNumber === false) {
- return String(input);
- }
- return input;
-};
+ if (negateOffset) this.pattern = pattern.substr(negateOffset)
+ this.negate = negate
+}
-const toMaxLen = (input, maxLength) => {
- let negative = input[0] === '-' ? '-' : '';
- if (negative) {
- input = input.slice(1);
- maxLength--;
+// Brace expansion:
+// a{b,c}d -> abd acd
+// a{b,}c -> abc ac
+// a{0..3}d -> a0d a1d a2d a3d
+// a{b,c{d,e}f}g -> abg acdfg acefg
+// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
+//
+// Invalid sets are not expanded.
+// a{2..}b -> a{2..}b
+// a{b}c -> a{b}c
+minimatch.braceExpand = function (pattern, options) {
+ return braceExpand(pattern, options)
+}
+
+Minimatch.prototype.braceExpand = braceExpand
+
+function braceExpand (pattern, options) {
+ if (!options) {
+ if (this instanceof Minimatch) {
+ options = this.options
+ } else {
+ options = {}
+ }
}
- while (input.length < maxLength) input = '0' + input;
- return negative ? ('-' + input) : input;
-};
-const toSequence = (parts, options) => {
- parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
- parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
+ pattern = typeof pattern === 'undefined'
+ ? this.pattern : pattern
- let prefix = options.capture ? '' : '?:';
- let positives = '';
- let negatives = '';
- let result;
+ assertValidPattern(pattern)
- if (parts.positives.length) {
- positives = parts.positives.join('|');
+ // Thanks to Yeting Li for
+ // improving this regexp to avoid a ReDOS vulnerability.
+ if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
+ // shortcut. no need to expand.
+ return [pattern]
}
- if (parts.negatives.length) {
- negatives = `-(${prefix}${parts.negatives.join('|')})`;
- }
+ return expand(pattern)
+}
- if (positives && negatives) {
- result = `${positives}|${negatives}`;
- } else {
- result = positives || negatives;
+var MAX_PATTERN_LENGTH = 1024 * 64
+var assertValidPattern = function (pattern) {
+ if (typeof pattern !== 'string') {
+ throw new TypeError('invalid pattern')
}
- if (options.wrap) {
- return `(${prefix}${result})`;
+ if (pattern.length > MAX_PATTERN_LENGTH) {
+ throw new TypeError('pattern is too long')
}
+}
- return result;
-};
+// parse a component of the expanded set.
+// At this point, no pattern may contain "/" in it
+// so we're going to return a 2d array, where each entry is the full
+// pattern, split on '/', and then turned into a regular expression.
+// A regexp is made at the end which joins each array with an
+// escaped /, and another full one which joins each regexp with |.
+//
+// Following the lead of Bash 4.1, note that "**" only has special meaning
+// when it is the *only* thing in a path portion. Otherwise, any series
+// of * is equivalent to a single *. Globstar behavior is enabled by
+// default, and can be disabled by setting options.noglobstar.
+Minimatch.prototype.parse = parse
+var SUBPARSE = {}
+function parse (pattern, isSub) {
+ assertValidPattern(pattern)
-const toRange = (a, b, isNumbers, options) => {
- if (isNumbers) {
- return toRegexRange(a, b, { wrap: false, ...options });
- }
+ var options = this.options
- let start = String.fromCharCode(a);
- if (a === b) return start;
+ // shortcuts
+ if (pattern === '**') {
+ if (!options.noglobstar)
+ return GLOBSTAR
+ else
+ pattern = '*'
+ }
+ if (pattern === '') return ''
- let stop = String.fromCharCode(b);
- return `[${start}-${stop}]`;
-};
+ var re = ''
+ var hasMagic = !!options.nocase
+ var escaping = false
+ // ? => one single character
+ var patternListStack = []
+ var negativeLists = []
+ var stateChar
+ var inClass = false
+ var reClassStart = -1
+ var classStart = -1
+ // . and .. never match anything that doesn't start with .,
+ // even when options.dot is set.
+ var patternStart = pattern.charAt(0) === '.' ? '' // anything
+ // not (start or / followed by . or .. followed by / or end)
+ : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))'
+ : '(?!\\.)'
+ var self = this
-const toRegex = (start, end, options) => {
- if (Array.isArray(start)) {
- let wrap = options.wrap === true;
- let prefix = options.capture ? '' : '?:';
- return wrap ? `(${prefix}${start.join('|')})` : start.join('|');
+ function clearStateChar () {
+ if (stateChar) {
+ // we had some state-tracking character
+ // that wasn't consumed by this pass.
+ switch (stateChar) {
+ case '*':
+ re += star
+ hasMagic = true
+ break
+ case '?':
+ re += qmark
+ hasMagic = true
+ break
+ default:
+ re += '\\' + stateChar
+ break
+ }
+ self.debug('clearStateChar %j %j', stateChar, re)
+ stateChar = false
+ }
}
- return toRegexRange(start, end, options);
-};
-const rangeError = (...args) => {
- return new RangeError('Invalid range arguments: ' + util.inspect(...args));
-};
+ for (var i = 0, len = pattern.length, c
+ ; (i < len) && (c = pattern.charAt(i))
+ ; i++) {
+ this.debug('%s\t%s %s %j', pattern, i, re, c)
-const invalidRange = (start, end, options) => {
- if (options.strictRanges === true) throw rangeError([start, end]);
- return [];
-};
+ // skip over any that are escaped.
+ if (escaping && reSpecials[c]) {
+ re += '\\' + c
+ escaping = false
+ continue
+ }
-const invalidStep = (step, options) => {
- if (options.strictRanges === true) {
- throw new TypeError(`Expected step "${step}" to be a number`);
- }
- return [];
-};
+ switch (c) {
+ /* istanbul ignore next */
+ case '/': {
+ // completely not allowed, even escaped.
+ // Should already be path-split by now.
+ return false
+ }
-const fillNumbers = (start, end, step = 1, options = {}) => {
- let a = Number(start);
- let b = Number(end);
+ case '\\':
+ clearStateChar()
+ escaping = true
+ continue
- if (!Number.isInteger(a) || !Number.isInteger(b)) {
- if (options.strictRanges === true) throw rangeError([start, end]);
- return [];
- }
+ // the various stateChar values
+ // for the "extglob" stuff.
+ case '?':
+ case '*':
+ case '+':
+ case '@':
+ case '!':
+ this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c)
- // fix negative zero
- if (a === 0) a = 0;
- if (b === 0) b = 0;
+ // all of those are literals inside a class, except that
+ // the glob [!a] means [^a] in regexp
+ if (inClass) {
+ this.debug(' in class')
+ if (c === '!' && i === classStart + 1) c = '^'
+ re += c
+ continue
+ }
- let descending = a > b;
- let startString = String(start);
- let endString = String(end);
- let stepString = String(step);
- step = Math.max(Math.abs(step), 1);
+ // if we already have a stateChar, then it means
+ // that there was something like ** or +? in there.
+ // Handle the stateChar, then proceed with this one.
+ self.debug('call clearStateChar %j', stateChar)
+ clearStateChar()
+ stateChar = c
+ // if extglob is disabled, then +(asdf|foo) isn't a thing.
+ // just clear the statechar *now*, rather than even diving into
+ // the patternList stuff.
+ if (options.noext) clearStateChar()
+ continue
- let padded = zeros(startString) || zeros(endString) || zeros(stepString);
- let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0;
- let toNumber = padded === false && stringify(start, end, options) === false;
- let format = options.transform || transform(toNumber);
+ case '(':
+ if (inClass) {
+ re += '('
+ continue
+ }
- if (options.toRegex && step === 1) {
- return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options);
- }
+ if (!stateChar) {
+ re += '\\('
+ continue
+ }
- let parts = { negatives: [], positives: [] };
- let push = num => parts[num < 0 ? 'negatives' : 'positives'].push(Math.abs(num));
- let range = [];
- let index = 0;
+ patternListStack.push({
+ type: stateChar,
+ start: i - 1,
+ reStart: re.length,
+ open: plTypes[stateChar].open,
+ close: plTypes[stateChar].close
+ })
+ // negation is (?:(?!js)[^/]*)
+ re += stateChar === '!' ? '(?:(?!(?:' : '(?:'
+ this.debug('plType %j %j', stateChar, re)
+ stateChar = false
+ continue
- while (descending ? a >= b : a <= b) {
- if (options.toRegex === true && step > 1) {
- push(a);
- } else {
- range.push(pad(format(a, index), maxLen, toNumber));
- }
- a = descending ? a - step : a + step;
- index++;
- }
+ case ')':
+ if (inClass || !patternListStack.length) {
+ re += '\\)'
+ continue
+ }
- if (options.toRegex === true) {
- return step > 1
- ? toSequence(parts, options)
- : toRegex(range, null, { wrap: false, ...options });
- }
+ clearStateChar()
+ hasMagic = true
+ var pl = patternListStack.pop()
+ // negation is (?:(?!js)[^/]*)
+ // The others are (?:)
+ re += pl.close
+ if (pl.type === '!') {
+ negativeLists.push(pl)
+ }
+ pl.reEnd = re.length
+ continue
- return range;
-};
+ case '|':
+ if (inClass || !patternListStack.length || escaping) {
+ re += '\\|'
+ escaping = false
+ continue
+ }
-const fillLetters = (start, end, step = 1, options = {}) => {
- if ((!isNumber(start) && start.length > 1) || (!isNumber(end) && end.length > 1)) {
- return invalidRange(start, end, options);
- }
+ clearStateChar()
+ re += '|'
+ continue
+ // these are mostly the same in regexp and glob
+ case '[':
+ // swallow any state-tracking char before the [
+ clearStateChar()
- let format = options.transform || (val => String.fromCharCode(val));
- let a = `${start}`.charCodeAt(0);
- let b = `${end}`.charCodeAt(0);
+ if (inClass) {
+ re += '\\' + c
+ continue
+ }
- let descending = a > b;
- let min = Math.min(a, b);
- let max = Math.max(a, b);
+ inClass = true
+ classStart = i
+ reClassStart = re.length
+ re += c
+ continue
- if (options.toRegex && step === 1) {
- return toRange(min, max, false, options);
- }
+ case ']':
+ // a right bracket shall lose its special
+ // meaning and represent itself in
+ // a bracket expression if it occurs
+ // first in the list. -- POSIX.2 2.8.3.2
+ if (i === classStart + 1 || !inClass) {
+ re += '\\' + c
+ escaping = false
+ continue
+ }
- let range = [];
- let index = 0;
+ // handle the case where we left a class open.
+ // "[z-a]" is valid, equivalent to "\[z-a\]"
+ // split where the last [ was, make sure we don't have
+ // an invalid re. if so, re-walk the contents of the
+ // would-be class to re-translate any characters that
+ // were passed through as-is
+ // TODO: It would probably be faster to determine this
+ // without a try/catch and a new RegExp, but it's tricky
+ // to do safely. For now, this is safe and works.
+ var cs = pattern.substring(classStart + 1, i)
+ try {
+ RegExp('[' + cs + ']')
+ } catch (er) {
+ // not a valid class!
+ var sp = this.parse(cs, SUBPARSE)
+ re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]'
+ hasMagic = hasMagic || sp[1]
+ inClass = false
+ continue
+ }
- while (descending ? a >= b : a <= b) {
- range.push(format(a, index));
- a = descending ? a - step : a + step;
- index++;
- }
+ // finish up the class.
+ hasMagic = true
+ inClass = false
+ re += c
+ continue
- if (options.toRegex === true) {
- return toRegex(range, null, { wrap: false, options });
- }
+ default:
+ // swallow any state char that wasn't consumed
+ clearStateChar()
- return range;
-};
+ if (escaping) {
+ // no need
+ escaping = false
+ } else if (reSpecials[c]
+ && !(c === '^' && inClass)) {
+ re += '\\'
+ }
-const fill = (start, end, step, options = {}) => {
- if (end == null && isValidValue(start)) {
- return [start];
- }
+ re += c
- if (!isValidValue(start) || !isValidValue(end)) {
- return invalidRange(start, end, options);
- }
+ } // switch
+ } // for
- if (typeof step === 'function') {
- return fill(start, end, 1, { transform: step });
+ // handle the case where we left a class open.
+ // "[abc" is valid, equivalent to "\[abc"
+ if (inClass) {
+ // split where the last [ was, and escape it
+ // this is a huge pita. We now have to re-walk
+ // the contents of the would-be class to re-translate
+ // any characters that were passed through as-is
+ cs = pattern.substr(classStart + 1)
+ sp = this.parse(cs, SUBPARSE)
+ re = re.substr(0, reClassStart) + '\\[' + sp[0]
+ hasMagic = hasMagic || sp[1]
}
- if (isObject(step)) {
- return fill(start, end, 0, step);
- }
+ // handle the case where we had a +( thing at the *end*
+ // of the pattern.
+ // each pattern list stack adds 3 chars, and we need to go through
+ // and escape any | chars that were passed through as-is for the regexp.
+ // Go through and escape them, taking care not to double-escape any
+ // | chars that were already escaped.
+ for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
+ var tail = re.slice(pl.reStart + pl.open.length)
+ this.debug('setting tail', re, pl)
+ // maybe some even number of \, then maybe 1 \, followed by a |
+ tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) {
+ if (!$2) {
+ // the | isn't already escaped, so escape it.
+ $2 = '\\'
+ }
- let opts = { ...options };
- if (opts.capture === true) opts.wrap = true;
- step = step || opts.step || 1;
+ // need to escape all those slashes *again*, without escaping the
+ // one that we need for escaping the | character. As it works out,
+ // escaping an even number of slashes can be done by simply repeating
+ // it exactly after itself. That's why this trick works.
+ //
+ // I am sorry that you have to see this.
+ return $1 + $1 + $2 + '|'
+ })
- if (!isNumber(step)) {
- if (step != null && !isObject(step)) return invalidStep(step, opts);
- return fill(start, end, 1, step);
- }
+ this.debug('tail=%j\n %s', tail, tail, pl, re)
+ var t = pl.type === '*' ? star
+ : pl.type === '?' ? qmark
+ : '\\' + pl.type
- if (isNumber(start) && isNumber(end)) {
- return fillNumbers(start, end, step, opts);
+ hasMagic = true
+ re = re.slice(0, pl.reStart) + t + '\\(' + tail
}
- return fillLetters(start, end, Math.max(Math.abs(step), 1), opts);
-};
-
-module.exports = fill;
-
+ // handle trailing things that only matter at the very end.
+ clearStateChar()
+ if (escaping) {
+ // trailing \\
+ re += '\\\\'
+ }
-/***/ }),
+ // only need to apply the nodot start if the re starts with
+ // something that could conceivably capture a dot
+ var addPatternStart = false
+ switch (re.charAt(0)) {
+ case '[': case '.': case '(': addPatternStart = true
+ }
-/***/ 7399:
-/***/ ((module) => {
+ // Hack to work around lack of negative lookbehind in JS
+ // A pattern like: *.!(x).!(y|z) needs to ensure that a name
+ // like 'a.xyz.yz' doesn't match. So, the first negative
+ // lookahead, has to look ALL the way ahead, to the end of
+ // the pattern.
+ for (var n = negativeLists.length - 1; n > -1; n--) {
+ var nl = negativeLists[n]
-"use strict";
-/*!
- * is-number
- *
- * Copyright (c) 2014-present, Jon Schlinkert.
- * Released under the MIT License.
- */
+ var nlBefore = re.slice(0, nl.reStart)
+ var nlFirst = re.slice(nl.reStart, nl.reEnd - 8)
+ var nlLast = re.slice(nl.reEnd - 8, nl.reEnd)
+ var nlAfter = re.slice(nl.reEnd)
+ nlLast += nlAfter
+ // Handle nested stuff like *(*.js|!(*.json)), where open parens
+ // mean that we should *not* include the ) in the bit that is considered
+ // "after" the negated section.
+ var openParensBefore = nlBefore.split('(').length - 1
+ var cleanAfter = nlAfter
+ for (i = 0; i < openParensBefore; i++) {
+ cleanAfter = cleanAfter.replace(/\)[+*?]?/, '')
+ }
+ nlAfter = cleanAfter
-module.exports = function(num) {
- if (typeof num === 'number') {
- return num - num === 0;
+ var dollar = ''
+ if (nlAfter === '' && isSub !== SUBPARSE) {
+ dollar = '$'
+ }
+ var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast
+ re = newRe
}
- if (typeof num === 'string' && num.trim() !== '') {
- return Number.isFinite ? Number.isFinite(+num) : isFinite(+num);
+
+ // if the re is not "" at this point, then we need to make sure
+ // it doesn't match against an empty path part.
+ // Otherwise a/* will match a/, which it should not.
+ if (re !== '' && hasMagic) {
+ re = '(?=.)' + re
}
- return false;
-};
+ if (addPatternStart) {
+ re = patternStart + re
+ }
-/***/ }),
+ // parsing just a piece of a larger pattern.
+ if (isSub === SUBPARSE) {
+ return [re, hasMagic]
+ }
-/***/ 151:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // skip the regexp for non-magical patterns
+ // unescape anything in it, though, so that it'll be
+ // an exact match against a file etc.
+ if (!hasMagic) {
+ return globUnescape(pattern)
+ }
-"use strict";
-/*!
- * to-regex-range
- *
- * Copyright (c) 2015-present, Jon Schlinkert.
- * Released under the MIT License.
- */
+ var flags = options.nocase ? 'i' : ''
+ try {
+ var regExp = new RegExp('^' + re + '$', flags)
+ } catch (er) /* istanbul ignore next - should be impossible */ {
+ // If it was an invalid regular expression, then it can't match
+ // anything. This trick looks for a character after the end of
+ // the string, which is of course impossible, except in multi-line
+ // mode, but it's not a /m regex.
+ return new RegExp('$.')
+ }
+ regExp._glob = pattern
+ regExp._src = re
+ return regExp
+}
-const isNumber = __nccwpck_require__(7399);
+minimatch.makeRe = function (pattern, options) {
+ return new Minimatch(pattern, options || {}).makeRe()
+}
-const toRegexRange = (min, max, options) => {
- if (isNumber(min) === false) {
- throw new TypeError('toRegexRange: expected the first argument to be a number');
- }
+Minimatch.prototype.makeRe = makeRe
+function makeRe () {
+ if (this.regexp || this.regexp === false) return this.regexp
- if (max === void 0 || min === max) {
- return String(min);
- }
+ // at this point, this.set is a 2d array of partial
+ // pattern strings, or "**".
+ //
+ // It's better to use .match(). This function shouldn't
+ // be used, really, but it's pretty convenient sometimes,
+ // when you just want to work with a regex.
+ var set = this.set
- if (isNumber(max) === false) {
- throw new TypeError('toRegexRange: expected the second argument to be a number.');
+ if (!set.length) {
+ this.regexp = false
+ return this.regexp
}
+ var options = this.options
- let opts = { relaxZeros: true, ...options };
- if (typeof opts.strictZeros === 'boolean') {
- opts.relaxZeros = opts.strictZeros === false;
- }
+ var twoStar = options.noglobstar ? star
+ : options.dot ? twoStarDot
+ : twoStarNoDot
+ var flags = options.nocase ? 'i' : ''
- let relax = String(opts.relaxZeros);
- let shorthand = String(opts.shorthand);
- let capture = String(opts.capture);
- let wrap = String(opts.wrap);
- let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap;
+ var re = set.map(function (pattern) {
+ return pattern.map(function (p) {
+ return (p === GLOBSTAR) ? twoStar
+ : (typeof p === 'string') ? regExpEscape(p)
+ : p._src
+ }).join('\\\/')
+ }).join('|')
- if (toRegexRange.cache.hasOwnProperty(cacheKey)) {
- return toRegexRange.cache[cacheKey].result;
- }
+ // must match entire pattern
+ // ending in a * or ** will make it less strict.
+ re = '^(?:' + re + ')$'
- let a = Math.min(min, max);
- let b = Math.max(min, max);
+ // can match anything, as long as it's not this.
+ if (this.negate) re = '^(?!' + re + ').*$'
- if (Math.abs(a - b) === 1) {
- let result = min + '|' + max;
- if (opts.capture) {
- return `(${result})`;
- }
- if (opts.wrap === false) {
- return result;
- }
- return `(?:${result})`;
+ try {
+ this.regexp = new RegExp(re, flags)
+ } catch (ex) /* istanbul ignore next - should be impossible */ {
+ this.regexp = false
}
+ return this.regexp
+}
- let isPadded = hasPadding(min) || hasPadding(max);
- let state = { min, max, a, b };
- let positives = [];
- let negatives = [];
-
- if (isPadded) {
- state.isPadded = isPadded;
- state.maxLen = String(state.max).length;
+minimatch.match = function (list, pattern, options) {
+ options = options || {}
+ var mm = new Minimatch(pattern, options)
+ list = list.filter(function (f) {
+ return mm.match(f)
+ })
+ if (mm.options.nonull && !list.length) {
+ list.push(pattern)
}
+ return list
+}
- if (a < 0) {
- let newMin = b < 0 ? Math.abs(b) : 1;
- negatives = splitToPatterns(newMin, Math.abs(a), state, opts);
- a = state.a = 0;
- }
+Minimatch.prototype.match = function match (f, partial) {
+ if (typeof partial === 'undefined') partial = this.partial
+ this.debug('match', f, this.pattern)
+ // short-circuit in the case of busted things.
+ // comments, etc.
+ if (this.comment) return false
+ if (this.empty) return f === ''
- if (b >= 0) {
- positives = splitToPatterns(a, b, state, opts);
- }
+ if (f === '/' && partial) return true
- state.negatives = negatives;
- state.positives = positives;
- state.result = collatePatterns(negatives, positives, opts);
+ var options = this.options
- if (opts.capture === true) {
- state.result = `(${state.result})`;
- } else if (opts.wrap !== false && (positives.length + negatives.length) > 1) {
- state.result = `(?:${state.result})`;
+ // windows: need to use /, not \
+ if (path.sep !== '/') {
+ f = f.split(path.sep).join('/')
}
- toRegexRange.cache[cacheKey] = state;
- return state.result;
-};
-
-function collatePatterns(neg, pos, options) {
- let onlyNegative = filterPatterns(neg, pos, '-', false, options) || [];
- let onlyPositive = filterPatterns(pos, neg, '', false, options) || [];
- let intersected = filterPatterns(neg, pos, '-?', true, options) || [];
- let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive);
- return subpatterns.join('|');
-}
+ // treat the test path as a set of pathparts.
+ f = f.split(slashSplit)
+ this.debug(this.pattern, 'split', f)
-function splitToRanges(min, max) {
- let nines = 1;
- let zeros = 1;
+ // just ONE of the pattern sets in this.set needs to match
+ // in order for it to be valid. If negating, then just one
+ // match means that we have failed.
+ // Either way, return on the first hit.
- let stop = countNines(min, nines);
- let stops = new Set([max]);
+ var set = this.set
+ this.debug(this.pattern, 'set', set)
- while (min <= stop && stop <= max) {
- stops.add(stop);
- nines += 1;
- stop = countNines(min, nines);
+ // Find the basename of the path by looking for the last non-empty segment
+ var filename
+ var i
+ for (i = f.length - 1; i >= 0; i--) {
+ filename = f[i]
+ if (filename) break
}
- stop = countZeros(max + 1, zeros) - 1;
-
- while (min < stop && stop <= max) {
- stops.add(stop);
- zeros += 1;
- stop = countZeros(max + 1, zeros) - 1;
+ for (i = 0; i < set.length; i++) {
+ var pattern = set[i]
+ var file = f
+ if (options.matchBase && pattern.length === 1) {
+ file = [filename]
+ }
+ var hit = this.matchOne(file, pattern, partial)
+ if (hit) {
+ if (options.flipNegate) return true
+ return !this.negate
+ }
}
- stops = [...stops];
- stops.sort(compare);
- return stops;
+ // didn't get any hits. this is success if it's a negative
+ // pattern, failure otherwise.
+ if (options.flipNegate) return false
+ return this.negate
}
-/**
- * Convert a range to a regex pattern
- * @param {Number} `start`
- * @param {Number} `stop`
- * @return {String}
- */
+// set partial to true to test if, for example,
+// "/a/b" matches the start of "/*/b/*/d"
+// Partial means, if you run out of file before you run
+// out of pattern, then that's fine, as long as all
+// the parts match.
+Minimatch.prototype.matchOne = function (file, pattern, partial) {
+ var options = this.options
-function rangeToPattern(start, stop, options) {
- if (start === stop) {
- return { pattern: start, count: [], digits: 0 };
- }
+ this.debug('matchOne',
+ { 'this': this, file: file, pattern: pattern })
- let zipped = zip(start, stop);
- let digits = zipped.length;
- let pattern = '';
- let count = 0;
+ this.debug('matchOne', file.length, pattern.length)
- for (let i = 0; i < digits; i++) {
- let [startDigit, stopDigit] = zipped[i];
+ for (var fi = 0,
+ pi = 0,
+ fl = file.length,
+ pl = pattern.length
+ ; (fi < fl) && (pi < pl)
+ ; fi++, pi++) {
+ this.debug('matchOne loop')
+ var p = pattern[pi]
+ var f = file[fi]
- if (startDigit === stopDigit) {
- pattern += startDigit;
+ this.debug(pattern, p, f)
- } else if (startDigit !== '0' || stopDigit !== '9') {
- pattern += toCharacterClass(startDigit, stopDigit, options);
+ // should be impossible.
+ // some invalid regexp stuff in the set.
+ /* istanbul ignore if */
+ if (p === false) return false
- } else {
- count++;
- }
- }
+ if (p === GLOBSTAR) {
+ this.debug('GLOBSTAR', [pattern, p, f])
- if (count) {
- pattern += options.shorthand === true ? '\\d' : '[0-9]';
- }
+ // "**"
+ // a/**/b/**/c would match the following:
+ // a/b/x/y/z/c
+ // a/x/y/z/b/c
+ // a/b/x/b/x/c
+ // a/b/c
+ // To do this, take the rest of the pattern after
+ // the **, and see if it would match the file remainder.
+ // If so, return success.
+ // If not, the ** "swallows" a segment, and try again.
+ // This is recursively awful.
+ //
+ // a/**/b/**/c matching a/b/x/y/z/c
+ // - a matches a
+ // - doublestar
+ // - matchOne(b/x/y/z/c, b/**/c)
+ // - b matches b
+ // - doublestar
+ // - matchOne(x/y/z/c, c) -> no
+ // - matchOne(y/z/c, c) -> no
+ // - matchOne(z/c, c) -> no
+ // - matchOne(c, c) yes, hit
+ var fr = fi
+ var pr = pi + 1
+ if (pr === pl) {
+ this.debug('** at the end')
+ // a ** at the end will just swallow the rest.
+ // We have found a match.
+ // however, it will not swallow /.x, unless
+ // options.dot is set.
+ // . and .. are *never* matched by **, for explosively
+ // exponential reasons.
+ for (; fi < fl; fi++) {
+ if (file[fi] === '.' || file[fi] === '..' ||
+ (!options.dot && file[fi].charAt(0) === '.')) return false
+ }
+ return true
+ }
- return { pattern, count: [count], digits };
-}
+ // ok, let's see if we can swallow whatever we can.
+ while (fr < fl) {
+ var swallowee = file[fr]
-function splitToPatterns(min, max, tok, options) {
- let ranges = splitToRanges(min, max);
- let tokens = [];
- let start = min;
- let prev;
+ this.debug('\nglobstar while', file, fr, pattern, pr, swallowee)
- for (let i = 0; i < ranges.length; i++) {
- let max = ranges[i];
- let obj = rangeToPattern(String(start), String(max), options);
- let zeros = '';
+ // XXX remove this slice. Just pass the start index.
+ if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
+ this.debug('globstar found match!', fr, fl, swallowee)
+ // found a match.
+ return true
+ } else {
+ // can't swallow "." or ".." ever.
+ // can only swallow ".foo" when explicitly asked.
+ if (swallowee === '.' || swallowee === '..' ||
+ (!options.dot && swallowee.charAt(0) === '.')) {
+ this.debug('dot detected!', file, fr, pattern, pr)
+ break
+ }
- if (!tok.isPadded && prev && prev.pattern === obj.pattern) {
- if (prev.count.length > 1) {
- prev.count.pop();
+ // ** swallows a segment, and continue.
+ this.debug('globstar swallow a segment, and continue')
+ fr++
+ }
}
- prev.count.push(obj.count[0]);
- prev.string = prev.pattern + toQuantifier(prev.count);
- start = max + 1;
- continue;
+ // no match was found.
+ // However, in partial mode, we can't say this is necessarily over.
+ // If there's more *pattern* left, then
+ /* istanbul ignore if */
+ if (partial) {
+ // ran out of file
+ this.debug('\n>>> no match, partial?', file, fr, pattern, pr)
+ if (fr === fl) return true
+ }
+ return false
}
- if (tok.isPadded) {
- zeros = padZeros(max, tok, options);
+ // something other than **
+ // non-magic patterns just have to match exactly
+ // patterns with magic have been turned into regexps.
+ var hit
+ if (typeof p === 'string') {
+ hit = f === p
+ this.debug('string match', p, f, hit)
+ } else {
+ hit = f.match(p)
+ this.debug('pattern match', p, f, hit)
}
- obj.string = zeros + obj.pattern + toQuantifier(obj.count);
- tokens.push(obj);
- start = max + 1;
- prev = obj;
+ if (!hit) return false
}
- return tokens;
-}
-
-function filterPatterns(arr, comparison, prefix, intersection, options) {
- let result = [];
-
- for (let ele of arr) {
- let { string } = ele;
-
- // only push if _both_ are negative...
- if (!intersection && !contains(comparison, 'string', string)) {
- result.push(prefix + string);
- }
+ // Note: ending in / means that we'll get a final ""
+ // at the end of the pattern. This can only match a
+ // corresponding "" at the end of the file.
+ // If the file ends in /, then it can only match a
+ // a pattern that ends in /, unless the pattern just
+ // doesn't have any more for it. But, a/b/ should *not*
+ // match "a/b/*", even though "" matches against the
+ // [^/]*? pattern, except in partial mode, where it might
+ // simply not be reached yet.
+ // However, a/b/ should still satisfy a/*
- // or _both_ are positive
- if (intersection && contains(comparison, 'string', string)) {
- result.push(prefix + string);
- }
+ // now either we fell off the end of the pattern, or we're done.
+ if (fi === fl && pi === pl) {
+ // ran out of pattern and filename at the same time.
+ // an exact hit!
+ return true
+ } else if (fi === fl) {
+ // ran out of file, but still had pattern left.
+ // this is ok if we're doing the match as part of
+ // a glob fs traversal.
+ return partial
+ } else /* istanbul ignore else */ if (pi === pl) {
+ // ran out of pattern, still have file left.
+ // this is only acceptable if we're on the very last
+ // empty segment of a file with a trailing slash.
+ // a/* should match a/b/
+ return (fi === fl - 1) && (file[fi] === '')
}
- return result;
-}
-
-/**
- * Zip strings
- */
-function zip(a, b) {
- let arr = [];
- for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]);
- return arr;
+ // should be unreachable.
+ /* istanbul ignore next */
+ throw new Error('wtf?')
}
-function compare(a, b) {
- return a > b ? 1 : b > a ? -1 : 0;
+// replace stuff like \* with *
+function globUnescape (s) {
+ return s.replace(/\\(.)/g, '$1')
}
-function contains(arr, key, val) {
- return arr.some(ele => ele[key] === val);
+function regExpEscape (s) {
+ return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')
}
-function countNines(min, len) {
- return Number(String(min).slice(0, -len) + '9'.repeat(len));
-}
-function countZeros(integer, zeros) {
- return integer - (integer % Math.pow(10, zeros));
-}
+/***/ }),
-function toQuantifier(digits) {
- let [start = 0, stop = ''] = digits;
- if (stop || start > 1) {
- return `{${start + (stop ? ',' + stop : '')}}`;
- }
- return '';
-}
+/***/ 467:
+/***/ ((module, exports, __nccwpck_require__) => {
-function toCharacterClass(a, b, options) {
- return `[${a}${(b - a === 1) ? '' : '-'}${b}]`;
-}
+"use strict";
-function hasPadding(str) {
- return /^-?(0+)\d/.test(str);
-}
-function padZeros(value, tok, options) {
- if (!tok.isPadded) {
- return value;
- }
+Object.defineProperty(exports, "__esModule", ({ value: true }));
- let diff = Math.abs(tok.maxLen - String(value).length);
- let relax = options.relaxZeros !== false;
+function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
- switch (diff) {
- case 0:
- return '';
- case 1:
- return relax ? '0?' : '0';
- case 2:
- return relax ? '0{0,2}' : '00';
- default: {
- return relax ? `0{0,${diff}}` : `0{${diff}}`;
- }
- }
-}
+var Stream = _interopDefault(__nccwpck_require__(2781));
+var http = _interopDefault(__nccwpck_require__(3685));
+var Url = _interopDefault(__nccwpck_require__(7310));
+var whatwgUrl = _interopDefault(__nccwpck_require__(8665));
+var https = _interopDefault(__nccwpck_require__(5687));
+var zlib = _interopDefault(__nccwpck_require__(9796));
-/**
- * Cache
- */
+// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js
-toRegexRange.cache = {};
-toRegexRange.clearCache = () => (toRegexRange.cache = {});
+// fix for "Readable" isn't a named export issue
+const Readable = Stream.Readable;
-/**
- * Expose `toRegexRange`
- */
+const BUFFER = Symbol('buffer');
+const TYPE = Symbol('type');
-module.exports = toRegexRange;
+class Blob {
+ constructor() {
+ this[TYPE] = '';
+ const blobParts = arguments[0];
+ const options = arguments[1];
-/***/ }),
+ const buffers = [];
+ let size = 0;
-/***/ 7426:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ if (blobParts) {
+ const a = blobParts;
+ const length = Number(a.length);
+ for (let i = 0; i < length; i++) {
+ const element = a[i];
+ let buffer;
+ if (element instanceof Buffer) {
+ buffer = element;
+ } else if (ArrayBuffer.isView(element)) {
+ buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength);
+ } else if (element instanceof ArrayBuffer) {
+ buffer = Buffer.from(element);
+ } else if (element instanceof Blob) {
+ buffer = element[BUFFER];
+ } else {
+ buffer = Buffer.from(typeof element === 'string' ? element : String(element));
+ }
+ size += buffer.length;
+ buffers.push(buffer);
+ }
+ }
-/*!
- * mime-db
- * Copyright(c) 2014 Jonathan Ong
- * MIT Licensed
- */
+ this[BUFFER] = Buffer.concat(buffers);
-/**
- * Module exports.
- */
+ let type = options && options.type !== undefined && String(options.type).toLowerCase();
+ if (type && !/[^\u0020-\u007E]/.test(type)) {
+ this[TYPE] = type;
+ }
+ }
+ get size() {
+ return this[BUFFER].length;
+ }
+ get type() {
+ return this[TYPE];
+ }
+ text() {
+ return Promise.resolve(this[BUFFER].toString());
+ }
+ arrayBuffer() {
+ const buf = this[BUFFER];
+ const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
+ return Promise.resolve(ab);
+ }
+ stream() {
+ const readable = new Readable();
+ readable._read = function () {};
+ readable.push(this[BUFFER]);
+ readable.push(null);
+ return readable;
+ }
+ toString() {
+ return '[object Blob]';
+ }
+ slice() {
+ const size = this.size;
-module.exports = __nccwpck_require__(3313)
+ const start = arguments[0];
+ const end = arguments[1];
+ let relativeStart, relativeEnd;
+ if (start === undefined) {
+ relativeStart = 0;
+ } else if (start < 0) {
+ relativeStart = Math.max(size + start, 0);
+ } else {
+ relativeStart = Math.min(start, size);
+ }
+ if (end === undefined) {
+ relativeEnd = size;
+ } else if (end < 0) {
+ relativeEnd = Math.max(size + end, 0);
+ } else {
+ relativeEnd = Math.min(end, size);
+ }
+ const span = Math.max(relativeEnd - relativeStart, 0);
+ const buffer = this[BUFFER];
+ const slicedBuffer = buffer.slice(relativeStart, relativeStart + span);
+ const blob = new Blob([], { type: arguments[2] });
+ blob[BUFFER] = slicedBuffer;
+ return blob;
+ }
+}
-/***/ }),
+Object.defineProperties(Blob.prototype, {
+ size: { enumerable: true },
+ type: { enumerable: true },
+ slice: { enumerable: true }
+});
-/***/ 3583:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+Object.defineProperty(Blob.prototype, Symbol.toStringTag, {
+ value: 'Blob',
+ writable: false,
+ enumerable: false,
+ configurable: true
+});
-"use strict";
-/*!
- * mime-types
- * Copyright(c) 2014 Jonathan Ong
- * Copyright(c) 2015 Douglas Christopher Wilson
- * MIT Licensed
+/**
+ * fetch-error.js
+ *
+ * FetchError interface for operational errors
*/
-
-
/**
- * Module dependencies.
- * @private
+ * Create FetchError instance
+ *
+ * @param String message Error message for human
+ * @param String type Error type for machine
+ * @param String systemError For Node.js system error
+ * @return FetchError
*/
+function FetchError(message, type, systemError) {
+ Error.call(this, message);
-var db = __nccwpck_require__(7426)
-var extname = __nccwpck_require__(5622).extname
+ this.message = message;
+ this.type = type;
-/**
- * Module variables.
- * @private
- */
+ // when err.type is `system`, err.code contains system error code
+ if (systemError) {
+ this.code = this.errno = systemError.code;
+ }
-var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/
-var TEXT_TYPE_REGEXP = /^text\//i
+ // hide custom error implementation details from end-users
+ Error.captureStackTrace(this, this.constructor);
+}
-/**
- * Module exports.
- * @public
- */
+FetchError.prototype = Object.create(Error.prototype);
+FetchError.prototype.constructor = FetchError;
+FetchError.prototype.name = 'FetchError';
-exports.charset = charset
-exports.charsets = { lookup: charset }
-exports.contentType = contentType
-exports.extension = extension
-exports.extensions = Object.create(null)
-exports.lookup = lookup
-exports.types = Object.create(null)
+let convert;
+try {
+ convert = (__nccwpck_require__(2877).convert);
+} catch (e) {}
-// Populate the extensions/types maps
-populateMaps(exports.extensions, exports.types)
+const INTERNALS = Symbol('Body internals');
+
+// fix an issue where "PassThrough" isn't a named export for node <10
+const PassThrough = Stream.PassThrough;
/**
- * Get the default charset for a MIME type.
+ * Body mixin
*
- * @param {string} type
- * @return {boolean|string}
+ * Ref: https://fetch.spec.whatwg.org/#body
+ *
+ * @param Stream body Readable stream
+ * @param Object opts Response options
+ * @return Void
*/
+function Body(body) {
+ var _this = this;
-function charset (type) {
- if (!type || typeof type !== 'string') {
- return false
- }
-
- // TODO: use media-typer
- var match = EXTRACT_TYPE_REGEXP.exec(type)
- var mime = match && db[match[1].toLowerCase()]
+ var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
+ _ref$size = _ref.size;
- if (mime && mime.charset) {
- return mime.charset
- }
+ let size = _ref$size === undefined ? 0 : _ref$size;
+ var _ref$timeout = _ref.timeout;
+ let timeout = _ref$timeout === undefined ? 0 : _ref$timeout;
- // default text/* to utf-8
- if (match && TEXT_TYPE_REGEXP.test(match[1])) {
- return 'UTF-8'
- }
+ if (body == null) {
+ // body is undefined or null
+ body = null;
+ } else if (isURLSearchParams(body)) {
+ // body is a URLSearchParams
+ body = Buffer.from(body.toString());
+ } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') {
+ // body is ArrayBuffer
+ body = Buffer.from(body);
+ } else if (ArrayBuffer.isView(body)) {
+ // body is ArrayBufferView
+ body = Buffer.from(body.buffer, body.byteOffset, body.byteLength);
+ } else if (body instanceof Stream) ; else {
+ // none of the above
+ // coerce to string then buffer
+ body = Buffer.from(String(body));
+ }
+ this[INTERNALS] = {
+ body,
+ disturbed: false,
+ error: null
+ };
+ this.size = size;
+ this.timeout = timeout;
- return false
+ if (body instanceof Stream) {
+ body.on('error', function (err) {
+ const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err);
+ _this[INTERNALS].error = error;
+ });
+ }
}
-/**
- * Create a full Content-Type header given a MIME type or extension.
- *
- * @param {string} str
- * @return {boolean|string}
- */
+Body.prototype = {
+ get body() {
+ return this[INTERNALS].body;
+ },
-function contentType (str) {
- // TODO: should this even be in this module?
- if (!str || typeof str !== 'string') {
- return false
- }
+ get bodyUsed() {
+ return this[INTERNALS].disturbed;
+ },
- var mime = str.indexOf('/') === -1
- ? exports.lookup(str)
- : str
+ /**
+ * Decode response as ArrayBuffer
+ *
+ * @return Promise
+ */
+ arrayBuffer() {
+ return consumeBody.call(this).then(function (buf) {
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
+ });
+ },
- if (!mime) {
- return false
- }
+ /**
+ * Return raw response as Blob
+ *
+ * @return Promise
+ */
+ blob() {
+ let ct = this.headers && this.headers.get('content-type') || '';
+ return consumeBody.call(this).then(function (buf) {
+ return Object.assign(
+ // Prevent copying
+ new Blob([], {
+ type: ct.toLowerCase()
+ }), {
+ [BUFFER]: buf
+ });
+ });
+ },
- // TODO: use content-type or other module
- if (mime.indexOf('charset') === -1) {
- var charset = exports.charset(mime)
- if (charset) mime += '; charset=' + charset.toLowerCase()
- }
+ /**
+ * Decode response as json
+ *
+ * @return Promise
+ */
+ json() {
+ var _this2 = this;
- return mime
-}
+ return consumeBody.call(this).then(function (buffer) {
+ try {
+ return JSON.parse(buffer.toString());
+ } catch (err) {
+ return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json'));
+ }
+ });
+ },
-/**
- * Get the default extension for a MIME type.
- *
- * @param {string} type
- * @return {boolean|string}
- */
+ /**
+ * Decode response as text
+ *
+ * @return Promise
+ */
+ text() {
+ return consumeBody.call(this).then(function (buffer) {
+ return buffer.toString();
+ });
+ },
-function extension (type) {
- if (!type || typeof type !== 'string') {
- return false
- }
+ /**
+ * Decode response as buffer (non-spec api)
+ *
+ * @return Promise
+ */
+ buffer() {
+ return consumeBody.call(this);
+ },
- // TODO: use media-typer
- var match = EXTRACT_TYPE_REGEXP.exec(type)
+ /**
+ * Decode response as text, while automatically detecting the encoding and
+ * trying to decode to UTF-8 (non-spec api)
+ *
+ * @return Promise
+ */
+ textConverted() {
+ var _this3 = this;
- // get extensions
- var exts = match && exports.extensions[match[1].toLowerCase()]
+ return consumeBody.call(this).then(function (buffer) {
+ return convertBody(buffer, _this3.headers);
+ });
+ }
+};
- if (!exts || !exts.length) {
- return false
- }
+// In browsers, all properties are enumerable.
+Object.defineProperties(Body.prototype, {
+ body: { enumerable: true },
+ bodyUsed: { enumerable: true },
+ arrayBuffer: { enumerable: true },
+ blob: { enumerable: true },
+ json: { enumerable: true },
+ text: { enumerable: true }
+});
- return exts[0]
-}
+Body.mixIn = function (proto) {
+ for (const name of Object.getOwnPropertyNames(Body.prototype)) {
+ // istanbul ignore else: future proof
+ if (!(name in proto)) {
+ const desc = Object.getOwnPropertyDescriptor(Body.prototype, name);
+ Object.defineProperty(proto, name, desc);
+ }
+ }
+};
/**
- * Lookup the MIME type for a file path/extension.
+ * Consume and convert an entire Body to a Buffer.
*
- * @param {string} path
- * @return {boolean|string}
+ * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body
+ *
+ * @return Promise
*/
+function consumeBody() {
+ var _this4 = this;
-function lookup (path) {
- if (!path || typeof path !== 'string') {
- return false
- }
+ if (this[INTERNALS].disturbed) {
+ return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));
+ }
- // get the extension ("ext" or ".ext" or full path)
- var extension = extname('x.' + path)
- .toLowerCase()
- .substr(1)
+ this[INTERNALS].disturbed = true;
- if (!extension) {
- return false
- }
+ if (this[INTERNALS].error) {
+ return Body.Promise.reject(this[INTERNALS].error);
+ }
- return exports.types[extension] || false
-}
+ let body = this.body;
-/**
- * Populate the extensions and types maps.
- * @private
- */
+ // body is null
+ if (body === null) {
+ return Body.Promise.resolve(Buffer.alloc(0));
+ }
-function populateMaps (extensions, types) {
- // source preference (least -> most)
- var preference = ['nginx', 'apache', undefined, 'iana']
+ // body is blob
+ if (isBlob(body)) {
+ body = body.stream();
+ }
- Object.keys(db).forEach(function forEachMimeType (type) {
- var mime = db[type]
- var exts = mime.extensions
+ // body is buffer
+ if (Buffer.isBuffer(body)) {
+ return Body.Promise.resolve(body);
+ }
- if (!exts || !exts.length) {
- return
- }
+ // istanbul ignore if: should never happen
+ if (!(body instanceof Stream)) {
+ return Body.Promise.resolve(Buffer.alloc(0));
+ }
- // mime -> extensions
- extensions[type] = exts
+ // body is stream
+ // get ready to actually consume the body
+ let accum = [];
+ let accumBytes = 0;
+ let abort = false;
- // extension -> mime
- for (var i = 0; i < exts.length; i++) {
- var extension = exts[i]
+ return new Body.Promise(function (resolve, reject) {
+ let resTimeout;
- if (types[extension]) {
- var from = preference.indexOf(db[types[extension]].source)
- var to = preference.indexOf(mime.source)
+ // allow timeout on slow response body
+ if (_this4.timeout) {
+ resTimeout = setTimeout(function () {
+ abort = true;
+ reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout'));
+ }, _this4.timeout);
+ }
- if (types[extension] !== 'application/octet-stream' &&
- (from > to || (from === to && types[extension].substr(0, 12) === 'application/'))) {
- // skip the remapping
- continue
- }
- }
+ // handle stream errors
+ body.on('error', function (err) {
+ if (err.name === 'AbortError') {
+ // if the request was aborted, reject with this Error
+ abort = true;
+ reject(err);
+ } else {
+ // other errors, such as incorrect content-encoding
+ reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err));
+ }
+ });
- // set the extension -> mime
- types[extension] = type
- }
- })
-}
+ body.on('data', function (chunk) {
+ if (abort || chunk === null) {
+ return;
+ }
+ if (_this4.size && accumBytes + chunk.length > _this4.size) {
+ abort = true;
+ reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size'));
+ return;
+ }
-/***/ }),
+ accumBytes += chunk.length;
+ accum.push(chunk);
+ });
-/***/ 3973:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ body.on('end', function () {
+ if (abort) {
+ return;
+ }
-module.exports = minimatch
-minimatch.Minimatch = Minimatch
+ clearTimeout(resTimeout);
-var path = (function () { try { return __nccwpck_require__(5622) } catch (e) {}}()) || {
- sep: '/'
+ try {
+ resolve(Buffer.concat(accum, accumBytes));
+ } catch (err) {
+ // handle streams that have accumulated too much data (issue #414)
+ reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err));
+ }
+ });
+ });
}
-minimatch.sep = path.sep
-
-var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {}
-var expand = __nccwpck_require__(3717)
-var plTypes = {
- '!': { open: '(?:(?!(?:', close: '))[^/]*?)'},
- '?': { open: '(?:', close: ')?' },
- '+': { open: '(?:', close: ')+' },
- '*': { open: '(?:', close: ')*' },
- '@': { open: '(?:', close: ')' }
-}
+/**
+ * Detect buffer encoding and convert to target encoding
+ * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding
+ *
+ * @param Buffer buffer Incoming buffer
+ * @param String encoding Target encoding
+ * @return String
+ */
+function convertBody(buffer, headers) {
+ if (typeof convert !== 'function') {
+ throw new Error('The package `encoding` must be installed to use the textConverted() function');
+ }
-// any single thing other than /
-// don't need to escape / when using new RegExp()
-var qmark = '[^/]'
+ const ct = headers.get('content-type');
+ let charset = 'utf-8';
+ let res, str;
-// * => any number of characters
-var star = qmark + '*?'
+ // header
+ if (ct) {
+ res = /charset=([^;]*)/i.exec(ct);
+ }
-// ** when dots are allowed. Anything goes, except .. and .
-// not (^ or / followed by one or two dots followed by $ or /),
-// followed by anything, any number of times.
-var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?'
-
-// not a ^ or / followed by a dot,
-// followed by anything, any number of times.
-var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?'
-
-// characters that need to be escaped in RegExp.
-var reSpecials = charSet('().*{}+?[]^$\\!')
+ // no charset in content type, peek at response body for at most 1024 bytes
+ str = buffer.slice(0, 1024).toString();
-// "abc" -> { a:true, b:true, c:true }
-function charSet (s) {
- return s.split('').reduce(function (set, c) {
- set[c] = true
- return set
- }, {})
-}
+ // html5
+ if (!res && str) {
+ res = / 0 && arguments[0] !== undefined ? arguments[0] : undefined;
- // step 1: figure out negation, etc.
- this.parseNegate()
+ this[MAP] = Object.create(null);
- // step 2: expand braces
- var set = this.globSet = this.braceExpand()
+ if (init instanceof Headers) {
+ const rawHeaders = init.raw();
+ const headerNames = Object.keys(rawHeaders);
- if (options.debug) this.debug = function debug() { console.error.apply(console, arguments) }
+ for (const headerName of headerNames) {
+ for (const value of rawHeaders[headerName]) {
+ this.append(headerName, value);
+ }
+ }
- this.debug(this.pattern, set)
+ return;
+ }
- // step 3: now we have a set, so turn each one into a series of path-portion
- // matching patterns.
- // These will be regexps, except in the case of "**", which is
- // set to the GLOBSTAR object for globstar behavior,
- // and will not contain any / characters
- set = this.globParts = set.map(function (s) {
- return s.split(slashSplit)
- })
+ // We don't worry about converting prop to ByteString here as append()
+ // will handle it.
+ if (init == null) ; else if (typeof init === 'object') {
+ const method = init[Symbol.iterator];
+ if (method != null) {
+ if (typeof method !== 'function') {
+ throw new TypeError('Header pairs must be iterable');
+ }
- this.debug(this.pattern, set)
+ // sequence>
+ // Note: per spec we have to first exhaust the lists then process them
+ const pairs = [];
+ for (const pair of init) {
+ if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') {
+ throw new TypeError('Each header pair must be iterable');
+ }
+ pairs.push(Array.from(pair));
+ }
- // glob --> regexps
- set = set.map(function (s, si, set) {
- return s.map(this.parse, this)
- }, this)
+ for (const pair of pairs) {
+ if (pair.length !== 2) {
+ throw new TypeError('Each header pair must be a name/value tuple');
+ }
+ this.append(pair[0], pair[1]);
+ }
+ } else {
+ // record
+ for (const key of Object.keys(init)) {
+ const value = init[key];
+ this.append(key, value);
+ }
+ }
+ } else {
+ throw new TypeError('Provided initializer must be an object');
+ }
+ }
- this.debug(this.pattern, set)
+ /**
+ * Return combined header value given name
+ *
+ * @param String name Header name
+ * @return Mixed
+ */
+ get(name) {
+ name = `${name}`;
+ validateName(name);
+ const key = find(this[MAP], name);
+ if (key === undefined) {
+ return null;
+ }
- // filter out everything that didn't compile properly.
- set = set.filter(function (s) {
- return s.indexOf(false) === -1
- })
+ return this[MAP][key].join(', ');
+ }
- this.debug(this.pattern, set)
+ /**
+ * Iterate over all headers
+ *
+ * @param Function callback Executed for each item with parameters (value, name, thisArg)
+ * @param Boolean thisArg `this` context for callback function
+ * @return Void
+ */
+ forEach(callback) {
+ let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;
- this.set = set
-}
+ let pairs = getHeaders(this);
+ let i = 0;
+ while (i < pairs.length) {
+ var _pairs$i = pairs[i];
+ const name = _pairs$i[0],
+ value = _pairs$i[1];
-Minimatch.prototype.parseNegate = parseNegate
-function parseNegate () {
- var pattern = this.pattern
- var negate = false
- var options = this.options
- var negateOffset = 0
+ callback.call(thisArg, value, name, this);
+ pairs = getHeaders(this);
+ i++;
+ }
+ }
- if (options.nonegate) return
+ /**
+ * Overwrite header values given name
+ *
+ * @param String name Header name
+ * @param String value Header value
+ * @return Void
+ */
+ set(name, value) {
+ name = `${name}`;
+ value = `${value}`;
+ validateName(name);
+ validateValue(value);
+ const key = find(this[MAP], name);
+ this[MAP][key !== undefined ? key : name] = [value];
+ }
- for (var i = 0, l = pattern.length
- ; i < l && pattern.charAt(i) === '!'
- ; i++) {
- negate = !negate
- negateOffset++
- }
+ /**
+ * Append a value onto existing header
+ *
+ * @param String name Header name
+ * @param String value Header value
+ * @return Void
+ */
+ append(name, value) {
+ name = `${name}`;
+ value = `${value}`;
+ validateName(name);
+ validateValue(value);
+ const key = find(this[MAP], name);
+ if (key !== undefined) {
+ this[MAP][key].push(value);
+ } else {
+ this[MAP][name] = [value];
+ }
+ }
- if (negateOffset) this.pattern = pattern.substr(negateOffset)
- this.negate = negate
-}
+ /**
+ * Check for header name existence
+ *
+ * @param String name Header name
+ * @return Boolean
+ */
+ has(name) {
+ name = `${name}`;
+ validateName(name);
+ return find(this[MAP], name) !== undefined;
+ }
-// Brace expansion:
-// a{b,c}d -> abd acd
-// a{b,}c -> abc ac
-// a{0..3}d -> a0d a1d a2d a3d
-// a{b,c{d,e}f}g -> abg acdfg acefg
-// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
-//
-// Invalid sets are not expanded.
-// a{2..}b -> a{2..}b
-// a{b}c -> a{b}c
-minimatch.braceExpand = function (pattern, options) {
- return braceExpand(pattern, options)
-}
+ /**
+ * Delete all header values given name
+ *
+ * @param String name Header name
+ * @return Void
+ */
+ delete(name) {
+ name = `${name}`;
+ validateName(name);
+ const key = find(this[MAP], name);
+ if (key !== undefined) {
+ delete this[MAP][key];
+ }
+ }
-Minimatch.prototype.braceExpand = braceExpand
+ /**
+ * Return raw headers (non-spec api)
+ *
+ * @return Object
+ */
+ raw() {
+ return this[MAP];
+ }
-function braceExpand (pattern, options) {
- if (!options) {
- if (this instanceof Minimatch) {
- options = this.options
- } else {
- options = {}
- }
- }
+ /**
+ * Get an iterator on keys.
+ *
+ * @return Iterator
+ */
+ keys() {
+ return createHeadersIterator(this, 'key');
+ }
- pattern = typeof pattern === 'undefined'
- ? this.pattern : pattern
+ /**
+ * Get an iterator on values.
+ *
+ * @return Iterator
+ */
+ values() {
+ return createHeadersIterator(this, 'value');
+ }
- assertValidPattern(pattern)
+ /**
+ * Get an iterator on entries.
+ *
+ * This is the default iterator of the Headers object.
+ *
+ * @return Iterator
+ */
+ [Symbol.iterator]() {
+ return createHeadersIterator(this, 'key+value');
+ }
+}
+Headers.prototype.entries = Headers.prototype[Symbol.iterator];
- // Thanks to Yeting Li for
- // improving this regexp to avoid a ReDOS vulnerability.
- if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
- // shortcut. no need to expand.
- return [pattern]
- }
+Object.defineProperty(Headers.prototype, Symbol.toStringTag, {
+ value: 'Headers',
+ writable: false,
+ enumerable: false,
+ configurable: true
+});
- return expand(pattern)
+Object.defineProperties(Headers.prototype, {
+ get: { enumerable: true },
+ forEach: { enumerable: true },
+ set: { enumerable: true },
+ append: { enumerable: true },
+ has: { enumerable: true },
+ delete: { enumerable: true },
+ keys: { enumerable: true },
+ values: { enumerable: true },
+ entries: { enumerable: true }
+});
+
+function getHeaders(headers) {
+ let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value';
+
+ const keys = Object.keys(headers[MAP]).sort();
+ return keys.map(kind === 'key' ? function (k) {
+ return k.toLowerCase();
+ } : kind === 'value' ? function (k) {
+ return headers[MAP][k].join(', ');
+ } : function (k) {
+ return [k.toLowerCase(), headers[MAP][k].join(', ')];
+ });
}
-var MAX_PATTERN_LENGTH = 1024 * 64
-var assertValidPattern = function (pattern) {
- if (typeof pattern !== 'string') {
- throw new TypeError('invalid pattern')
- }
+const INTERNAL = Symbol('internal');
- if (pattern.length > MAX_PATTERN_LENGTH) {
- throw new TypeError('pattern is too long')
- }
+function createHeadersIterator(target, kind) {
+ const iterator = Object.create(HeadersIteratorPrototype);
+ iterator[INTERNAL] = {
+ target,
+ kind,
+ index: 0
+ };
+ return iterator;
}
-// parse a component of the expanded set.
-// At this point, no pattern may contain "/" in it
-// so we're going to return a 2d array, where each entry is the full
-// pattern, split on '/', and then turned into a regular expression.
-// A regexp is made at the end which joins each array with an
-// escaped /, and another full one which joins each regexp with |.
-//
-// Following the lead of Bash 4.1, note that "**" only has special meaning
-// when it is the *only* thing in a path portion. Otherwise, any series
-// of * is equivalent to a single *. Globstar behavior is enabled by
-// default, and can be disabled by setting options.noglobstar.
-Minimatch.prototype.parse = parse
-var SUBPARSE = {}
-function parse (pattern, isSub) {
- assertValidPattern(pattern)
+const HeadersIteratorPrototype = Object.setPrototypeOf({
+ next() {
+ // istanbul ignore if
+ if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) {
+ throw new TypeError('Value of `this` is not a HeadersIterator');
+ }
- var options = this.options
+ var _INTERNAL = this[INTERNAL];
+ const target = _INTERNAL.target,
+ kind = _INTERNAL.kind,
+ index = _INTERNAL.index;
- // shortcuts
- if (pattern === '**') {
- if (!options.noglobstar)
- return GLOBSTAR
- else
- pattern = '*'
- }
- if (pattern === '') return ''
+ const values = getHeaders(target, kind);
+ const len = values.length;
+ if (index >= len) {
+ return {
+ value: undefined,
+ done: true
+ };
+ }
- var re = ''
- var hasMagic = !!options.nocase
- var escaping = false
- // ? => one single character
- var patternListStack = []
- var negativeLists = []
- var stateChar
- var inClass = false
- var reClassStart = -1
- var classStart = -1
- // . and .. never match anything that doesn't start with .,
- // even when options.dot is set.
- var patternStart = pattern.charAt(0) === '.' ? '' // anything
- // not (start or / followed by . or .. followed by / or end)
- : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))'
- : '(?!\\.)'
- var self = this
+ this[INTERNAL].index = index + 1;
- function clearStateChar () {
- if (stateChar) {
- // we had some state-tracking character
- // that wasn't consumed by this pass.
- switch (stateChar) {
- case '*':
- re += star
- hasMagic = true
- break
- case '?':
- re += qmark
- hasMagic = true
- break
- default:
- re += '\\' + stateChar
- break
- }
- self.debug('clearStateChar %j %j', stateChar, re)
- stateChar = false
- }
- }
+ return {
+ value: values[index],
+ done: false
+ };
+ }
+}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())));
- for (var i = 0, len = pattern.length, c
- ; (i < len) && (c = pattern.charAt(i))
- ; i++) {
- this.debug('%s\t%s %s %j', pattern, i, re, c)
+Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, {
+ value: 'HeadersIterator',
+ writable: false,
+ enumerable: false,
+ configurable: true
+});
- // skip over any that are escaped.
- if (escaping && reSpecials[c]) {
- re += '\\' + c
- escaping = false
- continue
- }
+/**
+ * Export the Headers object in a form that Node.js can consume.
+ *
+ * @param Headers headers
+ * @return Object
+ */
+function exportNodeCompatibleHeaders(headers) {
+ const obj = Object.assign({ __proto__: null }, headers[MAP]);
- switch (c) {
- /* istanbul ignore next */
- case '/': {
- // completely not allowed, even escaped.
- // Should already be path-split by now.
- return false
- }
+ // http.request() only supports string as Host header. This hack makes
+ // specifying custom Host header possible.
+ const hostHeaderKey = find(headers[MAP], 'Host');
+ if (hostHeaderKey !== undefined) {
+ obj[hostHeaderKey] = obj[hostHeaderKey][0];
+ }
- case '\\':
- clearStateChar()
- escaping = true
- continue
+ return obj;
+}
- // the various stateChar values
- // for the "extglob" stuff.
- case '?':
- case '*':
- case '+':
- case '@':
- case '!':
- this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c)
+/**
+ * Create a Headers object from an object of headers, ignoring those that do
+ * not conform to HTTP grammar productions.
+ *
+ * @param Object obj Object of headers
+ * @return Headers
+ */
+function createHeadersLenient(obj) {
+ const headers = new Headers();
+ for (const name of Object.keys(obj)) {
+ if (invalidTokenRegex.test(name)) {
+ continue;
+ }
+ if (Array.isArray(obj[name])) {
+ for (const val of obj[name]) {
+ if (invalidHeaderCharRegex.test(val)) {
+ continue;
+ }
+ if (headers[MAP][name] === undefined) {
+ headers[MAP][name] = [val];
+ } else {
+ headers[MAP][name].push(val);
+ }
+ }
+ } else if (!invalidHeaderCharRegex.test(obj[name])) {
+ headers[MAP][name] = [obj[name]];
+ }
+ }
+ return headers;
+}
- // all of those are literals inside a class, except that
- // the glob [!a] means [^a] in regexp
- if (inClass) {
- this.debug(' in class')
- if (c === '!' && i === classStart + 1) c = '^'
- re += c
- continue
- }
+const INTERNALS$1 = Symbol('Response internals');
- // if we already have a stateChar, then it means
- // that there was something like ** or +? in there.
- // Handle the stateChar, then proceed with this one.
- self.debug('call clearStateChar %j', stateChar)
- clearStateChar()
- stateChar = c
- // if extglob is disabled, then +(asdf|foo) isn't a thing.
- // just clear the statechar *now*, rather than even diving into
- // the patternList stuff.
- if (options.noext) clearStateChar()
- continue
+// fix an issue where "STATUS_CODES" aren't a named export for node <10
+const STATUS_CODES = http.STATUS_CODES;
- case '(':
- if (inClass) {
- re += '('
- continue
- }
+/**
+ * Response class
+ *
+ * @param Stream body Readable stream
+ * @param Object opts Response options
+ * @return Void
+ */
+class Response {
+ constructor() {
+ let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
+ let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
- if (!stateChar) {
- re += '\\('
- continue
- }
+ Body.call(this, body, opts);
- patternListStack.push({
- type: stateChar,
- start: i - 1,
- reStart: re.length,
- open: plTypes[stateChar].open,
- close: plTypes[stateChar].close
- })
- // negation is (?:(?!js)[^/]*)
- re += stateChar === '!' ? '(?:(?!(?:' : '(?:'
- this.debug('plType %j %j', stateChar, re)
- stateChar = false
- continue
+ const status = opts.status || 200;
+ const headers = new Headers(opts.headers);
- case ')':
- if (inClass || !patternListStack.length) {
- re += '\\)'
- continue
- }
+ if (body != null && !headers.has('Content-Type')) {
+ const contentType = extractContentType(body);
+ if (contentType) {
+ headers.append('Content-Type', contentType);
+ }
+ }
- clearStateChar()
- hasMagic = true
- var pl = patternListStack.pop()
- // negation is (?:(?!js)[^/]*)
- // The others are (?:)
- re += pl.close
- if (pl.type === '!') {
- negativeLists.push(pl)
- }
- pl.reEnd = re.length
- continue
+ this[INTERNALS$1] = {
+ url: opts.url,
+ status,
+ statusText: opts.statusText || STATUS_CODES[status],
+ headers,
+ counter: opts.counter
+ };
+ }
- case '|':
- if (inClass || !patternListStack.length || escaping) {
- re += '\\|'
- escaping = false
- continue
- }
+ get url() {
+ return this[INTERNALS$1].url || '';
+ }
- clearStateChar()
- re += '|'
- continue
+ get status() {
+ return this[INTERNALS$1].status;
+ }
- // these are mostly the same in regexp and glob
- case '[':
- // swallow any state-tracking char before the [
- clearStateChar()
+ /**
+ * Convenience property representing if the request ended normally
+ */
+ get ok() {
+ return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300;
+ }
- if (inClass) {
- re += '\\' + c
- continue
- }
+ get redirected() {
+ return this[INTERNALS$1].counter > 0;
+ }
- inClass = true
- classStart = i
- reClassStart = re.length
- re += c
- continue
+ get statusText() {
+ return this[INTERNALS$1].statusText;
+ }
- case ']':
- // a right bracket shall lose its special
- // meaning and represent itself in
- // a bracket expression if it occurs
- // first in the list. -- POSIX.2 2.8.3.2
- if (i === classStart + 1 || !inClass) {
- re += '\\' + c
- escaping = false
- continue
- }
+ get headers() {
+ return this[INTERNALS$1].headers;
+ }
- // handle the case where we left a class open.
- // "[z-a]" is valid, equivalent to "\[z-a\]"
- // split where the last [ was, make sure we don't have
- // an invalid re. if so, re-walk the contents of the
- // would-be class to re-translate any characters that
- // were passed through as-is
- // TODO: It would probably be faster to determine this
- // without a try/catch and a new RegExp, but it's tricky
- // to do safely. For now, this is safe and works.
- var cs = pattern.substring(classStart + 1, i)
- try {
- RegExp('[' + cs + ']')
- } catch (er) {
- // not a valid class!
- var sp = this.parse(cs, SUBPARSE)
- re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]'
- hasMagic = hasMagic || sp[1]
- inClass = false
- continue
- }
+ /**
+ * Clone this response
+ *
+ * @return Response
+ */
+ clone() {
+ return new Response(clone(this), {
+ url: this.url,
+ status: this.status,
+ statusText: this.statusText,
+ headers: this.headers,
+ ok: this.ok,
+ redirected: this.redirected
+ });
+ }
+}
- // finish up the class.
- hasMagic = true
- inClass = false
- re += c
- continue
+Body.mixIn(Response.prototype);
- default:
- // swallow any state char that wasn't consumed
- clearStateChar()
+Object.defineProperties(Response.prototype, {
+ url: { enumerable: true },
+ status: { enumerable: true },
+ ok: { enumerable: true },
+ redirected: { enumerable: true },
+ statusText: { enumerable: true },
+ headers: { enumerable: true },
+ clone: { enumerable: true }
+});
- if (escaping) {
- // no need
- escaping = false
- } else if (reSpecials[c]
- && !(c === '^' && inClass)) {
- re += '\\'
- }
+Object.defineProperty(Response.prototype, Symbol.toStringTag, {
+ value: 'Response',
+ writable: false,
+ enumerable: false,
+ configurable: true
+});
- re += c
+const INTERNALS$2 = Symbol('Request internals');
+const URL = Url.URL || whatwgUrl.URL;
- } // switch
- } // for
+// fix an issue where "format", "parse" aren't a named export for node <10
+const parse_url = Url.parse;
+const format_url = Url.format;
- // handle the case where we left a class open.
- // "[abc" is valid, equivalent to "\[abc"
- if (inClass) {
- // split where the last [ was, and escape it
- // this is a huge pita. We now have to re-walk
- // the contents of the would-be class to re-translate
- // any characters that were passed through as-is
- cs = pattern.substr(classStart + 1)
- sp = this.parse(cs, SUBPARSE)
- re = re.substr(0, reClassStart) + '\\[' + sp[0]
- hasMagic = hasMagic || sp[1]
- }
-
- // handle the case where we had a +( thing at the *end*
- // of the pattern.
- // each pattern list stack adds 3 chars, and we need to go through
- // and escape any | chars that were passed through as-is for the regexp.
- // Go through and escape them, taking care not to double-escape any
- // | chars that were already escaped.
- for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
- var tail = re.slice(pl.reStart + pl.open.length)
- this.debug('setting tail', re, pl)
- // maybe some even number of \, then maybe 1 \, followed by a |
- tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) {
- if (!$2) {
- // the | isn't already escaped, so escape it.
- $2 = '\\'
- }
+/**
+ * Wrapper around `new URL` to handle arbitrary URLs
+ *
+ * @param {string} urlStr
+ * @return {void}
+ */
+function parseURL(urlStr) {
+ /*
+ Check whether the URL is absolute or not
+ Scheme: https://tools.ietf.org/html/rfc3986#section-3.1
+ Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3
+ */
+ if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.exec(urlStr)) {
+ urlStr = new URL(urlStr).toString();
+ }
- // need to escape all those slashes *again*, without escaping the
- // one that we need for escaping the | character. As it works out,
- // escaping an even number of slashes can be done by simply repeating
- // it exactly after itself. That's why this trick works.
- //
- // I am sorry that you have to see this.
- return $1 + $1 + $2 + '|'
- })
+ // Fallback to old implementation for arbitrary URLs
+ return parse_url(urlStr);
+}
- this.debug('tail=%j\n %s', tail, tail, pl, re)
- var t = pl.type === '*' ? star
- : pl.type === '?' ? qmark
- : '\\' + pl.type
+const streamDestructionSupported = 'destroy' in Stream.Readable.prototype;
- hasMagic = true
- re = re.slice(0, pl.reStart) + t + '\\(' + tail
- }
+/**
+ * Check if a value is an instance of Request.
+ *
+ * @param Mixed input
+ * @return Boolean
+ */
+function isRequest(input) {
+ return typeof input === 'object' && typeof input[INTERNALS$2] === 'object';
+}
- // handle trailing things that only matter at the very end.
- clearStateChar()
- if (escaping) {
- // trailing \\
- re += '\\\\'
- }
+function isAbortSignal(signal) {
+ const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal);
+ return !!(proto && proto.constructor.name === 'AbortSignal');
+}
- // only need to apply the nodot start if the re starts with
- // something that could conceivably capture a dot
- var addPatternStart = false
- switch (re.charAt(0)) {
- case '[': case '.': case '(': addPatternStart = true
- }
+/**
+ * Request class
+ *
+ * @param Mixed input Url or Request instance
+ * @param Object init Custom options
+ * @return Void
+ */
+class Request {
+ constructor(input) {
+ let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
- // Hack to work around lack of negative lookbehind in JS
- // A pattern like: *.!(x).!(y|z) needs to ensure that a name
- // like 'a.xyz.yz' doesn't match. So, the first negative
- // lookahead, has to look ALL the way ahead, to the end of
- // the pattern.
- for (var n = negativeLists.length - 1; n > -1; n--) {
- var nl = negativeLists[n]
+ let parsedURL;
- var nlBefore = re.slice(0, nl.reStart)
- var nlFirst = re.slice(nl.reStart, nl.reEnd - 8)
- var nlLast = re.slice(nl.reEnd - 8, nl.reEnd)
- var nlAfter = re.slice(nl.reEnd)
+ // normalize input
+ if (!isRequest(input)) {
+ if (input && input.href) {
+ // in order to support Node.js' Url objects; though WHATWG's URL objects
+ // will fall into this branch also (since their `toString()` will return
+ // `href` property anyway)
+ parsedURL = parseURL(input.href);
+ } else {
+ // coerce input to a string before attempting to parse
+ parsedURL = parseURL(`${input}`);
+ }
+ input = {};
+ } else {
+ parsedURL = parseURL(input.url);
+ }
- nlLast += nlAfter
+ let method = init.method || input.method || 'GET';
+ method = method.toUpperCase();
- // Handle nested stuff like *(*.js|!(*.json)), where open parens
- // mean that we should *not* include the ) in the bit that is considered
- // "after" the negated section.
- var openParensBefore = nlBefore.split('(').length - 1
- var cleanAfter = nlAfter
- for (i = 0; i < openParensBefore; i++) {
- cleanAfter = cleanAfter.replace(/\)[+*?]?/, '')
- }
- nlAfter = cleanAfter
+ if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) {
+ throw new TypeError('Request with GET/HEAD method cannot have body');
+ }
- var dollar = ''
- if (nlAfter === '' && isSub !== SUBPARSE) {
- dollar = '$'
- }
- var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast
- re = newRe
- }
+ let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null;
- // if the re is not "" at this point, then we need to make sure
- // it doesn't match against an empty path part.
- // Otherwise a/* will match a/, which it should not.
- if (re !== '' && hasMagic) {
- re = '(?=.)' + re
- }
+ Body.call(this, inputBody, {
+ timeout: init.timeout || input.timeout || 0,
+ size: init.size || input.size || 0
+ });
- if (addPatternStart) {
- re = patternStart + re
- }
+ const headers = new Headers(init.headers || input.headers || {});
- // parsing just a piece of a larger pattern.
- if (isSub === SUBPARSE) {
- return [re, hasMagic]
- }
+ if (inputBody != null && !headers.has('Content-Type')) {
+ const contentType = extractContentType(inputBody);
+ if (contentType) {
+ headers.append('Content-Type', contentType);
+ }
+ }
- // skip the regexp for non-magical patterns
- // unescape anything in it, though, so that it'll be
- // an exact match against a file etc.
- if (!hasMagic) {
- return globUnescape(pattern)
- }
+ let signal = isRequest(input) ? input.signal : null;
+ if ('signal' in init) signal = init.signal;
- var flags = options.nocase ? 'i' : ''
- try {
- var regExp = new RegExp('^' + re + '$', flags)
- } catch (er) /* istanbul ignore next - should be impossible */ {
- // If it was an invalid regular expression, then it can't match
- // anything. This trick looks for a character after the end of
- // the string, which is of course impossible, except in multi-line
- // mode, but it's not a /m regex.
- return new RegExp('$.')
- }
+ if (signal != null && !isAbortSignal(signal)) {
+ throw new TypeError('Expected signal to be an instanceof AbortSignal');
+ }
- regExp._glob = pattern
- regExp._src = re
+ this[INTERNALS$2] = {
+ method,
+ redirect: init.redirect || input.redirect || 'follow',
+ headers,
+ parsedURL,
+ signal
+ };
- return regExp
-}
+ // node-fetch-only options
+ this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20;
+ this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true;
+ this.counter = init.counter || input.counter || 0;
+ this.agent = init.agent || input.agent;
+ }
-minimatch.makeRe = function (pattern, options) {
- return new Minimatch(pattern, options || {}).makeRe()
-}
+ get method() {
+ return this[INTERNALS$2].method;
+ }
-Minimatch.prototype.makeRe = makeRe
-function makeRe () {
- if (this.regexp || this.regexp === false) return this.regexp
+ get url() {
+ return format_url(this[INTERNALS$2].parsedURL);
+ }
- // at this point, this.set is a 2d array of partial
- // pattern strings, or "**".
- //
- // It's better to use .match(). This function shouldn't
- // be used, really, but it's pretty convenient sometimes,
- // when you just want to work with a regex.
- var set = this.set
+ get headers() {
+ return this[INTERNALS$2].headers;
+ }
- if (!set.length) {
- this.regexp = false
- return this.regexp
- }
- var options = this.options
+ get redirect() {
+ return this[INTERNALS$2].redirect;
+ }
- var twoStar = options.noglobstar ? star
- : options.dot ? twoStarDot
- : twoStarNoDot
- var flags = options.nocase ? 'i' : ''
+ get signal() {
+ return this[INTERNALS$2].signal;
+ }
- var re = set.map(function (pattern) {
- return pattern.map(function (p) {
- return (p === GLOBSTAR) ? twoStar
- : (typeof p === 'string') ? regExpEscape(p)
- : p._src
- }).join('\\\/')
- }).join('|')
+ /**
+ * Clone this request
+ *
+ * @return Request
+ */
+ clone() {
+ return new Request(this);
+ }
+}
- // must match entire pattern
- // ending in a * or ** will make it less strict.
- re = '^(?:' + re + ')$'
+Body.mixIn(Request.prototype);
- // can match anything, as long as it's not this.
- if (this.negate) re = '^(?!' + re + ').*$'
+Object.defineProperty(Request.prototype, Symbol.toStringTag, {
+ value: 'Request',
+ writable: false,
+ enumerable: false,
+ configurable: true
+});
- try {
- this.regexp = new RegExp(re, flags)
- } catch (ex) /* istanbul ignore next - should be impossible */ {
- this.regexp = false
- }
- return this.regexp
-}
+Object.defineProperties(Request.prototype, {
+ method: { enumerable: true },
+ url: { enumerable: true },
+ headers: { enumerable: true },
+ redirect: { enumerable: true },
+ clone: { enumerable: true },
+ signal: { enumerable: true }
+});
-minimatch.match = function (list, pattern, options) {
- options = options || {}
- var mm = new Minimatch(pattern, options)
- list = list.filter(function (f) {
- return mm.match(f)
- })
- if (mm.options.nonull && !list.length) {
- list.push(pattern)
- }
- return list
-}
+/**
+ * Convert a Request to Node.js http request options.
+ *
+ * @param Request A Request instance
+ * @return Object The options object to be passed to http.request
+ */
+function getNodeRequestOptions(request) {
+ const parsedURL = request[INTERNALS$2].parsedURL;
+ const headers = new Headers(request[INTERNALS$2].headers);
-Minimatch.prototype.match = function match (f, partial) {
- if (typeof partial === 'undefined') partial = this.partial
- this.debug('match', f, this.pattern)
- // short-circuit in the case of busted things.
- // comments, etc.
- if (this.comment) return false
- if (this.empty) return f === ''
+ // fetch step 1.3
+ if (!headers.has('Accept')) {
+ headers.set('Accept', '*/*');
+ }
- if (f === '/' && partial) return true
+ // Basic fetch
+ if (!parsedURL.protocol || !parsedURL.hostname) {
+ throw new TypeError('Only absolute URLs are supported');
+ }
- var options = this.options
+ if (!/^https?:$/.test(parsedURL.protocol)) {
+ throw new TypeError('Only HTTP(S) protocols are supported');
+ }
- // windows: need to use /, not \
- if (path.sep !== '/') {
- f = f.split(path.sep).join('/')
- }
+ if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) {
+ throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8');
+ }
- // treat the test path as a set of pathparts.
- f = f.split(slashSplit)
- this.debug(this.pattern, 'split', f)
+ // HTTP-network-or-cache fetch steps 2.4-2.7
+ let contentLengthValue = null;
+ if (request.body == null && /^(POST|PUT)$/i.test(request.method)) {
+ contentLengthValue = '0';
+ }
+ if (request.body != null) {
+ const totalBytes = getTotalBytes(request);
+ if (typeof totalBytes === 'number') {
+ contentLengthValue = String(totalBytes);
+ }
+ }
+ if (contentLengthValue) {
+ headers.set('Content-Length', contentLengthValue);
+ }
- // just ONE of the pattern sets in this.set needs to match
- // in order for it to be valid. If negating, then just one
- // match means that we have failed.
- // Either way, return on the first hit.
+ // HTTP-network-or-cache fetch step 2.11
+ if (!headers.has('User-Agent')) {
+ headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)');
+ }
- var set = this.set
- this.debug(this.pattern, 'set', set)
+ // HTTP-network-or-cache fetch step 2.15
+ if (request.compress && !headers.has('Accept-Encoding')) {
+ headers.set('Accept-Encoding', 'gzip,deflate');
+ }
- // Find the basename of the path by looking for the last non-empty segment
- var filename
- var i
- for (i = f.length - 1; i >= 0; i--) {
- filename = f[i]
- if (filename) break
- }
+ let agent = request.agent;
+ if (typeof agent === 'function') {
+ agent = agent(parsedURL);
+ }
- for (i = 0; i < set.length; i++) {
- var pattern = set[i]
- var file = f
- if (options.matchBase && pattern.length === 1) {
- file = [filename]
- }
- var hit = this.matchOne(file, pattern, partial)
- if (hit) {
- if (options.flipNegate) return true
- return !this.negate
- }
- }
+ // HTTP-network fetch step 4.2
+ // chunked encoding is handled by Node.js
- // didn't get any hits. this is success if it's a negative
- // pattern, failure otherwise.
- if (options.flipNegate) return false
- return this.negate
+ return Object.assign({}, parsedURL, {
+ method: request.method,
+ headers: exportNodeCompatibleHeaders(headers),
+ agent
+ });
}
-// set partial to true to test if, for example,
-// "/a/b" matches the start of "/*/b/*/d"
-// Partial means, if you run out of file before you run
-// out of pattern, then that's fine, as long as all
-// the parts match.
-Minimatch.prototype.matchOne = function (file, pattern, partial) {
- var options = this.options
+/**
+ * abort-error.js
+ *
+ * AbortError interface for cancelled requests
+ */
- this.debug('matchOne',
- { 'this': this, file: file, pattern: pattern })
+/**
+ * Create AbortError instance
+ *
+ * @param String message Error message for human
+ * @return AbortError
+ */
+function AbortError(message) {
+ Error.call(this, message);
- this.debug('matchOne', file.length, pattern.length)
+ this.type = 'aborted';
+ this.message = message;
- for (var fi = 0,
- pi = 0,
- fl = file.length,
- pl = pattern.length
- ; (fi < fl) && (pi < pl)
- ; fi++, pi++) {
- this.debug('matchOne loop')
- var p = pattern[pi]
- var f = file[fi]
+ // hide custom error implementation details from end-users
+ Error.captureStackTrace(this, this.constructor);
+}
- this.debug(pattern, p, f)
+AbortError.prototype = Object.create(Error.prototype);
+AbortError.prototype.constructor = AbortError;
+AbortError.prototype.name = 'AbortError';
- // should be impossible.
- // some invalid regexp stuff in the set.
- /* istanbul ignore if */
- if (p === false) return false
+const URL$1 = Url.URL || whatwgUrl.URL;
- if (p === GLOBSTAR) {
- this.debug('GLOBSTAR', [pattern, p, f])
+// fix an issue where "PassThrough", "resolve" aren't a named export for node <10
+const PassThrough$1 = Stream.PassThrough;
- // "**"
- // a/**/b/**/c would match the following:
- // a/b/x/y/z/c
- // a/x/y/z/b/c
- // a/b/x/b/x/c
- // a/b/c
- // To do this, take the rest of the pattern after
- // the **, and see if it would match the file remainder.
- // If so, return success.
- // If not, the ** "swallows" a segment, and try again.
- // This is recursively awful.
- //
- // a/**/b/**/c matching a/b/x/y/z/c
- // - a matches a
- // - doublestar
- // - matchOne(b/x/y/z/c, b/**/c)
- // - b matches b
- // - doublestar
- // - matchOne(x/y/z/c, c) -> no
- // - matchOne(y/z/c, c) -> no
- // - matchOne(z/c, c) -> no
- // - matchOne(c, c) yes, hit
- var fr = fi
- var pr = pi + 1
- if (pr === pl) {
- this.debug('** at the end')
- // a ** at the end will just swallow the rest.
- // We have found a match.
- // however, it will not swallow /.x, unless
- // options.dot is set.
- // . and .. are *never* matched by **, for explosively
- // exponential reasons.
- for (; fi < fl; fi++) {
- if (file[fi] === '.' || file[fi] === '..' ||
- (!options.dot && file[fi].charAt(0) === '.')) return false
- }
- return true
- }
+const isDomainOrSubdomain = function isDomainOrSubdomain(destination, original) {
+ const orig = new URL$1(original).hostname;
+ const dest = new URL$1(destination).hostname;
- // ok, let's see if we can swallow whatever we can.
- while (fr < fl) {
- var swallowee = file[fr]
+ return orig === dest || orig[orig.length - dest.length - 1] === '.' && orig.endsWith(dest);
+};
- this.debug('\nglobstar while', file, fr, pattern, pr, swallowee)
+/**
+ * isSameProtocol reports whether the two provided URLs use the same protocol.
+ *
+ * Both domains must already be in canonical form.
+ * @param {string|URL} original
+ * @param {string|URL} destination
+ */
+const isSameProtocol = function isSameProtocol(destination, original) {
+ const orig = new URL$1(original).protocol;
+ const dest = new URL$1(destination).protocol;
- // XXX remove this slice. Just pass the start index.
- if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
- this.debug('globstar found match!', fr, fl, swallowee)
- // found a match.
- return true
- } else {
- // can't swallow "." or ".." ever.
- // can only swallow ".foo" when explicitly asked.
- if (swallowee === '.' || swallowee === '..' ||
- (!options.dot && swallowee.charAt(0) === '.')) {
- this.debug('dot detected!', file, fr, pattern, pr)
- break
- }
+ return orig === dest;
+};
- // ** swallows a segment, and continue.
- this.debug('globstar swallow a segment, and continue')
- fr++
- }
- }
+/**
+ * Fetch function
+ *
+ * @param Mixed url Absolute url or Request instance
+ * @param Object opts Fetch options
+ * @return Promise
+ */
+function fetch(url, opts) {
- // no match was found.
- // However, in partial mode, we can't say this is necessarily over.
- // If there's more *pattern* left, then
- /* istanbul ignore if */
- if (partial) {
- // ran out of file
- this.debug('\n>>> no match, partial?', file, fr, pattern, pr)
- if (fr === fl) return true
- }
- return false
- }
+ // allow custom promise
+ if (!fetch.Promise) {
+ throw new Error('native promise missing, set fetch.Promise to your favorite alternative');
+ }
- // something other than **
- // non-magic patterns just have to match exactly
- // patterns with magic have been turned into regexps.
- var hit
- if (typeof p === 'string') {
- hit = f === p
- this.debug('string match', p, f, hit)
- } else {
- hit = f.match(p)
- this.debug('pattern match', p, f, hit)
- }
+ Body.Promise = fetch.Promise;
- if (!hit) return false
- }
+ // wrap http.request into fetch
+ return new fetch.Promise(function (resolve, reject) {
+ // build request object
+ const request = new Request(url, opts);
+ const options = getNodeRequestOptions(request);
- // Note: ending in / means that we'll get a final ""
- // at the end of the pattern. This can only match a
- // corresponding "" at the end of the file.
- // If the file ends in /, then it can only match a
- // a pattern that ends in /, unless the pattern just
- // doesn't have any more for it. But, a/b/ should *not*
- // match "a/b/*", even though "" matches against the
- // [^/]*? pattern, except in partial mode, where it might
- // simply not be reached yet.
- // However, a/b/ should still satisfy a/*
+ const send = (options.protocol === 'https:' ? https : http).request;
+ const signal = request.signal;
- // now either we fell off the end of the pattern, or we're done.
- if (fi === fl && pi === pl) {
- // ran out of pattern and filename at the same time.
- // an exact hit!
- return true
- } else if (fi === fl) {
- // ran out of file, but still had pattern left.
- // this is ok if we're doing the match as part of
- // a glob fs traversal.
- return partial
- } else /* istanbul ignore else */ if (pi === pl) {
- // ran out of pattern, still have file left.
- // this is only acceptable if we're on the very last
- // empty segment of a file with a trailing slash.
- // a/* should match a/b/
- return (fi === fl - 1) && (file[fi] === '')
- }
+ let response = null;
- // should be unreachable.
- /* istanbul ignore next */
- throw new Error('wtf?')
-}
+ const abort = function abort() {
+ let error = new AbortError('The user aborted a request.');
+ reject(error);
+ if (request.body && request.body instanceof Stream.Readable) {
+ destroyStream(request.body, error);
+ }
+ if (!response || !response.body) return;
+ response.body.emit('error', error);
+ };
-// replace stuff like \* with *
-function globUnescape (s) {
- return s.replace(/\\(.)/g, '$1')
-}
+ if (signal && signal.aborted) {
+ abort();
+ return;
+ }
-function regExpEscape (s) {
- return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')
-}
+ const abortAndFinalize = function abortAndFinalize() {
+ abort();
+ finalize();
+ };
+ // send request
+ const req = send(options);
+ let reqTimeout;
-/***/ }),
+ if (signal) {
+ signal.addEventListener('abort', abortAndFinalize);
+ }
-/***/ 467:
-/***/ ((module, exports, __nccwpck_require__) => {
+ function finalize() {
+ req.abort();
+ if (signal) signal.removeEventListener('abort', abortAndFinalize);
+ clearTimeout(reqTimeout);
+ }
-"use strict";
+ if (request.timeout) {
+ req.once('socket', function (socket) {
+ reqTimeout = setTimeout(function () {
+ reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout'));
+ finalize();
+ }, request.timeout);
+ });
+ }
+ req.on('error', function (err) {
+ reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err));
-Object.defineProperty(exports, "__esModule", ({ value: true }));
+ if (response && response.body) {
+ destroyStream(response.body, err);
+ }
-function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
+ finalize();
+ });
-var Stream = _interopDefault(__nccwpck_require__(2413));
-var http = _interopDefault(__nccwpck_require__(8605));
-var Url = _interopDefault(__nccwpck_require__(8835));
-var whatwgUrl = _interopDefault(__nccwpck_require__(3323));
-var https = _interopDefault(__nccwpck_require__(7211));
-var zlib = _interopDefault(__nccwpck_require__(8761));
+ fixResponseChunkedTransferBadEnding(req, function (err) {
+ if (signal && signal.aborted) {
+ return;
+ }
-// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js
+ if (response && response.body) {
+ destroyStream(response.body, err);
+ }
+ });
-// fix for "Readable" isn't a named export issue
-const Readable = Stream.Readable;
+ /* c8 ignore next 18 */
+ if (parseInt(process.version.substring(1)) < 14) {
+ // Before Node.js 14, pipeline() does not fully support async iterators and does not always
+ // properly handle when the socket close/end events are out of order.
+ req.on('socket', function (s) {
+ s.addListener('close', function (hadError) {
+ // if a data listener is still present we didn't end cleanly
+ const hasDataListener = s.listenerCount('data') > 0;
+
+ // if end happened before close but the socket didn't emit an error, do it now
+ if (response && hasDataListener && !hadError && !(signal && signal.aborted)) {
+ const err = new Error('Premature close');
+ err.code = 'ERR_STREAM_PREMATURE_CLOSE';
+ response.body.emit('error', err);
+ }
+ });
+ });
+ }
-const BUFFER = Symbol('buffer');
-const TYPE = Symbol('type');
+ req.on('response', function (res) {
+ clearTimeout(reqTimeout);
-class Blob {
- constructor() {
- this[TYPE] = '';
+ const headers = createHeadersLenient(res.headers);
- const blobParts = arguments[0];
- const options = arguments[1];
+ // HTTP fetch step 5
+ if (fetch.isRedirect(res.statusCode)) {
+ // HTTP fetch step 5.2
+ const location = headers.get('Location');
- const buffers = [];
- let size = 0;
+ // HTTP fetch step 5.3
+ let locationURL = null;
+ try {
+ locationURL = location === null ? null : new URL$1(location, request.url).toString();
+ } catch (err) {
+ // error here can only be invalid URL in Location: header
+ // do not throw when options.redirect == manual
+ // let the user extract the errorneous redirect URL
+ if (request.redirect !== 'manual') {
+ reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect'));
+ finalize();
+ return;
+ }
+ }
- if (blobParts) {
- const a = blobParts;
- const length = Number(a.length);
- for (let i = 0; i < length; i++) {
- const element = a[i];
- let buffer;
- if (element instanceof Buffer) {
- buffer = element;
- } else if (ArrayBuffer.isView(element)) {
- buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength);
- } else if (element instanceof ArrayBuffer) {
- buffer = Buffer.from(element);
- } else if (element instanceof Blob) {
- buffer = element[BUFFER];
- } else {
- buffer = Buffer.from(typeof element === 'string' ? element : String(element));
+ // HTTP fetch step 5.5
+ switch (request.redirect) {
+ case 'error':
+ reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect'));
+ finalize();
+ return;
+ case 'manual':
+ // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL.
+ if (locationURL !== null) {
+ // handle corrupted header
+ try {
+ headers.set('Location', locationURL);
+ } catch (err) {
+ // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request
+ reject(err);
+ }
+ }
+ break;
+ case 'follow':
+ // HTTP-redirect fetch step 2
+ if (locationURL === null) {
+ break;
+ }
+
+ // HTTP-redirect fetch step 5
+ if (request.counter >= request.follow) {
+ reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect'));
+ finalize();
+ return;
+ }
+
+ // HTTP-redirect fetch step 6 (counter increment)
+ // Create a new Request object.
+ const requestOpts = {
+ headers: new Headers(request.headers),
+ follow: request.follow,
+ counter: request.counter + 1,
+ agent: request.agent,
+ compress: request.compress,
+ method: request.method,
+ body: request.body,
+ signal: request.signal,
+ timeout: request.timeout,
+ size: request.size
+ };
+
+ if (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) {
+ for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) {
+ requestOpts.headers.delete(name);
+ }
+ }
+
+ // HTTP-redirect fetch step 9
+ if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) {
+ reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect'));
+ finalize();
+ return;
+ }
+
+ // HTTP-redirect fetch step 11
+ if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') {
+ requestOpts.method = 'GET';
+ requestOpts.body = undefined;
+ requestOpts.headers.delete('content-length');
+ }
+
+ // HTTP-redirect fetch step 15
+ resolve(fetch(new Request(locationURL, requestOpts)));
+ finalize();
+ return;
}
- size += buffer.length;
- buffers.push(buffer);
}
- }
- this[BUFFER] = Buffer.concat(buffers);
+ // prepare response
+ res.once('end', function () {
+ if (signal) signal.removeEventListener('abort', abortAndFinalize);
+ });
+ let body = res.pipe(new PassThrough$1());
- let type = options && options.type !== undefined && String(options.type).toLowerCase();
- if (type && !/[^\u0020-\u007E]/.test(type)) {
- this[TYPE] = type;
- }
- }
- get size() {
- return this[BUFFER].length;
- }
- get type() {
- return this[TYPE];
- }
- text() {
- return Promise.resolve(this[BUFFER].toString());
- }
- arrayBuffer() {
- const buf = this[BUFFER];
- const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
- return Promise.resolve(ab);
- }
- stream() {
- const readable = new Readable();
- readable._read = function () {};
- readable.push(this[BUFFER]);
- readable.push(null);
- return readable;
- }
- toString() {
- return '[object Blob]';
- }
- slice() {
- const size = this.size;
+ const response_options = {
+ url: request.url,
+ status: res.statusCode,
+ statusText: res.statusMessage,
+ headers: headers,
+ size: request.size,
+ timeout: request.timeout,
+ counter: request.counter
+ };
- const start = arguments[0];
- const end = arguments[1];
- let relativeStart, relativeEnd;
- if (start === undefined) {
- relativeStart = 0;
- } else if (start < 0) {
- relativeStart = Math.max(size + start, 0);
- } else {
- relativeStart = Math.min(start, size);
- }
- if (end === undefined) {
- relativeEnd = size;
- } else if (end < 0) {
- relativeEnd = Math.max(size + end, 0);
- } else {
- relativeEnd = Math.min(end, size);
- }
- const span = Math.max(relativeEnd - relativeStart, 0);
+ // HTTP-network fetch step 12.1.1.3
+ const codings = headers.get('Content-Encoding');
- const buffer = this[BUFFER];
- const slicedBuffer = buffer.slice(relativeStart, relativeStart + span);
- const blob = new Blob([], { type: arguments[2] });
- blob[BUFFER] = slicedBuffer;
- return blob;
- }
-}
+ // HTTP-network fetch step 12.1.1.4: handle content codings
-Object.defineProperties(Blob.prototype, {
- size: { enumerable: true },
- type: { enumerable: true },
- slice: { enumerable: true }
-});
+ // in following scenarios we ignore compression support
+ // 1. compression support is disabled
+ // 2. HEAD request
+ // 3. no Content-Encoding header
+ // 4. no content response (204)
+ // 5. content not modified response (304)
+ if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) {
+ response = new Response(body, response_options);
+ resolve(response);
+ return;
+ }
-Object.defineProperty(Blob.prototype, Symbol.toStringTag, {
- value: 'Blob',
- writable: false,
- enumerable: false,
- configurable: true
-});
+ // For Node v6+
+ // Be less strict when decoding compressed responses, since sometimes
+ // servers send slightly invalid responses that are still accepted
+ // by common browsers.
+ // Always using Z_SYNC_FLUSH is what cURL does.
+ const zlibOptions = {
+ flush: zlib.Z_SYNC_FLUSH,
+ finishFlush: zlib.Z_SYNC_FLUSH
+ };
-/**
- * fetch-error.js
- *
- * FetchError interface for operational errors
- */
+ // for gzip
+ if (codings == 'gzip' || codings == 'x-gzip') {
+ body = body.pipe(zlib.createGunzip(zlibOptions));
+ response = new Response(body, response_options);
+ resolve(response);
+ return;
+ }
-/**
- * Create FetchError instance
- *
- * @param String message Error message for human
- * @param String type Error type for machine
- * @param String systemError For Node.js system error
- * @return FetchError
- */
-function FetchError(message, type, systemError) {
- Error.call(this, message);
+ // for deflate
+ if (codings == 'deflate' || codings == 'x-deflate') {
+ // handle the infamous raw deflate response from old servers
+ // a hack for old IIS and Apache servers
+ const raw = res.pipe(new PassThrough$1());
+ raw.once('data', function (chunk) {
+ // see http://stackoverflow.com/questions/37519828
+ if ((chunk[0] & 0x0F) === 0x08) {
+ body = body.pipe(zlib.createInflate());
+ } else {
+ body = body.pipe(zlib.createInflateRaw());
+ }
+ response = new Response(body, response_options);
+ resolve(response);
+ });
+ raw.on('end', function () {
+ // some old IIS servers return zero-length OK deflate responses, so 'data' is never emitted.
+ if (!response) {
+ response = new Response(body, response_options);
+ resolve(response);
+ }
+ });
+ return;
+ }
- this.message = message;
- this.type = type;
+ // for br
+ if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') {
+ body = body.pipe(zlib.createBrotliDecompress());
+ response = new Response(body, response_options);
+ resolve(response);
+ return;
+ }
- // when err.type is `system`, err.code contains system error code
- if (systemError) {
- this.code = this.errno = systemError.code;
- }
+ // otherwise, use response as-is
+ response = new Response(body, response_options);
+ resolve(response);
+ });
- // hide custom error implementation details from end-users
- Error.captureStackTrace(this, this.constructor);
+ writeToStream(req, request);
+ });
}
+function fixResponseChunkedTransferBadEnding(request, errorCallback) {
+ let socket;
-FetchError.prototype = Object.create(Error.prototype);
-FetchError.prototype.constructor = FetchError;
-FetchError.prototype.name = 'FetchError';
-
-let convert;
-try {
- convert = __nccwpck_require__(2877).convert;
-} catch (e) {}
+ request.on('socket', function (s) {
+ socket = s;
+ });
-const INTERNALS = Symbol('Body internals');
+ request.on('response', function (response) {
+ const headers = response.headers;
+
+ if (headers['transfer-encoding'] === 'chunked' && !headers['content-length']) {
+ response.once('close', function (hadError) {
+ // tests for socket presence, as in some situations the
+ // the 'socket' event is not triggered for the request
+ // (happens in deno), avoids `TypeError`
+ // if a data listener is still present we didn't end cleanly
+ const hasDataListener = socket && socket.listenerCount('data') > 0;
+
+ if (hasDataListener && !hadError) {
+ const err = new Error('Premature close');
+ err.code = 'ERR_STREAM_PREMATURE_CLOSE';
+ errorCallback(err);
+ }
+ });
+ }
+ });
+}
-// fix an issue where "PassThrough" isn't a named export for node <10
-const PassThrough = Stream.PassThrough;
+function destroyStream(stream, err) {
+ if (stream.destroy) {
+ stream.destroy(err);
+ } else {
+ // node < 8
+ stream.emit('error', err);
+ stream.end();
+ }
+}
/**
- * Body mixin
- *
- * Ref: https://fetch.spec.whatwg.org/#body
+ * Redirect code matching
*
- * @param Stream body Readable stream
- * @param Object opts Response options
- * @return Void
+ * @param Number code Status code
+ * @return Boolean
*/
-function Body(body) {
- var _this = this;
-
- var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
- _ref$size = _ref.size;
+fetch.isRedirect = function (code) {
+ return code === 301 || code === 302 || code === 303 || code === 307 || code === 308;
+};
- let size = _ref$size === undefined ? 0 : _ref$size;
- var _ref$timeout = _ref.timeout;
- let timeout = _ref$timeout === undefined ? 0 : _ref$timeout;
+// expose Promise
+fetch.Promise = global.Promise;
- if (body == null) {
- // body is undefined or null
- body = null;
- } else if (isURLSearchParams(body)) {
- // body is a URLSearchParams
- body = Buffer.from(body.toString());
- } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') {
- // body is ArrayBuffer
- body = Buffer.from(body);
- } else if (ArrayBuffer.isView(body)) {
- // body is ArrayBufferView
- body = Buffer.from(body.buffer, body.byteOffset, body.byteLength);
- } else if (body instanceof Stream) ; else {
- // none of the above
- // coerce to string then buffer
- body = Buffer.from(String(body));
- }
- this[INTERNALS] = {
- body,
- disturbed: false,
- error: null
- };
- this.size = size;
- this.timeout = timeout;
+module.exports = exports = fetch;
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports["default"] = exports;
+exports.Headers = Headers;
+exports.Request = Request;
+exports.Response = Response;
+exports.FetchError = FetchError;
+exports.AbortError = AbortError;
- if (body instanceof Stream) {
- body.on('error', function (err) {
- const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err);
- _this[INTERNALS].error = error;
- });
- }
-}
-Body.prototype = {
- get body() {
- return this[INTERNALS].body;
- },
+/***/ }),
- get bodyUsed() {
- return this[INTERNALS].disturbed;
- },
+/***/ 1223:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- /**
- * Decode response as ArrayBuffer
- *
- * @return Promise
- */
- arrayBuffer() {
- return consumeBody.call(this).then(function (buf) {
- return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
- });
- },
+var wrappy = __nccwpck_require__(2940)
+module.exports = wrappy(once)
+module.exports.strict = wrappy(onceStrict)
- /**
- * Return raw response as Blob
- *
- * @return Promise
- */
- blob() {
- let ct = this.headers && this.headers.get('content-type') || '';
- return consumeBody.call(this).then(function (buf) {
- return Object.assign(
- // Prevent copying
- new Blob([], {
- type: ct.toLowerCase()
- }), {
- [BUFFER]: buf
- });
- });
- },
+once.proto = once(function () {
+ Object.defineProperty(Function.prototype, 'once', {
+ value: function () {
+ return once(this)
+ },
+ configurable: true
+ })
- /**
- * Decode response as json
- *
- * @return Promise
- */
- json() {
- var _this2 = this;
+ Object.defineProperty(Function.prototype, 'onceStrict', {
+ value: function () {
+ return onceStrict(this)
+ },
+ configurable: true
+ })
+})
- return consumeBody.call(this).then(function (buffer) {
- try {
- return JSON.parse(buffer.toString());
- } catch (err) {
- return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json'));
- }
- });
- },
+function once (fn) {
+ var f = function () {
+ if (f.called) return f.value
+ f.called = true
+ return f.value = fn.apply(this, arguments)
+ }
+ f.called = false
+ return f
+}
- /**
- * Decode response as text
- *
- * @return Promise
- */
- text() {
- return consumeBody.call(this).then(function (buffer) {
- return buffer.toString();
- });
- },
+function onceStrict (fn) {
+ var f = function () {
+ if (f.called)
+ throw new Error(f.onceError)
+ f.called = true
+ return f.value = fn.apply(this, arguments)
+ }
+ var name = fn.name || 'Function wrapped with `once`'
+ f.onceError = name + " shouldn't be called more than once"
+ f.called = false
+ return f
+}
- /**
- * Decode response as buffer (non-spec api)
- *
- * @return Promise
- */
- buffer() {
- return consumeBody.call(this);
- },
- /**
- * Decode response as text, while automatically detecting the encoding and
- * trying to decode to UTF-8 (non-spec api)
- *
- * @return Promise
- */
- textConverted() {
- var _this3 = this;
+/***/ }),
- return consumeBody.call(this).then(function (buffer) {
- return convertBody(buffer, _this3.headers);
- });
- }
-};
+/***/ 1855:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-// In browsers, all properties are enumerable.
-Object.defineProperties(Body.prototype, {
- body: { enumerable: true },
- bodyUsed: { enumerable: true },
- arrayBuffer: { enumerable: true },
- blob: { enumerable: true },
- json: { enumerable: true },
- text: { enumerable: true }
-});
+"use strict";
-Body.mixIn = function (proto) {
- for (const name of Object.getOwnPropertyNames(Body.prototype)) {
- // istanbul ignore else: future proof
- if (!(name in proto)) {
- const desc = Object.getOwnPropertyDescriptor(Body.prototype, name);
- Object.defineProperty(proto, name, desc);
- }
- }
-};
+const AggregateError = __nccwpck_require__(1231);
-/**
- * Consume and convert an entire Body to a Buffer.
- *
- * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body
- *
- * @return Promise
- */
-function consumeBody() {
- var _this4 = this;
+module.exports = async (
+ iterable,
+ mapper,
+ {
+ concurrency = Infinity,
+ stopOnError = true
+ } = {}
+) => {
+ return new Promise((resolve, reject) => {
+ if (typeof mapper !== 'function') {
+ throw new TypeError('Mapper function is required');
+ }
- if (this[INTERNALS].disturbed) {
- return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));
- }
+ if (!(typeof concurrency === 'number' && concurrency >= 1)) {
+ throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${concurrency}\` (${typeof concurrency})`);
+ }
- this[INTERNALS].disturbed = true;
+ const ret = [];
+ const errors = [];
+ const iterator = iterable[Symbol.iterator]();
+ let isRejected = false;
+ let isIterableDone = false;
+ let resolvingCount = 0;
+ let currentIndex = 0;
- if (this[INTERNALS].error) {
- return Body.Promise.reject(this[INTERNALS].error);
- }
+ const next = () => {
+ if (isRejected) {
+ return;
+ }
- let body = this.body;
+ const nextItem = iterator.next();
+ const i = currentIndex;
+ currentIndex++;
- // body is null
- if (body === null) {
- return Body.Promise.resolve(Buffer.alloc(0));
- }
+ if (nextItem.done) {
+ isIterableDone = true;
- // body is blob
- if (isBlob(body)) {
- body = body.stream();
- }
+ if (resolvingCount === 0) {
+ if (!stopOnError && errors.length !== 0) {
+ reject(new AggregateError(errors));
+ } else {
+ resolve(ret);
+ }
+ }
- // body is buffer
- if (Buffer.isBuffer(body)) {
- return Body.Promise.resolve(body);
- }
+ return;
+ }
- // istanbul ignore if: should never happen
- if (!(body instanceof Stream)) {
- return Body.Promise.resolve(Buffer.alloc(0));
- }
+ resolvingCount++;
- // body is stream
- // get ready to actually consume the body
- let accum = [];
- let accumBytes = 0;
- let abort = false;
+ (async () => {
+ try {
+ const element = await nextItem.value;
+ ret[i] = await mapper(element, i);
+ resolvingCount--;
+ next();
+ } catch (error) {
+ if (stopOnError) {
+ isRejected = true;
+ reject(error);
+ } else {
+ errors.push(error);
+ resolvingCount--;
+ next();
+ }
+ }
+ })();
+ };
- return new Body.Promise(function (resolve, reject) {
- let resTimeout;
+ for (let i = 0; i < concurrency; i++) {
+ next();
- // allow timeout on slow response body
- if (_this4.timeout) {
- resTimeout = setTimeout(function () {
- abort = true;
- reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout'));
- }, _this4.timeout);
+ if (isIterableDone) {
+ break;
+ }
}
+ });
+};
- // handle stream errors
- body.on('error', function (err) {
- if (err.name === 'AbortError') {
- // if the request was aborted, reject with this Error
- abort = true;
- reject(err);
- } else {
- // other errors, such as incorrect content-encoding
- reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err));
- }
- });
- body.on('data', function (chunk) {
- if (abort || chunk === null) {
- return;
- }
+/***/ }),
- if (_this4.size && accumBytes + chunk.length > _this4.size) {
- abort = true;
- reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size'));
- return;
- }
+/***/ 8714:
+/***/ ((module) => {
- accumBytes += chunk.length;
- accum.push(chunk);
- });
+"use strict";
- body.on('end', function () {
- if (abort) {
- return;
- }
- clearTimeout(resTimeout);
+function posix(path) {
+ return path.charAt(0) === '/';
+}
- try {
- resolve(Buffer.concat(accum, accumBytes));
- } catch (err) {
- // handle streams that have accumulated too much data (issue #414)
- reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err));
- }
- });
- });
+function win32(path) {
+ // https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56
+ var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/;
+ var result = splitDeviceRe.exec(path);
+ var device = result[1] || '';
+ var isUnc = Boolean(device && device.charAt(1) !== ':');
+
+ // UNC paths are always absolute
+ return Boolean(result[2] || isUnc);
}
-/**
- * Detect buffer encoding and convert to target encoding
- * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding
- *
- * @param Buffer buffer Incoming buffer
- * @param String encoding Target encoding
- * @return String
- */
-function convertBody(buffer, headers) {
- if (typeof convert !== 'function') {
- throw new Error('The package `encoding` must be installed to use the textConverted() function');
- }
+module.exports = process.platform === 'win32' ? win32 : posix;
+module.exports.posix = posix;
+module.exports.win32 = win32;
- const ct = headers.get('content-type');
- let charset = 'utf-8';
- let res, str;
- // header
- if (ct) {
- res = /charset=([^;]*)/i.exec(ct);
- }
+/***/ }),
- // no charset in content type, peek at response body for at most 1024 bytes
- str = buffer.slice(0, 1024).toString();
+/***/ 3433:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // html5
- if (!res && str) {
- res = / {
- // don't allow cloning a used body
- if (instance.bodyUsed) {
- throw new Error('cannot clone body after it is used');
- }
+"use strict";
- // check that body is a stream and not form-data object
- // note: we can't clone the form-data object without having it as a dependency
- if (body instanceof Stream && typeof body.getBoundary !== 'function') {
- // tee instance body
- p1 = new PassThrough();
- p2 = new PassThrough();
- body.pipe(p1);
- body.pipe(p2);
- // set instance body to teed body and return the other teed body
- instance[INTERNALS].body = p1;
- body = p2;
- }
- return body;
-}
+module.exports = __nccwpck_require__(3322);
-/**
- * Performs the operation "extract a `Content-Type` value from |object|" as
- * specified in the specification:
- * https://fetch.spec.whatwg.org/#concept-bodyinit-extract
- *
- * This function assumes that instance.body is present.
- *
- * @param Mixed instance Any options.body input
- */
-function extractContentType(body) {
- if (body === null) {
- // body is null
- return null;
- } else if (typeof body === 'string') {
- // body is string
- return 'text/plain;charset=UTF-8';
- } else if (isURLSearchParams(body)) {
- // body is a URLSearchParams
- return 'application/x-www-form-urlencoded;charset=UTF-8';
- } else if (isBlob(body)) {
- // body is blob
- return body.type || null;
- } else if (Buffer.isBuffer(body)) {
- // body is buffer
- return null;
- } else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') {
- // body is ArrayBuffer
- return null;
- } else if (ArrayBuffer.isView(body)) {
- // body is ArrayBufferView
- return null;
- } else if (typeof body.getBoundary === 'function') {
- // detect form data input from form-data module
- return `multipart/form-data;boundary=${body.getBoundary()}`;
- } else if (body instanceof Stream) {
- // body is stream
- // can't really do much about this
- return null;
- } else {
- // Body constructor defaults other things to string
- return 'text/plain;charset=UTF-8';
- }
-}
+
+/***/ }),
+
+/***/ 6099:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+const path = __nccwpck_require__(1017);
+const WIN_SLASH = '\\\\/';
+const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
/**
- * The Fetch Standard treats this as if "total bytes" is a property on the body.
- * For us, we have to explicitly get it with a function.
- *
- * ref: https://fetch.spec.whatwg.org/#concept-body-total-bytes
- *
- * @param Body instance Instance of Body
- * @return Number? Number of bytes, or null if not possible
+ * Posix glob regex
*/
-function getTotalBytes(instance) {
- const body = instance.body;
-
- if (body === null) {
- // body is null
- return 0;
- } else if (isBlob(body)) {
- return body.size;
- } else if (Buffer.isBuffer(body)) {
- // body is buffer
- return body.length;
- } else if (body && typeof body.getLengthSync === 'function') {
- // detect form data input from form-data module
- if (body._lengthRetrievers && body._lengthRetrievers.length == 0 || // 1.x
- body.hasKnownLength && body.hasKnownLength()) {
- // 2.x
- return body.getLengthSync();
- }
- return null;
- } else {
- // body is stream
- return null;
- }
-}
+const DOT_LITERAL = '\\.';
+const PLUS_LITERAL = '\\+';
+const QMARK_LITERAL = '\\?';
+const SLASH_LITERAL = '\\/';
+const ONE_CHAR = '(?=.)';
+const QMARK = '[^/]';
+const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
+const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
+const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
+const NO_DOT = `(?!${DOT_LITERAL})`;
+const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
+const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
+const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
+const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
+const STAR = `${QMARK}*?`;
+
+const POSIX_CHARS = {
+ DOT_LITERAL,
+ PLUS_LITERAL,
+ QMARK_LITERAL,
+ SLASH_LITERAL,
+ ONE_CHAR,
+ QMARK,
+ END_ANCHOR,
+ DOTS_SLASH,
+ NO_DOT,
+ NO_DOTS,
+ NO_DOT_SLASH,
+ NO_DOTS_SLASH,
+ QMARK_NO_DOT,
+ STAR,
+ START_ANCHOR
+};
/**
- * Write a Body to a Node.js WritableStream (e.g. http.Request) object.
- *
- * @param Body instance Instance of Body
- * @return Void
+ * Windows glob regex
*/
-function writeToStream(dest, instance) {
- const body = instance.body;
-
- if (body === null) {
- // body is null
- dest.end();
- } else if (isBlob(body)) {
- body.stream().pipe(dest);
- } else if (Buffer.isBuffer(body)) {
- // body is buffer
- dest.write(body);
- dest.end();
- } else {
- // body is stream
- body.pipe(dest);
- }
-}
+const WINDOWS_CHARS = {
+ ...POSIX_CHARS,
-// expose Promise
-Body.Promise = global.Promise;
+ SLASH_LITERAL: `[${WIN_SLASH}]`,
+ QMARK: WIN_NO_SLASH,
+ STAR: `${WIN_NO_SLASH}*?`,
+ DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
+ NO_DOT: `(?!${DOT_LITERAL})`,
+ NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
+ NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
+ NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
+ QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
+ START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
+ END_ANCHOR: `(?:[${WIN_SLASH}]|$)`
+};
/**
- * headers.js
- *
- * Headers class offers convenient helpers
+ * POSIX Bracket Regex
*/
-const invalidTokenRegex = /[^\^_`a-zA-Z\-0-9!#$%&'*+.|~]/;
-const invalidHeaderCharRegex = /[^\t\x20-\x7e\x80-\xff]/;
+const POSIX_REGEX_SOURCE = {
+ alnum: 'a-zA-Z0-9',
+ alpha: 'a-zA-Z',
+ ascii: '\\x00-\\x7F',
+ blank: ' \\t',
+ cntrl: '\\x00-\\x1F\\x7F',
+ digit: '0-9',
+ graph: '\\x21-\\x7E',
+ lower: 'a-z',
+ print: '\\x20-\\x7E ',
+ punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
+ space: ' \\t\\r\\n\\v\\f',
+ upper: 'A-Z',
+ word: 'A-Za-z0-9_',
+ xdigit: 'A-Fa-f0-9'
+};
-function validateName(name) {
- name = `${name}`;
- if (invalidTokenRegex.test(name) || name === '') {
- throw new TypeError(`${name} is not a legal HTTP header name`);
- }
-}
+module.exports = {
+ MAX_LENGTH: 1024 * 64,
+ POSIX_REGEX_SOURCE,
-function validateValue(value) {
- value = `${value}`;
- if (invalidHeaderCharRegex.test(value)) {
- throw new TypeError(`${value} is not a legal HTTP header value`);
- }
-}
+ // regular expressions
+ REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
+ REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
+ REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
+ REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
+ REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
+ REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
-/**
- * Find the key in the map object given a header name.
- *
- * Returns undefined if not found.
- *
- * @param String name Header name
- * @return String|Undefined
- */
-function find(map, name) {
- name = name.toLowerCase();
- for (const key in map) {
- if (key.toLowerCase() === name) {
- return key;
- }
- }
- return undefined;
-}
+ // Replace globs with equivalent patterns to reduce parsing time.
+ REPLACEMENTS: {
+ '***': '*',
+ '**/**': '**',
+ '**/**/**': '**'
+ },
-const MAP = Symbol('map');
-class Headers {
- /**
- * Headers class
- *
- * @param Object headers Response headers
- * @return Void
- */
- constructor() {
- let init = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : undefined;
+ // Digits
+ CHAR_0: 48, /* 0 */
+ CHAR_9: 57, /* 9 */
- this[MAP] = Object.create(null);
+ // Alphabet chars.
+ CHAR_UPPERCASE_A: 65, /* A */
+ CHAR_LOWERCASE_A: 97, /* a */
+ CHAR_UPPERCASE_Z: 90, /* Z */
+ CHAR_LOWERCASE_Z: 122, /* z */
- if (init instanceof Headers) {
- const rawHeaders = init.raw();
- const headerNames = Object.keys(rawHeaders);
+ CHAR_LEFT_PARENTHESES: 40, /* ( */
+ CHAR_RIGHT_PARENTHESES: 41, /* ) */
- for (const headerName of headerNames) {
- for (const value of rawHeaders[headerName]) {
- this.append(headerName, value);
- }
- }
+ CHAR_ASTERISK: 42, /* * */
- return;
- }
+ // Non-alphabetic chars.
+ CHAR_AMPERSAND: 38, /* & */
+ CHAR_AT: 64, /* @ */
+ CHAR_BACKWARD_SLASH: 92, /* \ */
+ CHAR_CARRIAGE_RETURN: 13, /* \r */
+ CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */
+ CHAR_COLON: 58, /* : */
+ CHAR_COMMA: 44, /* , */
+ CHAR_DOT: 46, /* . */
+ CHAR_DOUBLE_QUOTE: 34, /* " */
+ CHAR_EQUAL: 61, /* = */
+ CHAR_EXCLAMATION_MARK: 33, /* ! */
+ CHAR_FORM_FEED: 12, /* \f */
+ CHAR_FORWARD_SLASH: 47, /* / */
+ CHAR_GRAVE_ACCENT: 96, /* ` */
+ CHAR_HASH: 35, /* # */
+ CHAR_HYPHEN_MINUS: 45, /* - */
+ CHAR_LEFT_ANGLE_BRACKET: 60, /* < */
+ CHAR_LEFT_CURLY_BRACE: 123, /* { */
+ CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */
+ CHAR_LINE_FEED: 10, /* \n */
+ CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */
+ CHAR_PERCENT: 37, /* % */
+ CHAR_PLUS: 43, /* + */
+ CHAR_QUESTION_MARK: 63, /* ? */
+ CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */
+ CHAR_RIGHT_CURLY_BRACE: 125, /* } */
+ CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */
+ CHAR_SEMICOLON: 59, /* ; */
+ CHAR_SINGLE_QUOTE: 39, /* ' */
+ CHAR_SPACE: 32, /* */
+ CHAR_TAB: 9, /* \t */
+ CHAR_UNDERSCORE: 95, /* _ */
+ CHAR_VERTICAL_LINE: 124, /* | */
+ CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */
- // We don't worry about converting prop to ByteString here as append()
- // will handle it.
- if (init == null) ; else if (typeof init === 'object') {
- const method = init[Symbol.iterator];
- if (method != null) {
- if (typeof method !== 'function') {
- throw new TypeError('Header pairs must be iterable');
- }
+ SEP: path.sep,
- // sequence>
- // Note: per spec we have to first exhaust the lists then process them
- const pairs = [];
- for (const pair of init) {
- if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') {
- throw new TypeError('Each header pair must be iterable');
- }
- pairs.push(Array.from(pair));
- }
+ /**
+ * Create EXTGLOB_CHARS
+ */
- for (const pair of pairs) {
- if (pair.length !== 2) {
- throw new TypeError('Each header pair must be a name/value tuple');
- }
- this.append(pair[0], pair[1]);
- }
- } else {
- // record
- for (const key of Object.keys(init)) {
- const value = init[key];
- this.append(key, value);
- }
- }
- } else {
- throw new TypeError('Provided initializer must be an object');
- }
- }
+ extglobChars(chars) {
+ return {
+ '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` },
+ '?': { type: 'qmark', open: '(?:', close: ')?' },
+ '+': { type: 'plus', open: '(?:', close: ')+' },
+ '*': { type: 'star', open: '(?:', close: ')*' },
+ '@': { type: 'at', open: '(?:', close: ')' }
+ };
+ },
- /**
- * Return combined header value given name
- *
- * @param String name Header name
- * @return Mixed
- */
- get(name) {
- name = `${name}`;
- validateName(name);
- const key = find(this[MAP], name);
- if (key === undefined) {
- return null;
- }
+ /**
+ * Create GLOB_CHARS
+ */
- return this[MAP][key].join(', ');
- }
+ globChars(win32) {
+ return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
+ }
+};
- /**
- * Iterate over all headers
- *
- * @param Function callback Executed for each item with parameters (value, name, thisArg)
- * @param Boolean thisArg `this` context for callback function
- * @return Void
- */
- forEach(callback) {
- let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;
- let pairs = getHeaders(this);
- let i = 0;
- while (i < pairs.length) {
- var _pairs$i = pairs[i];
- const name = _pairs$i[0],
- value = _pairs$i[1];
+/***/ }),
- callback.call(thisArg, value, name, this);
- pairs = getHeaders(this);
- i++;
- }
- }
+/***/ 2139:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- /**
- * Overwrite header values given name
- *
- * @param String name Header name
- * @param String value Header value
- * @return Void
- */
- set(name, value) {
- name = `${name}`;
- value = `${value}`;
- validateName(name);
- validateValue(value);
- const key = find(this[MAP], name);
- this[MAP][key !== undefined ? key : name] = [value];
- }
+"use strict";
- /**
- * Append a value onto existing header
- *
- * @param String name Header name
- * @param String value Header value
- * @return Void
- */
- append(name, value) {
- name = `${name}`;
- value = `${value}`;
- validateName(name);
- validateValue(value);
- const key = find(this[MAP], name);
- if (key !== undefined) {
- this[MAP][key].push(value);
- } else {
- this[MAP][name] = [value];
- }
- }
- /**
- * Check for header name existence
- *
- * @param String name Header name
- * @return Boolean
- */
- has(name) {
- name = `${name}`;
- validateName(name);
- return find(this[MAP], name) !== undefined;
- }
+const constants = __nccwpck_require__(6099);
+const utils = __nccwpck_require__(479);
- /**
- * Delete all header values given name
- *
- * @param String name Header name
- * @return Void
- */
- delete(name) {
- name = `${name}`;
- validateName(name);
- const key = find(this[MAP], name);
- if (key !== undefined) {
- delete this[MAP][key];
- }
- }
+/**
+ * Constants
+ */
- /**
- * Return raw headers (non-spec api)
- *
- * @return Object
- */
- raw() {
- return this[MAP];
- }
+const {
+ MAX_LENGTH,
+ POSIX_REGEX_SOURCE,
+ REGEX_NON_SPECIAL_CHARS,
+ REGEX_SPECIAL_CHARS_BACKREF,
+ REPLACEMENTS
+} = constants;
- /**
- * Get an iterator on keys.
- *
- * @return Iterator
- */
- keys() {
- return createHeadersIterator(this, 'key');
- }
+/**
+ * Helpers
+ */
- /**
- * Get an iterator on values.
- *
- * @return Iterator
- */
- values() {
- return createHeadersIterator(this, 'value');
- }
+const expandRange = (args, options) => {
+ if (typeof options.expandRange === 'function') {
+ return options.expandRange(...args, options);
+ }
- /**
- * Get an iterator on entries.
- *
- * This is the default iterator of the Headers object.
- *
- * @return Iterator
- */
- [Symbol.iterator]() {
- return createHeadersIterator(this, 'key+value');
- }
-}
-Headers.prototype.entries = Headers.prototype[Symbol.iterator];
+ args.sort();
+ const value = `[${args.join('-')}]`;
-Object.defineProperty(Headers.prototype, Symbol.toStringTag, {
- value: 'Headers',
- writable: false,
- enumerable: false,
- configurable: true
-});
+ try {
+ /* eslint-disable-next-line no-new */
+ new RegExp(value);
+ } catch (ex) {
+ return args.map(v => utils.escapeRegex(v)).join('..');
+ }
-Object.defineProperties(Headers.prototype, {
- get: { enumerable: true },
- forEach: { enumerable: true },
- set: { enumerable: true },
- append: { enumerable: true },
- has: { enumerable: true },
- delete: { enumerable: true },
- keys: { enumerable: true },
- values: { enumerable: true },
- entries: { enumerable: true }
-});
+ return value;
+};
-function getHeaders(headers) {
- let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value';
+/**
+ * Create the message for a syntax error
+ */
- const keys = Object.keys(headers[MAP]).sort();
- return keys.map(kind === 'key' ? function (k) {
- return k.toLowerCase();
- } : kind === 'value' ? function (k) {
- return headers[MAP][k].join(', ');
- } : function (k) {
- return [k.toLowerCase(), headers[MAP][k].join(', ')];
- });
-}
+const syntaxError = (type, char) => {
+ return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
+};
-const INTERNAL = Symbol('internal');
+/**
+ * Parse the given input string.
+ * @param {String} input
+ * @param {Object} options
+ * @return {Object}
+ */
-function createHeadersIterator(target, kind) {
- const iterator = Object.create(HeadersIteratorPrototype);
- iterator[INTERNAL] = {
- target,
- kind,
- index: 0
- };
- return iterator;
-}
+const parse = (input, options) => {
+ if (typeof input !== 'string') {
+ throw new TypeError('Expected a string');
+ }
-const HeadersIteratorPrototype = Object.setPrototypeOf({
- next() {
- // istanbul ignore if
- if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) {
- throw new TypeError('Value of `this` is not a HeadersIterator');
- }
+ input = REPLACEMENTS[input] || input;
- var _INTERNAL = this[INTERNAL];
- const target = _INTERNAL.target,
- kind = _INTERNAL.kind,
- index = _INTERNAL.index;
+ const opts = { ...options };
+ const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
- const values = getHeaders(target, kind);
- const len = values.length;
- if (index >= len) {
- return {
- value: undefined,
- done: true
- };
- }
+ let len = input.length;
+ if (len > max) {
+ throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
+ }
- this[INTERNAL].index = index + 1;
+ const bos = { type: 'bos', value: '', output: opts.prepend || '' };
+ const tokens = [bos];
- return {
- value: values[index],
- done: false
- };
- }
-}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())));
+ const capture = opts.capture ? '' : '?:';
+ const win32 = utils.isWindows(options);
-Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, {
- value: 'HeadersIterator',
- writable: false,
- enumerable: false,
- configurable: true
-});
+ // create constants based on platform, for windows or posix
+ const PLATFORM_CHARS = constants.globChars(win32);
+ const EXTGLOB_CHARS = constants.extglobChars(PLATFORM_CHARS);
-/**
- * Export the Headers object in a form that Node.js can consume.
- *
- * @param Headers headers
- * @return Object
- */
-function exportNodeCompatibleHeaders(headers) {
- const obj = Object.assign({ __proto__: null }, headers[MAP]);
+ const {
+ DOT_LITERAL,
+ PLUS_LITERAL,
+ SLASH_LITERAL,
+ ONE_CHAR,
+ DOTS_SLASH,
+ NO_DOT,
+ NO_DOT_SLASH,
+ NO_DOTS_SLASH,
+ QMARK,
+ QMARK_NO_DOT,
+ STAR,
+ START_ANCHOR
+ } = PLATFORM_CHARS;
- // http.request() only supports string as Host header. This hack makes
- // specifying custom Host header possible.
- const hostHeaderKey = find(headers[MAP], 'Host');
- if (hostHeaderKey !== undefined) {
- obj[hostHeaderKey] = obj[hostHeaderKey][0];
- }
+ const globstar = opts => {
+ return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
+ };
- return obj;
-}
+ const nodot = opts.dot ? '' : NO_DOT;
+ const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
+ let star = opts.bash === true ? globstar(opts) : STAR;
-/**
- * Create a Headers object from an object of headers, ignoring those that do
- * not conform to HTTP grammar productions.
- *
- * @param Object obj Object of headers
- * @return Headers
- */
-function createHeadersLenient(obj) {
- const headers = new Headers();
- for (const name of Object.keys(obj)) {
- if (invalidTokenRegex.test(name)) {
- continue;
- }
- if (Array.isArray(obj[name])) {
- for (const val of obj[name]) {
- if (invalidHeaderCharRegex.test(val)) {
- continue;
- }
- if (headers[MAP][name] === undefined) {
- headers[MAP][name] = [val];
- } else {
- headers[MAP][name].push(val);
- }
- }
- } else if (!invalidHeaderCharRegex.test(obj[name])) {
- headers[MAP][name] = [obj[name]];
- }
- }
- return headers;
-}
+ if (opts.capture) {
+ star = `(${star})`;
+ }
-const INTERNALS$1 = Symbol('Response internals');
+ // minimatch options support
+ if (typeof opts.noext === 'boolean') {
+ opts.noextglob = opts.noext;
+ }
-// fix an issue where "STATUS_CODES" aren't a named export for node <10
-const STATUS_CODES = http.STATUS_CODES;
+ const state = {
+ input,
+ index: -1,
+ start: 0,
+ dot: opts.dot === true,
+ consumed: '',
+ output: '',
+ prefix: '',
+ backtrack: false,
+ negated: false,
+ brackets: 0,
+ braces: 0,
+ parens: 0,
+ quotes: 0,
+ globstar: false,
+ tokens
+ };
-/**
- * Response class
- *
- * @param Stream body Readable stream
- * @param Object opts Response options
- * @return Void
- */
-class Response {
- constructor() {
- let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
- let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
+ input = utils.removePrefix(input, state);
+ len = input.length;
- Body.call(this, body, opts);
+ const extglobs = [];
+ const braces = [];
+ const stack = [];
+ let prev = bos;
+ let value;
- const status = opts.status || 200;
- const headers = new Headers(opts.headers);
+ /**
+ * Tokenizing helpers
+ */
- if (body != null && !headers.has('Content-Type')) {
- const contentType = extractContentType(body);
- if (contentType) {
- headers.append('Content-Type', contentType);
- }
- }
+ const eos = () => state.index === len - 1;
+ const peek = state.peek = (n = 1) => input[state.index + n];
+ const advance = state.advance = () => input[++state.index] || '';
+ const remaining = () => input.slice(state.index + 1);
+ const consume = (value = '', num = 0) => {
+ state.consumed += value;
+ state.index += num;
+ };
- this[INTERNALS$1] = {
- url: opts.url,
- status,
- statusText: opts.statusText || STATUS_CODES[status],
- headers,
- counter: opts.counter
- };
- }
+ const append = token => {
+ state.output += token.output != null ? token.output : token.value;
+ consume(token.value);
+ };
- get url() {
- return this[INTERNALS$1].url || '';
- }
+ const negate = () => {
+ let count = 1;
- get status() {
- return this[INTERNALS$1].status;
- }
+ while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {
+ advance();
+ state.start++;
+ count++;
+ }
- /**
- * Convenience property representing if the request ended normally
- */
- get ok() {
- return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300;
- }
+ if (count % 2 === 0) {
+ return false;
+ }
- get redirected() {
- return this[INTERNALS$1].counter > 0;
- }
+ state.negated = true;
+ state.start++;
+ return true;
+ };
- get statusText() {
- return this[INTERNALS$1].statusText;
- }
+ const increment = type => {
+ state[type]++;
+ stack.push(type);
+ };
- get headers() {
- return this[INTERNALS$1].headers;
- }
+ const decrement = type => {
+ state[type]--;
+ stack.pop();
+ };
- /**
- * Clone this response
- *
- * @return Response
- */
- clone() {
- return new Response(clone(this), {
- url: this.url,
- status: this.status,
- statusText: this.statusText,
- headers: this.headers,
- ok: this.ok,
- redirected: this.redirected
- });
- }
-}
+ /**
+ * Push tokens onto the tokens array. This helper speeds up
+ * tokenizing by 1) helping us avoid backtracking as much as possible,
+ * and 2) helping us avoid creating extra tokens when consecutive
+ * characters are plain text. This improves performance and simplifies
+ * lookbehinds.
+ */
-Body.mixIn(Response.prototype);
+ const push = tok => {
+ if (prev.type === 'globstar') {
+ const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
+ const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren'));
-Object.defineProperties(Response.prototype, {
- url: { enumerable: true },
- status: { enumerable: true },
- ok: { enumerable: true },
- redirected: { enumerable: true },
- statusText: { enumerable: true },
- headers: { enumerable: true },
- clone: { enumerable: true }
-});
+ if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
+ state.output = state.output.slice(0, -prev.output.length);
+ prev.type = 'star';
+ prev.value = '*';
+ prev.output = star;
+ state.output += prev.output;
+ }
+ }
-Object.defineProperty(Response.prototype, Symbol.toStringTag, {
- value: 'Response',
- writable: false,
- enumerable: false,
- configurable: true
-});
+ if (extglobs.length && tok.type !== 'paren') {
+ extglobs[extglobs.length - 1].inner += tok.value;
+ }
-const INTERNALS$2 = Symbol('Request internals');
-const URL = Url.URL || whatwgUrl.URL;
+ if (tok.value || tok.output) append(tok);
+ if (prev && prev.type === 'text' && tok.type === 'text') {
+ prev.value += tok.value;
+ prev.output = (prev.output || '') + tok.value;
+ return;
+ }
-// fix an issue where "format", "parse" aren't a named export for node <10
-const parse_url = Url.parse;
-const format_url = Url.format;
+ tok.prev = prev;
+ tokens.push(tok);
+ prev = tok;
+ };
-/**
- * Wrapper around `new URL` to handle arbitrary URLs
- *
- * @param {string} urlStr
- * @return {void}
- */
-function parseURL(urlStr) {
- /*
- Check whether the URL is absolute or not
- Scheme: https://tools.ietf.org/html/rfc3986#section-3.1
- Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3
- */
- if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.exec(urlStr)) {
- urlStr = new URL(urlStr).toString();
- }
+ const extglobOpen = (type, value) => {
+ const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' };
- // Fallback to old implementation for arbitrary URLs
- return parse_url(urlStr);
-}
+ token.prev = prev;
+ token.parens = state.parens;
+ token.output = state.output;
+ const output = (opts.capture ? '(' : '') + token.open;
-const streamDestructionSupported = 'destroy' in Stream.Readable.prototype;
+ increment('parens');
+ push({ type, value, output: state.output ? '' : ONE_CHAR });
+ push({ type: 'paren', extglob: true, value: advance(), output });
+ extglobs.push(token);
+ };
-/**
- * Check if a value is an instance of Request.
- *
- * @param Mixed input
- * @return Boolean
- */
-function isRequest(input) {
- return typeof input === 'object' && typeof input[INTERNALS$2] === 'object';
-}
+ const extglobClose = token => {
+ let output = token.close + (opts.capture ? ')' : '');
+ let rest;
-function isAbortSignal(signal) {
- const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal);
- return !!(proto && proto.constructor.name === 'AbortSignal');
-}
+ if (token.type === 'negate') {
+ let extglobStar = star;
-/**
- * Request class
- *
- * @param Mixed input Url or Request instance
- * @param Object init Custom options
- * @return Void
- */
-class Request {
- constructor(input) {
- let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
+ if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
+ extglobStar = globstar(opts);
+ }
- let parsedURL;
+ if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
+ output = token.close = `)$))${extglobStar}`;
+ }
- // normalize input
- if (!isRequest(input)) {
- if (input && input.href) {
- // in order to support Node.js' Url objects; though WHATWG's URL objects
- // will fall into this branch also (since their `toString()` will return
- // `href` property anyway)
- parsedURL = parseURL(input.href);
- } else {
- // coerce input to a string before attempting to parse
- parsedURL = parseURL(`${input}`);
- }
- input = {};
- } else {
- parsedURL = parseURL(input.url);
- }
+ if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) {
+ // Any non-magical string (`.ts`) or even nested expression (`.{ts,tsx}`) can follow after the closing parenthesis.
+ // In this case, we need to parse the string and use it in the output of the original pattern.
+ // Suitable patterns: `/!(*.d).ts`, `/!(*.d).{ts,tsx}`, `**/!(*-dbg).@(js)`.
+ //
+ // Disabling the `fastpaths` option due to a problem with parsing strings as `.ts` in the pattern like `**/!(*.d).ts`.
+ const expression = parse(rest, { ...options, fastpaths: false }).output;
- let method = init.method || input.method || 'GET';
- method = method.toUpperCase();
+ output = token.close = `)${expression})${extglobStar})`;
+ }
- if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) {
- throw new TypeError('Request with GET/HEAD method cannot have body');
- }
+ if (token.prev.type === 'bos') {
+ state.negatedExtglob = true;
+ }
+ }
- let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null;
+ push({ type: 'paren', extglob: true, value, output });
+ decrement('parens');
+ };
- Body.call(this, inputBody, {
- timeout: init.timeout || input.timeout || 0,
- size: init.size || input.size || 0
- });
+ /**
+ * Fast paths
+ */
- const headers = new Headers(init.headers || input.headers || {});
+ if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
+ let backslashes = false;
- if (inputBody != null && !headers.has('Content-Type')) {
- const contentType = extractContentType(inputBody);
- if (contentType) {
- headers.append('Content-Type', contentType);
- }
- }
+ let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
+ if (first === '\\') {
+ backslashes = true;
+ return m;
+ }
- let signal = isRequest(input) ? input.signal : null;
- if ('signal' in init) signal = init.signal;
+ if (first === '?') {
+ if (esc) {
+ return esc + first + (rest ? QMARK.repeat(rest.length) : '');
+ }
+ if (index === 0) {
+ return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
+ }
+ return QMARK.repeat(chars.length);
+ }
- if (signal != null && !isAbortSignal(signal)) {
- throw new TypeError('Expected signal to be an instanceof AbortSignal');
- }
+ if (first === '.') {
+ return DOT_LITERAL.repeat(chars.length);
+ }
- this[INTERNALS$2] = {
- method,
- redirect: init.redirect || input.redirect || 'follow',
- headers,
- parsedURL,
- signal
- };
+ if (first === '*') {
+ if (esc) {
+ return esc + first + (rest ? star : '');
+ }
+ return star;
+ }
+ return esc ? m : `\\${m}`;
+ });
- // node-fetch-only options
- this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20;
- this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true;
- this.counter = init.counter || input.counter || 0;
- this.agent = init.agent || input.agent;
- }
+ if (backslashes === true) {
+ if (opts.unescape === true) {
+ output = output.replace(/\\/g, '');
+ } else {
+ output = output.replace(/\\+/g, m => {
+ return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : '');
+ });
+ }
+ }
- get method() {
- return this[INTERNALS$2].method;
- }
+ if (output === input && opts.contains === true) {
+ state.output = input;
+ return state;
+ }
- get url() {
- return format_url(this[INTERNALS$2].parsedURL);
- }
+ state.output = utils.wrapOutput(output, state, options);
+ return state;
+ }
- get headers() {
- return this[INTERNALS$2].headers;
- }
+ /**
+ * Tokenize input until we reach end-of-string
+ */
- get redirect() {
- return this[INTERNALS$2].redirect;
- }
+ while (!eos()) {
+ value = advance();
- get signal() {
- return this[INTERNALS$2].signal;
- }
+ if (value === '\u0000') {
+ continue;
+ }
- /**
- * Clone this request
- *
- * @return Request
- */
- clone() {
- return new Request(this);
- }
-}
+ /**
+ * Escaped characters
+ */
-Body.mixIn(Request.prototype);
+ if (value === '\\') {
+ const next = peek();
-Object.defineProperty(Request.prototype, Symbol.toStringTag, {
- value: 'Request',
- writable: false,
- enumerable: false,
- configurable: true
-});
+ if (next === '/' && opts.bash !== true) {
+ continue;
+ }
-Object.defineProperties(Request.prototype, {
- method: { enumerable: true },
- url: { enumerable: true },
- headers: { enumerable: true },
- redirect: { enumerable: true },
- clone: { enumerable: true },
- signal: { enumerable: true }
-});
+ if (next === '.' || next === ';') {
+ continue;
+ }
-/**
- * Convert a Request to Node.js http request options.
- *
- * @param Request A Request instance
- * @return Object The options object to be passed to http.request
- */
-function getNodeRequestOptions(request) {
- const parsedURL = request[INTERNALS$2].parsedURL;
- const headers = new Headers(request[INTERNALS$2].headers);
+ if (!next) {
+ value += '\\';
+ push({ type: 'text', value });
+ continue;
+ }
- // fetch step 1.3
- if (!headers.has('Accept')) {
- headers.set('Accept', '*/*');
- }
+ // collapse slashes to reduce potential for exploits
+ const match = /^\\+/.exec(remaining());
+ let slashes = 0;
- // Basic fetch
- if (!parsedURL.protocol || !parsedURL.hostname) {
- throw new TypeError('Only absolute URLs are supported');
- }
+ if (match && match[0].length > 2) {
+ slashes = match[0].length;
+ state.index += slashes;
+ if (slashes % 2 !== 0) {
+ value += '\\';
+ }
+ }
- if (!/^https?:$/.test(parsedURL.protocol)) {
- throw new TypeError('Only HTTP(S) protocols are supported');
- }
+ if (opts.unescape === true) {
+ value = advance();
+ } else {
+ value += advance();
+ }
- if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) {
- throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8');
- }
+ if (state.brackets === 0) {
+ push({ type: 'text', value });
+ continue;
+ }
+ }
- // HTTP-network-or-cache fetch steps 2.4-2.7
- let contentLengthValue = null;
- if (request.body == null && /^(POST|PUT)$/i.test(request.method)) {
- contentLengthValue = '0';
- }
- if (request.body != null) {
- const totalBytes = getTotalBytes(request);
- if (typeof totalBytes === 'number') {
- contentLengthValue = String(totalBytes);
- }
- }
- if (contentLengthValue) {
- headers.set('Content-Length', contentLengthValue);
- }
+ /**
+ * If we're inside a regex character class, continue
+ * until we reach the closing bracket.
+ */
- // HTTP-network-or-cache fetch step 2.11
- if (!headers.has('User-Agent')) {
- headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)');
- }
+ if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
+ if (opts.posix !== false && value === ':') {
+ const inner = prev.value.slice(1);
+ if (inner.includes('[')) {
+ prev.posix = true;
- // HTTP-network-or-cache fetch step 2.15
- if (request.compress && !headers.has('Accept-Encoding')) {
- headers.set('Accept-Encoding', 'gzip,deflate');
- }
+ if (inner.includes(':')) {
+ const idx = prev.value.lastIndexOf('[');
+ const pre = prev.value.slice(0, idx);
+ const rest = prev.value.slice(idx + 2);
+ const posix = POSIX_REGEX_SOURCE[rest];
+ if (posix) {
+ prev.value = pre + posix;
+ state.backtrack = true;
+ advance();
- let agent = request.agent;
- if (typeof agent === 'function') {
- agent = agent(parsedURL);
- }
+ if (!bos.output && tokens.indexOf(prev) === 1) {
+ bos.output = ONE_CHAR;
+ }
+ continue;
+ }
+ }
+ }
+ }
- if (!headers.has('Connection') && !agent) {
- headers.set('Connection', 'close');
- }
+ if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) {
+ value = `\\${value}`;
+ }
- // HTTP-network fetch step 4.2
- // chunked encoding is handled by Node.js
+ if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
+ value = `\\${value}`;
+ }
- return Object.assign({}, parsedURL, {
- method: request.method,
- headers: exportNodeCompatibleHeaders(headers),
- agent
- });
-}
+ if (opts.posix === true && value === '!' && prev.value === '[') {
+ value = '^';
+ }
-/**
- * abort-error.js
- *
- * AbortError interface for cancelled requests
- */
+ prev.value += value;
+ append({ value });
+ continue;
+ }
-/**
- * Create AbortError instance
- *
- * @param String message Error message for human
- * @return AbortError
- */
-function AbortError(message) {
- Error.call(this, message);
+ /**
+ * If we're inside a quoted string, continue
+ * until we reach the closing double quote.
+ */
- this.type = 'aborted';
- this.message = message;
+ if (state.quotes === 1 && value !== '"') {
+ value = utils.escapeRegex(value);
+ prev.value += value;
+ append({ value });
+ continue;
+ }
- // hide custom error implementation details from end-users
- Error.captureStackTrace(this, this.constructor);
-}
+ /**
+ * Double quotes
+ */
-AbortError.prototype = Object.create(Error.prototype);
-AbortError.prototype.constructor = AbortError;
-AbortError.prototype.name = 'AbortError';
+ if (value === '"') {
+ state.quotes = state.quotes === 1 ? 0 : 1;
+ if (opts.keepQuotes === true) {
+ push({ type: 'text', value });
+ }
+ continue;
+ }
-const URL$1 = Url.URL || whatwgUrl.URL;
+ /**
+ * Parentheses
+ */
-// fix an issue where "PassThrough", "resolve" aren't a named export for node <10
-const PassThrough$1 = Stream.PassThrough;
+ if (value === '(') {
+ increment('parens');
+ push({ type: 'paren', value });
+ continue;
+ }
-const isDomainOrSubdomain = function isDomainOrSubdomain(destination, original) {
- const orig = new URL$1(original).hostname;
- const dest = new URL$1(destination).hostname;
+ if (value === ')') {
+ if (state.parens === 0 && opts.strictBrackets === true) {
+ throw new SyntaxError(syntaxError('opening', '('));
+ }
- return orig === dest || orig[orig.length - dest.length - 1] === '.' && orig.endsWith(dest);
-};
+ const extglob = extglobs[extglobs.length - 1];
+ if (extglob && state.parens === extglob.parens + 1) {
+ extglobClose(extglobs.pop());
+ continue;
+ }
-/**
- * Fetch function
- *
- * @param Mixed url Absolute url or Request instance
- * @param Object opts Fetch options
- * @return Promise
- */
-function fetch(url, opts) {
+ push({ type: 'paren', value, output: state.parens ? ')' : '\\)' });
+ decrement('parens');
+ continue;
+ }
- // allow custom promise
- if (!fetch.Promise) {
- throw new Error('native promise missing, set fetch.Promise to your favorite alternative');
- }
+ /**
+ * Square brackets
+ */
- Body.Promise = fetch.Promise;
+ if (value === '[') {
+ if (opts.nobracket === true || !remaining().includes(']')) {
+ if (opts.nobracket !== true && opts.strictBrackets === true) {
+ throw new SyntaxError(syntaxError('closing', ']'));
+ }
- // wrap http.request into fetch
- return new fetch.Promise(function (resolve, reject) {
- // build request object
- const request = new Request(url, opts);
- const options = getNodeRequestOptions(request);
+ value = `\\${value}`;
+ } else {
+ increment('brackets');
+ }
- const send = (options.protocol === 'https:' ? https : http).request;
- const signal = request.signal;
+ push({ type: 'bracket', value });
+ continue;
+ }
- let response = null;
+ if (value === ']') {
+ if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) {
+ push({ type: 'text', value, output: `\\${value}` });
+ continue;
+ }
- const abort = function abort() {
- let error = new AbortError('The user aborted a request.');
- reject(error);
- if (request.body && request.body instanceof Stream.Readable) {
- request.body.destroy(error);
- }
- if (!response || !response.body) return;
- response.body.emit('error', error);
- };
+ if (state.brackets === 0) {
+ if (opts.strictBrackets === true) {
+ throw new SyntaxError(syntaxError('opening', '['));
+ }
- if (signal && signal.aborted) {
- abort();
- return;
- }
+ push({ type: 'text', value, output: `\\${value}` });
+ continue;
+ }
- const abortAndFinalize = function abortAndFinalize() {
- abort();
- finalize();
- };
+ decrement('brackets');
- // send request
- const req = send(options);
- let reqTimeout;
+ const prevValue = prev.value.slice(1);
+ if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
+ value = `/${value}`;
+ }
- if (signal) {
- signal.addEventListener('abort', abortAndFinalize);
- }
+ prev.value += value;
+ append({ value });
- function finalize() {
- req.abort();
- if (signal) signal.removeEventListener('abort', abortAndFinalize);
- clearTimeout(reqTimeout);
- }
+ // when literal brackets are explicitly disabled
+ // assume we should match with a regex character class
+ if (opts.literalBrackets === false || utils.hasRegexChars(prevValue)) {
+ continue;
+ }
- if (request.timeout) {
- req.once('socket', function (socket) {
- reqTimeout = setTimeout(function () {
- reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout'));
- finalize();
- }, request.timeout);
- });
- }
+ const escaped = utils.escapeRegex(prev.value);
+ state.output = state.output.slice(0, -prev.value.length);
- req.on('error', function (err) {
- reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err));
- finalize();
- });
+ // when literal brackets are explicitly enabled
+ // assume we should escape the brackets to match literal characters
+ if (opts.literalBrackets === true) {
+ state.output += escaped;
+ prev.value = escaped;
+ continue;
+ }
- req.on('response', function (res) {
- clearTimeout(reqTimeout);
+ // when the user specifies nothing, try to match both
+ prev.value = `(${capture}${escaped}|${prev.value})`;
+ state.output += prev.value;
+ continue;
+ }
- const headers = createHeadersLenient(res.headers);
+ /**
+ * Braces
+ */
- // HTTP fetch step 5
- if (fetch.isRedirect(res.statusCode)) {
- // HTTP fetch step 5.2
- const location = headers.get('Location');
+ if (value === '{' && opts.nobrace !== true) {
+ increment('braces');
- // HTTP fetch step 5.3
- let locationURL = null;
- try {
- locationURL = location === null ? null : new URL$1(location, request.url).toString();
- } catch (err) {
- // error here can only be invalid URL in Location: header
- // do not throw when options.redirect == manual
- // let the user extract the errorneous redirect URL
- if (request.redirect !== 'manual') {
- reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect'));
- finalize();
- return;
- }
- }
+ const open = {
+ type: 'brace',
+ value,
+ output: '(',
+ outputIndex: state.output.length,
+ tokensIndex: state.tokens.length
+ };
- // HTTP fetch step 5.5
- switch (request.redirect) {
- case 'error':
- reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect'));
- finalize();
- return;
- case 'manual':
- // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL.
- if (locationURL !== null) {
- // handle corrupted header
- try {
- headers.set('Location', locationURL);
- } catch (err) {
- // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request
- reject(err);
- }
- }
- break;
- case 'follow':
- // HTTP-redirect fetch step 2
- if (locationURL === null) {
- break;
- }
+ braces.push(open);
+ push(open);
+ continue;
+ }
- // HTTP-redirect fetch step 5
- if (request.counter >= request.follow) {
- reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect'));
- finalize();
- return;
- }
+ if (value === '}') {
+ const brace = braces[braces.length - 1];
- // HTTP-redirect fetch step 6 (counter increment)
- // Create a new Request object.
- const requestOpts = {
- headers: new Headers(request.headers),
- follow: request.follow,
- counter: request.counter + 1,
- agent: request.agent,
- compress: request.compress,
- method: request.method,
- body: request.body,
- signal: request.signal,
- timeout: request.timeout,
- size: request.size
- };
+ if (opts.nobrace === true || !brace) {
+ push({ type: 'text', value, output: value });
+ continue;
+ }
- if (!isDomainOrSubdomain(request.url, locationURL)) {
- for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) {
- requestOpts.headers.delete(name);
- }
- }
+ let output = ')';
- // HTTP-redirect fetch step 9
- if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) {
- reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect'));
- finalize();
- return;
- }
+ if (brace.dots === true) {
+ const arr = tokens.slice();
+ const range = [];
- // HTTP-redirect fetch step 11
- if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') {
- requestOpts.method = 'GET';
- requestOpts.body = undefined;
- requestOpts.headers.delete('content-length');
- }
+ for (let i = arr.length - 1; i >= 0; i--) {
+ tokens.pop();
+ if (arr[i].type === 'brace') {
+ break;
+ }
+ if (arr[i].type !== 'dots') {
+ range.unshift(arr[i].value);
+ }
+ }
- // HTTP-redirect fetch step 15
- resolve(fetch(new Request(locationURL, requestOpts)));
- finalize();
- return;
- }
- }
+ output = expandRange(range, opts);
+ state.backtrack = true;
+ }
- // prepare response
- res.once('end', function () {
- if (signal) signal.removeEventListener('abort', abortAndFinalize);
- });
- let body = res.pipe(new PassThrough$1());
+ if (brace.comma !== true && brace.dots !== true) {
+ const out = state.output.slice(0, brace.outputIndex);
+ const toks = state.tokens.slice(brace.tokensIndex);
+ brace.value = brace.output = '\\{';
+ value = output = '\\}';
+ state.output = out;
+ for (const t of toks) {
+ state.output += (t.output || t.value);
+ }
+ }
- const response_options = {
- url: request.url,
- status: res.statusCode,
- statusText: res.statusMessage,
- headers: headers,
- size: request.size,
- timeout: request.timeout,
- counter: request.counter
- };
+ push({ type: 'brace', value, output });
+ decrement('braces');
+ braces.pop();
+ continue;
+ }
- // HTTP-network fetch step 12.1.1.3
- const codings = headers.get('Content-Encoding');
+ /**
+ * Pipes
+ */
- // HTTP-network fetch step 12.1.1.4: handle content codings
+ if (value === '|') {
+ if (extglobs.length > 0) {
+ extglobs[extglobs.length - 1].conditions++;
+ }
+ push({ type: 'text', value });
+ continue;
+ }
- // in following scenarios we ignore compression support
- // 1. compression support is disabled
- // 2. HEAD request
- // 3. no Content-Encoding header
- // 4. no content response (204)
- // 5. content not modified response (304)
- if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) {
- response = new Response(body, response_options);
- resolve(response);
- return;
- }
+ /**
+ * Commas
+ */
- // For Node v6+
- // Be less strict when decoding compressed responses, since sometimes
- // servers send slightly invalid responses that are still accepted
- // by common browsers.
- // Always using Z_SYNC_FLUSH is what cURL does.
- const zlibOptions = {
- flush: zlib.Z_SYNC_FLUSH,
- finishFlush: zlib.Z_SYNC_FLUSH
- };
+ if (value === ',') {
+ let output = value;
- // for gzip
- if (codings == 'gzip' || codings == 'x-gzip') {
- body = body.pipe(zlib.createGunzip(zlibOptions));
- response = new Response(body, response_options);
- resolve(response);
- return;
- }
+ const brace = braces[braces.length - 1];
+ if (brace && stack[stack.length - 1] === 'braces') {
+ brace.comma = true;
+ output = '|';
+ }
- // for deflate
- if (codings == 'deflate' || codings == 'x-deflate') {
- // handle the infamous raw deflate response from old servers
- // a hack for old IIS and Apache servers
- const raw = res.pipe(new PassThrough$1());
- raw.once('data', function (chunk) {
- // see http://stackoverflow.com/questions/37519828
- if ((chunk[0] & 0x0F) === 0x08) {
- body = body.pipe(zlib.createInflate());
- } else {
- body = body.pipe(zlib.createInflateRaw());
- }
- response = new Response(body, response_options);
- resolve(response);
- });
- return;
- }
-
- // for br
- if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') {
- body = body.pipe(zlib.createBrotliDecompress());
- response = new Response(body, response_options);
- resolve(response);
- return;
- }
+ push({ type: 'comma', value, output });
+ continue;
+ }
- // otherwise, use response as-is
- response = new Response(body, response_options);
- resolve(response);
- });
+ /**
+ * Slashes
+ */
- writeToStream(req, request);
- });
-}
-/**
- * Redirect code matching
- *
- * @param Number code Status code
- * @return Boolean
- */
-fetch.isRedirect = function (code) {
- return code === 301 || code === 302 || code === 303 || code === 307 || code === 308;
-};
+ if (value === '/') {
+ // if the beginning of the glob is "./", advance the start
+ // to the current index, and don't add the "./" characters
+ // to the state. This greatly simplifies lookbehinds when
+ // checking for BOS characters like "!" and "." (not "./")
+ if (prev.type === 'dot' && state.index === state.start + 1) {
+ state.start = state.index + 1;
+ state.consumed = '';
+ state.output = '';
+ tokens.pop();
+ prev = bos; // reset "prev" to the first token
+ continue;
+ }
-// expose Promise
-fetch.Promise = global.Promise;
+ push({ type: 'slash', value, output: SLASH_LITERAL });
+ continue;
+ }
-module.exports = exports = fetch;
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.default = exports;
-exports.Headers = Headers;
-exports.Request = Request;
-exports.Response = Response;
-exports.FetchError = FetchError;
+ /**
+ * Dots
+ */
+ if (value === '.') {
+ if (state.braces > 0 && prev.type === 'dot') {
+ if (prev.value === '.') prev.output = DOT_LITERAL;
+ const brace = braces[braces.length - 1];
+ prev.type = 'dots';
+ prev.output += value;
+ prev.value += value;
+ brace.dots = true;
+ continue;
+ }
-/***/ }),
+ if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') {
+ push({ type: 'text', value, output: DOT_LITERAL });
+ continue;
+ }
-/***/ 2299:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ push({ type: 'dot', value, output: DOT_LITERAL });
+ continue;
+ }
-"use strict";
+ /**
+ * Question marks
+ */
+ if (value === '?') {
+ const isGroup = prev && prev.value === '(';
+ if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
+ extglobOpen('qmark', value);
+ continue;
+ }
-var punycode = __nccwpck_require__(4213);
-var mappingTable = __nccwpck_require__(8661);
+ if (prev && prev.type === 'paren') {
+ const next = peek();
+ let output = value;
-var PROCESSING_OPTIONS = {
- TRANSITIONAL: 0,
- NONTRANSITIONAL: 1
-};
+ if (next === '<' && !utils.supportsLookbehinds()) {
+ throw new Error('Node.js v10 or higher is required for regex lookbehinds');
+ }
-function normalize(str) { // fix bug in v8
- return str.split('\u0000').map(function (s) { return s.normalize('NFC'); }).join('\u0000');
-}
+ if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) {
+ output = `\\${value}`;
+ }
-function findStatus(val) {
- var start = 0;
- var end = mappingTable.length - 1;
+ push({ type: 'text', value, output });
+ continue;
+ }
- while (start <= end) {
- var mid = Math.floor((start + end) / 2);
+ if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
+ push({ type: 'qmark', value, output: QMARK_NO_DOT });
+ continue;
+ }
- var target = mappingTable[mid];
- if (target[0][0] <= val && target[0][1] >= val) {
- return target;
- } else if (target[0][0] > val) {
- end = mid - 1;
- } else {
- start = mid + 1;
+ push({ type: 'qmark', value, output: QMARK });
+ continue;
}
- }
- return null;
-}
+ /**
+ * Exclamation
+ */
-var regexAstralSymbols = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
+ if (value === '!') {
+ if (opts.noextglob !== true && peek() === '(') {
+ if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
+ extglobOpen('negate', value);
+ continue;
+ }
+ }
-function countSymbols(string) {
- return string
- // replace every surrogate pair with a BMP symbol
- .replace(regexAstralSymbols, '_')
- // then get the length
- .length;
-}
+ if (opts.nonegate !== true && state.index === 0) {
+ negate();
+ continue;
+ }
+ }
-function mapChars(domain_name, useSTD3, processing_option) {
- var hasError = false;
- var processed = "";
+ /**
+ * Plus
+ */
- var len = countSymbols(domain_name);
- for (var i = 0; i < len; ++i) {
- var codePoint = domain_name.codePointAt(i);
- var status = findStatus(codePoint);
+ if (value === '+') {
+ if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
+ extglobOpen('plus', value);
+ continue;
+ }
- switch (status[1]) {
- case "disallowed":
- hasError = true;
- processed += String.fromCodePoint(codePoint);
- break;
- case "ignored":
- break;
- case "mapped":
- processed += String.fromCodePoint.apply(String, status[2]);
- break;
- case "deviation":
- if (processing_option === PROCESSING_OPTIONS.TRANSITIONAL) {
- processed += String.fromCodePoint.apply(String, status[2]);
- } else {
- processed += String.fromCodePoint(codePoint);
- }
- break;
- case "valid":
- processed += String.fromCodePoint(codePoint);
- break;
- case "disallowed_STD3_mapped":
- if (useSTD3) {
- hasError = true;
- processed += String.fromCodePoint(codePoint);
- } else {
- processed += String.fromCodePoint.apply(String, status[2]);
- }
- break;
- case "disallowed_STD3_valid":
- if (useSTD3) {
- hasError = true;
- }
+ if ((prev && prev.value === '(') || opts.regex === false) {
+ push({ type: 'plus', value, output: PLUS_LITERAL });
+ continue;
+ }
- processed += String.fromCodePoint(codePoint);
- break;
+ if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) {
+ push({ type: 'plus', value });
+ continue;
+ }
+
+ push({ type: 'plus', value: PLUS_LITERAL });
+ continue;
}
- }
- return {
- string: processed,
- error: hasError
- };
-}
+ /**
+ * Plain text
+ */
-var combiningMarksRegex = /[\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08E4-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C03\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D01-\u0D03\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u18A9\u1920-\u192B\u1930-\u193B\u19B0-\u19C0\u19C8\u19C9\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF5\u1DFC-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C4\uA8E0-\uA8F1\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2D]|\uD800[\uDDFD\uDEE0\uDF76-\uDF7A]|\uD802[\uDE01-\uDE03\uDE05\uDE06\uDE0C-\uDE0F\uDE38-\uDE3A\uDE3F\uDEE5\uDEE6]|\uD804[\uDC00-\uDC02\uDC38-\uDC46\uDC7F-\uDC82\uDCB0-\uDCBA\uDD00-\uDD02\uDD27-\uDD34\uDD73\uDD80-\uDD82\uDDB3-\uDDC0\uDE2C-\uDE37\uDEDF-\uDEEA\uDF01-\uDF03\uDF3C\uDF3E-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF57\uDF62\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDCB0-\uDCC3\uDDAF-\uDDB5\uDDB8-\uDDC0\uDE30-\uDE40\uDEAB-\uDEB7]|\uD81A[\uDEF0-\uDEF4\uDF30-\uDF36]|\uD81B[\uDF51-\uDF7E\uDF8F-\uDF92]|\uD82F[\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD83A[\uDCD0-\uDCD6]|\uDB40[\uDD00-\uDDEF]/;
+ if (value === '@') {
+ if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
+ push({ type: 'at', extglob: true, value, output: '' });
+ continue;
+ }
-function validateLabel(label, processing_option) {
- if (label.substr(0, 4) === "xn--") {
- label = punycode.toUnicode(label);
- processing_option = PROCESSING_OPTIONS.NONTRANSITIONAL;
- }
+ push({ type: 'text', value });
+ continue;
+ }
- var error = false;
+ /**
+ * Plain text
+ */
- if (normalize(label) !== label ||
- (label[3] === "-" && label[4] === "-") ||
- label[0] === "-" || label[label.length - 1] === "-" ||
- label.indexOf(".") !== -1 ||
- label.search(combiningMarksRegex) === 0) {
- error = true;
- }
+ if (value !== '*') {
+ if (value === '$' || value === '^') {
+ value = `\\${value}`;
+ }
- var len = countSymbols(label);
- for (var i = 0; i < len; ++i) {
- var status = findStatus(label.codePointAt(i));
- if ((processing === PROCESSING_OPTIONS.TRANSITIONAL && status[1] !== "valid") ||
- (processing === PROCESSING_OPTIONS.NONTRANSITIONAL &&
- status[1] !== "valid" && status[1] !== "deviation")) {
- error = true;
- break;
+ const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
+ if (match) {
+ value += match[0];
+ state.index += match[0].length;
+ }
+
+ push({ type: 'text', value });
+ continue;
}
- }
- return {
- label: label,
- error: error
- };
-}
+ /**
+ * Stars
+ */
-function processing(domain_name, useSTD3, processing_option) {
- var result = mapChars(domain_name, useSTD3, processing_option);
- result.string = normalize(result.string);
+ if (prev && (prev.type === 'globstar' || prev.star === true)) {
+ prev.type = 'star';
+ prev.star = true;
+ prev.value += value;
+ prev.output = star;
+ state.backtrack = true;
+ state.globstar = true;
+ consume(value);
+ continue;
+ }
- var labels = result.string.split(".");
- for (var i = 0; i < labels.length; ++i) {
- try {
- var validation = validateLabel(labels[i]);
- labels[i] = validation.label;
- result.error = result.error || validation.error;
- } catch(e) {
- result.error = true;
+ let rest = remaining();
+ if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
+ extglobOpen('star', value);
+ continue;
}
- }
- return {
- string: labels.join("."),
- error: result.error
- };
-}
+ if (prev.type === 'star') {
+ if (opts.noglobstar === true) {
+ consume(value);
+ continue;
+ }
-module.exports.toASCII = function(domain_name, useSTD3, processing_option, verifyDnsLength) {
- var result = processing(domain_name, useSTD3, processing_option);
- var labels = result.string.split(".");
- labels = labels.map(function(l) {
- try {
- return punycode.toASCII(l);
- } catch(e) {
- result.error = true;
- return l;
- }
- });
+ const prior = prev.prev;
+ const before = prior.prev;
+ const isStart = prior.type === 'slash' || prior.type === 'bos';
+ const afterStar = before && (before.type === 'star' || before.type === 'globstar');
- if (verifyDnsLength) {
- var total = labels.slice(0, labels.length - 1).join(".").length;
- if (total.length > 253 || total.length === 0) {
- result.error = true;
- }
+ if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) {
+ push({ type: 'star', value, output: '' });
+ continue;
+ }
- for (var i=0; i < labels.length; ++i) {
- if (labels.length > 63 || labels.length === 0) {
- result.error = true;
- break;
+ const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
+ const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
+ if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
+ push({ type: 'star', value, output: '' });
+ continue;
}
- }
- }
- if (result.error) return null;
- return labels.join(".");
-};
+ // strip consecutive `/**/`
+ while (rest.slice(0, 3) === '/**') {
+ const after = input[state.index + 4];
+ if (after && after !== '/') {
+ break;
+ }
+ rest = rest.slice(3);
+ consume('/**', 3);
+ }
-module.exports.toUnicode = function(domain_name, useSTD3) {
- var result = processing(domain_name, useSTD3, PROCESSING_OPTIONS.NONTRANSITIONAL);
+ if (prior.type === 'bos' && eos()) {
+ prev.type = 'globstar';
+ prev.value += value;
+ prev.output = globstar(opts);
+ state.output = prev.output;
+ state.globstar = true;
+ consume(value);
+ continue;
+ }
- return {
- domain: result.string,
- error: result.error
- };
-};
+ if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
+ state.output = state.output.slice(0, -(prior.output + prev.output).length);
+ prior.output = `(?:${prior.output}`;
-module.exports.PROCESSING_OPTIONS = PROCESSING_OPTIONS;
+ prev.type = 'globstar';
+ prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');
+ prev.value += value;
+ state.globstar = true;
+ state.output += prior.output + prev.output;
+ consume(value);
+ continue;
+ }
+ if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {
+ const end = rest[1] !== void 0 ? '|$' : '';
-/***/ }),
+ state.output = state.output.slice(0, -(prior.output + prev.output).length);
+ prior.output = `(?:${prior.output}`;
-/***/ 5871:
-/***/ ((module) => {
+ prev.type = 'globstar';
+ prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
+ prev.value += value;
-"use strict";
+ state.output += prior.output + prev.output;
+ state.globstar = true;
+ consume(value + advance());
-var conversions = {};
-module.exports = conversions;
+ push({ type: 'slash', value: '/', output: '' });
+ continue;
+ }
-function sign(x) {
- return x < 0 ? -1 : 1;
-}
+ if (prior.type === 'bos' && rest[0] === '/') {
+ prev.type = 'globstar';
+ prev.value += value;
+ prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
+ state.output = prev.output;
+ state.globstar = true;
+ consume(value + advance());
+ push({ type: 'slash', value: '/', output: '' });
+ continue;
+ }
-function evenRound(x) {
- // Round x to the nearest integer, choosing the even integer if it lies halfway between two.
- if ((x % 1) === 0.5 && (x & 1) === 0) { // [even number].5; round down (i.e. floor)
- return Math.floor(x);
- } else {
- return Math.round(x);
- }
-}
+ // remove single star from output
+ state.output = state.output.slice(0, -prev.output.length);
-function createNumberConversion(bitLength, typeOpts) {
- if (!typeOpts.unsigned) {
- --bitLength;
+ // reset previous token to globstar
+ prev.type = 'globstar';
+ prev.output = globstar(opts);
+ prev.value += value;
+
+ // reset output with globstar
+ state.output += prev.output;
+ state.globstar = true;
+ consume(value);
+ continue;
}
- const lowerBound = typeOpts.unsigned ? 0 : -Math.pow(2, bitLength);
- const upperBound = Math.pow(2, bitLength) - 1;
- const moduloVal = typeOpts.moduloBitLength ? Math.pow(2, typeOpts.moduloBitLength) : Math.pow(2, bitLength);
- const moduloBound = typeOpts.moduloBitLength ? Math.pow(2, typeOpts.moduloBitLength - 1) : Math.pow(2, bitLength - 1);
+ const token = { type: 'star', value, output: star };
- return function(V, opts) {
- if (!opts) opts = {};
+ if (opts.bash === true) {
+ token.output = '.*?';
+ if (prev.type === 'bos' || prev.type === 'slash') {
+ token.output = nodot + token.output;
+ }
+ push(token);
+ continue;
+ }
- let x = +V;
+ if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
+ token.output = value;
+ push(token);
+ continue;
+ }
- if (opts.enforceRange) {
- if (!Number.isFinite(x)) {
- throw new TypeError("Argument is not a finite number");
- }
+ if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
+ if (prev.type === 'dot') {
+ state.output += NO_DOT_SLASH;
+ prev.output += NO_DOT_SLASH;
- x = sign(x) * Math.floor(Math.abs(x));
- if (x < lowerBound || x > upperBound) {
- throw new TypeError("Argument is not in byte range");
- }
+ } else if (opts.dot === true) {
+ state.output += NO_DOTS_SLASH;
+ prev.output += NO_DOTS_SLASH;
- return x;
- }
+ } else {
+ state.output += nodot;
+ prev.output += nodot;
+ }
- if (!isNaN(x) && opts.clamp) {
- x = evenRound(x);
+ if (peek() !== '*') {
+ state.output += ONE_CHAR;
+ prev.output += ONE_CHAR;
+ }
+ }
- if (x < lowerBound) x = lowerBound;
- if (x > upperBound) x = upperBound;
- return x;
- }
+ push(token);
+ }
- if (!Number.isFinite(x) || x === 0) {
- return 0;
- }
+ while (state.brackets > 0) {
+ if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']'));
+ state.output = utils.escapeLast(state.output, '[');
+ decrement('brackets');
+ }
- x = sign(x) * Math.floor(Math.abs(x));
- x = x % moduloVal;
+ while (state.parens > 0) {
+ if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')'));
+ state.output = utils.escapeLast(state.output, '(');
+ decrement('parens');
+ }
- if (!typeOpts.unsigned && x >= moduloBound) {
- return x - moduloVal;
- } else if (typeOpts.unsigned) {
- if (x < 0) {
- x += moduloVal;
- } else if (x === -0) { // don't return negative zero
- return 0;
- }
- }
+ while (state.braces > 0) {
+ if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}'));
+ state.output = utils.escapeLast(state.output, '{');
+ decrement('braces');
+ }
- return x;
+ if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
+ push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` });
+ }
+
+ // rebuild the output if we had to backtrack at any point
+ if (state.backtrack === true) {
+ state.output = '';
+
+ for (const token of state.tokens) {
+ state.output += token.output != null ? token.output : token.value;
+
+ if (token.suffix) {
+ state.output += token.suffix;
+ }
}
-}
+ }
-conversions["void"] = function () {
- return undefined;
+ return state;
};
-conversions["boolean"] = function (val) {
- return !!val;
-};
+/**
+ * Fast paths for creating regular expressions for common glob patterns.
+ * This can significantly speed up processing and has very little downside
+ * impact when none of the fast paths match.
+ */
-conversions["byte"] = createNumberConversion(8, { unsigned: false });
-conversions["octet"] = createNumberConversion(8, { unsigned: true });
+parse.fastpaths = (input, options) => {
+ const opts = { ...options };
+ const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
+ const len = input.length;
+ if (len > max) {
+ throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
+ }
-conversions["short"] = createNumberConversion(16, { unsigned: false });
-conversions["unsigned short"] = createNumberConversion(16, { unsigned: true });
+ input = REPLACEMENTS[input] || input;
+ const win32 = utils.isWindows(options);
-conversions["long"] = createNumberConversion(32, { unsigned: false });
-conversions["unsigned long"] = createNumberConversion(32, { unsigned: true });
+ // create constants based on platform, for windows or posix
+ const {
+ DOT_LITERAL,
+ SLASH_LITERAL,
+ ONE_CHAR,
+ DOTS_SLASH,
+ NO_DOT,
+ NO_DOTS,
+ NO_DOTS_SLASH,
+ STAR,
+ START_ANCHOR
+ } = constants.globChars(win32);
-conversions["long long"] = createNumberConversion(32, { unsigned: false, moduloBitLength: 64 });
-conversions["unsigned long long"] = createNumberConversion(32, { unsigned: true, moduloBitLength: 64 });
+ const nodot = opts.dot ? NO_DOTS : NO_DOT;
+ const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
+ const capture = opts.capture ? '' : '?:';
+ const state = { negated: false, prefix: '' };
+ let star = opts.bash === true ? '.*?' : STAR;
-conversions["double"] = function (V) {
- const x = +V;
+ if (opts.capture) {
+ star = `(${star})`;
+ }
- if (!Number.isFinite(x)) {
- throw new TypeError("Argument is not a finite floating-point value");
- }
+ const globstar = opts => {
+ if (opts.noglobstar === true) return star;
+ return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
+ };
- return x;
-};
+ const create = str => {
+ switch (str) {
+ case '*':
+ return `${nodot}${ONE_CHAR}${star}`;
-conversions["unrestricted double"] = function (V) {
- const x = +V;
+ case '.*':
+ return `${DOT_LITERAL}${ONE_CHAR}${star}`;
- if (isNaN(x)) {
- throw new TypeError("Argument is NaN");
- }
+ case '*.*':
+ return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
- return x;
-};
+ case '*/*':
+ return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
-// not quite valid, but good enough for JS
-conversions["float"] = conversions["double"];
-conversions["unrestricted float"] = conversions["unrestricted double"];
+ case '**':
+ return nodot + globstar(opts);
-conversions["DOMString"] = function (V, opts) {
- if (!opts) opts = {};
+ case '**/*':
+ return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
- if (opts.treatNullAsEmptyString && V === null) {
- return "";
- }
+ case '**/*.*':
+ return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
- return String(V);
-};
+ case '**/.*':
+ return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
-conversions["ByteString"] = function (V, opts) {
- const x = String(V);
- let c = undefined;
- for (let i = 0; (c = x.codePointAt(i)) !== undefined; ++i) {
- if (c > 255) {
- throw new TypeError("Argument is not a valid bytestring");
- }
- }
+ default: {
+ const match = /^(.*?)\.(\w+)$/.exec(str);
+ if (!match) return;
- return x;
-};
+ const source = create(match[1]);
+ if (!source) return;
-conversions["USVString"] = function (V) {
- const S = String(V);
- const n = S.length;
- const U = [];
- for (let i = 0; i < n; ++i) {
- const c = S.charCodeAt(i);
- if (c < 0xD800 || c > 0xDFFF) {
- U.push(String.fromCodePoint(c));
- } else if (0xDC00 <= c && c <= 0xDFFF) {
- U.push(String.fromCodePoint(0xFFFD));
- } else {
- if (i === n - 1) {
- U.push(String.fromCodePoint(0xFFFD));
- } else {
- const d = S.charCodeAt(i + 1);
- if (0xDC00 <= d && d <= 0xDFFF) {
- const a = c & 0x3FF;
- const b = d & 0x3FF;
- U.push(String.fromCodePoint((2 << 15) + (2 << 9) * a + b));
- ++i;
- } else {
- U.push(String.fromCodePoint(0xFFFD));
- }
- }
- }
+ return source + DOT_LITERAL + match[2];
+ }
}
+ };
- return U.join('');
-};
+ const output = utils.removePrefix(input, state);
+ let source = create(output);
-conversions["Date"] = function (V, opts) {
- if (!(V instanceof Date)) {
- throw new TypeError("Argument is not a Date object");
- }
- if (isNaN(V)) {
- return undefined;
- }
+ if (source && opts.strictSlashes !== true) {
+ source += `${SLASH_LITERAL}?`;
+ }
- return V;
+ return source;
};
-conversions["RegExp"] = function (V, opts) {
- if (!(V instanceof RegExp)) {
- V = new RegExp(V);
- }
-
- return V;
-};
+module.exports = parse;
/***/ }),
-/***/ 8262:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+/***/ 3322:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
-const usm = __nccwpck_require__(33);
-
-exports.implementation = class URLImpl {
- constructor(constructorArgs) {
- const url = constructorArgs[0];
- const base = constructorArgs[1];
-
- let parsedBase = null;
- if (base !== undefined) {
- parsedBase = usm.basicURLParse(base);
- if (parsedBase === "failure") {
- throw new TypeError("Invalid base URL");
- }
- }
-
- const parsedURL = usm.basicURLParse(url, { baseURL: parsedBase });
- if (parsedURL === "failure") {
- throw new TypeError("Invalid URL");
- }
- this._url = parsedURL;
+const path = __nccwpck_require__(1017);
+const scan = __nccwpck_require__(2429);
+const parse = __nccwpck_require__(2139);
+const utils = __nccwpck_require__(479);
+const constants = __nccwpck_require__(6099);
+const isObject = val => val && typeof val === 'object' && !Array.isArray(val);
- // TODO: query stuff
- }
+/**
+ * Creates a matcher function from one or more glob patterns. The
+ * returned function takes a string to match as its first argument,
+ * and returns true if the string is a match. The returned matcher
+ * function also takes a boolean as the second argument that, when true,
+ * returns an object with additional information.
+ *
+ * ```js
+ * const picomatch = require('picomatch');
+ * // picomatch(glob[, options]);
+ *
+ * const isMatch = picomatch('*.!(*a)');
+ * console.log(isMatch('a.a')); //=> false
+ * console.log(isMatch('a.b')); //=> true
+ * ```
+ * @name picomatch
+ * @param {String|Array} `globs` One or more glob patterns.
+ * @param {Object=} `options`
+ * @return {Function=} Returns a matcher function.
+ * @api public
+ */
- get href() {
- return usm.serializeURL(this._url);
+const picomatch = (glob, options, returnState = false) => {
+ if (Array.isArray(glob)) {
+ const fns = glob.map(input => picomatch(input, options, returnState));
+ const arrayMatcher = str => {
+ for (const isMatch of fns) {
+ const state = isMatch(str);
+ if (state) return state;
+ }
+ return false;
+ };
+ return arrayMatcher;
}
- set href(v) {
- const parsedURL = usm.basicURLParse(v);
- if (parsedURL === "failure") {
- throw new TypeError("Invalid URL");
- }
+ const isState = isObject(glob) && glob.tokens && glob.input;
- this._url = parsedURL;
+ if (glob === '' || (typeof glob !== 'string' && !isState)) {
+ throw new TypeError('Expected pattern to be a non-empty string');
}
- get origin() {
- return usm.serializeURLOrigin(this._url);
- }
+ const opts = options || {};
+ const posix = utils.isWindows(options);
+ const regex = isState
+ ? picomatch.compileRe(glob, options)
+ : picomatch.makeRe(glob, options, false, true);
- get protocol() {
- return this._url.scheme + ":";
- }
+ const state = regex.state;
+ delete regex.state;
- set protocol(v) {
- usm.basicURLParse(v + ":", { url: this._url, stateOverride: "scheme start" });
+ let isIgnored = () => false;
+ if (opts.ignore) {
+ const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
+ isIgnored = picomatch(opts.ignore, ignoreOpts, returnState);
}
- get username() {
- return this._url.username;
- }
+ const matcher = (input, returnObject = false) => {
+ const { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix });
+ const result = { glob, state, regex, posix, input, output, match, isMatch };
- set username(v) {
- if (usm.cannotHaveAUsernamePasswordPort(this._url)) {
- return;
+ if (typeof opts.onResult === 'function') {
+ opts.onResult(result);
}
- usm.setTheUsername(this._url, v);
- }
-
- get password() {
- return this._url.password;
- }
-
- set password(v) {
- if (usm.cannotHaveAUsernamePasswordPort(this._url)) {
- return;
+ if (isMatch === false) {
+ result.isMatch = false;
+ return returnObject ? result : false;
}
- usm.setThePassword(this._url, v);
- }
-
- get host() {
- const url = this._url;
-
- if (url.host === null) {
- return "";
+ if (isIgnored(input)) {
+ if (typeof opts.onIgnore === 'function') {
+ opts.onIgnore(result);
+ }
+ result.isMatch = false;
+ return returnObject ? result : false;
}
- if (url.port === null) {
- return usm.serializeHost(url.host);
+ if (typeof opts.onMatch === 'function') {
+ opts.onMatch(result);
}
+ return returnObject ? result : true;
+ };
- return usm.serializeHost(url.host) + ":" + usm.serializeInteger(url.port);
+ if (returnState) {
+ matcher.state = state;
}
- set host(v) {
- if (this._url.cannotBeABaseURL) {
- return;
- }
-
- usm.basicURLParse(v, { url: this._url, stateOverride: "host" });
- }
+ return matcher;
+};
- get hostname() {
- if (this._url.host === null) {
- return "";
- }
+/**
+ * Test `input` with the given `regex`. This is used by the main
+ * `picomatch()` function to test the input string.
+ *
+ * ```js
+ * const picomatch = require('picomatch');
+ * // picomatch.test(input, regex[, options]);
+ *
+ * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
+ * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
+ * ```
+ * @param {String} `input` String to test.
+ * @param {RegExp} `regex`
+ * @return {Object} Returns an object with matching info.
+ * @api public
+ */
- return usm.serializeHost(this._url.host);
+picomatch.test = (input, regex, options, { glob, posix } = {}) => {
+ if (typeof input !== 'string') {
+ throw new TypeError('Expected input to be a string');
}
- set hostname(v) {
- if (this._url.cannotBeABaseURL) {
- return;
- }
-
- usm.basicURLParse(v, { url: this._url, stateOverride: "hostname" });
+ if (input === '') {
+ return { isMatch: false, output: '' };
}
- get port() {
- if (this._url.port === null) {
- return "";
- }
+ const opts = options || {};
+ const format = opts.format || (posix ? utils.toPosixSlashes : null);
+ let match = input === glob;
+ let output = (match && format) ? format(input) : input;
- return usm.serializeInteger(this._url.port);
+ if (match === false) {
+ output = format ? format(input) : input;
+ match = output === glob;
}
- set port(v) {
- if (usm.cannotHaveAUsernamePasswordPort(this._url)) {
- return;
- }
-
- if (v === "") {
- this._url.port = null;
+ if (match === false || opts.capture === true) {
+ if (opts.matchBase === true || opts.basename === true) {
+ match = picomatch.matchBase(input, regex, options, posix);
} else {
- usm.basicURLParse(v, { url: this._url, stateOverride: "port" });
+ match = regex.exec(output);
}
}
- get pathname() {
- if (this._url.cannotBeABaseURL) {
- return this._url.path[0];
- }
-
- if (this._url.path.length === 0) {
- return "";
- }
+ return { isMatch: Boolean(match), match, output };
+};
- return "/" + this._url.path.join("/");
- }
+/**
+ * Match the basename of a filepath.
+ *
+ * ```js
+ * const picomatch = require('picomatch');
+ * // picomatch.matchBase(input, glob[, options]);
+ * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
+ * ```
+ * @param {String} `input` String to test.
+ * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
+ * @return {Boolean}
+ * @api public
+ */
- set pathname(v) {
- if (this._url.cannotBeABaseURL) {
- return;
- }
+picomatch.matchBase = (input, glob, options, posix = utils.isWindows(options)) => {
+ const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options);
+ return regex.test(path.basename(input));
+};
- this._url.path = [];
- usm.basicURLParse(v, { url: this._url, stateOverride: "path start" });
- }
+/**
+ * Returns true if **any** of the given glob `patterns` match the specified `string`.
+ *
+ * ```js
+ * const picomatch = require('picomatch');
+ * // picomatch.isMatch(string, patterns[, options]);
+ *
+ * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
+ * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
+ * ```
+ * @param {String|Array} str The string to test.
+ * @param {String|Array} patterns One or more glob patterns to use for matching.
+ * @param {Object} [options] See available [options](#options).
+ * @return {Boolean} Returns true if any patterns match `str`
+ * @api public
+ */
- get search() {
- if (this._url.query === null || this._url.query === "") {
- return "";
- }
+picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
- return "?" + this._url.query;
- }
+/**
+ * Parse a glob pattern to create the source string for a regular
+ * expression.
+ *
+ * ```js
+ * const picomatch = require('picomatch');
+ * const result = picomatch.parse(pattern[, options]);
+ * ```
+ * @param {String} `pattern`
+ * @param {Object} `options`
+ * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
+ * @api public
+ */
- set search(v) {
- // TODO: query stuff
+picomatch.parse = (pattern, options) => {
+ if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options));
+ return parse(pattern, { ...options, fastpaths: false });
+};
- const url = this._url;
+/**
+ * Scan a glob pattern to separate the pattern into segments.
+ *
+ * ```js
+ * const picomatch = require('picomatch');
+ * // picomatch.scan(input[, options]);
+ *
+ * const result = picomatch.scan('!./foo/*.js');
+ * console.log(result);
+ * { prefix: '!./',
+ * input: '!./foo/*.js',
+ * start: 3,
+ * base: 'foo',
+ * glob: '*.js',
+ * isBrace: false,
+ * isBracket: false,
+ * isGlob: true,
+ * isExtglob: false,
+ * isGlobstar: false,
+ * negated: true }
+ * ```
+ * @param {String} `input` Glob pattern to scan.
+ * @param {Object} `options`
+ * @return {Object} Returns an object with
+ * @api public
+ */
- if (v === "") {
- url.query = null;
- return;
- }
+picomatch.scan = (input, options) => scan(input, options);
- const input = v[0] === "?" ? v.substring(1) : v;
- url.query = "";
- usm.basicURLParse(input, { url, stateOverride: "query" });
+/**
+ * Compile a regular expression from the `state` object returned by the
+ * [parse()](#parse) method.
+ *
+ * @param {Object} `state`
+ * @param {Object} `options`
+ * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser.
+ * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging.
+ * @return {RegExp}
+ * @api public
+ */
+
+picomatch.compileRe = (state, options, returnOutput = false, returnState = false) => {
+ if (returnOutput === true) {
+ return state.output;
}
- get hash() {
- if (this._url.fragment === null || this._url.fragment === "") {
- return "";
- }
+ const opts = options || {};
+ const prepend = opts.contains ? '' : '^';
+ const append = opts.contains ? '' : '$';
- return "#" + this._url.fragment;
+ let source = `${prepend}(?:${state.output})${append}`;
+ if (state && state.negated === true) {
+ source = `^(?!${source}).*$`;
}
- set hash(v) {
- if (v === "") {
- this._url.fragment = null;
- return;
- }
+ const regex = picomatch.toRegex(source, options);
+ if (returnState === true) {
+ regex.state = state;
+ }
- const input = v[0] === "#" ? v.substring(1) : v;
- this._url.fragment = "";
- usm.basicURLParse(input, { url: this._url, stateOverride: "fragment" });
+ return regex;
+};
+
+/**
+ * Create a regular expression from a parsed glob pattern.
+ *
+ * ```js
+ * const picomatch = require('picomatch');
+ * const state = picomatch.parse('*.js');
+ * // picomatch.compileRe(state[, options]);
+ *
+ * console.log(picomatch.compileRe(state));
+ * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
+ * ```
+ * @param {String} `state` The object returned from the `.parse` method.
+ * @param {Object} `options`
+ * @param {Boolean} `returnOutput` Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result.
+ * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression.
+ * @return {RegExp} Returns a regex created from the given pattern.
+ * @api public
+ */
+
+picomatch.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
+ if (!input || typeof input !== 'string') {
+ throw new TypeError('Expected a non-empty string');
}
- toJSON() {
- return this.href;
+ let parsed = { negated: false, fastpaths: true };
+
+ if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
+ parsed.output = parse.fastpaths(input, options);
+ }
+
+ if (!parsed.output) {
+ parsed = parse(input, options);
+ }
+
+ return picomatch.compileRe(parsed, options, returnOutput, returnState);
+};
+
+/**
+ * Create a regular expression from the given regex source string.
+ *
+ * ```js
+ * const picomatch = require('picomatch');
+ * // picomatch.toRegex(source[, options]);
+ *
+ * const { output } = picomatch.parse('*.js');
+ * console.log(picomatch.toRegex(output));
+ * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
+ * ```
+ * @param {String} `source` Regular expression source string.
+ * @param {Object} `options`
+ * @return {RegExp}
+ * @api public
+ */
+
+picomatch.toRegex = (source, options) => {
+ try {
+ const opts = options || {};
+ return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
+ } catch (err) {
+ if (options && options.debug === true) throw err;
+ return /$^/;
}
};
+/**
+ * Picomatch constants.
+ * @return {Object}
+ */
+
+picomatch.constants = constants;
+
+/**
+ * Expose "picomatch"
+ */
+
+module.exports = picomatch;
+
/***/ }),
-/***/ 653:
+/***/ 2429:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
-const conversions = __nccwpck_require__(5871);
-const utils = __nccwpck_require__(276);
-const Impl = __nccwpck_require__(8262);
+const utils = __nccwpck_require__(479);
+const {
+ CHAR_ASTERISK, /* * */
+ CHAR_AT, /* @ */
+ CHAR_BACKWARD_SLASH, /* \ */
+ CHAR_COMMA, /* , */
+ CHAR_DOT, /* . */
+ CHAR_EXCLAMATION_MARK, /* ! */
+ CHAR_FORWARD_SLASH, /* / */
+ CHAR_LEFT_CURLY_BRACE, /* { */
+ CHAR_LEFT_PARENTHESES, /* ( */
+ CHAR_LEFT_SQUARE_BRACKET, /* [ */
+ CHAR_PLUS, /* + */
+ CHAR_QUESTION_MARK, /* ? */
+ CHAR_RIGHT_CURLY_BRACE, /* } */
+ CHAR_RIGHT_PARENTHESES, /* ) */
+ CHAR_RIGHT_SQUARE_BRACKET /* ] */
+} = __nccwpck_require__(6099);
-const impl = utils.implSymbol;
+const isPathSeparator = code => {
+ return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
+};
-function URL(url) {
- if (!this || this[impl] || !(this instanceof URL)) {
- throw new TypeError("Failed to construct 'URL': Please use the 'new' operator, this DOM object constructor cannot be called as a function.");
- }
- if (arguments.length < 1) {
- throw new TypeError("Failed to construct 'URL': 1 argument required, but only " + arguments.length + " present.");
- }
- const args = [];
- for (let i = 0; i < arguments.length && i < 2; ++i) {
- args[i] = arguments[i];
- }
- args[0] = conversions["USVString"](args[0]);
- if (args[1] !== undefined) {
- args[1] = conversions["USVString"](args[1]);
+const depth = token => {
+ if (token.isPrefix !== true) {
+ token.depth = token.isGlobstar ? Infinity : 1;
}
+};
- module.exports.setup(this, args);
-}
+/**
+ * Quickly scans a glob pattern and returns an object with a handful of
+ * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
+ * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not
+ * with `!(`) and `negatedExtglob` (true if the path starts with `!(`).
+ *
+ * ```js
+ * const pm = require('picomatch');
+ * console.log(pm.scan('foo/bar/*.js'));
+ * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
+ * ```
+ * @param {String} `str`
+ * @param {Object} `options`
+ * @return {Object} Returns an object with tokens and regex source string.
+ * @api public
+ */
-URL.prototype.toJSON = function toJSON() {
- if (!this || !module.exports.is(this)) {
- throw new TypeError("Illegal invocation");
- }
- const args = [];
- for (let i = 0; i < arguments.length && i < 0; ++i) {
- args[i] = arguments[i];
- }
- return this[impl].toJSON.apply(this[impl], args);
-};
-Object.defineProperty(URL.prototype, "href", {
- get() {
- return this[impl].href;
- },
- set(V) {
- V = conversions["USVString"](V);
- this[impl].href = V;
- },
- enumerable: true,
- configurable: true
-});
+const scan = (input, options) => {
+ const opts = options || {};
-URL.prototype.toString = function () {
- if (!this || !module.exports.is(this)) {
- throw new TypeError("Illegal invocation");
- }
- return this.href;
-};
+ const length = input.length - 1;
+ const scanToEnd = opts.parts === true || opts.scanToEnd === true;
+ const slashes = [];
+ const tokens = [];
+ const parts = [];
-Object.defineProperty(URL.prototype, "origin", {
- get() {
- return this[impl].origin;
- },
- enumerable: true,
- configurable: true
-});
+ let str = input;
+ let index = -1;
+ let start = 0;
+ let lastIndex = 0;
+ let isBrace = false;
+ let isBracket = false;
+ let isGlob = false;
+ let isExtglob = false;
+ let isGlobstar = false;
+ let braceEscaped = false;
+ let backslashes = false;
+ let negated = false;
+ let negatedExtglob = false;
+ let finished = false;
+ let braces = 0;
+ let prev;
+ let code;
+ let token = { value: '', depth: 0, isGlob: false };
-Object.defineProperty(URL.prototype, "protocol", {
- get() {
- return this[impl].protocol;
- },
- set(V) {
- V = conversions["USVString"](V);
- this[impl].protocol = V;
- },
- enumerable: true,
- configurable: true
-});
+ const eos = () => index >= length;
+ const peek = () => str.charCodeAt(index + 1);
+ const advance = () => {
+ prev = code;
+ return str.charCodeAt(++index);
+ };
-Object.defineProperty(URL.prototype, "username", {
- get() {
- return this[impl].username;
- },
- set(V) {
- V = conversions["USVString"](V);
- this[impl].username = V;
- },
- enumerable: true,
- configurable: true
-});
+ while (index < length) {
+ code = advance();
+ let next;
-Object.defineProperty(URL.prototype, "password", {
- get() {
- return this[impl].password;
- },
- set(V) {
- V = conversions["USVString"](V);
- this[impl].password = V;
- },
- enumerable: true,
- configurable: true
-});
+ if (code === CHAR_BACKWARD_SLASH) {
+ backslashes = token.backslashes = true;
+ code = advance();
-Object.defineProperty(URL.prototype, "host", {
- get() {
- return this[impl].host;
- },
- set(V) {
- V = conversions["USVString"](V);
- this[impl].host = V;
- },
- enumerable: true,
- configurable: true
-});
+ if (code === CHAR_LEFT_CURLY_BRACE) {
+ braceEscaped = true;
+ }
+ continue;
+ }
-Object.defineProperty(URL.prototype, "hostname", {
- get() {
- return this[impl].hostname;
- },
- set(V) {
- V = conversions["USVString"](V);
- this[impl].hostname = V;
- },
- enumerable: true,
- configurable: true
-});
+ if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {
+ braces++;
-Object.defineProperty(URL.prototype, "port", {
- get() {
- return this[impl].port;
- },
- set(V) {
- V = conversions["USVString"](V);
- this[impl].port = V;
- },
- enumerable: true,
- configurable: true
-});
+ while (eos() !== true && (code = advance())) {
+ if (code === CHAR_BACKWARD_SLASH) {
+ backslashes = token.backslashes = true;
+ advance();
+ continue;
+ }
-Object.defineProperty(URL.prototype, "pathname", {
- get() {
- return this[impl].pathname;
- },
- set(V) {
- V = conversions["USVString"](V);
- this[impl].pathname = V;
- },
- enumerable: true,
- configurable: true
-});
+ if (code === CHAR_LEFT_CURLY_BRACE) {
+ braces++;
+ continue;
+ }
-Object.defineProperty(URL.prototype, "search", {
- get() {
- return this[impl].search;
- },
- set(V) {
- V = conversions["USVString"](V);
- this[impl].search = V;
- },
- enumerable: true,
- configurable: true
-});
+ if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {
+ isBrace = token.isBrace = true;
+ isGlob = token.isGlob = true;
+ finished = true;
-Object.defineProperty(URL.prototype, "hash", {
- get() {
- return this[impl].hash;
- },
- set(V) {
- V = conversions["USVString"](V);
- this[impl].hash = V;
- },
- enumerable: true,
- configurable: true
-});
+ if (scanToEnd === true) {
+ continue;
+ }
+ break;
+ }
-module.exports = {
- is(obj) {
- return !!obj && obj[impl] instanceof Impl.implementation;
- },
- create(constructorArgs, privateData) {
- let obj = Object.create(URL.prototype);
- this.setup(obj, constructorArgs, privateData);
- return obj;
- },
- setup(obj, constructorArgs, privateData) {
- if (!privateData) privateData = {};
- privateData.wrapper = obj;
+ if (braceEscaped !== true && code === CHAR_COMMA) {
+ isBrace = token.isBrace = true;
+ isGlob = token.isGlob = true;
+ finished = true;
- obj[impl] = new Impl.implementation(constructorArgs, privateData);
- obj[impl][utils.wrapperSymbol] = obj;
- },
- interface: URL,
- expose: {
- Window: { URL: URL },
- Worker: { URL: URL }
- }
-};
+ if (scanToEnd === true) {
+ continue;
+ }
+ break;
+ }
+ if (code === CHAR_RIGHT_CURLY_BRACE) {
+ braces--;
-/***/ }),
+ if (braces === 0) {
+ braceEscaped = false;
+ isBrace = token.isBrace = true;
+ finished = true;
+ break;
+ }
+ }
+ }
-/***/ 3323:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ if (scanToEnd === true) {
+ continue;
+ }
-"use strict";
+ break;
+ }
+ if (code === CHAR_FORWARD_SLASH) {
+ slashes.push(index);
+ tokens.push(token);
+ token = { value: '', depth: 0, isGlob: false };
-exports.URL = __nccwpck_require__(653).interface;
-exports.serializeURL = __nccwpck_require__(33).serializeURL;
-exports.serializeURLOrigin = __nccwpck_require__(33).serializeURLOrigin;
-exports.basicURLParse = __nccwpck_require__(33).basicURLParse;
-exports.setTheUsername = __nccwpck_require__(33).setTheUsername;
-exports.setThePassword = __nccwpck_require__(33).setThePassword;
-exports.serializeHost = __nccwpck_require__(33).serializeHost;
-exports.serializeInteger = __nccwpck_require__(33).serializeInteger;
-exports.parseURL = __nccwpck_require__(33).parseURL;
+ if (finished === true) continue;
+ if (prev === CHAR_DOT && index === (start + 1)) {
+ start += 2;
+ continue;
+ }
+ lastIndex = index + 1;
+ continue;
+ }
-/***/ }),
+ if (opts.noext !== true) {
+ const isExtglobChar = code === CHAR_PLUS
+ || code === CHAR_AT
+ || code === CHAR_ASTERISK
+ || code === CHAR_QUESTION_MARK
+ || code === CHAR_EXCLAMATION_MARK;
-/***/ 33:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) {
+ isGlob = token.isGlob = true;
+ isExtglob = token.isExtglob = true;
+ finished = true;
+ if (code === CHAR_EXCLAMATION_MARK && index === start) {
+ negatedExtglob = true;
+ }
-"use strict";
-
-const punycode = __nccwpck_require__(4213);
-const tr46 = __nccwpck_require__(2299);
-
-const specialSchemes = {
- ftp: 21,
- file: null,
- gopher: 70,
- http: 80,
- https: 443,
- ws: 80,
- wss: 443
-};
-
-const failure = Symbol("failure");
-
-function countSymbols(str) {
- return punycode.ucs2.decode(str).length;
-}
-
-function at(input, idx) {
- const c = input[idx];
- return isNaN(c) ? undefined : String.fromCodePoint(c);
-}
-
-function isASCIIDigit(c) {
- return c >= 0x30 && c <= 0x39;
-}
-
-function isASCIIAlpha(c) {
- return (c >= 0x41 && c <= 0x5A) || (c >= 0x61 && c <= 0x7A);
-}
-
-function isASCIIAlphanumeric(c) {
- return isASCIIAlpha(c) || isASCIIDigit(c);
-}
-
-function isASCIIHex(c) {
- return isASCIIDigit(c) || (c >= 0x41 && c <= 0x46) || (c >= 0x61 && c <= 0x66);
-}
-
-function isSingleDot(buffer) {
- return buffer === "." || buffer.toLowerCase() === "%2e";
-}
-
-function isDoubleDot(buffer) {
- buffer = buffer.toLowerCase();
- return buffer === ".." || buffer === "%2e." || buffer === ".%2e" || buffer === "%2e%2e";
-}
-
-function isWindowsDriveLetterCodePoints(cp1, cp2) {
- return isASCIIAlpha(cp1) && (cp2 === 58 || cp2 === 124);
-}
-
-function isWindowsDriveLetterString(string) {
- return string.length === 2 && isASCIIAlpha(string.codePointAt(0)) && (string[1] === ":" || string[1] === "|");
-}
-
-function isNormalizedWindowsDriveLetterString(string) {
- return string.length === 2 && isASCIIAlpha(string.codePointAt(0)) && string[1] === ":";
-}
-
-function containsForbiddenHostCodePoint(string) {
- return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|%|\/|:|\?|@|\[|\\|\]/) !== -1;
-}
-
-function containsForbiddenHostCodePointExcludingPercent(string) {
- return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|\?|@|\[|\\|\]/) !== -1;
-}
-
-function isSpecialScheme(scheme) {
- return specialSchemes[scheme] !== undefined;
-}
-
-function isSpecial(url) {
- return isSpecialScheme(url.scheme);
-}
-
-function defaultPort(scheme) {
- return specialSchemes[scheme];
-}
-
-function percentEncode(c) {
- let hex = c.toString(16).toUpperCase();
- if (hex.length === 1) {
- hex = "0" + hex;
- }
-
- return "%" + hex;
-}
-
-function utf8PercentEncode(c) {
- const buf = new Buffer(c);
-
- let str = "";
-
- for (let i = 0; i < buf.length; ++i) {
- str += percentEncode(buf[i]);
- }
-
- return str;
-}
-
-function utf8PercentDecode(str) {
- const input = new Buffer(str);
- const output = [];
- for (let i = 0; i < input.length; ++i) {
- if (input[i] !== 37) {
- output.push(input[i]);
- } else if (input[i] === 37 && isASCIIHex(input[i + 1]) && isASCIIHex(input[i + 2])) {
- output.push(parseInt(input.slice(i + 1, i + 3).toString(), 16));
- i += 2;
- } else {
- output.push(input[i]);
- }
- }
- return new Buffer(output).toString();
-}
-
-function isC0ControlPercentEncode(c) {
- return c <= 0x1F || c > 0x7E;
-}
-
-const extraPathPercentEncodeSet = new Set([32, 34, 35, 60, 62, 63, 96, 123, 125]);
-function isPathPercentEncode(c) {
- return isC0ControlPercentEncode(c) || extraPathPercentEncodeSet.has(c);
-}
-
-const extraUserinfoPercentEncodeSet =
- new Set([47, 58, 59, 61, 64, 91, 92, 93, 94, 124]);
-function isUserinfoPercentEncode(c) {
- return isPathPercentEncode(c) || extraUserinfoPercentEncodeSet.has(c);
-}
-
-function percentEncodeChar(c, encodeSetPredicate) {
- const cStr = String.fromCodePoint(c);
-
- if (encodeSetPredicate(c)) {
- return utf8PercentEncode(cStr);
- }
-
- return cStr;
-}
-
-function parseIPv4Number(input) {
- let R = 10;
-
- if (input.length >= 2 && input.charAt(0) === "0" && input.charAt(1).toLowerCase() === "x") {
- input = input.substring(2);
- R = 16;
- } else if (input.length >= 2 && input.charAt(0) === "0") {
- input = input.substring(1);
- R = 8;
- }
-
- if (input === "") {
- return 0;
- }
-
- const regex = R === 10 ? /[^0-9]/ : (R === 16 ? /[^0-9A-Fa-f]/ : /[^0-7]/);
- if (regex.test(input)) {
- return failure;
- }
-
- return parseInt(input, R);
-}
-
-function parseIPv4(input) {
- const parts = input.split(".");
- if (parts[parts.length - 1] === "") {
- if (parts.length > 1) {
- parts.pop();
- }
- }
-
- if (parts.length > 4) {
- return input;
- }
-
- const numbers = [];
- for (const part of parts) {
- if (part === "") {
- return input;
- }
- const n = parseIPv4Number(part);
- if (n === failure) {
- return input;
- }
-
- numbers.push(n);
- }
-
- for (let i = 0; i < numbers.length - 1; ++i) {
- if (numbers[i] > 255) {
- return failure;
- }
- }
- if (numbers[numbers.length - 1] >= Math.pow(256, 5 - numbers.length)) {
- return failure;
- }
-
- let ipv4 = numbers.pop();
- let counter = 0;
-
- for (const n of numbers) {
- ipv4 += n * Math.pow(256, 3 - counter);
- ++counter;
- }
-
- return ipv4;
-}
-
-function serializeIPv4(address) {
- let output = "";
- let n = address;
-
- for (let i = 1; i <= 4; ++i) {
- output = String(n % 256) + output;
- if (i !== 4) {
- output = "." + output;
- }
- n = Math.floor(n / 256);
- }
-
- return output;
-}
-
-function parseIPv6(input) {
- const address = [0, 0, 0, 0, 0, 0, 0, 0];
- let pieceIndex = 0;
- let compress = null;
- let pointer = 0;
-
- input = punycode.ucs2.decode(input);
-
- if (input[pointer] === 58) {
- if (input[pointer + 1] !== 58) {
- return failure;
- }
-
- pointer += 2;
- ++pieceIndex;
- compress = pieceIndex;
- }
-
- while (pointer < input.length) {
- if (pieceIndex === 8) {
- return failure;
- }
-
- if (input[pointer] === 58) {
- if (compress !== null) {
- return failure;
- }
- ++pointer;
- ++pieceIndex;
- compress = pieceIndex;
- continue;
- }
-
- let value = 0;
- let length = 0;
-
- while (length < 4 && isASCIIHex(input[pointer])) {
- value = value * 0x10 + parseInt(at(input, pointer), 16);
- ++pointer;
- ++length;
- }
-
- if (input[pointer] === 46) {
- if (length === 0) {
- return failure;
- }
-
- pointer -= length;
-
- if (pieceIndex > 6) {
- return failure;
- }
-
- let numbersSeen = 0;
-
- while (input[pointer] !== undefined) {
- let ipv4Piece = null;
-
- if (numbersSeen > 0) {
- if (input[pointer] === 46 && numbersSeen < 4) {
- ++pointer;
- } else {
- return failure;
- }
- }
-
- if (!isASCIIDigit(input[pointer])) {
- return failure;
- }
-
- while (isASCIIDigit(input[pointer])) {
- const number = parseInt(at(input, pointer));
- if (ipv4Piece === null) {
- ipv4Piece = number;
- } else if (ipv4Piece === 0) {
- return failure;
- } else {
- ipv4Piece = ipv4Piece * 10 + number;
- }
- if (ipv4Piece > 255) {
- return failure;
- }
- ++pointer;
- }
-
- address[pieceIndex] = address[pieceIndex] * 0x100 + ipv4Piece;
-
- ++numbersSeen;
-
- if (numbersSeen === 2 || numbersSeen === 4) {
- ++pieceIndex;
- }
- }
-
- if (numbersSeen !== 4) {
- return failure;
- }
-
- break;
- } else if (input[pointer] === 58) {
- ++pointer;
- if (input[pointer] === undefined) {
- return failure;
- }
- } else if (input[pointer] !== undefined) {
- return failure;
- }
-
- address[pieceIndex] = value;
- ++pieceIndex;
- }
-
- if (compress !== null) {
- let swaps = pieceIndex - compress;
- pieceIndex = 7;
- while (pieceIndex !== 0 && swaps > 0) {
- const temp = address[compress + swaps - 1];
- address[compress + swaps - 1] = address[pieceIndex];
- address[pieceIndex] = temp;
- --pieceIndex;
- --swaps;
- }
- } else if (compress === null && pieceIndex !== 8) {
- return failure;
- }
-
- return address;
-}
-
-function serializeIPv6(address) {
- let output = "";
- const seqResult = findLongestZeroSequence(address);
- const compress = seqResult.idx;
- let ignore0 = false;
-
- for (let pieceIndex = 0; pieceIndex <= 7; ++pieceIndex) {
- if (ignore0 && address[pieceIndex] === 0) {
- continue;
- } else if (ignore0) {
- ignore0 = false;
- }
-
- if (compress === pieceIndex) {
- const separator = pieceIndex === 0 ? "::" : ":";
- output += separator;
- ignore0 = true;
- continue;
- }
-
- output += address[pieceIndex].toString(16);
-
- if (pieceIndex !== 7) {
- output += ":";
- }
- }
-
- return output;
-}
-
-function parseHost(input, isSpecialArg) {
- if (input[0] === "[") {
- if (input[input.length - 1] !== "]") {
- return failure;
- }
-
- return parseIPv6(input.substring(1, input.length - 1));
- }
-
- if (!isSpecialArg) {
- return parseOpaqueHost(input);
- }
-
- const domain = utf8PercentDecode(input);
- const asciiDomain = tr46.toASCII(domain, false, tr46.PROCESSING_OPTIONS.NONTRANSITIONAL, false);
- if (asciiDomain === null) {
- return failure;
- }
-
- if (containsForbiddenHostCodePoint(asciiDomain)) {
- return failure;
- }
-
- const ipv4Host = parseIPv4(asciiDomain);
- if (typeof ipv4Host === "number" || ipv4Host === failure) {
- return ipv4Host;
- }
-
- return asciiDomain;
-}
-
-function parseOpaqueHost(input) {
- if (containsForbiddenHostCodePointExcludingPercent(input)) {
- return failure;
- }
-
- let output = "";
- const decoded = punycode.ucs2.decode(input);
- for (let i = 0; i < decoded.length; ++i) {
- output += percentEncodeChar(decoded[i], isC0ControlPercentEncode);
- }
- return output;
-}
-
-function findLongestZeroSequence(arr) {
- let maxIdx = null;
- let maxLen = 1; // only find elements > 1
- let currStart = null;
- let currLen = 0;
-
- for (let i = 0; i < arr.length; ++i) {
- if (arr[i] !== 0) {
- if (currLen > maxLen) {
- maxIdx = currStart;
- maxLen = currLen;
- }
-
- currStart = null;
- currLen = 0;
- } else {
- if (currStart === null) {
- currStart = i;
- }
- ++currLen;
- }
- }
-
- // if trailing zeros
- if (currLen > maxLen) {
- maxIdx = currStart;
- maxLen = currLen;
- }
-
- return {
- idx: maxIdx,
- len: maxLen
- };
-}
-
-function serializeHost(host) {
- if (typeof host === "number") {
- return serializeIPv4(host);
- }
-
- // IPv6 serializer
- if (host instanceof Array) {
- return "[" + serializeIPv6(host) + "]";
- }
-
- return host;
-}
-
-function trimControlChars(url) {
- return url.replace(/^[\u0000-\u001F\u0020]+|[\u0000-\u001F\u0020]+$/g, "");
-}
-
-function trimTabAndNewline(url) {
- return url.replace(/\u0009|\u000A|\u000D/g, "");
-}
-
-function shortenPath(url) {
- const path = url.path;
- if (path.length === 0) {
- return;
- }
- if (url.scheme === "file" && path.length === 1 && isNormalizedWindowsDriveLetter(path[0])) {
- return;
- }
-
- path.pop();
-}
-
-function includesCredentials(url) {
- return url.username !== "" || url.password !== "";
-}
-
-function cannotHaveAUsernamePasswordPort(url) {
- return url.host === null || url.host === "" || url.cannotBeABaseURL || url.scheme === "file";
-}
-
-function isNormalizedWindowsDriveLetter(string) {
- return /^[A-Za-z]:$/.test(string);
-}
-
-function URLStateMachine(input, base, encodingOverride, url, stateOverride) {
- this.pointer = 0;
- this.input = input;
- this.base = base || null;
- this.encodingOverride = encodingOverride || "utf-8";
- this.stateOverride = stateOverride;
- this.url = url;
- this.failure = false;
- this.parseError = false;
-
- if (!this.url) {
- this.url = {
- scheme: "",
- username: "",
- password: "",
- host: null,
- port: null,
- path: [],
- query: null,
- fragment: null,
-
- cannotBeABaseURL: false
- };
-
- const res = trimControlChars(this.input);
- if (res !== this.input) {
- this.parseError = true;
- }
- this.input = res;
- }
-
- const res = trimTabAndNewline(this.input);
- if (res !== this.input) {
- this.parseError = true;
- }
- this.input = res;
-
- this.state = stateOverride || "scheme start";
-
- this.buffer = "";
- this.atFlag = false;
- this.arrFlag = false;
- this.passwordTokenSeenFlag = false;
-
- this.input = punycode.ucs2.decode(this.input);
-
- for (; this.pointer <= this.input.length; ++this.pointer) {
- const c = this.input[this.pointer];
- const cStr = isNaN(c) ? undefined : String.fromCodePoint(c);
-
- // exec state machine
- const ret = this["parse " + this.state](c, cStr);
- if (!ret) {
- break; // terminate algorithm
- } else if (ret === failure) {
- this.failure = true;
- break;
- }
- }
-}
-
-URLStateMachine.prototype["parse scheme start"] = function parseSchemeStart(c, cStr) {
- if (isASCIIAlpha(c)) {
- this.buffer += cStr.toLowerCase();
- this.state = "scheme";
- } else if (!this.stateOverride) {
- this.state = "no scheme";
- --this.pointer;
- } else {
- this.parseError = true;
- return failure;
- }
-
- return true;
-};
-
-URLStateMachine.prototype["parse scheme"] = function parseScheme(c, cStr) {
- if (isASCIIAlphanumeric(c) || c === 43 || c === 45 || c === 46) {
- this.buffer += cStr.toLowerCase();
- } else if (c === 58) {
- if (this.stateOverride) {
- if (isSpecial(this.url) && !isSpecialScheme(this.buffer)) {
- return false;
- }
-
- if (!isSpecial(this.url) && isSpecialScheme(this.buffer)) {
- return false;
- }
-
- if ((includesCredentials(this.url) || this.url.port !== null) && this.buffer === "file") {
- return false;
- }
-
- if (this.url.scheme === "file" && (this.url.host === "" || this.url.host === null)) {
- return false;
- }
- }
- this.url.scheme = this.buffer;
- this.buffer = "";
- if (this.stateOverride) {
- return false;
- }
- if (this.url.scheme === "file") {
- if (this.input[this.pointer + 1] !== 47 || this.input[this.pointer + 2] !== 47) {
- this.parseError = true;
- }
- this.state = "file";
- } else if (isSpecial(this.url) && this.base !== null && this.base.scheme === this.url.scheme) {
- this.state = "special relative or authority";
- } else if (isSpecial(this.url)) {
- this.state = "special authority slashes";
- } else if (this.input[this.pointer + 1] === 47) {
- this.state = "path or authority";
- ++this.pointer;
- } else {
- this.url.cannotBeABaseURL = true;
- this.url.path.push("");
- this.state = "cannot-be-a-base-URL path";
- }
- } else if (!this.stateOverride) {
- this.buffer = "";
- this.state = "no scheme";
- this.pointer = -1;
- } else {
- this.parseError = true;
- return failure;
- }
-
- return true;
-};
-
-URLStateMachine.prototype["parse no scheme"] = function parseNoScheme(c) {
- if (this.base === null || (this.base.cannotBeABaseURL && c !== 35)) {
- return failure;
- } else if (this.base.cannotBeABaseURL && c === 35) {
- this.url.scheme = this.base.scheme;
- this.url.path = this.base.path.slice();
- this.url.query = this.base.query;
- this.url.fragment = "";
- this.url.cannotBeABaseURL = true;
- this.state = "fragment";
- } else if (this.base.scheme === "file") {
- this.state = "file";
- --this.pointer;
- } else {
- this.state = "relative";
- --this.pointer;
- }
-
- return true;
-};
-
-URLStateMachine.prototype["parse special relative or authority"] = function parseSpecialRelativeOrAuthority(c) {
- if (c === 47 && this.input[this.pointer + 1] === 47) {
- this.state = "special authority ignore slashes";
- ++this.pointer;
- } else {
- this.parseError = true;
- this.state = "relative";
- --this.pointer;
- }
-
- return true;
-};
-
-URLStateMachine.prototype["parse path or authority"] = function parsePathOrAuthority(c) {
- if (c === 47) {
- this.state = "authority";
- } else {
- this.state = "path";
- --this.pointer;
- }
-
- return true;
-};
-
-URLStateMachine.prototype["parse relative"] = function parseRelative(c) {
- this.url.scheme = this.base.scheme;
- if (isNaN(c)) {
- this.url.username = this.base.username;
- this.url.password = this.base.password;
- this.url.host = this.base.host;
- this.url.port = this.base.port;
- this.url.path = this.base.path.slice();
- this.url.query = this.base.query;
- } else if (c === 47) {
- this.state = "relative slash";
- } else if (c === 63) {
- this.url.username = this.base.username;
- this.url.password = this.base.password;
- this.url.host = this.base.host;
- this.url.port = this.base.port;
- this.url.path = this.base.path.slice();
- this.url.query = "";
- this.state = "query";
- } else if (c === 35) {
- this.url.username = this.base.username;
- this.url.password = this.base.password;
- this.url.host = this.base.host;
- this.url.port = this.base.port;
- this.url.path = this.base.path.slice();
- this.url.query = this.base.query;
- this.url.fragment = "";
- this.state = "fragment";
- } else if (isSpecial(this.url) && c === 92) {
- this.parseError = true;
- this.state = "relative slash";
- } else {
- this.url.username = this.base.username;
- this.url.password = this.base.password;
- this.url.host = this.base.host;
- this.url.port = this.base.port;
- this.url.path = this.base.path.slice(0, this.base.path.length - 1);
-
- this.state = "path";
- --this.pointer;
- }
-
- return true;
-};
-
-URLStateMachine.prototype["parse relative slash"] = function parseRelativeSlash(c) {
- if (isSpecial(this.url) && (c === 47 || c === 92)) {
- if (c === 92) {
- this.parseError = true;
- }
- this.state = "special authority ignore slashes";
- } else if (c === 47) {
- this.state = "authority";
- } else {
- this.url.username = this.base.username;
- this.url.password = this.base.password;
- this.url.host = this.base.host;
- this.url.port = this.base.port;
- this.state = "path";
- --this.pointer;
- }
-
- return true;
-};
-
-URLStateMachine.prototype["parse special authority slashes"] = function parseSpecialAuthoritySlashes(c) {
- if (c === 47 && this.input[this.pointer + 1] === 47) {
- this.state = "special authority ignore slashes";
- ++this.pointer;
- } else {
- this.parseError = true;
- this.state = "special authority ignore slashes";
- --this.pointer;
- }
-
- return true;
-};
-
-URLStateMachine.prototype["parse special authority ignore slashes"] = function parseSpecialAuthorityIgnoreSlashes(c) {
- if (c !== 47 && c !== 92) {
- this.state = "authority";
- --this.pointer;
- } else {
- this.parseError = true;
- }
-
- return true;
-};
-
-URLStateMachine.prototype["parse authority"] = function parseAuthority(c, cStr) {
- if (c === 64) {
- this.parseError = true;
- if (this.atFlag) {
- this.buffer = "%40" + this.buffer;
- }
- this.atFlag = true;
-
- // careful, this is based on buffer and has its own pointer (this.pointer != pointer) and inner chars
- const len = countSymbols(this.buffer);
- for (let pointer = 0; pointer < len; ++pointer) {
- const codePoint = this.buffer.codePointAt(pointer);
-
- if (codePoint === 58 && !this.passwordTokenSeenFlag) {
- this.passwordTokenSeenFlag = true;
- continue;
- }
- const encodedCodePoints = percentEncodeChar(codePoint, isUserinfoPercentEncode);
- if (this.passwordTokenSeenFlag) {
- this.url.password += encodedCodePoints;
- } else {
- this.url.username += encodedCodePoints;
- }
- }
- this.buffer = "";
- } else if (isNaN(c) || c === 47 || c === 63 || c === 35 ||
- (isSpecial(this.url) && c === 92)) {
- if (this.atFlag && this.buffer === "") {
- this.parseError = true;
- return failure;
- }
- this.pointer -= countSymbols(this.buffer) + 1;
- this.buffer = "";
- this.state = "host";
- } else {
- this.buffer += cStr;
- }
-
- return true;
-};
-
-URLStateMachine.prototype["parse hostname"] =
-URLStateMachine.prototype["parse host"] = function parseHostName(c, cStr) {
- if (this.stateOverride && this.url.scheme === "file") {
- --this.pointer;
- this.state = "file host";
- } else if (c === 58 && !this.arrFlag) {
- if (this.buffer === "") {
- this.parseError = true;
- return failure;
- }
-
- const host = parseHost(this.buffer, isSpecial(this.url));
- if (host === failure) {
- return failure;
- }
-
- this.url.host = host;
- this.buffer = "";
- this.state = "port";
- if (this.stateOverride === "hostname") {
- return false;
- }
- } else if (isNaN(c) || c === 47 || c === 63 || c === 35 ||
- (isSpecial(this.url) && c === 92)) {
- --this.pointer;
- if (isSpecial(this.url) && this.buffer === "") {
- this.parseError = true;
- return failure;
- } else if (this.stateOverride && this.buffer === "" &&
- (includesCredentials(this.url) || this.url.port !== null)) {
- this.parseError = true;
- return false;
- }
-
- const host = parseHost(this.buffer, isSpecial(this.url));
- if (host === failure) {
- return failure;
- }
-
- this.url.host = host;
- this.buffer = "";
- this.state = "path start";
- if (this.stateOverride) {
- return false;
- }
- } else {
- if (c === 91) {
- this.arrFlag = true;
- } else if (c === 93) {
- this.arrFlag = false;
- }
- this.buffer += cStr;
- }
-
- return true;
-};
-
-URLStateMachine.prototype["parse port"] = function parsePort(c, cStr) {
- if (isASCIIDigit(c)) {
- this.buffer += cStr;
- } else if (isNaN(c) || c === 47 || c === 63 || c === 35 ||
- (isSpecial(this.url) && c === 92) ||
- this.stateOverride) {
- if (this.buffer !== "") {
- const port = parseInt(this.buffer);
- if (port > Math.pow(2, 16) - 1) {
- this.parseError = true;
- return failure;
- }
- this.url.port = port === defaultPort(this.url.scheme) ? null : port;
- this.buffer = "";
- }
- if (this.stateOverride) {
- return false;
- }
- this.state = "path start";
- --this.pointer;
- } else {
- this.parseError = true;
- return failure;
- }
-
- return true;
-};
-
-const fileOtherwiseCodePoints = new Set([47, 92, 63, 35]);
-
-URLStateMachine.prototype["parse file"] = function parseFile(c) {
- this.url.scheme = "file";
-
- if (c === 47 || c === 92) {
- if (c === 92) {
- this.parseError = true;
- }
- this.state = "file slash";
- } else if (this.base !== null && this.base.scheme === "file") {
- if (isNaN(c)) {
- this.url.host = this.base.host;
- this.url.path = this.base.path.slice();
- this.url.query = this.base.query;
- } else if (c === 63) {
- this.url.host = this.base.host;
- this.url.path = this.base.path.slice();
- this.url.query = "";
- this.state = "query";
- } else if (c === 35) {
- this.url.host = this.base.host;
- this.url.path = this.base.path.slice();
- this.url.query = this.base.query;
- this.url.fragment = "";
- this.state = "fragment";
- } else {
- if (this.input.length - this.pointer - 1 === 0 || // remaining consists of 0 code points
- !isWindowsDriveLetterCodePoints(c, this.input[this.pointer + 1]) ||
- (this.input.length - this.pointer - 1 >= 2 && // remaining has at least 2 code points
- !fileOtherwiseCodePoints.has(this.input[this.pointer + 2]))) {
- this.url.host = this.base.host;
- this.url.path = this.base.path.slice();
- shortenPath(this.url);
- } else {
- this.parseError = true;
- }
-
- this.state = "path";
- --this.pointer;
- }
- } else {
- this.state = "path";
- --this.pointer;
- }
-
- return true;
-};
-
-URLStateMachine.prototype["parse file slash"] = function parseFileSlash(c) {
- if (c === 47 || c === 92) {
- if (c === 92) {
- this.parseError = true;
- }
- this.state = "file host";
- } else {
- if (this.base !== null && this.base.scheme === "file") {
- if (isNormalizedWindowsDriveLetterString(this.base.path[0])) {
- this.url.path.push(this.base.path[0]);
- } else {
- this.url.host = this.base.host;
- }
- }
- this.state = "path";
- --this.pointer;
- }
-
- return true;
-};
-
-URLStateMachine.prototype["parse file host"] = function parseFileHost(c, cStr) {
- if (isNaN(c) || c === 47 || c === 92 || c === 63 || c === 35) {
- --this.pointer;
- if (!this.stateOverride && isWindowsDriveLetterString(this.buffer)) {
- this.parseError = true;
- this.state = "path";
- } else if (this.buffer === "") {
- this.url.host = "";
- if (this.stateOverride) {
- return false;
- }
- this.state = "path start";
- } else {
- let host = parseHost(this.buffer, isSpecial(this.url));
- if (host === failure) {
- return failure;
- }
- if (host === "localhost") {
- host = "";
- }
- this.url.host = host;
-
- if (this.stateOverride) {
- return false;
- }
-
- this.buffer = "";
- this.state = "path start";
- }
- } else {
- this.buffer += cStr;
- }
-
- return true;
-};
+ if (scanToEnd === true) {
+ while (eos() !== true && (code = advance())) {
+ if (code === CHAR_BACKWARD_SLASH) {
+ backslashes = token.backslashes = true;
+ code = advance();
+ continue;
+ }
+
+ if (code === CHAR_RIGHT_PARENTHESES) {
+ isGlob = token.isGlob = true;
+ finished = true;
+ break;
+ }
+ }
+ continue;
+ }
+ break;
+ }
+ }
+
+ if (code === CHAR_ASTERISK) {
+ if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
+ isGlob = token.isGlob = true;
+ finished = true;
+
+ if (scanToEnd === true) {
+ continue;
+ }
+ break;
+ }
+
+ if (code === CHAR_QUESTION_MARK) {
+ isGlob = token.isGlob = true;
+ finished = true;
+
+ if (scanToEnd === true) {
+ continue;
+ }
+ break;
+ }
+
+ if (code === CHAR_LEFT_SQUARE_BRACKET) {
+ while (eos() !== true && (next = advance())) {
+ if (next === CHAR_BACKWARD_SLASH) {
+ backslashes = token.backslashes = true;
+ advance();
+ continue;
+ }
+
+ if (next === CHAR_RIGHT_SQUARE_BRACKET) {
+ isBracket = token.isBracket = true;
+ isGlob = token.isGlob = true;
+ finished = true;
+ break;
+ }
+ }
+
+ if (scanToEnd === true) {
+ continue;
+ }
+
+ break;
+ }
+
+ if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
+ negated = token.negated = true;
+ start++;
+ continue;
+ }
+
+ if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {
+ isGlob = token.isGlob = true;
+
+ if (scanToEnd === true) {
+ while (eos() !== true && (code = advance())) {
+ if (code === CHAR_LEFT_PARENTHESES) {
+ backslashes = token.backslashes = true;
+ code = advance();
+ continue;
+ }
+
+ if (code === CHAR_RIGHT_PARENTHESES) {
+ finished = true;
+ break;
+ }
+ }
+ continue;
+ }
+ break;
+ }
+
+ if (isGlob === true) {
+ finished = true;
+
+ if (scanToEnd === true) {
+ continue;
+ }
+
+ break;
+ }
+ }
+
+ if (opts.noext === true) {
+ isExtglob = false;
+ isGlob = false;
+ }
+
+ let base = str;
+ let prefix = '';
+ let glob = '';
+
+ if (start > 0) {
+ prefix = str.slice(0, start);
+ str = str.slice(start);
+ lastIndex -= start;
+ }
+
+ if (base && isGlob === true && lastIndex > 0) {
+ base = str.slice(0, lastIndex);
+ glob = str.slice(lastIndex);
+ } else if (isGlob === true) {
+ base = '';
+ glob = str;
+ } else {
+ base = str;
+ }
+
+ if (base && base !== '' && base !== '/' && base !== str) {
+ if (isPathSeparator(base.charCodeAt(base.length - 1))) {
+ base = base.slice(0, -1);
+ }
+ }
+
+ if (opts.unescape === true) {
+ if (glob) glob = utils.removeBackslashes(glob);
+
+ if (base && backslashes === true) {
+ base = utils.removeBackslashes(base);
+ }
+ }
+
+ const state = {
+ prefix,
+ input,
+ start,
+ base,
+ glob,
+ isBrace,
+ isBracket,
+ isGlob,
+ isExtglob,
+ isGlobstar,
+ negated,
+ negatedExtglob
+ };
+
+ if (opts.tokens === true) {
+ state.maxDepth = 0;
+ if (!isPathSeparator(code)) {
+ tokens.push(token);
+ }
+ state.tokens = tokens;
+ }
+
+ if (opts.parts === true || opts.tokens === true) {
+ let prevIndex;
+
+ for (let idx = 0; idx < slashes.length; idx++) {
+ const n = prevIndex ? prevIndex + 1 : start;
+ const i = slashes[idx];
+ const value = input.slice(n, i);
+ if (opts.tokens) {
+ if (idx === 0 && start !== 0) {
+ tokens[idx].isPrefix = true;
+ tokens[idx].value = prefix;
+ } else {
+ tokens[idx].value = value;
+ }
+ depth(tokens[idx]);
+ state.maxDepth += tokens[idx].depth;
+ }
+ if (idx !== 0 || value !== '') {
+ parts.push(value);
+ }
+ prevIndex = i;
+ }
+
+ if (prevIndex && prevIndex + 1 < input.length) {
+ const value = input.slice(prevIndex + 1);
+ parts.push(value);
+
+ if (opts.tokens) {
+ tokens[tokens.length - 1].value = value;
+ depth(tokens[tokens.length - 1]);
+ state.maxDepth += tokens[tokens.length - 1].depth;
+ }
+ }
+
+ state.slashes = slashes;
+ state.parts = parts;
+ }
+
+ return state;
+};
+
+module.exports = scan;
+
+
+/***/ }),
+
+/***/ 479:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+const path = __nccwpck_require__(1017);
+const win32 = process.platform === 'win32';
+const {
+ REGEX_BACKSLASH,
+ REGEX_REMOVE_BACKSLASH,
+ REGEX_SPECIAL_CHARS,
+ REGEX_SPECIAL_CHARS_GLOBAL
+} = __nccwpck_require__(6099);
+
+exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
+exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
+exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
+exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
+exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');
+
+exports.removeBackslashes = str => {
+ return str.replace(REGEX_REMOVE_BACKSLASH, match => {
+ return match === '\\' ? '' : match;
+ });
+};
+
+exports.supportsLookbehinds = () => {
+ const segs = process.version.slice(1).split('.').map(Number);
+ if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) {
+ return true;
+ }
+ return false;
+};
+
+exports.isWindows = options => {
+ if (options && typeof options.windows === 'boolean') {
+ return options.windows;
+ }
+ return win32 === true || path.sep === '\\';
+};
+
+exports.escapeLast = (input, char, lastIdx) => {
+ const idx = input.lastIndexOf(char, lastIdx);
+ if (idx === -1) return input;
+ if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1);
+ return `${input.slice(0, idx)}\\${input.slice(idx)}`;
+};
+
+exports.removePrefix = (input, state = {}) => {
+ let output = input;
+ if (output.startsWith('./')) {
+ output = output.slice(2);
+ state.prefix = './';
+ }
+ return output;
+};
+
+exports.wrapOutput = (input, state = {}, options = {}) => {
+ const prepend = options.contains ? '' : '^';
+ const append = options.contains ? '' : '$';
+
+ let output = `${prepend}(?:${input})${append}`;
+ if (state.negated === true) {
+ output = `(?:^(?!${output}).*$)`;
+ }
+ return output;
+};
+
+
+/***/ }),
+
+/***/ 9795:
+/***/ ((module) => {
+
+/*! queue-microtask. MIT License. Feross Aboukhadijeh */
+let promise
+
+module.exports = typeof queueMicrotask === 'function'
+ ? queueMicrotask.bind(typeof window !== 'undefined' ? window : global)
+ // reuse resolved promise, and allocate it lazily
+ : cb => (promise || (promise = Promise.resolve()))
+ .then(cb)
+ .catch(err => setTimeout(() => { throw err }, 0))
+
+
+/***/ }),
+
+/***/ 2113:
+/***/ ((module) => {
+
+"use strict";
+
+
+function reusify (Constructor) {
+ var head = new Constructor()
+ var tail = head
+
+ function get () {
+ var current = head
+
+ if (current.next) {
+ head = current.next
+ } else {
+ head = new Constructor()
+ tail = head
+ }
+
+ current.next = null
+
+ return current
+ }
+
+ function release (obj) {
+ tail.next = obj
+ tail = obj
+ }
+
+ return {
+ get: get,
+ release: release
+ }
+}
+
+module.exports = reusify
+
+
+/***/ }),
+
+/***/ 4959:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+const assert = __nccwpck_require__(9491)
+const path = __nccwpck_require__(1017)
+const fs = __nccwpck_require__(7147)
+let glob = undefined
+try {
+ glob = __nccwpck_require__(1957)
+} catch (_err) {
+ // treat glob as optional.
+}
+
+const defaultGlobOpts = {
+ nosort: true,
+ silent: true
+}
+
+// for EMFILE handling
+let timeout = 0
+
+const isWindows = (process.platform === "win32")
+
+const defaults = options => {
+ const methods = [
+ 'unlink',
+ 'chmod',
+ 'stat',
+ 'lstat',
+ 'rmdir',
+ 'readdir'
+ ]
+ methods.forEach(m => {
+ options[m] = options[m] || fs[m]
+ m = m + 'Sync'
+ options[m] = options[m] || fs[m]
+ })
+
+ options.maxBusyTries = options.maxBusyTries || 3
+ options.emfileWait = options.emfileWait || 1000
+ if (options.glob === false) {
+ options.disableGlob = true
+ }
+ if (options.disableGlob !== true && glob === undefined) {
+ throw Error('glob dependency not found, set `options.disableGlob = true` if intentional')
+ }
+ options.disableGlob = options.disableGlob || false
+ options.glob = options.glob || defaultGlobOpts
+}
+
+const rimraf = (p, options, cb) => {
+ if (typeof options === 'function') {
+ cb = options
+ options = {}
+ }
+
+ assert(p, 'rimraf: missing path')
+ assert.equal(typeof p, 'string', 'rimraf: path should be a string')
+ assert.equal(typeof cb, 'function', 'rimraf: callback function required')
+ assert(options, 'rimraf: invalid options argument provided')
+ assert.equal(typeof options, 'object', 'rimraf: options should be object')
+
+ defaults(options)
+
+ let busyTries = 0
+ let errState = null
+ let n = 0
+
+ const next = (er) => {
+ errState = errState || er
+ if (--n === 0)
+ cb(errState)
+ }
+
+ const afterGlob = (er, results) => {
+ if (er)
+ return cb(er)
+
+ n = results.length
+ if (n === 0)
+ return cb()
+
+ results.forEach(p => {
+ const CB = (er) => {
+ if (er) {
+ if ((er.code === "EBUSY" || er.code === "ENOTEMPTY" || er.code === "EPERM") &&
+ busyTries < options.maxBusyTries) {
+ busyTries ++
+ // try again, with the same exact callback as this one.
+ return setTimeout(() => rimraf_(p, options, CB), busyTries * 100)
+ }
+
+ // this one won't happen if graceful-fs is used.
+ if (er.code === "EMFILE" && timeout < options.emfileWait) {
+ return setTimeout(() => rimraf_(p, options, CB), timeout ++)
+ }
+
+ // already gone
+ if (er.code === "ENOENT") er = null
+ }
+
+ timeout = 0
+ next(er)
+ }
+ rimraf_(p, options, CB)
+ })
+ }
+
+ if (options.disableGlob || !glob.hasMagic(p))
+ return afterGlob(null, [p])
+
+ options.lstat(p, (er, stat) => {
+ if (!er)
+ return afterGlob(null, [p])
+
+ glob(p, options.glob, afterGlob)
+ })
+
+}
+
+// Two possible strategies.
+// 1. Assume it's a file. unlink it, then do the dir stuff on EPERM or EISDIR
+// 2. Assume it's a directory. readdir, then do the file stuff on ENOTDIR
+//
+// Both result in an extra syscall when you guess wrong. However, there
+// are likely far more normal files in the world than directories. This
+// is based on the assumption that a the average number of files per
+// directory is >= 1.
+//
+// If anyone ever complains about this, then I guess the strategy could
+// be made configurable somehow. But until then, YAGNI.
+const rimraf_ = (p, options, cb) => {
+ assert(p)
+ assert(options)
+ assert(typeof cb === 'function')
+
+ // sunos lets the root user unlink directories, which is... weird.
+ // so we have to lstat here and make sure it's not a dir.
+ options.lstat(p, (er, st) => {
+ if (er && er.code === "ENOENT")
+ return cb(null)
+
+ // Windows can EPERM on stat. Life is suffering.
+ if (er && er.code === "EPERM" && isWindows)
+ fixWinEPERM(p, options, er, cb)
+
+ if (st && st.isDirectory())
+ return rmdir(p, options, er, cb)
+
+ options.unlink(p, er => {
+ if (er) {
+ if (er.code === "ENOENT")
+ return cb(null)
+ if (er.code === "EPERM")
+ return (isWindows)
+ ? fixWinEPERM(p, options, er, cb)
+ : rmdir(p, options, er, cb)
+ if (er.code === "EISDIR")
+ return rmdir(p, options, er, cb)
+ }
+ return cb(er)
+ })
+ })
+}
+
+const fixWinEPERM = (p, options, er, cb) => {
+ assert(p)
+ assert(options)
+ assert(typeof cb === 'function')
+
+ options.chmod(p, 0o666, er2 => {
+ if (er2)
+ cb(er2.code === "ENOENT" ? null : er)
+ else
+ options.stat(p, (er3, stats) => {
+ if (er3)
+ cb(er3.code === "ENOENT" ? null : er)
+ else if (stats.isDirectory())
+ rmdir(p, options, er, cb)
+ else
+ options.unlink(p, cb)
+ })
+ })
+}
+
+const fixWinEPERMSync = (p, options, er) => {
+ assert(p)
+ assert(options)
+
+ try {
+ options.chmodSync(p, 0o666)
+ } catch (er2) {
+ if (er2.code === "ENOENT")
+ return
+ else
+ throw er
+ }
+
+ let stats
+ try {
+ stats = options.statSync(p)
+ } catch (er3) {
+ if (er3.code === "ENOENT")
+ return
+ else
+ throw er
+ }
+
+ if (stats.isDirectory())
+ rmdirSync(p, options, er)
+ else
+ options.unlinkSync(p)
+}
+
+const rmdir = (p, options, originalEr, cb) => {
+ assert(p)
+ assert(options)
+ assert(typeof cb === 'function')
+
+ // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS)
+ // if we guessed wrong, and it's not a directory, then
+ // raise the original error.
+ options.rmdir(p, er => {
+ if (er && (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM"))
+ rmkids(p, options, cb)
+ else if (er && er.code === "ENOTDIR")
+ cb(originalEr)
+ else
+ cb(er)
+ })
+}
+
+const rmkids = (p, options, cb) => {
+ assert(p)
+ assert(options)
+ assert(typeof cb === 'function')
+
+ options.readdir(p, (er, files) => {
+ if (er)
+ return cb(er)
+ let n = files.length
+ if (n === 0)
+ return options.rmdir(p, cb)
+ let errState
+ files.forEach(f => {
+ rimraf(path.join(p, f), options, er => {
+ if (errState)
+ return
+ if (er)
+ return cb(errState = er)
+ if (--n === 0)
+ options.rmdir(p, cb)
+ })
+ })
+ })
+}
+
+// this looks simpler, and is strictly *faster*, but will
+// tie up the JavaScript thread and fail on excessively
+// deep directory trees.
+const rimrafSync = (p, options) => {
+ options = options || {}
+ defaults(options)
+
+ assert(p, 'rimraf: missing path')
+ assert.equal(typeof p, 'string', 'rimraf: path should be a string')
+ assert(options, 'rimraf: missing options')
+ assert.equal(typeof options, 'object', 'rimraf: options should be object')
+
+ let results
+
+ if (options.disableGlob || !glob.hasMagic(p)) {
+ results = [p]
+ } else {
+ try {
+ options.lstatSync(p)
+ results = [p]
+ } catch (er) {
+ results = glob.sync(p, options.glob)
+ }
+ }
+
+ if (!results.length)
+ return
+
+ for (let i = 0; i < results.length; i++) {
+ const p = results[i]
+
+ let st
+ try {
+ st = options.lstatSync(p)
+ } catch (er) {
+ if (er.code === "ENOENT")
+ return
+
+ // Windows can EPERM on stat. Life is suffering.
+ if (er.code === "EPERM" && isWindows)
+ fixWinEPERMSync(p, options, er)
+ }
+
+ try {
+ // sunos lets the root user unlink directories, which is... weird.
+ if (st && st.isDirectory())
+ rmdirSync(p, options, null)
+ else
+ options.unlinkSync(p)
+ } catch (er) {
+ if (er.code === "ENOENT")
+ return
+ if (er.code === "EPERM")
+ return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er)
+ if (er.code !== "EISDIR")
+ throw er
+
+ rmdirSync(p, options, er)
+ }
+ }
+}
+
+const rmdirSync = (p, options, originalEr) => {
+ assert(p)
+ assert(options)
+
+ try {
+ options.rmdirSync(p)
+ } catch (er) {
+ if (er.code === "ENOENT")
+ return
+ if (er.code === "ENOTDIR")
+ throw originalEr
+ if (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM")
+ rmkidsSync(p, options)
+ }
+}
+
+const rmkidsSync = (p, options) => {
+ assert(p)
+ assert(options)
+ options.readdirSync(p).forEach(f => rimrafSync(path.join(p, f), options))
+
+ // We only end up here once we got ENOTEMPTY at least once, and
+ // at this point, we are guaranteed to have removed all the kids.
+ // So, we know that it won't be ENOENT or ENOTDIR or anything else.
+ // try really hard to delete stuff on windows, because it has a
+ // PROFOUNDLY annoying habit of not closing handles promptly when
+ // files are deleted, resulting in spurious ENOTEMPTY errors.
+ const retries = isWindows ? 100 : 1
+ let i = 0
+ do {
+ let threw = true
+ try {
+ const ret = options.rmdirSync(p, options)
+ threw = false
+ return ret
+ } finally {
+ if (++i < retries && threw)
+ continue
+ }
+ } while (true)
+}
+
+module.exports = rimraf
+rimraf.sync = rimrafSync
+
+
+/***/ }),
+
+/***/ 5288:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+/*! run-parallel. MIT License. Feross Aboukhadijeh */
+module.exports = runParallel
+
+const queueMicrotask = __nccwpck_require__(9795)
+
+function runParallel (tasks, cb) {
+ let results, pending, keys
+ let isSync = true
+
+ if (Array.isArray(tasks)) {
+ results = []
+ pending = tasks.length
+ } else {
+ keys = Object.keys(tasks)
+ results = {}
+ pending = keys.length
+ }
+
+ function done (err) {
+ function end () {
+ if (cb) cb(err, results)
+ cb = null
+ }
+ if (isSync) queueMicrotask(end)
+ else end()
+ }
+
+ function each (i, err, result) {
+ results[i] = result
+ if (--pending === 0 || err) {
+ done(err)
+ }
+ }
+
+ if (!pending) {
+ // empty
+ done(null)
+ } else if (keys) {
+ // object
+ keys.forEach(function (key) {
+ tasks[key](function (err, result) { each(key, err, result) })
+ })
+ } else {
+ // array
+ tasks.forEach(function (task, i) {
+ task(function (err, result) { each(i, err, result) })
+ })
+ }
+
+ isSync = false
+}
+
+
+/***/ }),
+
+/***/ 2043:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+;(function (sax) { // wrapper for non-node envs
+ sax.parser = function (strict, opt) { return new SAXParser(strict, opt) }
+ sax.SAXParser = SAXParser
+ sax.SAXStream = SAXStream
+ sax.createStream = createStream
+
+ // When we pass the MAX_BUFFER_LENGTH position, start checking for buffer overruns.
+ // When we check, schedule the next check for MAX_BUFFER_LENGTH - (max(buffer lengths)),
+ // since that's the earliest that a buffer overrun could occur. This way, checks are
+ // as rare as required, but as often as necessary to ensure never crossing this bound.
+ // Furthermore, buffers are only tested at most once per write(), so passing a very
+ // large string into write() might have undesirable effects, but this is manageable by
+ // the caller, so it is assumed to be safe. Thus, a call to write() may, in the extreme
+ // edge case, result in creating at most one complete copy of the string passed in.
+ // Set to Infinity to have unlimited buffers.
+ sax.MAX_BUFFER_LENGTH = 64 * 1024
+
+ var buffers = [
+ 'comment', 'sgmlDecl', 'textNode', 'tagName', 'doctype',
+ 'procInstName', 'procInstBody', 'entity', 'attribName',
+ 'attribValue', 'cdata', 'script'
+ ]
+
+ sax.EVENTS = [
+ 'text',
+ 'processinginstruction',
+ 'sgmldeclaration',
+ 'doctype',
+ 'comment',
+ 'opentagstart',
+ 'attribute',
+ 'opentag',
+ 'closetag',
+ 'opencdata',
+ 'cdata',
+ 'closecdata',
+ 'error',
+ 'end',
+ 'ready',
+ 'script',
+ 'opennamespace',
+ 'closenamespace'
+ ]
+
+ function SAXParser (strict, opt) {
+ if (!(this instanceof SAXParser)) {
+ return new SAXParser(strict, opt)
+ }
+
+ var parser = this
+ clearBuffers(parser)
+ parser.q = parser.c = ''
+ parser.bufferCheckPosition = sax.MAX_BUFFER_LENGTH
+ parser.opt = opt || {}
+ parser.opt.lowercase = parser.opt.lowercase || parser.opt.lowercasetags
+ parser.looseCase = parser.opt.lowercase ? 'toLowerCase' : 'toUpperCase'
+ parser.tags = []
+ parser.closed = parser.closedRoot = parser.sawRoot = false
+ parser.tag = parser.error = null
+ parser.strict = !!strict
+ parser.noscript = !!(strict || parser.opt.noscript)
+ parser.state = S.BEGIN
+ parser.strictEntities = parser.opt.strictEntities
+ parser.ENTITIES = parser.strictEntities ? Object.create(sax.XML_ENTITIES) : Object.create(sax.ENTITIES)
+ parser.attribList = []
+
+ // namespaces form a prototype chain.
+ // it always points at the current tag,
+ // which protos to its parent tag.
+ if (parser.opt.xmlns) {
+ parser.ns = Object.create(rootNS)
+ }
+
+ // mostly just for error reporting
+ parser.trackPosition = parser.opt.position !== false
+ if (parser.trackPosition) {
+ parser.position = parser.line = parser.column = 0
+ }
+ emit(parser, 'onready')
+ }
+
+ if (!Object.create) {
+ Object.create = function (o) {
+ function F () {}
+ F.prototype = o
+ var newf = new F()
+ return newf
+ }
+ }
+
+ if (!Object.keys) {
+ Object.keys = function (o) {
+ var a = []
+ for (var i in o) if (o.hasOwnProperty(i)) a.push(i)
+ return a
+ }
+ }
+
+ function checkBufferLength (parser) {
+ var maxAllowed = Math.max(sax.MAX_BUFFER_LENGTH, 10)
+ var maxActual = 0
+ for (var i = 0, l = buffers.length; i < l; i++) {
+ var len = parser[buffers[i]].length
+ if (len > maxAllowed) {
+ // Text/cdata nodes can get big, and since they're buffered,
+ // we can get here under normal conditions.
+ // Avoid issues by emitting the text node now,
+ // so at least it won't get any bigger.
+ switch (buffers[i]) {
+ case 'textNode':
+ closeText(parser)
+ break
+
+ case 'cdata':
+ emitNode(parser, 'oncdata', parser.cdata)
+ parser.cdata = ''
+ break
+
+ case 'script':
+ emitNode(parser, 'onscript', parser.script)
+ parser.script = ''
+ break
+
+ default:
+ error(parser, 'Max buffer length exceeded: ' + buffers[i])
+ }
+ }
+ maxActual = Math.max(maxActual, len)
+ }
+ // schedule the next check for the earliest possible buffer overrun.
+ var m = sax.MAX_BUFFER_LENGTH - maxActual
+ parser.bufferCheckPosition = m + parser.position
+ }
+
+ function clearBuffers (parser) {
+ for (var i = 0, l = buffers.length; i < l; i++) {
+ parser[buffers[i]] = ''
+ }
+ }
+
+ function flushBuffers (parser) {
+ closeText(parser)
+ if (parser.cdata !== '') {
+ emitNode(parser, 'oncdata', parser.cdata)
+ parser.cdata = ''
+ }
+ if (parser.script !== '') {
+ emitNode(parser, 'onscript', parser.script)
+ parser.script = ''
+ }
+ }
+
+ SAXParser.prototype = {
+ end: function () { end(this) },
+ write: write,
+ resume: function () { this.error = null; return this },
+ close: function () { return this.write(null) },
+ flush: function () { flushBuffers(this) }
+ }
+
+ var Stream
+ try {
+ Stream = (__nccwpck_require__(2781).Stream)
+ } catch (ex) {
+ Stream = function () {}
+ }
+ if (!Stream) Stream = function () {}
+
+ var streamWraps = sax.EVENTS.filter(function (ev) {
+ return ev !== 'error' && ev !== 'end'
+ })
+
+ function createStream (strict, opt) {
+ return new SAXStream(strict, opt)
+ }
+
+ function SAXStream (strict, opt) {
+ if (!(this instanceof SAXStream)) {
+ return new SAXStream(strict, opt)
+ }
+
+ Stream.apply(this)
+
+ this._parser = new SAXParser(strict, opt)
+ this.writable = true
+ this.readable = true
+
+ var me = this
+
+ this._parser.onend = function () {
+ me.emit('end')
+ }
+
+ this._parser.onerror = function (er) {
+ me.emit('error', er)
+
+ // if didn't throw, then means error was handled.
+ // go ahead and clear error, so we can write again.
+ me._parser.error = null
+ }
+
+ this._decoder = null
+
+ streamWraps.forEach(function (ev) {
+ Object.defineProperty(me, 'on' + ev, {
+ get: function () {
+ return me._parser['on' + ev]
+ },
+ set: function (h) {
+ if (!h) {
+ me.removeAllListeners(ev)
+ me._parser['on' + ev] = h
+ return h
+ }
+ me.on(ev, h)
+ },
+ enumerable: true,
+ configurable: false
+ })
+ })
+ }
+
+ SAXStream.prototype = Object.create(Stream.prototype, {
+ constructor: {
+ value: SAXStream
+ }
+ })
+
+ SAXStream.prototype.write = function (data) {
+ if (typeof Buffer === 'function' &&
+ typeof Buffer.isBuffer === 'function' &&
+ Buffer.isBuffer(data)) {
+ if (!this._decoder) {
+ var SD = (__nccwpck_require__(1576).StringDecoder)
+ this._decoder = new SD('utf8')
+ }
+ data = this._decoder.write(data)
+ }
+
+ this._parser.write(data.toString())
+ this.emit('data', data)
+ return true
+ }
+
+ SAXStream.prototype.end = function (chunk) {
+ if (chunk && chunk.length) {
+ this.write(chunk)
+ }
+ this._parser.end()
+ return true
+ }
+
+ SAXStream.prototype.on = function (ev, handler) {
+ var me = this
+ if (!me._parser['on' + ev] && streamWraps.indexOf(ev) !== -1) {
+ me._parser['on' + ev] = function () {
+ var args = arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments)
+ args.splice(0, 0, ev)
+ me.emit.apply(me, args)
+ }
+ }
+
+ return Stream.prototype.on.call(me, ev, handler)
+ }
+
+ // this really needs to be replaced with character classes.
+ // XML allows all manner of ridiculous numbers and digits.
+ var CDATA = '[CDATA['
+ var DOCTYPE = 'DOCTYPE'
+ var XML_NAMESPACE = 'http://www.w3.org/XML/1998/namespace'
+ var XMLNS_NAMESPACE = 'http://www.w3.org/2000/xmlns/'
+ var rootNS = { xml: XML_NAMESPACE, xmlns: XMLNS_NAMESPACE }
+
+ // http://www.w3.org/TR/REC-xml/#NT-NameStartChar
+ // This implementation works on strings, a single character at a time
+ // as such, it cannot ever support astral-plane characters (10000-EFFFF)
+ // without a significant breaking change to either this parser, or the
+ // JavaScript language. Implementation of an emoji-capable xml parser
+ // is left as an exercise for the reader.
+ var nameStart = /[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/
+
+ var nameBody = /[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/
+
+ var entityStart = /[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/
+ var entityBody = /[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/
+
+ function isWhitespace (c) {
+ return c === ' ' || c === '\n' || c === '\r' || c === '\t'
+ }
+
+ function isQuote (c) {
+ return c === '"' || c === '\''
+ }
+
+ function isAttribEnd (c) {
+ return c === '>' || isWhitespace(c)
+ }
+
+ function isMatch (regex, c) {
+ return regex.test(c)
+ }
+
+ function notMatch (regex, c) {
+ return !isMatch(regex, c)
+ }
+
+ var S = 0
+ sax.STATE = {
+ BEGIN: S++, // leading byte order mark or whitespace
+ BEGIN_WHITESPACE: S++, // leading whitespace
+ TEXT: S++, // general stuff
+ TEXT_ENTITY: S++, // & and such.
+ OPEN_WAKA: S++, // <
+ SGML_DECL: S++, //
+ SCRIPT: S++, //