From 9ab3ce70d6d64cd6e4f4506ccb757152453ccaa6 Mon Sep 17 00:00:00 2001 From: Graham Christensen Date: Wed, 6 Nov 2024 16:05:00 -0500 Subject: [PATCH] Matrix (#96) * Update `detsys-ts` for: `Merge pull request #67 from DeterminateSystems/allow-obliterating-id-token-privs` (`4280bc94c9545f31ccf08001cc16f20ccb91b770`) * Update the defaults / docs on the use-flakehub and use-gha-cache options * Support the MNC trinary, to allow GHA cache to turn off if FHC is enabled * let's go? * arg, you can't parameterize the permissions * don't fail fast * Maybe if we bust the token sooner..? * Clearer job names * Debug... * ? * ...? * ? * fancy it up * more seed * Test against determinate too * ... * derp, obliterate * Identify the failed-to-setup FHC as not being enabled * Don't fail on github if the cache is throttled * derp * Add a success job for the ci workflow --------- Co-authored-by: grahamc <76716+grahamc@users.noreply.github.com> --- .github/workflows/cache-test.sh | 95 +- .github/workflows/ci.yml | 41 +- action.yml | 16 +- dist/index.js | 35040 +++++++++++++++++------------- dist/index.js.map | 2 +- pnpm-lock.yaml | 180 +- src/helpers.ts | 27 + src/index.ts | 16 +- 8 files changed, 20760 insertions(+), 14657 deletions(-) diff --git a/.github/workflows/cache-test.sh b/.github/workflows/cache-test.sh index 4d938ac..c6cc6f8 100755 --- a/.github/workflows/cache-test.sh +++ b/.github/workflows/cache-test.sh @@ -3,39 +3,80 @@ set -e set -ux -seed=$(date) +seed="$(date)-$RANDOM" log="${MAGIC_NIX_CACHE_DAEMONDIR}/daemon.log" -binary_cache=https://cache.flakehub.com +flakehub_binary_cache=https://cache.flakehub.com +gha_binary_cache=http://127.0.0.1:37515 + +is_gh_throttled() { + grep 'GitHub Actions Cache throttled Magic Nix Cache' "${log}" +} # Check that the action initialized correctly. -grep 'FlakeHub cache is enabled' "${log}" -grep 'Using cache' "${log}" -grep 'GitHub Action cache is enabled' "${log}" +if [ "$EXPECT_FLAKEHUB" == "true" ]; then + grep 'FlakeHub cache is enabled' "${log}" + grep 'Using cache' "${log}" +else + grep 'FlakeHub cache is disabled' "${log}" \ + || grep 'FlakeHub cache initialization failed:' "${log}" +fi + +if [ "$EXPECT_GITHUB_CACHE" == "true" ]; then + grep 'GitHub Action cache is enabled' "${log}" +else + grep 'Native GitHub Action cache is disabled' "${log}" +fi # Build something. outpath=$(nix-build .github/workflows/cache-tester.nix --argstr seed "$seed") # Wait until it has been pushed succesfully. -found= -for ((i = 0; i < 60; i++)); do - sleep 1 - if grep "✅ $(basename "${outpath}")" "${log}"; then - found=1 - break - fi -done -if [[ -z $found ]]; then - echo "FlakeHub push did not happen." >&2 - exit 1 +if [ "$EXPECT_FLAKEHUB" == "true" ]; then + found= + for ((i = 0; i < 60; i++)); do + sleep 1 + if grep "✅ $(basename "${outpath}")" "${log}"; then + found=1 + break + fi + done + if [[ -z $found ]]; then + echo "FlakeHub push did not happen." >&2 + exit 1 + fi fi -# Check the FlakeHub binary cache to see if the path is really there. -nix path-info --store "${binary_cache}" "${outpath}" +if [ "$EXPECT_GITHUB_CACHE" == "true" ]; then + found= + for ((i = 0; i < 60; i++)); do + sleep 1 + if grep "Uploaded '${outpath}' to the GitHub Action Cache" "${log}"; then + found=1 + break + fi + done + if [[ -z $found ]]; then + echo "GitHub Actions Cache push did not happen." >&2 + + if ! is_gh_throttled; then + exit 1 + fi + fi +fi -# FIXME: remove this once the daemon also uploads to GHA automatically. -nix copy --to 'http://127.0.0.1:37515' "${outpath}" + + +if [ "$EXPECT_FLAKEHUB" == "true" ]; then + # Check the FlakeHub binary cache to see if the path is really there. + nix path-info --store "${flakehub_binary_cache}" "${outpath}" +fi + +if [ "$EXPECT_GITHUB_CACHE" == "true" ] && ! is_gh_throttled; then + # Check the GitHub binary cache to see if the path is really there. + nix path-info --store "${gha_binary_cache}" "${outpath}" +fi rm ./result nix store delete "${outpath}" @@ -50,4 +91,16 @@ echo "-------" echo "Trying to substitute the build again..." echo "if it fails, the cache is broken." -nix-store --realize -vvvvvvvv "$outpath" +if [ "$EXPECT_FLAKEHUB" == "true" ]; then + # Check the FlakeHub binary cache to see if the path is really there. + nix path-info --store "${flakehub_binary_cache}" "${outpath}" +fi + +if [ "$EXPECT_GITHUB_CACHE" == "true" ] && ! is_gh_throttled; then + # Check the FlakeHub binary cache to see if the path is really there. + nix path-info --store "${gha_binary_cache}" "${outpath}" +fi + +if ([ "$EXPECT_GITHUB_CACHE" == "true" ] && ! is_gh_throttled) || [ "$EXPECT_FLAKEHUB" == "true" ]; then + nix-store --realize -vvvvvvvv "$outpath" +fi diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e8d308e..b3c3c23 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -72,8 +72,9 @@ jobs: _internal-strict-mode: true run-systems: + if: github.event_name == 'merge_group' needs: build - name: "Run ${{ matrix.systems.nix-system }}" + name: "Test: ${{ matrix.systems.nix-system }} gha:${{matrix.use-gha-cache}},fhc:${{matrix.use-flakehub}},id:${{matrix.id-token}},determinate:${{matrix.determinate}}" runs-on: "${{ matrix.systems.runner }}" permissions: id-token: "write" @@ -81,10 +82,15 @@ jobs: env: ACTIONS_STEP_DEBUG: true strategy: + fail-fast: false matrix: + determinate: [true, false] + use-gha-cache: ["disabled", "no-preference", "enabled"] + use-flakehub: ["disabled", "no-preference", "enabled"] + id-token: ["write", "none"] systems: - nix-system: "aarch64-darwin" - runner: "macos-latest-xlarge" + runner: "macos-latest" - nix-system: "x86_64-darwin" runner: "macos-13" - nix-system: "aarch64-linux" @@ -93,20 +99,41 @@ jobs: runner: "ubuntu-22.04" steps: - uses: actions/checkout@v4 - if: github.event_name == 'merge_group' - name: Install Nix on ${{ matrix.systems.nix-system }} system - if: github.event_name == 'merge_group' uses: DeterminateSystems/nix-installer-action@main with: - flakehub: true + _internal-obliterate-actions-id-token-request-variables: ${{ matrix.id-token == 'none' }} + determinate: ${{ matrix.determinate }} extra-conf: | narinfo-cache-negative-ttl = 0 - name: Cache the store - if: github.event_name == 'merge_group' uses: ./ with: _internal-strict-mode: true + _internal-obliterate-actions-id-token-request-variables: ${{ matrix.id-token == 'none' }} + use-gha-cache: ${{ matrix.use-gha-cache }} + use-flakehub: ${{ matrix.use-flakehub }} - name: Check the cache for liveness - if: github.event_name == 'merge_group' + env: + EXPECT_FLAKEHUB: ${{ toJson(matrix.use-flakehub != 'disabled' && matrix.id-token == 'write') }} + EXPECT_GITHUB_CACHE: ${{ toJson( + (matrix.use-gha-cache != 'disabled') + && ( + (!(matrix.use-flakehub != 'disabled' && matrix.id-token == 'write')) + || (matrix.use-gha-cache == 'enabled') + ) + ) }} run: | .github/workflows/cache-test.sh + + success: + runs-on: ubuntu-latest + needs: run-systems + steps: + - run: "true" + - run: | + echo "A dependent in the build matrix failed." + exit 1 + if: | + contains(needs.*.result, 'failure') || + contains(needs.*.result, 'cancelled') diff --git a/action.yml b/action.yml index 8de381d..d413066 100644 --- a/action.yml +++ b/action.yml @@ -5,8 +5,12 @@ branding: description: "Free, no-configuration Nix cache. Cut CI time by 50% or more by caching to GitHub Actions' cache." inputs: use-gha-cache: - description: "Whether to upload build results to the GitHub Actions cache." - default: true + description: | + Whether to upload build results to the Github Actions cache. + Set to "no-preference" or null to have the GitHub Actions cache turn on if it is available, and FlakeHub Cache is not available (default). + Set to "enabled" or true to explicitly request the GitHub Actions Cache. + Set to "disabled" or false to explicitly disable the GitHub Actions Cache. + default: null required: false listen: description: The host and port to listen on. @@ -18,8 +22,12 @@ inputs: description: "Diagnostic endpoint url where diagnostics and performance data is sent. To disable set this to an empty string." default: "-" use-flakehub: - description: "Whether to upload build results to FlakeHub Cache." - default: true + description: | + Whether to upload build results to FlakeHub Cache. + Set to "no-preference" or null to have FlakeHub Cache turn on opportunistically (default). + Set to "enabled" or true to explicitly request FlakeHub Cache. + Set to "disabled" or false to explicitly disable FlakeHub Cache. + default: null required: false flakehub-cache-server: description: "The FlakeHub binary cache server." diff --git a/dist/index.js b/dist/index.js index 4f3885e..8f9f0a8 100644 --- a/dist/index.js +++ b/dist/index.js @@ -1,7 +1,7 @@ import { createRequire as __WEBPACK_EXTERNAL_createRequire } from "module"; /******/ var __webpack_modules__ = ({ -/***/ 6878: +/***/ 5591: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { @@ -39,11 +39,11 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.saveCache = exports.restoreCache = exports.isFeatureAvailable = exports.ReserveCacheError = exports.ValidationError = void 0; -const core = __importStar(__nccwpck_require__(9093)); +const core = __importStar(__nccwpck_require__(8407)); const path = __importStar(__nccwpck_require__(1017)); -const utils = __importStar(__nccwpck_require__(9522)); -const cacheHttpClient = __importStar(__nccwpck_require__(5213)); -const tar_1 = __nccwpck_require__(3686); +const utils = __importStar(__nccwpck_require__(2071)); +const cacheHttpClient = __importStar(__nccwpck_require__(5062)); +const tar_1 = __nccwpck_require__(1630); class ValidationError extends Error { constructor(message) { super(message); @@ -242,7 +242,7 @@ exports.saveCache = saveCache; /***/ }), -/***/ 5213: +/***/ 5062: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { @@ -280,16 +280,16 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.saveCache = exports.reserveCache = exports.downloadCache = exports.getCacheEntry = exports.getCacheVersion = void 0; -const core = __importStar(__nccwpck_require__(9093)); +const core = __importStar(__nccwpck_require__(8407)); const http_client_1 = __nccwpck_require__(6634); const auth_1 = __nccwpck_require__(2177); const crypto = __importStar(__nccwpck_require__(6113)); const fs = __importStar(__nccwpck_require__(7147)); const url_1 = __nccwpck_require__(7310); -const utils = __importStar(__nccwpck_require__(9522)); -const downloadUtils_1 = __nccwpck_require__(1428); -const options_1 = __nccwpck_require__(730); -const requestUtils_1 = __nccwpck_require__(6264); +const utils = __importStar(__nccwpck_require__(2071)); +const downloadUtils_1 = __nccwpck_require__(9314); +const options_1 = __nccwpck_require__(8272); +const requestUtils_1 = __nccwpck_require__(4299); const versionSalt = '1.0'; function getCacheApiUrl(resource) { const baseUrl = process.env['ACTIONS_CACHE_URL'] || ''; @@ -510,7 +510,7 @@ exports.saveCache = saveCache; /***/ }), -/***/ 9522: +/***/ 2071: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { @@ -555,16 +555,16 @@ var __asyncValues = (this && this.__asyncValues) || function (o) { }; 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__(9093)); +const core = __importStar(__nccwpck_require__(8407)); const exec = __importStar(__nccwpck_require__(7775)); const glob = __importStar(__nccwpck_require__(7272)); const io = __importStar(__nccwpck_require__(2826)); +const crypto = __importStar(__nccwpck_require__(6113)); const fs = __importStar(__nccwpck_require__(7147)); const path = __importStar(__nccwpck_require__(1017)); const semver = __importStar(__nccwpck_require__(6843)); const util = __importStar(__nccwpck_require__(3837)); -const uuid_1 = __nccwpck_require__(8493); -const constants_1 = __nccwpck_require__(4498); +const constants_1 = __nccwpck_require__(1034); // From https://github.com/actions/toolkit/blob/main/packages/tool-cache/src/tool-cache.ts#L23 function createTempDirectory() { return __awaiter(this, void 0, void 0, function* () { @@ -586,7 +586,7 @@ function createTempDirectory() { } tempDirectory = path.join(baseLocation, 'actions', 'temp'); } - const dest = path.join(tempDirectory, (0, uuid_1.v4)()); + const dest = path.join(tempDirectory, crypto.randomUUID()); yield io.mkdirP(dest); return dest; }); @@ -714,7 +714,7 @@ exports.isGhes = isGhes; /***/ }), -/***/ 4498: +/***/ 1034: /***/ ((__unused_webpack_module, exports) => { @@ -756,7 +756,7 @@ exports.ManifestFilename = 'manifest.txt'; /***/ }), -/***/ 1428: +/***/ 9314: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { @@ -794,16 +794,16 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.downloadCacheStorageSDK = exports.downloadCacheHttpClientConcurrent = exports.downloadCacheHttpClient = exports.DownloadProgress = void 0; -const core = __importStar(__nccwpck_require__(9093)); +const core = __importStar(__nccwpck_require__(8407)); const http_client_1 = __nccwpck_require__(6634); -const storage_blob_1 = __nccwpck_require__(3626); +const storage_blob_1 = __nccwpck_require__(1758); 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__(9522)); -const constants_1 = __nccwpck_require__(4498); -const requestUtils_1 = __nccwpck_require__(6264); +const utils = __importStar(__nccwpck_require__(2071)); +const constants_1 = __nccwpck_require__(1034); +const requestUtils_1 = __nccwpck_require__(4299); const abort_controller_1 = __nccwpck_require__(4732); /** * Pipes the body of a HTTP response to a stream @@ -1140,7 +1140,7 @@ const promiseWithTimeout = (timeoutMs, promise) => __awaiter(void 0, void 0, voi /***/ }), -/***/ 6264: +/***/ 4299: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { @@ -1178,9 +1178,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }; 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__(9093)); +const core = __importStar(__nccwpck_require__(8407)); const http_client_1 = __nccwpck_require__(6634); -const constants_1 = __nccwpck_require__(4498); +const constants_1 = __nccwpck_require__(1034); function isSuccessStatusCode(statusCode) { if (!statusCode) { return false; @@ -1283,7 +1283,7 @@ exports.retryHttpClientResponse = retryHttpClientResponse; /***/ }), -/***/ 3686: +/***/ 1630: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { @@ -1325,8 +1325,8 @@ const exec_1 = __nccwpck_require__(7775); const io = __importStar(__nccwpck_require__(2826)); const fs_1 = __nccwpck_require__(7147); const path = __importStar(__nccwpck_require__(1017)); -const utils = __importStar(__nccwpck_require__(9522)); -const constants_1 = __nccwpck_require__(4498); +const utils = __importStar(__nccwpck_require__(2071)); +const constants_1 = __nccwpck_require__(1034); const IS_WINDOWS = process.platform === 'win32'; // Returns tar path and type: BSD or GNU function getTarPath() { @@ -1561,7 +1561,7 @@ exports.createTar = createTar; /***/ }), -/***/ 730: +/***/ 8272: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { @@ -1590,7 +1590,7 @@ var __importStar = (this && this.__importStar) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getDownloadOptions = exports.getUploadOptions = void 0; -const core = __importStar(__nccwpck_require__(9093)); +const core = __importStar(__nccwpck_require__(8407)); /** * Returns a copy of the upload options with defaults filled in. * @@ -2653,13 +2653,17 @@ exports.toCommandProperties = toCommandProperties; /***/ }), -/***/ 7775: +/***/ 2561: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { 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]; @@ -2672,7 +2676,109 @@ 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; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.issue = exports.issueCommand = void 0; +const os = __importStar(__nccwpck_require__(2037)); +const utils_1 = __nccwpck_require__(1691); +/** + * Commands + * + * Command Format: + * ::name key=value,key=value::message + * + * Examples: + * ::warning::This is the message + * ::set-env name=MY_VAR::some value + */ +function issueCommand(command, properties, message) { + const cmd = new Command(command, properties, message); + process.stdout.write(cmd.toString() + os.EOL); +} +exports.issueCommand = issueCommand; +function issue(name, message = '') { + issueCommand(name, {}, message); +} +exports.issue = issue; +const CMD_STRING = '::'; +class Command { + constructor(command, properties, message) { + if (!command) { + command = 'missing.command'; + } + this.command = command; + this.properties = properties; + this.message = message; + } + toString() { + let cmdStr = CMD_STRING + this.command; + if (this.properties && Object.keys(this.properties).length > 0) { + cmdStr += ' '; + let first = true; + for (const key in this.properties) { + if (this.properties.hasOwnProperty(key)) { + const val = this.properties[key]; + if (val) { + if (first) { + first = false; + } + else { + cmdStr += ','; + } + cmdStr += `${key}=${escapeProperty(val)}`; + } + } + } + } + cmdStr += `${CMD_STRING}${escapeData(this.message)}`; + return cmdStr; + } +} +function escapeData(s) { + return (0, utils_1.toCommandValue)(s) + .replace(/%/g, '%25') + .replace(/\r/g, '%0D') + .replace(/\n/g, '%0A'); +} +function escapeProperty(s) { + return (0, utils_1.toCommandValue)(s) + .replace(/%/g, '%25') + .replace(/\r/g, '%0D') + .replace(/\n/g, '%0A') + .replace(/:/g, '%3A') + .replace(/,/g, '%2C'); +} +//# sourceMappingURL=command.js.map + +/***/ }), + +/***/ 8407: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + +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; }; @@ -2686,89 +2792,331 @@ 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__(1576); -const tr = __importStar(__nccwpck_require__(8374)); +exports.platform = exports.toPlatformPath = exports.toWin32Path = exports.toPosixPath = exports.markdownSummary = exports.summary = exports.getIDToken = exports.getState = exports.saveState = exports.group = exports.endGroup = exports.startGroup = exports.info = exports.notice = exports.warning = exports.error = exports.debug = exports.isDebug = exports.setFailed = exports.setCommandEcho = exports.setOutput = exports.getBooleanInput = exports.getMultilineInput = exports.getInput = exports.addPath = exports.setSecret = exports.exportVariable = exports.ExitCode = void 0; +const command_1 = __nccwpck_require__(2561); +const file_command_1 = __nccwpck_require__(1982); +const utils_1 = __nccwpck_require__(1691); +const os = __importStar(__nccwpck_require__(2037)); +const path = __importStar(__nccwpck_require__(1017)); +const oidc_utils_1 = __nccwpck_require__(5318); /** - * Exec a command. - * Output will be streamed to the live console. - * Returns promise with return code + * The code to exit an action + */ +var ExitCode; +(function (ExitCode) { + /** + * A code indicating that the action was successful + */ + ExitCode[ExitCode["Success"] = 0] = "Success"; + /** + * A code indicating that the action was a failure + */ + ExitCode[ExitCode["Failure"] = 1] = "Failure"; +})(ExitCode || (exports.ExitCode = ExitCode = {})); +//----------------------------------------------------------------------- +// Variables +//----------------------------------------------------------------------- +/** + * Sets env variable for this action and future actions in the job + * @param name the name of the variable to set + * @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function exportVariable(name, val) { + const convertedVal = (0, utils_1.toCommandValue)(val); + process.env[name] = convertedVal; + const filePath = process.env['GITHUB_ENV'] || ''; + if (filePath) { + return (0, file_command_1.issueFileCommand)('ENV', (0, file_command_1.prepareKeyValueMessage)(name, val)); + } + (0, command_1.issueCommand)('set-env', { name }, convertedVal); +} +exports.exportVariable = exportVariable; +/** + * Registers a secret which will get masked from logs + * @param secret value of the secret + */ +function setSecret(secret) { + (0, command_1.issueCommand)('add-mask', {}, secret); +} +exports.setSecret = setSecret; +/** + * Prepends inputPath to the PATH (for this action and future actions) + * @param inputPath + */ +function addPath(inputPath) { + const filePath = process.env['GITHUB_PATH'] || ''; + if (filePath) { + (0, file_command_1.issueFileCommand)('PATH', inputPath); + } + else { + (0, command_1.issueCommand)('add-path', {}, inputPath); + } + process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`; +} +exports.addPath = addPath; +/** + * Gets the value of an input. + * Unless trimWhitespace is set to false in InputOptions, the value is also trimmed. + * Returns an empty string if the value is not defined. * - * @param commandLine command to execute (can include additional args). Must be correctly escaped. - * @param args optional arguments for tool. Escaping is handled by the lib. - * @param options optional exec options. See ExecOptions - * @returns Promise exit code + * @param name name of the input to get + * @param options optional. See InputOptions. + * @returns string */ -function exec(commandLine, args, options) { +function getInput(name, options) { + const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || ''; + if (options && options.required && !val) { + throw new Error(`Input required and not supplied: ${name}`); + } + if (options && options.trimWhitespace === false) { + return val; + } + return val.trim(); +} +exports.getInput = getInput; +/** + * Gets the values of an multiline input. Each value is also trimmed. + * + * @param name name of the input to get + * @param options optional. See InputOptions. + * @returns string[] + * + */ +function getMultilineInput(name, options) { + const inputs = getInput(name, options) + .split('\n') + .filter(x => x !== ''); + if (options && options.trimWhitespace === false) { + return inputs; + } + return inputs.map(input => input.trim()); +} +exports.getMultilineInput = getMultilineInput; +/** + * Gets the input value of the boolean type in the YAML 1.2 "core schema" specification. + * Support boolean input list: `true | True | TRUE | false | False | FALSE` . + * The return value is also in boolean type. + * ref: https://yaml.org/spec/1.2/spec.html#id2804923 + * + * @param name name of the input to get + * @param options optional. See InputOptions. + * @returns boolean + */ +function getBooleanInput(name, options) { + const trueValue = ['true', 'True', 'TRUE']; + const falseValue = ['false', 'False', 'FALSE']; + const val = getInput(name, options); + if (trueValue.includes(val)) + return true; + if (falseValue.includes(val)) + return false; + throw new TypeError(`Input does not meet YAML 1.2 "Core Schema" specification: ${name}\n` + + `Support boolean input list: \`true | True | TRUE | false | False | FALSE\``); +} +exports.getBooleanInput = getBooleanInput; +/** + * Sets the value of an output. + * + * @param name name of the output to set + * @param value value to store. Non-string values will be converted to a string via JSON.stringify + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function setOutput(name, value) { + const filePath = process.env['GITHUB_OUTPUT'] || ''; + if (filePath) { + return (0, file_command_1.issueFileCommand)('OUTPUT', (0, file_command_1.prepareKeyValueMessage)(name, value)); + } + process.stdout.write(os.EOL); + (0, command_1.issueCommand)('set-output', { name }, (0, utils_1.toCommandValue)(value)); +} +exports.setOutput = setOutput; +/** + * Enables or disables the echoing of commands into stdout for the rest of the step. + * Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set. + * + */ +function setCommandEcho(enabled) { + (0, command_1.issue)('echo', enabled ? 'on' : 'off'); +} +exports.setCommandEcho = setCommandEcho; +//----------------------------------------------------------------------- +// Results +//----------------------------------------------------------------------- +/** + * Sets the action status to failed. + * When the action exits it will be with an exit code of 1 + * @param message add error issue message + */ +function setFailed(message) { + process.exitCode = ExitCode.Failure; + error(message); +} +exports.setFailed = setFailed; +//----------------------------------------------------------------------- +// Logging Commands +//----------------------------------------------------------------------- +/** + * Gets whether Actions Step Debug is on or not + */ +function isDebug() { + return process.env['RUNNER_DEBUG'] === '1'; +} +exports.isDebug = isDebug; +/** + * Writes debug message to user log + * @param message debug message + */ +function debug(message) { + (0, command_1.issueCommand)('debug', {}, message); +} +exports.debug = debug; +/** + * Adds an error issue + * @param message error issue message. Errors will be converted to string via toString() + * @param properties optional properties to add to the annotation. + */ +function error(message, properties = {}) { + (0, command_1.issueCommand)('error', (0, utils_1.toCommandProperties)(properties), message instanceof Error ? message.toString() : message); +} +exports.error = error; +/** + * Adds a warning issue + * @param message warning issue message. Errors will be converted to string via toString() + * @param properties optional properties to add to the annotation. + */ +function warning(message, properties = {}) { + (0, command_1.issueCommand)('warning', (0, utils_1.toCommandProperties)(properties), message instanceof Error ? message.toString() : message); +} +exports.warning = warning; +/** + * Adds a notice issue + * @param message notice issue message. Errors will be converted to string via toString() + * @param properties optional properties to add to the annotation. + */ +function notice(message, properties = {}) { + (0, command_1.issueCommand)('notice', (0, utils_1.toCommandProperties)(properties), message instanceof Error ? message.toString() : message); +} +exports.notice = notice; +/** + * Writes info to log with console.log. + * @param message info message + */ +function info(message) { + process.stdout.write(message + os.EOL); +} +exports.info = info; +/** + * Begin an output group. + * + * Output until the next `groupEnd` will be foldable in this group + * + * @param name The name of the output group + */ +function startGroup(name) { + (0, command_1.issue)('group', name); +} +exports.startGroup = startGroup; +/** + * End an output group. + */ +function endGroup() { + (0, command_1.issue)('endgroup'); +} +exports.endGroup = endGroup; +/** + * Wrap an asynchronous function call in a group. + * + * Returns the same type as the function itself. + * + * @param name The name of the group + * @param fn The function to wrap in the group + */ +function group(name, fn) { return __awaiter(this, void 0, void 0, function* () { - const commandArgs = tr.argStringToArray(commandLine); - if (commandArgs.length === 0) { - throw new Error(`Parameter 'commandLine' cannot be null or empty.`); + startGroup(name); + let result; + try { + result = yield fn(); } - // Path to tool to execute should be first arg - const toolPath = commandArgs[0]; - args = commandArgs.slice(1).concat(args || []); - const runner = new tr.ToolRunner(toolPath, args, options); - return runner.exec(); + finally { + endGroup(); + } + return result; }); } -exports.exec = exec; +exports.group = group; +//----------------------------------------------------------------------- +// Wrapper action state +//----------------------------------------------------------------------- /** - * Exec a command and get the output. - * Output will be streamed to the live console. - * Returns promise with the exit code and collected stdout and stderr + * Saves state for current action, the state can only be retrieved by this action's post job execution. * - * @param commandLine command to execute (can include additional args). Must be correctly escaped. - * @param args optional arguments for tool. Escaping is handled by the lib. - * @param options optional exec options. See ExecOptions - * @returns Promise exit code, stdout, and stderr + * @param name name of the state to store + * @param value value to store. Non-string values will be converted to a string via JSON.stringify */ -function getExecOutput(commandLine, args, options) { - var _a, _b; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function saveState(name, value) { + const filePath = process.env['GITHUB_STATE'] || ''; + if (filePath) { + return (0, file_command_1.issueFileCommand)('STATE', (0, file_command_1.prepareKeyValueMessage)(name, value)); + } + (0, command_1.issueCommand)('save-state', { name }, (0, utils_1.toCommandValue)(value)); +} +exports.saveState = saveState; +/** + * Gets the value of an state set by this action's main execution. + * + * @param name name of the state to get + * @returns string + */ +function getState(name) { + return process.env[`STATE_${name}`] || ''; +} +exports.getState = getState; +function getIDToken(aud) { return __awaiter(this, void 0, void 0, function* () { - let stdout = ''; - let stderr = ''; - //Using string decoder covers the case where a mult-byte character is split - const stdoutDecoder = new string_decoder_1.StringDecoder('utf8'); - const stderrDecoder = new string_decoder_1.StringDecoder('utf8'); - const originalStdoutListener = (_a = options === null || options === void 0 ? void 0 : options.listeners) === null || _a === void 0 ? void 0 : _a.stdout; - const originalStdErrListener = (_b = options === null || options === void 0 ? void 0 : options.listeners) === null || _b === void 0 ? void 0 : _b.stderr; - const stdErrListener = (data) => { - stderr += stderrDecoder.write(data); - if (originalStdErrListener) { - originalStdErrListener(data); - } - }; - const stdOutListener = (data) => { - stdout += stdoutDecoder.write(data); - if (originalStdoutListener) { - originalStdoutListener(data); - } - }; - const listeners = Object.assign(Object.assign({}, options === null || options === void 0 ? void 0 : options.listeners), { stdout: stdOutListener, stderr: stdErrListener }); - const exitCode = yield exec(commandLine, args, Object.assign(Object.assign({}, options), { listeners })); - //flush any remaining characters - stdout += stdoutDecoder.end(); - stderr += stderrDecoder.end(); - return { - exitCode, - stdout, - stderr - }; + return yield oidc_utils_1.OidcClient.getIDToken(aud); }); } -exports.getExecOutput = getExecOutput; -//# sourceMappingURL=exec.js.map +exports.getIDToken = getIDToken; +/** + * Summary exports + */ +var summary_1 = __nccwpck_require__(6970); +Object.defineProperty(exports, "summary", ({ enumerable: true, get: function () { return summary_1.summary; } })); +/** + * @deprecated use core.summary + */ +var summary_2 = __nccwpck_require__(6970); +Object.defineProperty(exports, "markdownSummary", ({ enumerable: true, get: function () { return summary_2.markdownSummary; } })); +/** + * Path exports + */ +var path_utils_1 = __nccwpck_require__(2711); +Object.defineProperty(exports, "toPosixPath", ({ enumerable: true, get: function () { return path_utils_1.toPosixPath; } })); +Object.defineProperty(exports, "toWin32Path", ({ enumerable: true, get: function () { return path_utils_1.toWin32Path; } })); +Object.defineProperty(exports, "toPlatformPath", ({ enumerable: true, get: function () { return path_utils_1.toPlatformPath; } })); +/** + * Platform utilities exports + */ +exports.platform = __importStar(__nccwpck_require__(8170)); +//# sourceMappingURL=core.js.map /***/ }), -/***/ 8374: +/***/ 1982: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +// For internal use, subject to change. 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]; @@ -2781,10 +3129,54 @@ 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; }; +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 crypto = __importStar(__nccwpck_require__(6113)); +const fs = __importStar(__nccwpck_require__(7147)); +const os = __importStar(__nccwpck_require__(2037)); +const utils_1 = __nccwpck_require__(1691); +function issueFileCommand(command, message) { + const filePath = process.env[`GITHUB_${command}`]; + if (!filePath) { + throw new Error(`Unable to find environment variable for file command ${command}`); + } + if (!fs.existsSync(filePath)) { + throw new Error(`Missing file at path: ${filePath}`); + } + fs.appendFileSync(filePath, `${(0, utils_1.toCommandValue)(message)}${os.EOL}`, { + encoding: 'utf8' + }); +} +exports.issueFileCommand = issueFileCommand; +function prepareKeyValueMessage(key, value) { + const delimiter = `ghadelimiter_${crypto.randomUUID()}`; + const convertedValue = (0, utils_1.toCommandValue)(value); + // These should realistically never happen, but just in case someone finds a + // way to exploit uuid generation let's not allow keys or values that contain + // the delimiter. + if (key.includes(delimiter)) { + throw new Error(`Unexpected input: name should not contain the delimiter "${delimiter}"`); + } + if (convertedValue.includes(delimiter)) { + throw new Error(`Unexpected input: value should not contain the delimiter "${delimiter}"`); + } + return `${key}<<${delimiter}${os.EOL}${convertedValue}${os.EOL}${delimiter}`; +} +exports.prepareKeyValueMessage = prepareKeyValueMessage; +//# sourceMappingURL=file-command.js.map + +/***/ }), + +/***/ 5318: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + 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) { @@ -2795,686 +3187,579 @@ 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__(2037)); -const events = __importStar(__nccwpck_require__(2361)); -const child = __importStar(__nccwpck_require__(2081)); -const path = __importStar(__nccwpck_require__(1017)); -const io = __importStar(__nccwpck_require__(2826)); -const ioUtil = __importStar(__nccwpck_require__(3446)); -const timers_1 = __nccwpck_require__(9512); -/* eslint-disable @typescript-eslint/unbound-method */ -const IS_WINDOWS = process.platform === 'win32'; -/* - * Class for running command line tools. Handles quoting and arg parsing in a platform agnostic way. - */ -class ToolRunner extends events.EventEmitter { - constructor(toolPath, args, options) { - super(); - if (!toolPath) { - throw new Error("Parameter 'toolPath' cannot be null or empty."); - } - this.toolPath = toolPath; - this.args = args || []; - this.options = options || {}; - } - _debug(message) { - if (this.options.listeners && this.options.listeners.debug) { - this.options.listeners.debug(message); - } +exports.OidcClient = void 0; +const http_client_1 = __nccwpck_require__(6634); +const auth_1 = __nccwpck_require__(2177); +const core_1 = __nccwpck_require__(8407); +class OidcClient { + static createHttpClient(allowRetry = true, maxRetry = 10) { + const requestOptions = { + allowRetries: allowRetry, + maxRetries: maxRetry + }; + return new http_client_1.HttpClient('actions/oidc-client', [new auth_1.BearerCredentialHandler(OidcClient.getRequestToken())], requestOptions); } - _getCommandString(options, noPrefix) { - const toolPath = this._getSpawnFileName(); - const args = this._getSpawnArgs(options); - let cmd = noPrefix ? '' : '[command]'; // omit prefix when piped to a second tool - if (IS_WINDOWS) { - // Windows + cmd file - if (this._isCmdFile()) { - cmd += toolPath; - for (const a of args) { - cmd += ` ${a}`; - } - } - // Windows + verbatim - else if (options.windowsVerbatimArguments) { - cmd += `"${toolPath}"`; - for (const a of args) { - cmd += ` ${a}`; - } - } - // Windows (regular) - else { - cmd += this._windowsQuoteCmdArg(toolPath); - for (const a of args) { - cmd += ` ${this._windowsQuoteCmdArg(a)}`; - } - } - } - else { - // OSX/Linux - this can likely be improved with some form of quoting. - // creating processes on Unix is fundamentally different than Windows. - // on Unix, execvp() takes an arg array. - cmd += toolPath; - for (const a of args) { - cmd += ` ${a}`; - } + static getRequestToken() { + const token = process.env['ACTIONS_ID_TOKEN_REQUEST_TOKEN']; + if (!token) { + throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_TOKEN env variable'); } - return cmd; + return token; } - _processLineBuffer(data, strBuffer, onLine) { - try { - let s = strBuffer + data.toString(); - let n = s.indexOf(os.EOL); - while (n > -1) { - const line = s.substring(0, n); - onLine(line); - // the rest of the string ... - s = s.substring(n + os.EOL.length); - n = s.indexOf(os.EOL); - } - return s; - } - catch (err) { - // streaming lines to console is best effort. Don't fail a build. - this._debug(`error processing line. Failed with error ${err}`); - return ''; + static getIDTokenUrl() { + const runtimeUrl = process.env['ACTIONS_ID_TOKEN_REQUEST_URL']; + if (!runtimeUrl) { + throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_URL env variable'); } + return runtimeUrl; } - _getSpawnFileName() { - if (IS_WINDOWS) { - if (this._isCmdFile()) { - return process.env['COMSPEC'] || 'cmd.exe'; + static getCall(id_token_url) { + var _a; + return __awaiter(this, void 0, void 0, function* () { + const httpclient = OidcClient.createHttpClient(); + const res = yield httpclient + .getJson(id_token_url) + .catch(error => { + throw new Error(`Failed to get ID Token. \n + Error Code : ${error.statusCode}\n + Error Message: ${error.message}`); + }); + const id_token = (_a = res.result) === null || _a === void 0 ? void 0 : _a.value; + if (!id_token) { + throw new Error('Response json body do not have ID Token field'); } - } - return this.toolPath; + return id_token; + }); } - _getSpawnArgs(options) { - if (IS_WINDOWS) { - if (this._isCmdFile()) { - let argline = `/D /S /C "${this._windowsQuoteCmdArg(this.toolPath)}`; - for (const a of this.args) { - argline += ' '; - argline += options.windowsVerbatimArguments - ? a - : this._windowsQuoteCmdArg(a); + static getIDToken(audience) { + return __awaiter(this, void 0, void 0, function* () { + try { + // New ID Token is requested from action service + let id_token_url = OidcClient.getIDTokenUrl(); + if (audience) { + const encodedAudience = encodeURIComponent(audience); + id_token_url = `${id_token_url}&audience=${encodedAudience}`; } - argline += '"'; - return [argline]; + (0, core_1.debug)(`ID token url is ${id_token_url}`); + const id_token = yield OidcClient.getCall(id_token_url); + (0, core_1.setSecret)(id_token); + return id_token; } - } - return this.args; + catch (error) { + throw new Error(`Error message: ${error.message}`); + } + }); } - _endsWith(str, end) { - return str.endsWith(end); +} +exports.OidcClient = OidcClient; +//# sourceMappingURL=oidc-utils.js.map + +/***/ }), + +/***/ 2711: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + +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]; } }; } - _isCmdFile() { - const upperToolPath = this.toolPath.toUpperCase(); - return (this._endsWith(upperToolPath, '.CMD') || - this._endsWith(upperToolPath, '.BAT')); + 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; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.toPlatformPath = exports.toWin32Path = exports.toPosixPath = void 0; +const path = __importStar(__nccwpck_require__(1017)); +/** + * toPosixPath converts the given path to the posix form. On Windows, \\ will be + * replaced with /. + * + * @param pth. Path to transform. + * @return string Posix path. + */ +function toPosixPath(pth) { + return pth.replace(/[\\]/g, '/'); +} +exports.toPosixPath = toPosixPath; +/** + * toWin32Path converts the given path to the win32 form. On Linux, / will be + * replaced with \\. + * + * @param pth. Path to transform. + * @return string Win32 path. + */ +function toWin32Path(pth) { + return pth.replace(/[/]/g, '\\'); +} +exports.toWin32Path = toWin32Path; +/** + * toPlatformPath converts the given path to a platform-specific path. It does + * this by replacing instances of / and \ with the platform-specific path + * separator. + * + * @param pth The path to platformize. + * @return string The platform-specific path. + */ +function toPlatformPath(pth) { + return pth.replace(/[/\\]/g, path.sep); +} +exports.toPlatformPath = toPlatformPath; +//# sourceMappingURL=path-utils.js.map + +/***/ }), + +/***/ 8170: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + +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]; } }; } - _windowsQuoteCmdArg(arg) { - // for .exe, apply the normal quoting rules that libuv applies - if (!this._isCmdFile()) { - return this._uvQuoteCmdArg(arg); - } - // otherwise apply quoting rules specific to the cmd.exe command line parser. - // the libuv rules are generic and are not designed specifically for cmd.exe - // command line parser. - // - // for a detailed description of the cmd.exe command line parser, refer to - // http://stackoverflow.com/questions/4094699/how-does-the-windows-command-interpreter-cmd-exe-parse-scripts/7970912#7970912 - // need quotes for empty arg - if (!arg) { - return '""'; - } - // determine whether the arg needs to be quoted - const cmdSpecialChars = [ - ' ', - '\t', - '&', - '(', - ')', - '[', - ']', - '{', - '}', - '^', - '=', - ';', - '!', - "'", - '+', - ',', - '`', - '~', - '|', - '<', - '>', - '"' - ]; - let needsQuotes = false; - for (const char of arg) { - if (cmdSpecialChars.some(x => x === char)) { - needsQuotes = true; - break; + 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()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getDetails = exports.isLinux = exports.isMacOS = exports.isWindows = exports.arch = exports.platform = void 0; +const os_1 = __importDefault(__nccwpck_require__(2037)); +const exec = __importStar(__nccwpck_require__(7775)); +const getWindowsInfo = () => __awaiter(void 0, void 0, void 0, function* () { + const { stdout: version } = yield exec.getExecOutput('powershell -command "(Get-CimInstance -ClassName Win32_OperatingSystem).Version"', undefined, { + silent: true + }); + const { stdout: name } = yield exec.getExecOutput('powershell -command "(Get-CimInstance -ClassName Win32_OperatingSystem).Caption"', undefined, { + silent: true + }); + return { + name: name.trim(), + version: version.trim() + }; +}); +const getMacOsInfo = () => __awaiter(void 0, void 0, void 0, function* () { + var _a, _b, _c, _d; + const { stdout } = yield exec.getExecOutput('sw_vers', undefined, { + silent: true + }); + const version = (_b = (_a = stdout.match(/ProductVersion:\s*(.+)/)) === null || _a === void 0 ? void 0 : _a[1]) !== null && _b !== void 0 ? _b : ''; + const name = (_d = (_c = stdout.match(/ProductName:\s*(.+)/)) === null || _c === void 0 ? void 0 : _c[1]) !== null && _d !== void 0 ? _d : ''; + return { + name, + version + }; +}); +const getLinuxInfo = () => __awaiter(void 0, void 0, void 0, function* () { + const { stdout } = yield exec.getExecOutput('lsb_release', ['-i', '-r', '-s'], { + silent: true + }); + const [name, version] = stdout.trim().split('\n'); + return { + name, + version + }; +}); +exports.platform = os_1.default.platform(); +exports.arch = os_1.default.arch(); +exports.isWindows = exports.platform === 'win32'; +exports.isMacOS = exports.platform === 'darwin'; +exports.isLinux = exports.platform === 'linux'; +function getDetails() { + return __awaiter(this, void 0, void 0, function* () { + return Object.assign(Object.assign({}, (yield (exports.isWindows + ? getWindowsInfo() + : exports.isMacOS + ? getMacOsInfo() + : getLinuxInfo()))), { platform: exports.platform, + arch: exports.arch, + isWindows: exports.isWindows, + isMacOS: exports.isMacOS, + isLinux: exports.isLinux }); + }); +} +exports.getDetails = getDetails; +//# sourceMappingURL=platform.js.map + +/***/ }), + +/***/ 6970: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + +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.summary = exports.markdownSummary = exports.SUMMARY_DOCS_URL = exports.SUMMARY_ENV_VAR = void 0; +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'; +class Summary { + constructor() { + this._buffer = ''; + } + /** + * Finds the summary file path from the environment, rejects if env var is not found or file does not exist + * Also checks r/w permissions. + * + * @returns step summary file path + */ + filePath() { + return __awaiter(this, void 0, void 0, function* () { + if (this._filePath) { + return this._filePath; } - } - // short-circuit if quotes not needed - if (!needsQuotes) { - return arg; - } - // the following quoting rules are very similar to the rules that by libuv applies. - // - // 1) wrap the string in quotes - // - // 2) double-up quotes - i.e. " => "" - // - // this is different from the libuv quoting rules. libuv replaces " with \", which unfortunately - // doesn't work well with a cmd.exe command line. - // - // note, replacing " with "" also works well if the arg is passed to a downstream .NET console app. - // for example, the command line: - // foo.exe "myarg:""my val""" - // is parsed by a .NET console app into an arg array: - // [ "myarg:\"my val\"" ] - // which is the same end result when applying libuv quoting rules. although the actual - // command line from libuv quoting rules would look like: - // foo.exe "myarg:\"my val\"" - // - // 3) double-up slashes that precede a quote, - // e.g. hello \world => "hello \world" - // hello\"world => "hello\\""world" - // hello\\"world => "hello\\\\""world" - // hello world\ => "hello world\\" - // - // technically this is not required for a cmd.exe command line, or the batch argument parser. - // the reasons for including this as a .cmd quoting rule are: - // - // a) this is optimized for the scenario where the argument is passed from the .cmd file to an - // external program. many programs (e.g. .NET console apps) rely on the slash-doubling rule. - // - // b) it's what we've been doing previously (by deferring to node default behavior) and we - // haven't heard any complaints about that aspect. - // - // note, a weakness of the quoting rules chosen here, is that % is not escaped. in fact, % cannot be - // escaped when used on the command line directly - even though within a .cmd file % can be escaped - // by using %%. - // - // the saving grace is, on the command line, %var% is left as-is if var is not defined. this contrasts - // the line parsing rules within a .cmd file, where if var is not defined it is replaced with nothing. - // - // one option that was explored was replacing % with ^% - i.e. %var% => ^%var^%. this hack would - // often work, since it is unlikely that var^ would exist, and the ^ character is removed when the - // variable is used. the problem, however, is that ^ is not removed when %* is used to pass the args - // to an external program. - // - // an unexplored potential solution for the % escaping problem, is to create a wrapper .cmd file. - // % can be escaped within a .cmd file. - let reverse = '"'; - let quoteHit = true; - for (let i = arg.length; i > 0; i--) { - // walk the string in reverse - reverse += arg[i - 1]; - if (quoteHit && arg[i - 1] === '\\') { - reverse += '\\'; // double the slash + const pathFromEnv = process.env[exports.SUMMARY_ENV_VAR]; + if (!pathFromEnv) { + throw new Error(`Unable to find environment variable for $${exports.SUMMARY_ENV_VAR}. Check if your runtime environment supports job summaries.`); } - else if (arg[i - 1] === '"') { - quoteHit = true; - reverse += '"'; // double the quote + try { + yield access(pathFromEnv, fs_1.constants.R_OK | fs_1.constants.W_OK); } - else { - quoteHit = false; + catch (_a) { + throw new Error(`Unable to access summary file: '${pathFromEnv}'. Check if the file has correct read/write permissions.`); } - } - reverse += '"'; - return reverse - .split('') - .reverse() - .join(''); + this._filePath = pathFromEnv; + return this._filePath; + }); } - _uvQuoteCmdArg(arg) { - // Tool runner wraps child_process.spawn() and needs to apply the same quoting as - // Node in certain cases where the undocumented spawn option windowsVerbatimArguments - // is used. - // - // Since this function is a port of quote_cmd_arg from Node 4.x (technically, lib UV, - // see https://github.com/nodejs/node/blob/v4.x/deps/uv/src/win/process.c for details), - // pasting copyright notice from Node within this function: - // - // Copyright Joyent, Inc. and other Node contributors. All rights reserved. - // - // 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. - if (!arg) { - // Need double quotation for empty argument - return '""'; - } - if (!arg.includes(' ') && !arg.includes('\t') && !arg.includes('"')) { - // No quotation needed - return arg; - } - if (!arg.includes('"') && !arg.includes('\\')) { - // No embedded double quotes or backslashes, so I can just wrap - // quote marks around the whole thing. - return `"${arg}"`; + /** + * Wraps content in an HTML tag, adding any HTML attributes + * + * @param {string} tag HTML tag to wrap + * @param {string | null} content content within the tag + * @param {[attribute: string]: string} attrs key-value list of HTML attributes to add + * + * @returns {string} content wrapped in HTML element + */ + wrap(tag, content, attrs = {}) { + const htmlAttrs = Object.entries(attrs) + .map(([key, value]) => ` ${key}="${value}"`) + .join(''); + if (!content) { + return `<${tag}${htmlAttrs}>`; } - // Expected input/output: - // input : hello"world - // output: "hello\"world" - // input : hello""world - // output: "hello\"\"world" - // input : hello\world - // output: hello\world - // input : hello\\world - // output: hello\\world - // input : hello\"world - // output: "hello\\\"world" - // input : hello\\"world - // output: "hello\\\\\"world" - // input : hello world\ - // output: "hello world\\" - note the comment in libuv actually reads "hello world\" - // but it appears the comment is wrong, it should be "hello world\\" - let reverse = '"'; - let quoteHit = true; - for (let i = arg.length; i > 0; i--) { - // walk the string in reverse - reverse += arg[i - 1]; - if (quoteHit && arg[i - 1] === '\\') { - reverse += '\\'; - } - else if (arg[i - 1] === '"') { - quoteHit = true; - reverse += '\\'; - } - else { - quoteHit = false; - } - } - reverse += '"'; - return reverse - .split('') - .reverse() - .join(''); - } - _cloneExecOptions(options) { - options = options || {}; - const result = { - cwd: options.cwd || process.cwd(), - env: options.env || process.env, - silent: options.silent || false, - windowsVerbatimArguments: options.windowsVerbatimArguments || false, - failOnStdErr: options.failOnStdErr || false, - ignoreReturnCode: options.ignoreReturnCode || false, - delay: options.delay || 10000 - }; - result.outStream = options.outStream || process.stdout; - result.errStream = options.errStream || process.stderr; - return result; + return `<${tag}${htmlAttrs}>${content}`; } - _getSpawnOptions(options, toolPath) { - options = options || {}; - const result = {}; - result.cwd = options.cwd; - result.env = options.env; - result['windowsVerbatimArguments'] = - options.windowsVerbatimArguments || this._isCmdFile(); - if (options.windowsVerbatimArguments) { - result.argv0 = `"${toolPath}"`; - } - return result; + /** + * Writes text in the buffer to the summary buffer file and empties buffer. Will append by default. + * + * @param {SummaryWriteOptions} [options] (optional) options for write operation + * + * @returns {Promise} summary instance + */ + write(options) { + return __awaiter(this, void 0, void 0, function* () { + const overwrite = !!(options === null || options === void 0 ? void 0 : options.overwrite); + const filePath = yield this.filePath(); + const writeFunc = overwrite ? writeFile : appendFile; + yield writeFunc(filePath, this._buffer, { encoding: 'utf8' }); + return this.emptyBuffer(); + }); } /** - * Exec a tool. - * Output will be streamed to the live console. - * Returns promise with return code + * Clears the summary buffer and wipes the summary file * - * @param tool path to tool to exec - * @param options optional exec options. See ExecOptions - * @returns number + * @returns {Summary} summary instance */ - exec() { + clear() { return __awaiter(this, void 0, void 0, function* () { - // root the tool path if it is unrooted and contains relative pathing - if (!ioUtil.isRooted(this.toolPath) && - (this.toolPath.includes('/') || - (IS_WINDOWS && this.toolPath.includes('\\')))) { - // prefer options.cwd if it is specified, however options.cwd may also need to be rooted - this.toolPath = path.resolve(process.cwd(), this.options.cwd || process.cwd(), this.toolPath); - } - // if the tool is only a file name, then resolve it from the PATH - // otherwise verify it exists (add extension on Windows if necessary) - this.toolPath = yield io.which(this.toolPath, true); - return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { - this._debug(`exec tool: ${this.toolPath}`); - this._debug('arguments:'); - for (const arg of this.args) { - this._debug(` ${arg}`); - } - const optionsNonNull = this._cloneExecOptions(this.options); - if (!optionsNonNull.silent && optionsNonNull.outStream) { - optionsNonNull.outStream.write(this._getCommandString(optionsNonNull) + os.EOL); - } - const state = new ExecState(optionsNonNull, this.toolPath); - state.on('debug', (message) => { - this._debug(message); - }); - if (this.options.cwd && !(yield ioUtil.exists(this.options.cwd))) { - return reject(new Error(`The cwd: ${this.options.cwd} does not exist!`)); - } - const fileName = this._getSpawnFileName(); - const cp = child.spawn(fileName, this._getSpawnArgs(optionsNonNull), this._getSpawnOptions(this.options, fileName)); - let stdbuffer = ''; - if (cp.stdout) { - cp.stdout.on('data', (data) => { - if (this.options.listeners && this.options.listeners.stdout) { - this.options.listeners.stdout(data); - } - if (!optionsNonNull.silent && optionsNonNull.outStream) { - optionsNonNull.outStream.write(data); - } - stdbuffer = this._processLineBuffer(data, stdbuffer, (line) => { - if (this.options.listeners && this.options.listeners.stdline) { - this.options.listeners.stdline(line); - } - }); - }); - } - let errbuffer = ''; - if (cp.stderr) { - cp.stderr.on('data', (data) => { - state.processStderr = true; - if (this.options.listeners && this.options.listeners.stderr) { - this.options.listeners.stderr(data); - } - if (!optionsNonNull.silent && - optionsNonNull.errStream && - optionsNonNull.outStream) { - const s = optionsNonNull.failOnStdErr - ? optionsNonNull.errStream - : optionsNonNull.outStream; - s.write(data); - } - errbuffer = this._processLineBuffer(data, errbuffer, (line) => { - if (this.options.listeners && this.options.listeners.errline) { - this.options.listeners.errline(line); - } - }); - }); - } - cp.on('error', (err) => { - state.processError = err.message; - state.processExited = true; - state.processClosed = true; - state.CheckComplete(); - }); - cp.on('exit', (code) => { - state.processExitCode = code; - state.processExited = true; - this._debug(`Exit code ${code} received from tool '${this.toolPath}'`); - state.CheckComplete(); - }); - cp.on('close', (code) => { - state.processExitCode = code; - state.processExited = true; - state.processClosed = true; - this._debug(`STDIO streams have closed for tool '${this.toolPath}'`); - state.CheckComplete(); - }); - state.on('done', (error, exitCode) => { - if (stdbuffer.length > 0) { - this.emit('stdline', stdbuffer); - } - if (errbuffer.length > 0) { - this.emit('errline', errbuffer); - } - cp.removeAllListeners(); - if (error) { - reject(error); - } - else { - resolve(exitCode); - } - }); - if (this.options.input) { - if (!cp.stdin) { - throw new Error('child process missing stdin'); - } - cp.stdin.end(this.options.input); - } - })); + return this.emptyBuffer().write({ overwrite: true }); }); } -} -exports.ToolRunner = ToolRunner; -/** - * Convert an arg string to an array of args. Handles escaping - * - * @param argString string of arguments - * @returns string[] array of arguments - */ -function argStringToArray(argString) { - const args = []; - let inQuotes = false; - let escaped = false; - let arg = ''; - function append(c) { - // we only escape double quotes. - if (escaped && c !== '"') { - arg += '\\'; - } - arg += c; - escaped = false; + /** + * Returns the current summary buffer as a string + * + * @returns {string} string of summary buffer + */ + stringify() { + return this._buffer; } - for (let i = 0; i < argString.length; i++) { - const c = argString.charAt(i); - if (c === '"') { - if (!escaped) { - inQuotes = !inQuotes; - } - else { - append(c); - } - continue; - } - if (c === '\\' && escaped) { - append(c); - continue; - } - if (c === '\\' && inQuotes) { - escaped = true; - continue; - } - if (c === ' ' && !inQuotes) { - if (arg.length > 0) { - args.push(arg); - arg = ''; - } - continue; - } - append(c); + /** + * If the summary buffer is empty + * + * @returns {boolen} true if the buffer is empty + */ + isEmptyBuffer() { + return this._buffer.length === 0; } - if (arg.length > 0) { - args.push(arg.trim()); + /** + * Resets the summary buffer without writing to summary file + * + * @returns {Summary} summary instance + */ + emptyBuffer() { + this._buffer = ''; + return this; } - return args; -} -exports.argStringToArray = argStringToArray; -class ExecState extends events.EventEmitter { - constructor(options, toolPath) { - super(); - this.processClosed = false; // tracks whether the process has exited and stdio is closed - this.processError = ''; - this.processExitCode = 0; - this.processExited = false; // tracks whether the process has exited - this.processStderr = false; // tracks whether stderr was written to - this.delay = 10000; // 10 seconds - this.done = false; - this.timeout = null; - if (!toolPath) { - throw new Error('toolPath must not be empty'); - } - this.options = options; - this.toolPath = toolPath; - if (options.delay) { - this.delay = options.delay; - } + /** + * Adds raw text to the summary buffer + * + * @param {string} text content to add + * @param {boolean} [addEOL=false] (optional) append an EOL to the raw text (default: false) + * + * @returns {Summary} summary instance + */ + addRaw(text, addEOL = false) { + this._buffer += text; + return addEOL ? this.addEOL() : this; } - CheckComplete() { - if (this.done) { - return; - } - if (this.processClosed) { - this._setResult(); - } - else if (this.processExited) { - this.timeout = timers_1.setTimeout(ExecState.HandleTimeout, this.delay, this); - } + /** + * Adds the operating system-specific end-of-line marker to the buffer + * + * @returns {Summary} summary instance + */ + addEOL() { + return this.addRaw(os_1.EOL); } - _debug(message) { - this.emit('debug', message); + /** + * Adds an HTML codeblock to the summary buffer + * + * @param {string} code content to render within fenced code block + * @param {string} lang (optional) language to syntax highlight code + * + * @returns {Summary} summary instance + */ + addCodeBlock(code, lang) { + const attrs = Object.assign({}, (lang && { lang })); + const element = this.wrap('pre', this.wrap('code', code), attrs); + return this.addRaw(element).addEOL(); } - _setResult() { - // determine whether there is an error - let error; - if (this.processExited) { - if (this.processError) { - error = new Error(`There was an error when attempting to execute the process '${this.toolPath}'. This may indicate the process failed to start. Error: ${this.processError}`); - } - else if (this.processExitCode !== 0 && !this.options.ignoreReturnCode) { - error = new Error(`The process '${this.toolPath}' failed with exit code ${this.processExitCode}`); - } - else if (this.processStderr && this.options.failOnStdErr) { - error = new Error(`The process '${this.toolPath}' failed because one or more lines were written to the STDERR stream`); - } - } - // clear the timeout - if (this.timeout) { - clearTimeout(this.timeout); - this.timeout = null; - } - this.done = true; - this.emit('done', error, this.processExitCode); + /** + * Adds an HTML list to the summary buffer + * + * @param {string[]} items list of items to render + * @param {boolean} [ordered=false] (optional) if the rendered list should be ordered or not (default: false) + * + * @returns {Summary} summary instance + */ + addList(items, ordered = false) { + const tag = ordered ? 'ol' : 'ul'; + const listItems = items.map(item => this.wrap('li', item)).join(''); + const element = this.wrap(tag, listItems); + return this.addRaw(element).addEOL(); } - static HandleTimeout(state) { - if (state.done) { - return; - } - if (!state.processClosed && state.processExited) { - const message = `The STDIO streams did not close within ${state.delay / - 1000} seconds of the exit event from process '${state.toolPath}'. This may indicate a child process inherited the STDIO streams and has not yet exited.`; - state._debug(message); - } - state._setResult(); + /** + * Adds an HTML table to the summary buffer + * + * @param {SummaryTableCell[]} rows table rows + * + * @returns {Summary} summary instance + */ + addTable(rows) { + const tableBody = rows + .map(row => { + const cells = row + .map(cell => { + if (typeof cell === 'string') { + return this.wrap('td', cell); + } + const { header, data, colspan, rowspan } = cell; + const tag = header ? 'th' : 'td'; + const attrs = Object.assign(Object.assign({}, (colspan && { colspan })), (rowspan && { rowspan })); + return this.wrap(tag, data, attrs); + }) + .join(''); + return this.wrap('tr', cells); + }) + .join(''); + const element = this.wrap('table', tableBody); + return this.addRaw(element).addEOL(); + } + /** + * Adds a collapsable HTML details element to the summary buffer + * + * @param {string} label text for the closed state + * @param {string} content collapsable content + * + * @returns {Summary} summary instance + */ + addDetails(label, content) { + const element = this.wrap('details', this.wrap('summary', label) + content); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML image tag to the summary buffer + * + * @param {string} src path to the image you to embed + * @param {string} alt text description of the image + * @param {SummaryImageOptions} options (optional) addition image attributes + * + * @returns {Summary} summary instance + */ + addImage(src, alt, options) { + const { width, height } = options || {}; + const attrs = Object.assign(Object.assign({}, (width && { width })), (height && { height })); + const element = this.wrap('img', null, Object.assign({ src, alt }, attrs)); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML section heading element + * + * @param {string} text heading text + * @param {number | string} [level=1] (optional) the heading level, default: 1 + * + * @returns {Summary} summary instance + */ + addHeading(text, level) { + const tag = `h${level}`; + const allowedTag = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].includes(tag) + ? tag + : 'h1'; + const element = this.wrap(allowedTag, text); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML thematic break (
) to the summary buffer + * + * @returns {Summary} summary instance + */ + addSeparator() { + const element = this.wrap('hr', null); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML line break (
) to the summary buffer + * + * @returns {Summary} summary instance + */ + addBreak() { + const element = this.wrap('br', null); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML blockquote to the summary buffer + * + * @param {string} text quote text + * @param {string} cite (optional) citation url + * + * @returns {Summary} summary instance + */ + addQuote(text, cite) { + const attrs = Object.assign({}, (cite && { cite })); + const element = this.wrap('blockquote', text, attrs); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML anchor tag to the summary buffer + * + * @param {string} text link text/content + * @param {string} href hyperlink + * + * @returns {Summary} summary instance + */ + addLink(text, href) { + const element = this.wrap('a', text, { href }); + return this.addRaw(element).addEOL(); } } -//# sourceMappingURL=toolrunner.js.map +const _summary = new Summary(); +/** + * @deprecated use `core.summary` + */ +exports.markdownSummary = _summary; +exports.summary = _summary; +//# sourceMappingURL=summary.js.map /***/ }), -/***/ 7272: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 1691: +/***/ ((__unused_webpack_module, exports) => { -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()); - }); -}; +// We use any as a valid input type +/* eslint-disable @typescript-eslint/no-explicit-any */ Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.create = void 0; -const internal_globber_1 = __nccwpck_require__(2692); +exports.toCommandProperties = exports.toCommandValue = void 0; /** - * Constructs a globber - * - * @param patterns Patterns separated by newlines - * @param options Glob options + * Sanitizes an input into a string so it can be passed into issueCommand safely + * @param input input to sanitize into a string */ -function create(patterns, options) { - return __awaiter(this, void 0, void 0, function* () { - return yield internal_globber_1.DefaultGlobber.create(patterns, options); - }); +function toCommandValue(input) { + if (input === null || input === undefined) { + return ''; + } + else if (typeof input === 'string' || input instanceof String) { + return input; + } + return JSON.stringify(input); } -exports.create = create; -//# sourceMappingURL=glob.js.map - -/***/ }), - -/***/ 5228: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - - -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.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getOptions = void 0; -const core = __importStar(__nccwpck_require__(9093)); +exports.toCommandValue = toCommandValue; /** - * Returns a copy with defaults filled in. + * + * @param annotationProperties + * @returns The command properties to send with the actual annotation command + * See IssueCommandProperties: https://github.com/actions/runner/blob/main/src/Runner.Worker/ActionCommandManager.cs#L646 */ -function getOptions(copy) { - const result = { - followSymbolicLinks: true, - implicitDescendants: true, - omitBrokenSymbolicLinks: true - }; - if (copy) { - if (typeof copy.followSymbolicLinks === 'boolean') { - result.followSymbolicLinks = copy.followSymbolicLinks; - core.debug(`followSymbolicLinks '${result.followSymbolicLinks}'`); - } - if (typeof copy.implicitDescendants === 'boolean') { - result.implicitDescendants = copy.implicitDescendants; - core.debug(`implicitDescendants '${result.implicitDescendants}'`); - } - if (typeof copy.omitBrokenSymbolicLinks === 'boolean') { - result.omitBrokenSymbolicLinks = copy.omitBrokenSymbolicLinks; - core.debug(`omitBrokenSymbolicLinks '${result.omitBrokenSymbolicLinks}'`); - } +function toCommandProperties(annotationProperties) { + if (!Object.keys(annotationProperties).length) { + return {}; } - return result; + return { + title: annotationProperties.title, + file: annotationProperties.file, + line: annotationProperties.startLine, + endLine: annotationProperties.endLine, + col: annotationProperties.startColumn, + endColumn: annotationProperties.endColumn + }; } -exports.getOptions = getOptions; -//# sourceMappingURL=internal-glob-options-helper.js.map +exports.toCommandProperties = toCommandProperties; +//# sourceMappingURL=utils.js.map /***/ }), -/***/ 2692: +/***/ 7775: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { @@ -3506,240 +3791,84 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; -var __asyncValues = (this && this.__asyncValues) || function (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); } -}; -var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } -var __asyncGenerator = (this && this.__asyncGenerator) || function (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]); } -}; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.DefaultGlobber = void 0; -const core = __importStar(__nccwpck_require__(9093)); -const fs = __importStar(__nccwpck_require__(7147)); -const globOptionsHelper = __importStar(__nccwpck_require__(5228)); -const path = __importStar(__nccwpck_require__(1017)); -const patternHelper = __importStar(__nccwpck_require__(5677)); -const internal_match_kind_1 = __nccwpck_require__(4195); -const internal_pattern_1 = __nccwpck_require__(1548); -const internal_search_state_1 = __nccwpck_require__(5935); -const IS_WINDOWS = process.platform === 'win32'; -class DefaultGlobber { - constructor(options) { - this.patterns = []; - this.searchPaths = []; - this.options = globOptionsHelper.getOptions(options); - } - getSearchPaths() { - // Return a copy - return this.searchPaths.slice(); - } - glob() { - var e_1, _a; - return __awaiter(this, void 0, void 0, function* () { - const result = []; - try { - for (var _b = __asyncValues(this.globGenerator()), _c; _c = yield _b.next(), !_c.done;) { - const itemPath = _c.value; - result.push(itemPath); - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (_c && !_c.done && (_a = _b.return)) yield _a.call(_b); - } - finally { if (e_1) throw e_1.error; } - } - return result; - }); - } - globGenerator() { - return __asyncGenerator(this, arguments, function* globGenerator_1() { - // Fill in defaults options - const options = globOptionsHelper.getOptions(this.options); - // Implicit descendants? - const patterns = []; - for (const pattern of this.patterns) { - patterns.push(pattern); - if (options.implicitDescendants && - (pattern.trailingSeparator || - pattern.segments[pattern.segments.length - 1] !== '**')) { - patterns.push(new internal_pattern_1.Pattern(pattern.negate, true, pattern.segments.concat('**'))); - } - } - // Push the search paths - const stack = []; - for (const searchPath of patternHelper.getSearchPaths(patterns)) { - core.debug(`Search path '${searchPath}'`); - // Exists? - try { - // Intentionally using lstat. Detection for broken symlink - // will be performed later (if following symlinks). - yield __await(fs.promises.lstat(searchPath)); - } - catch (err) { - if (err.code === 'ENOENT') { - continue; - } - throw err; - } - stack.unshift(new internal_search_state_1.SearchState(searchPath, 1)); - } - // Search - const traversalChain = []; // used to detect cycles - while (stack.length) { - // Pop - const item = stack.pop(); - // Match? - const match = patternHelper.match(patterns, item.path); - const partialMatch = !!match || patternHelper.partialMatch(patterns, item.path); - if (!match && !partialMatch) { - continue; - } - // Stat - const stats = yield __await(DefaultGlobber.stat(item, options, traversalChain) - // Broken symlink, or symlink cycle detected, or no longer exists - ); - // Broken symlink, or symlink cycle detected, or no longer exists - if (!stats) { - continue; - } - // Directory - if (stats.isDirectory()) { - // Matched - if (match & internal_match_kind_1.MatchKind.Directory) { - yield yield __await(item.path); - } - // Descend? - else if (!partialMatch) { - continue; - } - // Push the child items in reverse - const childLevel = item.level + 1; - const childItems = (yield __await(fs.promises.readdir(item.path))).map(x => new internal_search_state_1.SearchState(path.join(item.path, x), childLevel)); - stack.push(...childItems.reverse()); - } - // File - else if (match & internal_match_kind_1.MatchKind.File) { - yield yield __await(item.path); - } - } - }); - } - /** - * Constructs a DefaultGlobber - */ - static create(patterns, options) { - return __awaiter(this, void 0, void 0, function* () { - const result = new DefaultGlobber(options); - if (IS_WINDOWS) { - patterns = patterns.replace(/\r\n/g, '\n'); - patterns = patterns.replace(/\r/g, '\n'); - } - const lines = patterns.split('\n').map(x => x.trim()); - for (const line of lines) { - // Empty or comment - if (!line || line.startsWith('#')) { - continue; - } - // Pattern - else { - result.patterns.push(new internal_pattern_1.Pattern(line)); - } - } - result.searchPaths.push(...patternHelper.getSearchPaths(result.patterns)); - return result; - }); - } - static stat(item, options, traversalChain) { - return __awaiter(this, void 0, void 0, function* () { - // Note: - // `stat` returns info about the target of a symlink (or symlink chain) - // `lstat` returns info about a symlink itself - let stats; - if (options.followSymbolicLinks) { - try { - // Use `stat` (following symlinks) - stats = yield fs.promises.stat(item.path); - } - catch (err) { - if (err.code === 'ENOENT') { - if (options.omitBrokenSymbolicLinks) { - core.debug(`Broken symlink '${item.path}'`); - return undefined; - } - throw new Error(`No information found for the path '${item.path}'. This may indicate a broken symbolic link.`); - } - throw err; - } - } - else { - // Use `lstat` (not following symlinks) - stats = yield fs.promises.lstat(item.path); - } - // Note, isDirectory() returns false for the lstat of a symlink - if (stats.isDirectory() && options.followSymbolicLinks) { - // Get the realpath - const realPath = yield fs.promises.realpath(item.path); - // Fixup the traversal chain to match the item level - while (traversalChain.length >= item.level) { - traversalChain.pop(); - } - // Test for a cycle - if (traversalChain.some((x) => x === realPath)) { - core.debug(`Symlink cycle detected for path '${item.path}' and realpath '${realPath}'`); - return undefined; - } - // Update the traversal chain - traversalChain.push(realPath); - } - return stats; - }); - } +exports.getExecOutput = exports.exec = void 0; +const string_decoder_1 = __nccwpck_require__(1576); +const tr = __importStar(__nccwpck_require__(8374)); +/** + * Exec a command. + * Output will be streamed to the live console. + * Returns promise with return code + * + * @param commandLine command to execute (can include additional args). Must be correctly escaped. + * @param args optional arguments for tool. Escaping is handled by the lib. + * @param options optional exec options. See ExecOptions + * @returns Promise exit code + */ +function exec(commandLine, args, options) { + return __awaiter(this, void 0, void 0, function* () { + const commandArgs = tr.argStringToArray(commandLine); + if (commandArgs.length === 0) { + throw new Error(`Parameter 'commandLine' cannot be null or empty.`); + } + // Path to tool to execute should be first arg + const toolPath = commandArgs[0]; + args = commandArgs.slice(1).concat(args || []); + const runner = new tr.ToolRunner(toolPath, args, options); + return runner.exec(); + }); } -exports.DefaultGlobber = DefaultGlobber; -//# sourceMappingURL=internal-globber.js.map - -/***/ }), - -/***/ 4195: -/***/ ((__unused_webpack_module, exports) => { - - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.MatchKind = void 0; +exports.exec = exec; /** - * Indicates whether a pattern matches a path + * Exec a command and get the output. + * Output will be streamed to the live console. + * Returns promise with the exit code and collected stdout and stderr + * + * @param commandLine command to execute (can include additional args). Must be correctly escaped. + * @param args optional arguments for tool. Escaping is handled by the lib. + * @param options optional exec options. See ExecOptions + * @returns Promise exit code, stdout, and stderr */ -var MatchKind; -(function (MatchKind) { - /** Not matched */ - MatchKind[MatchKind["None"] = 0] = "None"; - /** Matched if the path is a directory */ - MatchKind[MatchKind["Directory"] = 1] = "Directory"; - /** Matched if the path is a regular file */ - MatchKind[MatchKind["File"] = 2] = "File"; - /** Matched */ - MatchKind[MatchKind["All"] = 3] = "All"; -})(MatchKind = exports.MatchKind || (exports.MatchKind = {})); -//# sourceMappingURL=internal-match-kind.js.map +function getExecOutput(commandLine, args, options) { + var _a, _b; + return __awaiter(this, void 0, void 0, function* () { + let stdout = ''; + let stderr = ''; + //Using string decoder covers the case where a mult-byte character is split + const stdoutDecoder = new string_decoder_1.StringDecoder('utf8'); + const stderrDecoder = new string_decoder_1.StringDecoder('utf8'); + const originalStdoutListener = (_a = options === null || options === void 0 ? void 0 : options.listeners) === null || _a === void 0 ? void 0 : _a.stdout; + const originalStdErrListener = (_b = options === null || options === void 0 ? void 0 : options.listeners) === null || _b === void 0 ? void 0 : _b.stderr; + const stdErrListener = (data) => { + stderr += stderrDecoder.write(data); + if (originalStdErrListener) { + originalStdErrListener(data); + } + }; + const stdOutListener = (data) => { + stdout += stdoutDecoder.write(data); + if (originalStdoutListener) { + originalStdoutListener(data); + } + }; + const listeners = Object.assign(Object.assign({}, options === null || options === void 0 ? void 0 : options.listeners), { stdout: stdOutListener, stderr: stdErrListener }); + const exitCode = yield exec(commandLine, args, Object.assign(Object.assign({}, options), { listeners })); + //flush any remaining characters + stdout += stdoutDecoder.end(); + stderr += stderrDecoder.end(); + return { + exitCode, + stdout, + stderr + }; + }); +} +exports.getExecOutput = getExecOutput; +//# sourceMappingURL=exec.js.map /***/ }), -/***/ 8155: +/***/ 8374: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { @@ -3762,686 +3891,609 @@ var __importStar = (this && this.__importStar) || function (mod) { __setModuleDefault(result, mod); return result; }; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; +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.safeTrimTrailingSeparator = exports.normalizeSeparators = exports.hasRoot = exports.hasAbsoluteRoot = exports.ensureAbsoluteRoot = exports.dirname = void 0; +exports.argStringToArray = exports.ToolRunner = void 0; +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 assert_1 = __importDefault(__nccwpck_require__(9491)); +const io = __importStar(__nccwpck_require__(2826)); +const ioUtil = __importStar(__nccwpck_require__(3446)); +const timers_1 = __nccwpck_require__(9512); +/* eslint-disable @typescript-eslint/unbound-method */ const IS_WINDOWS = process.platform === 'win32'; -/** - * Similar to path.dirname except normalizes the path separators and slightly better handling for Windows UNC paths. - * - * For example, on Linux/macOS: - * - `/ => /` - * - `/hello => /` - * - * For example, on Windows: - * - `C:\ => C:\` - * - `C:\hello => C:\` - * - `C: => C:` - * - `C:hello => C:` - * - `\ => \` - * - `\hello => \` - * - `\\hello => \\hello` - * - `\\hello\world => \\hello\world` +/* + * Class for running command line tools. Handles quoting and arg parsing in a platform agnostic way. */ -function dirname(p) { - // Normalize slashes and trim unnecessary trailing slash - p = safeTrimTrailingSeparator(p); - // Windows UNC root, e.g. \\hello or \\hello\world - if (IS_WINDOWS && /^\\\\[^\\]+(\\[^\\]+)?$/.test(p)) { - return p; - } - // Get dirname - let result = path.dirname(p); - // Trim trailing slash for Windows UNC root, e.g. \\hello\world\ - if (IS_WINDOWS && /^\\\\[^\\]+\\[^\\]+\\$/.test(result)) { - result = safeTrimTrailingSeparator(result); +class ToolRunner extends events.EventEmitter { + constructor(toolPath, args, options) { + super(); + if (!toolPath) { + throw new Error("Parameter 'toolPath' cannot be null or empty."); + } + this.toolPath = toolPath; + this.args = args || []; + this.options = options || {}; } - return result; -} -exports.dirname = dirname; -/** - * Roots the path if not already rooted. On Windows, relative roots like `\` - * or `C:` are expanded based on the current working directory. - */ -function ensureAbsoluteRoot(root, itemPath) { - assert_1.default(root, `ensureAbsoluteRoot parameter 'root' must not be empty`); - assert_1.default(itemPath, `ensureAbsoluteRoot parameter 'itemPath' must not be empty`); - // Already rooted - if (hasAbsoluteRoot(itemPath)) { - return itemPath; + _debug(message) { + if (this.options.listeners && this.options.listeners.debug) { + this.options.listeners.debug(message); + } } - // Windows - if (IS_WINDOWS) { - // Check for itemPath like C: or C:foo - if (itemPath.match(/^[A-Z]:[^\\/]|^[A-Z]:$/i)) { - let cwd = process.cwd(); - assert_1.default(cwd.match(/^[A-Z]:\\/i), `Expected current directory to start with an absolute drive root. Actual '${cwd}'`); - // Drive letter matches cwd? Expand to cwd - if (itemPath[0].toUpperCase() === cwd[0].toUpperCase()) { - // Drive only, e.g. C: - if (itemPath.length === 2) { - // Preserve specified drive letter case (upper or lower) - return `${itemPath[0]}:\\${cwd.substr(3)}`; + _getCommandString(options, noPrefix) { + const toolPath = this._getSpawnFileName(); + const args = this._getSpawnArgs(options); + let cmd = noPrefix ? '' : '[command]'; // omit prefix when piped to a second tool + if (IS_WINDOWS) { + // Windows + cmd file + if (this._isCmdFile()) { + cmd += toolPath; + for (const a of args) { + cmd += ` ${a}`; } - // Drive + path, e.g. C:foo - else { - if (!cwd.endsWith('\\')) { - cwd += '\\'; - } - // Preserve specified drive letter case (upper or lower) - return `${itemPath[0]}:\\${cwd.substr(3)}${itemPath.substr(2)}`; + } + // Windows + verbatim + else if (options.windowsVerbatimArguments) { + cmd += `"${toolPath}"`; + for (const a of args) { + cmd += ` ${a}`; } } - // Different drive + // Windows (regular) else { - return `${itemPath[0]}:\\${itemPath.substr(2)}`; + cmd += this._windowsQuoteCmdArg(toolPath); + for (const a of args) { + cmd += ` ${this._windowsQuoteCmdArg(a)}`; + } } } - // Check for itemPath like \ or \foo - else if (normalizeSeparators(itemPath).match(/^\\$|^\\[^\\]/)) { - const cwd = process.cwd(); - assert_1.default(cwd.match(/^[A-Z]:\\/i), `Expected current directory to start with an absolute drive root. Actual '${cwd}'`); - return `${cwd[0]}:\\${itemPath.substr(1)}`; + else { + // OSX/Linux - this can likely be improved with some form of quoting. + // creating processes on Unix is fundamentally different than Windows. + // on Unix, execvp() takes an arg array. + cmd += toolPath; + for (const a of args) { + cmd += ` ${a}`; + } } + return cmd; } - assert_1.default(hasAbsoluteRoot(root), `ensureAbsoluteRoot parameter 'root' must have an absolute root`); - // Otherwise ensure root ends with a separator - if (root.endsWith('/') || (IS_WINDOWS && root.endsWith('\\'))) { - // Intentionally empty - } - else { - // Append separator - root += path.sep; - } - return root + itemPath; -} -exports.ensureAbsoluteRoot = ensureAbsoluteRoot; -/** - * On Linux/macOS, true if path starts with `/`. On Windows, true for paths like: - * `\\hello\share` and `C:\hello` (and using alternate separator). - */ -function hasAbsoluteRoot(itemPath) { - assert_1.default(itemPath, `hasAbsoluteRoot parameter 'itemPath' must not be empty`); - // Normalize separators - itemPath = normalizeSeparators(itemPath); - // Windows - if (IS_WINDOWS) { - // E.g. \\hello\share or C:\hello - return itemPath.startsWith('\\\\') || /^[A-Z]:\\/i.test(itemPath); - } - // E.g. /hello - return itemPath.startsWith('/'); -} -exports.hasAbsoluteRoot = hasAbsoluteRoot; -/** - * On Linux/macOS, true if path starts with `/`. On Windows, true for paths like: - * `\`, `\hello`, `\\hello\share`, `C:`, and `C:\hello` (and using alternate separator). - */ -function hasRoot(itemPath) { - assert_1.default(itemPath, `isRooted parameter 'itemPath' must not be empty`); - // Normalize separators - itemPath = normalizeSeparators(itemPath); - // Windows - if (IS_WINDOWS) { - // E.g. \ or \hello or \\hello - // E.g. C: or C:\hello - return itemPath.startsWith('\\') || /^[A-Z]:/i.test(itemPath); - } - // E.g. /hello - return itemPath.startsWith('/'); -} -exports.hasRoot = hasRoot; -/** - * Removes redundant slashes and converts `/` to `\` on Windows - */ -function normalizeSeparators(p) { - p = p || ''; - // Windows - if (IS_WINDOWS) { - // Convert slashes on Windows - p = p.replace(/\//g, '\\'); - // Remove redundant slashes - const isUnc = /^\\\\+[^\\]/.test(p); // e.g. \\hello - return (isUnc ? '\\' : '') + p.replace(/\\\\+/g, '\\'); // preserve leading \\ for UNC - } - // Remove redundant slashes - return p.replace(/\/\/+/g, '/'); -} -exports.normalizeSeparators = normalizeSeparators; -/** - * Normalizes the path separators and trims the trailing separator (when safe). - * For example, `/foo/ => /foo` but `/ => /` - */ -function safeTrimTrailingSeparator(p) { - // Short-circuit if empty - if (!p) { - return ''; - } - // Normalize separators - p = normalizeSeparators(p); - // No trailing slash - if (!p.endsWith(path.sep)) { - return p; - } - // Check '/' on Linux/macOS and '\' on Windows - if (p === path.sep) { - return p; - } - // On Windows check if drive root. E.g. C:\ - if (IS_WINDOWS && /^[A-Z]:\\$/i.test(p)) { - return p; - } - // Otherwise trim trailing slash - return p.substr(0, p.length - 1); -} -exports.safeTrimTrailingSeparator = safeTrimTrailingSeparator; -//# sourceMappingURL=internal-path-helper.js.map - -/***/ }), - -/***/ 4674: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - - -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.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Path = void 0; -const path = __importStar(__nccwpck_require__(1017)); -const pathHelper = __importStar(__nccwpck_require__(8155)); -const assert_1 = __importDefault(__nccwpck_require__(9491)); -const IS_WINDOWS = process.platform === 'win32'; -/** - * Helper class for parsing paths into segments - */ -class Path { - /** - * Constructs a Path - * @param itemPath Path or array of segments - */ - constructor(itemPath) { - this.segments = []; - // String - if (typeof itemPath === 'string') { - assert_1.default(itemPath, `Parameter 'itemPath' must not be empty`); - // Normalize slashes and trim unnecessary trailing slash - itemPath = pathHelper.safeTrimTrailingSeparator(itemPath); - // Not rooted - if (!pathHelper.hasRoot(itemPath)) { - this.segments = itemPath.split(path.sep); - } - // Rooted - else { - // Add all segments, while not at the root - let remaining = itemPath; - let dir = pathHelper.dirname(remaining); - while (dir !== remaining) { - // Add the segment - const basename = path.basename(remaining); - this.segments.unshift(basename); - // Truncate the last segment - remaining = dir; - dir = pathHelper.dirname(remaining); - } - // Remainder is the root - this.segments.unshift(remaining); + _processLineBuffer(data, strBuffer, onLine) { + try { + let s = strBuffer + data.toString(); + let n = s.indexOf(os.EOL); + while (n > -1) { + const line = s.substring(0, n); + onLine(line); + // the rest of the string ... + s = s.substring(n + os.EOL.length); + n = s.indexOf(os.EOL); } + return s; } - // Array - else { - // Must not be empty - assert_1.default(itemPath.length > 0, `Parameter 'itemPath' must not be an empty array`); - // Each segment - for (let i = 0; i < itemPath.length; i++) { - let segment = itemPath[i]; - // Must not be empty - assert_1.default(segment, `Parameter 'itemPath' must not contain any empty segments`); - // Normalize slashes - segment = pathHelper.normalizeSeparators(itemPath[i]); - // Root segment - if (i === 0 && pathHelper.hasRoot(segment)) { - segment = pathHelper.safeTrimTrailingSeparator(segment); - assert_1.default(segment === pathHelper.dirname(segment), `Parameter 'itemPath' root segment contains information for multiple segments`); - this.segments.push(segment); - } - // All other segments - else { - // Must not contain slash - assert_1.default(!segment.includes(path.sep), `Parameter 'itemPath' contains unexpected path separators`); - this.segments.push(segment); - } - } + catch (err) { + // streaming lines to console is best effort. Don't fail a build. + this._debug(`error processing line. Failed with error ${err}`); + return ''; } } - /** - * Converts the path to it's string representation - */ - toString() { - // First segment - let result = this.segments[0]; - // All others - let skipSlash = result.endsWith(path.sep) || (IS_WINDOWS && /^[A-Z]:$/i.test(result)); - for (let i = 1; i < this.segments.length; i++) { - if (skipSlash) { - skipSlash = false; + _getSpawnFileName() { + if (IS_WINDOWS) { + if (this._isCmdFile()) { + return process.env['COMSPEC'] || 'cmd.exe'; } - else { - result += path.sep; + } + return this.toolPath; + } + _getSpawnArgs(options) { + if (IS_WINDOWS) { + if (this._isCmdFile()) { + let argline = `/D /S /C "${this._windowsQuoteCmdArg(this.toolPath)}`; + for (const a of this.args) { + argline += ' '; + argline += options.windowsVerbatimArguments + ? a + : this._windowsQuoteCmdArg(a); + } + argline += '"'; + return [argline]; } - result += this.segments[i]; } - return result; + return this.args; } -} -exports.Path = Path; -//# sourceMappingURL=internal-path.js.map - -/***/ }), - -/***/ 5677: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - - -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.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.partialMatch = exports.match = exports.getSearchPaths = void 0; -const pathHelper = __importStar(__nccwpck_require__(8155)); -const internal_match_kind_1 = __nccwpck_require__(4195); -const IS_WINDOWS = process.platform === 'win32'; -/** - * Given an array of patterns, returns an array of paths to search. - * Duplicates and paths under other included paths are filtered out. - */ -function getSearchPaths(patterns) { - // Ignore negate patterns - patterns = patterns.filter(x => !x.negate); - // Create a map of all search paths - const searchPathMap = {}; - for (const pattern of patterns) { - const key = IS_WINDOWS - ? pattern.searchPath.toUpperCase() - : pattern.searchPath; - searchPathMap[key] = 'candidate'; + _endsWith(str, end) { + return str.endsWith(end); } - const result = []; - for (const pattern of patterns) { - // Check if already included - const key = IS_WINDOWS - ? pattern.searchPath.toUpperCase() - : pattern.searchPath; - if (searchPathMap[key] === 'included') { - continue; + _isCmdFile() { + const upperToolPath = this.toolPath.toUpperCase(); + return (this._endsWith(upperToolPath, '.CMD') || + this._endsWith(upperToolPath, '.BAT')); + } + _windowsQuoteCmdArg(arg) { + // for .exe, apply the normal quoting rules that libuv applies + if (!this._isCmdFile()) { + return this._uvQuoteCmdArg(arg); } - // Check for an ancestor search path - let foundAncestor = false; - let tempKey = key; - let parent = pathHelper.dirname(tempKey); - while (parent !== tempKey) { - if (searchPathMap[parent]) { - foundAncestor = true; + // otherwise apply quoting rules specific to the cmd.exe command line parser. + // the libuv rules are generic and are not designed specifically for cmd.exe + // command line parser. + // + // for a detailed description of the cmd.exe command line parser, refer to + // http://stackoverflow.com/questions/4094699/how-does-the-windows-command-interpreter-cmd-exe-parse-scripts/7970912#7970912 + // need quotes for empty arg + if (!arg) { + return '""'; + } + // determine whether the arg needs to be quoted + const cmdSpecialChars = [ + ' ', + '\t', + '&', + '(', + ')', + '[', + ']', + '{', + '}', + '^', + '=', + ';', + '!', + "'", + '+', + ',', + '`', + '~', + '|', + '<', + '>', + '"' + ]; + let needsQuotes = false; + for (const char of arg) { + if (cmdSpecialChars.some(x => x === char)) { + needsQuotes = true; break; } - tempKey = parent; - parent = pathHelper.dirname(tempKey); } - // Include the search pattern in the result - if (!foundAncestor) { - result.push(pattern.searchPath); - searchPathMap[key] = 'included'; + // short-circuit if quotes not needed + if (!needsQuotes) { + return arg; + } + // the following quoting rules are very similar to the rules that by libuv applies. + // + // 1) wrap the string in quotes + // + // 2) double-up quotes - i.e. " => "" + // + // this is different from the libuv quoting rules. libuv replaces " with \", which unfortunately + // doesn't work well with a cmd.exe command line. + // + // note, replacing " with "" also works well if the arg is passed to a downstream .NET console app. + // for example, the command line: + // foo.exe "myarg:""my val""" + // is parsed by a .NET console app into an arg array: + // [ "myarg:\"my val\"" ] + // which is the same end result when applying libuv quoting rules. although the actual + // command line from libuv quoting rules would look like: + // foo.exe "myarg:\"my val\"" + // + // 3) double-up slashes that precede a quote, + // e.g. hello \world => "hello \world" + // hello\"world => "hello\\""world" + // hello\\"world => "hello\\\\""world" + // hello world\ => "hello world\\" + // + // technically this is not required for a cmd.exe command line, or the batch argument parser. + // the reasons for including this as a .cmd quoting rule are: + // + // a) this is optimized for the scenario where the argument is passed from the .cmd file to an + // external program. many programs (e.g. .NET console apps) rely on the slash-doubling rule. + // + // b) it's what we've been doing previously (by deferring to node default behavior) and we + // haven't heard any complaints about that aspect. + // + // note, a weakness of the quoting rules chosen here, is that % is not escaped. in fact, % cannot be + // escaped when used on the command line directly - even though within a .cmd file % can be escaped + // by using %%. + // + // the saving grace is, on the command line, %var% is left as-is if var is not defined. this contrasts + // the line parsing rules within a .cmd file, where if var is not defined it is replaced with nothing. + // + // one option that was explored was replacing % with ^% - i.e. %var% => ^%var^%. this hack would + // often work, since it is unlikely that var^ would exist, and the ^ character is removed when the + // variable is used. the problem, however, is that ^ is not removed when %* is used to pass the args + // to an external program. + // + // an unexplored potential solution for the % escaping problem, is to create a wrapper .cmd file. + // % can be escaped within a .cmd file. + let reverse = '"'; + let quoteHit = true; + for (let i = arg.length; i > 0; i--) { + // walk the string in reverse + reverse += arg[i - 1]; + if (quoteHit && arg[i - 1] === '\\') { + reverse += '\\'; // double the slash + } + else if (arg[i - 1] === '"') { + quoteHit = true; + reverse += '"'; // double the quote + } + else { + quoteHit = false; + } } + reverse += '"'; + return reverse + .split('') + .reverse() + .join(''); } - return result; -} -exports.getSearchPaths = getSearchPaths; -/** - * Matches the patterns against the path - */ -function match(patterns, itemPath) { - let result = internal_match_kind_1.MatchKind.None; - for (const pattern of patterns) { - if (pattern.negate) { - result &= ~pattern.match(itemPath); + _uvQuoteCmdArg(arg) { + // Tool runner wraps child_process.spawn() and needs to apply the same quoting as + // Node in certain cases where the undocumented spawn option windowsVerbatimArguments + // is used. + // + // Since this function is a port of quote_cmd_arg from Node 4.x (technically, lib UV, + // see https://github.com/nodejs/node/blob/v4.x/deps/uv/src/win/process.c for details), + // pasting copyright notice from Node within this function: + // + // Copyright Joyent, Inc. and other Node contributors. All rights reserved. + // + // 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. + if (!arg) { + // Need double quotation for empty argument + return '""'; } - else { - result |= pattern.match(itemPath); + if (!arg.includes(' ') && !arg.includes('\t') && !arg.includes('"')) { + // No quotation needed + return arg; + } + if (!arg.includes('"') && !arg.includes('\\')) { + // No embedded double quotes or backslashes, so I can just wrap + // quote marks around the whole thing. + return `"${arg}"`; + } + // Expected input/output: + // input : hello"world + // output: "hello\"world" + // input : hello""world + // output: "hello\"\"world" + // input : hello\world + // output: hello\world + // input : hello\\world + // output: hello\\world + // input : hello\"world + // output: "hello\\\"world" + // input : hello\\"world + // output: "hello\\\\\"world" + // input : hello world\ + // output: "hello world\\" - note the comment in libuv actually reads "hello world\" + // but it appears the comment is wrong, it should be "hello world\\" + let reverse = '"'; + let quoteHit = true; + for (let i = arg.length; i > 0; i--) { + // walk the string in reverse + reverse += arg[i - 1]; + if (quoteHit && arg[i - 1] === '\\') { + reverse += '\\'; + } + else if (arg[i - 1] === '"') { + quoteHit = true; + reverse += '\\'; + } + else { + quoteHit = false; + } } + reverse += '"'; + return reverse + .split('') + .reverse() + .join(''); } - return result; -} -exports.match = match; -/** - * Checks whether to descend further into the directory - */ -function partialMatch(patterns, itemPath) { - return patterns.some(x => !x.negate && x.partialMatch(itemPath)); -} -exports.partialMatch = partialMatch; -//# sourceMappingURL=internal-pattern-helper.js.map - -/***/ }), - -/***/ 1548: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - - -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.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Pattern = void 0; -const os = __importStar(__nccwpck_require__(2037)); -const path = __importStar(__nccwpck_require__(1017)); -const pathHelper = __importStar(__nccwpck_require__(8155)); -const assert_1 = __importDefault(__nccwpck_require__(9491)); -const minimatch_1 = __nccwpck_require__(7151); -const internal_match_kind_1 = __nccwpck_require__(4195); -const internal_path_1 = __nccwpck_require__(4674); -const IS_WINDOWS = process.platform === 'win32'; -class Pattern { - constructor(patternOrNegate, isImplicitPattern = false, segments, homedir) { - /** - * Indicates whether matches should be excluded from the result set - */ - this.negate = false; - // Pattern overload - let pattern; - if (typeof patternOrNegate === 'string') { - pattern = patternOrNegate.trim(); - } - // Segments overload - else { - // Convert to pattern - segments = segments || []; - assert_1.default(segments.length, `Parameter 'segments' must not empty`); - const root = Pattern.getLiteral(segments[0]); - assert_1.default(root && pathHelper.hasAbsoluteRoot(root), `Parameter 'segments' first element must be a root path`); - pattern = new internal_path_1.Path(segments).toString().trim(); - if (patternOrNegate) { - pattern = `!${pattern}`; - } - } - // Negate - while (pattern.startsWith('!')) { - this.negate = !this.negate; - pattern = pattern.substr(1).trim(); - } - // Normalize slashes and ensures absolute root - pattern = Pattern.fixupPattern(pattern, homedir); - // Segments - this.segments = new internal_path_1.Path(pattern).segments; - // Trailing slash indicates the pattern should only match directories, not regular files - this.trailingSeparator = pathHelper - .normalizeSeparators(pattern) - .endsWith(path.sep); - pattern = pathHelper.safeTrimTrailingSeparator(pattern); - // Search path (literal path prior to the first glob segment) - let foundGlob = false; - const searchSegments = this.segments - .map(x => Pattern.getLiteral(x)) - .filter(x => !foundGlob && !(foundGlob = x === '')); - this.searchPath = new internal_path_1.Path(searchSegments).toString(); - // Root RegExp (required when determining partial match) - this.rootRegExp = new RegExp(Pattern.regExpEscape(searchSegments[0]), IS_WINDOWS ? 'i' : ''); - this.isImplicitPattern = isImplicitPattern; - // Create minimatch - const minimatchOptions = { - dot: true, - nobrace: true, - nocase: IS_WINDOWS, - nocomment: true, - noext: true, - nonegate: true + _cloneExecOptions(options) { + options = options || {}; + const result = { + cwd: options.cwd || process.cwd(), + env: options.env || process.env, + silent: options.silent || false, + windowsVerbatimArguments: options.windowsVerbatimArguments || false, + failOnStdErr: options.failOnStdErr || false, + ignoreReturnCode: options.ignoreReturnCode || false, + delay: options.delay || 10000 }; - pattern = IS_WINDOWS ? pattern.replace(/\\/g, '/') : pattern; - this.minimatch = new minimatch_1.Minimatch(pattern, minimatchOptions); + result.outStream = options.outStream || process.stdout; + result.errStream = options.errStream || process.stderr; + return result; + } + _getSpawnOptions(options, toolPath) { + options = options || {}; + const result = {}; + result.cwd = options.cwd; + result.env = options.env; + result['windowsVerbatimArguments'] = + options.windowsVerbatimArguments || this._isCmdFile(); + if (options.windowsVerbatimArguments) { + result.argv0 = `"${toolPath}"`; + } + return result; } /** - * Matches the pattern against the specified path + * Exec a tool. + * Output will be streamed to the live console. + * Returns promise with return code + * + * @param tool path to tool to exec + * @param options optional exec options. See ExecOptions + * @returns number */ - match(itemPath) { - // Last segment is globstar? - if (this.segments[this.segments.length - 1] === '**') { - // Normalize slashes - itemPath = pathHelper.normalizeSeparators(itemPath); - // Append a trailing slash. Otherwise Minimatch will not match the directory immediately - // preceding the globstar. For example, given the pattern `/foo/**`, Minimatch returns - // false for `/foo` but returns true for `/foo/`. Append a trailing slash to handle that quirk. - if (!itemPath.endsWith(path.sep) && this.isImplicitPattern === false) { - // Note, this is safe because the constructor ensures the pattern has an absolute root. - // For example, formats like C: and C:foo on Windows are resolved to an absolute root. - itemPath = `${itemPath}${path.sep}`; + exec() { + return __awaiter(this, void 0, void 0, function* () { + // root the tool path if it is unrooted and contains relative pathing + if (!ioUtil.isRooted(this.toolPath) && + (this.toolPath.includes('/') || + (IS_WINDOWS && this.toolPath.includes('\\')))) { + // prefer options.cwd if it is specified, however options.cwd may also need to be rooted + this.toolPath = path.resolve(process.cwd(), this.options.cwd || process.cwd(), this.toolPath); + } + // if the tool is only a file name, then resolve it from the PATH + // otherwise verify it exists (add extension on Windows if necessary) + this.toolPath = yield io.which(this.toolPath, true); + return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { + this._debug(`exec tool: ${this.toolPath}`); + this._debug('arguments:'); + for (const arg of this.args) { + this._debug(` ${arg}`); + } + const optionsNonNull = this._cloneExecOptions(this.options); + if (!optionsNonNull.silent && optionsNonNull.outStream) { + optionsNonNull.outStream.write(this._getCommandString(optionsNonNull) + os.EOL); + } + const state = new ExecState(optionsNonNull, this.toolPath); + state.on('debug', (message) => { + this._debug(message); + }); + if (this.options.cwd && !(yield ioUtil.exists(this.options.cwd))) { + return reject(new Error(`The cwd: ${this.options.cwd} does not exist!`)); + } + const fileName = this._getSpawnFileName(); + const cp = child.spawn(fileName, this._getSpawnArgs(optionsNonNull), this._getSpawnOptions(this.options, fileName)); + let stdbuffer = ''; + if (cp.stdout) { + cp.stdout.on('data', (data) => { + if (this.options.listeners && this.options.listeners.stdout) { + this.options.listeners.stdout(data); + } + if (!optionsNonNull.silent && optionsNonNull.outStream) { + optionsNonNull.outStream.write(data); + } + stdbuffer = this._processLineBuffer(data, stdbuffer, (line) => { + if (this.options.listeners && this.options.listeners.stdline) { + this.options.listeners.stdline(line); + } + }); + }); + } + let errbuffer = ''; + if (cp.stderr) { + cp.stderr.on('data', (data) => { + state.processStderr = true; + if (this.options.listeners && this.options.listeners.stderr) { + this.options.listeners.stderr(data); + } + if (!optionsNonNull.silent && + optionsNonNull.errStream && + optionsNonNull.outStream) { + const s = optionsNonNull.failOnStdErr + ? optionsNonNull.errStream + : optionsNonNull.outStream; + s.write(data); + } + errbuffer = this._processLineBuffer(data, errbuffer, (line) => { + if (this.options.listeners && this.options.listeners.errline) { + this.options.listeners.errline(line); + } + }); + }); + } + cp.on('error', (err) => { + state.processError = err.message; + state.processExited = true; + state.processClosed = true; + state.CheckComplete(); + }); + cp.on('exit', (code) => { + state.processExitCode = code; + state.processExited = true; + this._debug(`Exit code ${code} received from tool '${this.toolPath}'`); + state.CheckComplete(); + }); + cp.on('close', (code) => { + state.processExitCode = code; + state.processExited = true; + state.processClosed = true; + this._debug(`STDIO streams have closed for tool '${this.toolPath}'`); + state.CheckComplete(); + }); + state.on('done', (error, exitCode) => { + if (stdbuffer.length > 0) { + this.emit('stdline', stdbuffer); + } + if (errbuffer.length > 0) { + this.emit('errline', errbuffer); + } + cp.removeAllListeners(); + if (error) { + reject(error); + } + else { + resolve(exitCode); + } + }); + if (this.options.input) { + if (!cp.stdin) { + throw new Error('child process missing stdin'); + } + cp.stdin.end(this.options.input); + } + })); + }); + } +} +exports.ToolRunner = ToolRunner; +/** + * Convert an arg string to an array of args. Handles escaping + * + * @param argString string of arguments + * @returns string[] array of arguments + */ +function argStringToArray(argString) { + const args = []; + let inQuotes = false; + let escaped = false; + let arg = ''; + function append(c) { + // we only escape double quotes. + if (escaped && c !== '"') { + arg += '\\'; + } + arg += c; + escaped = false; + } + for (let i = 0; i < argString.length; i++) { + const c = argString.charAt(i); + if (c === '"') { + if (!escaped) { + inQuotes = !inQuotes; + } + else { + append(c); } + continue; } - else { - // Normalize slashes and trim unnecessary trailing slash - itemPath = pathHelper.safeTrimTrailingSeparator(itemPath); + if (c === '\\' && escaped) { + append(c); + continue; } - // Match - if (this.minimatch.match(itemPath)) { - return this.trailingSeparator ? internal_match_kind_1.MatchKind.Directory : internal_match_kind_1.MatchKind.All; + if (c === '\\' && inQuotes) { + escaped = true; + continue; } - return internal_match_kind_1.MatchKind.None; - } - /** - * Indicates whether the pattern may match descendants of the specified path - */ - partialMatch(itemPath) { - // Normalize slashes and trim unnecessary trailing slash - itemPath = pathHelper.safeTrimTrailingSeparator(itemPath); - // matchOne does not handle root path correctly - if (pathHelper.dirname(itemPath) === itemPath) { - return this.rootRegExp.test(itemPath); + if (c === ' ' && !inQuotes) { + if (arg.length > 0) { + args.push(arg); + arg = ''; + } + continue; } - return this.minimatch.matchOne(itemPath.split(IS_WINDOWS ? /\\+/ : /\/+/), this.minimatch.set[0], true); + append(c); } - /** - * Escapes glob patterns within a path - */ - static globEscape(s) { - return (IS_WINDOWS ? s : s.replace(/\\/g, '\\\\')) // escape '\' on Linux/macOS - .replace(/(\[)(?=[^/]+\])/g, '[[]') // escape '[' when ']' follows within the path segment - .replace(/\?/g, '[?]') // escape '?' - .replace(/\*/g, '[*]'); // escape '*' + if (arg.length > 0) { + args.push(arg.trim()); } - /** - * Normalizes slashes and ensures absolute root - */ - static fixupPattern(pattern, homedir) { - // Empty - assert_1.default(pattern, 'pattern cannot be empty'); - // Must not contain `.` segment, unless first segment - // Must not contain `..` segment - const literalSegments = new internal_path_1.Path(pattern).segments.map(x => Pattern.getLiteral(x)); - assert_1.default(literalSegments.every((x, i) => (x !== '.' || i === 0) && x !== '..'), `Invalid pattern '${pattern}'. Relative pathing '.' and '..' is not allowed.`); - // Must not contain globs in root, e.g. Windows UNC path \\foo\b*r - assert_1.default(!pathHelper.hasRoot(pattern) || literalSegments[0], `Invalid pattern '${pattern}'. Root segment must not contain globs.`); - // Normalize slashes - pattern = pathHelper.normalizeSeparators(pattern); - // Replace leading `.` segment - if (pattern === '.' || pattern.startsWith(`.${path.sep}`)) { - pattern = Pattern.globEscape(process.cwd()) + pattern.substr(1); + return args; +} +exports.argStringToArray = argStringToArray; +class ExecState extends events.EventEmitter { + constructor(options, toolPath) { + super(); + this.processClosed = false; // tracks whether the process has exited and stdio is closed + this.processError = ''; + this.processExitCode = 0; + this.processExited = false; // tracks whether the process has exited + this.processStderr = false; // tracks whether stderr was written to + this.delay = 10000; // 10 seconds + this.done = false; + this.timeout = null; + if (!toolPath) { + throw new Error('toolPath must not be empty'); } - // Replace leading `~` segment - else if (pattern === '~' || pattern.startsWith(`~${path.sep}`)) { - homedir = homedir || os.homedir(); - assert_1.default(homedir, 'Unable to determine HOME directory'); - assert_1.default(pathHelper.hasAbsoluteRoot(homedir), `Expected HOME directory to be a rooted path. Actual '${homedir}'`); - pattern = Pattern.globEscape(homedir) + pattern.substr(1); + this.options = options; + this.toolPath = toolPath; + if (options.delay) { + this.delay = options.delay; } - // Replace relative drive root, e.g. pattern is C: or C:foo - else if (IS_WINDOWS && - (pattern.match(/^[A-Z]:$/i) || pattern.match(/^[A-Z]:[^\\]/i))) { - let root = pathHelper.ensureAbsoluteRoot('C:\\dummy-root', pattern.substr(0, 2)); - if (pattern.length > 2 && !root.endsWith('\\')) { - root += '\\'; - } - pattern = Pattern.globEscape(root) + pattern.substr(2); + } + CheckComplete() { + if (this.done) { + return; } - // Replace relative root, e.g. pattern is \ or \foo - else if (IS_WINDOWS && (pattern === '\\' || pattern.match(/^\\[^\\]/))) { - let root = pathHelper.ensureAbsoluteRoot('C:\\dummy-root', '\\'); - if (!root.endsWith('\\')) { - root += '\\'; - } - pattern = Pattern.globEscape(root) + pattern.substr(1); + if (this.processClosed) { + this._setResult(); } - // Otherwise ensure absolute root - else { - pattern = pathHelper.ensureAbsoluteRoot(Pattern.globEscape(process.cwd()), pattern); + else if (this.processExited) { + this.timeout = timers_1.setTimeout(ExecState.HandleTimeout, this.delay, this); } - return pathHelper.normalizeSeparators(pattern); } - /** - * Attempts to unescape a pattern segment to create a literal path segment. - * Otherwise returns empty string. - */ - static getLiteral(segment) { - let literal = ''; - for (let i = 0; i < segment.length; i++) { - const c = segment[i]; - // Escape - if (c === '\\' && !IS_WINDOWS && i + 1 < segment.length) { - literal += segment[++i]; - continue; + _debug(message) { + this.emit('debug', message); + } + _setResult() { + // determine whether there is an error + let error; + if (this.processExited) { + if (this.processError) { + error = new Error(`There was an error when attempting to execute the process '${this.toolPath}'. This may indicate the process failed to start. Error: ${this.processError}`); } - // Wildcard - else if (c === '*' || c === '?') { - return ''; + else if (this.processExitCode !== 0 && !this.options.ignoreReturnCode) { + error = new Error(`The process '${this.toolPath}' failed with exit code ${this.processExitCode}`); } - // Character set - else if (c === '[' && i + 1 < segment.length) { - let set = ''; - let closed = -1; - for (let i2 = i + 1; i2 < segment.length; i2++) { - const c2 = segment[i2]; - // Escape - if (c2 === '\\' && !IS_WINDOWS && i2 + 1 < segment.length) { - set += segment[++i2]; - continue; - } - // Closed - else if (c2 === ']') { - closed = i2; - break; - } - // Otherwise - else { - set += c2; - } - } - // Closed? - if (closed >= 0) { - // Cannot convert - if (set.length > 1) { - return ''; - } - // Convert to literal - if (set) { - literal += set; - i = closed; - continue; - } - } - // Otherwise fall thru + else if (this.processStderr && this.options.failOnStdErr) { + error = new Error(`The process '${this.toolPath}' failed because one or more lines were written to the STDERR stream`); } - // Append - literal += c; } - return literal; - } - /** - * Escapes regexp special characters - * https://javascript.info/regexp-escaping - */ - static regExpEscape(s) { - return s.replace(/[[\\^$.|?*+()]/g, '\\$&'); + // clear the timeout + if (this.timeout) { + clearTimeout(this.timeout); + this.timeout = null; + } + this.done = true; + this.emit('done', error, this.processExitCode); } -} -exports.Pattern = Pattern; -//# sourceMappingURL=internal-pattern.js.map - -/***/ }), - -/***/ 5935: -/***/ ((__unused_webpack_module, exports) => { - - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.SearchState = void 0; -class SearchState { - constructor(path, level) { - this.path = path; - this.level = level; + static HandleTimeout(state) { + if (state.done) { + return; + } + if (!state.processClosed && state.processExited) { + const message = `The STDIO streams did not close within ${state.delay / + 1000} seconds of the exit event from process '${state.toolPath}'. This may indicate a child process inherited the STDIO streams and has not yet exited.`; + state._debug(message); + } + state._setResult(); } } -exports.SearchState = SearchState; -//# sourceMappingURL=internal-search-state.js.map +//# sourceMappingURL=toolrunner.js.map /***/ }), -/***/ 8603: -/***/ (function(__unused_webpack_module, exports) { +/***/ 7272: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { @@ -4454,91 +4506,87 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.PersonalAccessTokenCredentialHandler = exports.BearerCredentialHandler = exports.BasicCredentialHandler = void 0; -class BasicCredentialHandler { - constructor(username, password) { - this.username = username; - this.password = password; - } - prepareRequest(options) { - if (!options.headers) { - throw Error('The request has no headers'); - } - options.headers['Authorization'] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString('base64')}`; - } - // This handler cannot handle 401 - canHandleAuthentication() { - return false; - } - handleAuthentication() { - return __awaiter(this, void 0, void 0, function* () { - throw new Error('not implemented'); - }); - } +exports.create = void 0; +const internal_globber_1 = __nccwpck_require__(2692); +/** + * Constructs a globber + * + * @param patterns Patterns separated by newlines + * @param options Glob options + */ +function create(patterns, options) { + return __awaiter(this, void 0, void 0, function* () { + return yield internal_globber_1.DefaultGlobber.create(patterns, options); + }); } -exports.BasicCredentialHandler = BasicCredentialHandler; -class BearerCredentialHandler { - constructor(token) { - this.token = token; - } - // currently implements pre-authorization - // TODO: support preAuth = false where it hooks on 401 - prepareRequest(options) { - if (!options.headers) { - throw Error('The request has no headers'); +exports.create = create; +//# sourceMappingURL=glob.js.map + +/***/ }), + +/***/ 5228: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + +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.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getOptions = void 0; +const core = __importStar(__nccwpck_require__(9093)); +/** + * Returns a copy with defaults filled in. + */ +function getOptions(copy) { + const result = { + followSymbolicLinks: true, + implicitDescendants: true, + omitBrokenSymbolicLinks: true + }; + if (copy) { + if (typeof copy.followSymbolicLinks === 'boolean') { + result.followSymbolicLinks = copy.followSymbolicLinks; + core.debug(`followSymbolicLinks '${result.followSymbolicLinks}'`); } - options.headers['Authorization'] = `Bearer ${this.token}`; - } - // This handler cannot handle 401 - canHandleAuthentication() { - return false; - } - handleAuthentication() { - return __awaiter(this, void 0, void 0, function* () { - throw new Error('not implemented'); - }); - } -} -exports.BearerCredentialHandler = BearerCredentialHandler; -class PersonalAccessTokenCredentialHandler { - constructor(token) { - this.token = token; - } - // currently implements pre-authorization - // TODO: support preAuth = false where it hooks on 401 - prepareRequest(options) { - if (!options.headers) { - throw Error('The request has no headers'); + if (typeof copy.implicitDescendants === 'boolean') { + result.implicitDescendants = copy.implicitDescendants; + core.debug(`implicitDescendants '${result.implicitDescendants}'`); + } + if (typeof copy.omitBrokenSymbolicLinks === 'boolean') { + result.omitBrokenSymbolicLinks = copy.omitBrokenSymbolicLinks; + core.debug(`omitBrokenSymbolicLinks '${result.omitBrokenSymbolicLinks}'`); } - options.headers['Authorization'] = `Basic ${Buffer.from(`PAT:${this.token}`).toString('base64')}`; - } - // This handler cannot handle 401 - canHandleAuthentication() { - return false; - } - handleAuthentication() { - return __awaiter(this, void 0, void 0, function* () { - throw new Error('not implemented'); - }); } + return result; } -exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler; -//# sourceMappingURL=auth.js.map +exports.getOptions = getOptions; +//# sourceMappingURL=internal-glob-options-helper.js.map /***/ }), -/***/ 6372: +/***/ 2692: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { -/* eslint-disable @typescript-eslint/no-explicit-any */ 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); + 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]; @@ -4551,7 +4599,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.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; @@ -4564,814 +4612,669 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; +var __asyncValues = (this && this.__asyncValues) || function (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); } +}; +var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } +var __asyncGenerator = (this && this.__asyncGenerator) || function (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]); } +}; 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__(3685)); -const https = __importStar(__nccwpck_require__(5687)); -const pm = __importStar(__nccwpck_require__(2067)); -const tunnel = __importStar(__nccwpck_require__(4225)); -const undici_1 = __nccwpck_require__(7181); -var HttpCodes; -(function (HttpCodes) { - HttpCodes[HttpCodes["OK"] = 200] = "OK"; - HttpCodes[HttpCodes["MultipleChoices"] = 300] = "MultipleChoices"; - HttpCodes[HttpCodes["MovedPermanently"] = 301] = "MovedPermanently"; - HttpCodes[HttpCodes["ResourceMoved"] = 302] = "ResourceMoved"; - HttpCodes[HttpCodes["SeeOther"] = 303] = "SeeOther"; - HttpCodes[HttpCodes["NotModified"] = 304] = "NotModified"; - HttpCodes[HttpCodes["UseProxy"] = 305] = "UseProxy"; - HttpCodes[HttpCodes["SwitchProxy"] = 306] = "SwitchProxy"; - HttpCodes[HttpCodes["TemporaryRedirect"] = 307] = "TemporaryRedirect"; - HttpCodes[HttpCodes["PermanentRedirect"] = 308] = "PermanentRedirect"; - HttpCodes[HttpCodes["BadRequest"] = 400] = "BadRequest"; - HttpCodes[HttpCodes["Unauthorized"] = 401] = "Unauthorized"; - HttpCodes[HttpCodes["PaymentRequired"] = 402] = "PaymentRequired"; - HttpCodes[HttpCodes["Forbidden"] = 403] = "Forbidden"; - HttpCodes[HttpCodes["NotFound"] = 404] = "NotFound"; - HttpCodes[HttpCodes["MethodNotAllowed"] = 405] = "MethodNotAllowed"; - HttpCodes[HttpCodes["NotAcceptable"] = 406] = "NotAcceptable"; - HttpCodes[HttpCodes["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; - HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout"; - HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict"; - HttpCodes[HttpCodes["Gone"] = 410] = "Gone"; - HttpCodes[HttpCodes["TooManyRequests"] = 429] = "TooManyRequests"; - HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError"; - HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented"; - HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway"; - HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable"; - HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout"; -})(HttpCodes || (exports.HttpCodes = HttpCodes = {})); -var Headers; -(function (Headers) { - Headers["Accept"] = "accept"; - Headers["ContentType"] = "content-type"; -})(Headers || (exports.Headers = Headers = {})); -var MediaTypes; -(function (MediaTypes) { - MediaTypes["ApplicationJson"] = "application/json"; -})(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 - */ -function getProxyUrl(serverUrl) { - const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); - return proxyUrl ? proxyUrl.href : ''; -} -exports.getProxyUrl = getProxyUrl; -const HttpRedirectCodes = [ - HttpCodes.MovedPermanently, - HttpCodes.ResourceMoved, - HttpCodes.SeeOther, - HttpCodes.TemporaryRedirect, - HttpCodes.PermanentRedirect -]; -const HttpResponseRetryCodes = [ - HttpCodes.BadGateway, - HttpCodes.ServiceUnavailable, - HttpCodes.GatewayTimeout -]; -const RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD']; -const ExponentialBackoffCeiling = 10; -const ExponentialBackoffTimeSlice = 5; -class HttpClientError extends Error { - constructor(message, statusCode) { - super(message); - this.name = 'HttpClientError'; - this.statusCode = statusCode; - Object.setPrototypeOf(this, HttpClientError.prototype); - } -} -exports.HttpClientError = HttpClientError; -class HttpClientResponse { - constructor(message) { - this.message = message; +exports.DefaultGlobber = void 0; +const core = __importStar(__nccwpck_require__(9093)); +const fs = __importStar(__nccwpck_require__(7147)); +const globOptionsHelper = __importStar(__nccwpck_require__(5228)); +const path = __importStar(__nccwpck_require__(1017)); +const patternHelper = __importStar(__nccwpck_require__(5677)); +const internal_match_kind_1 = __nccwpck_require__(4195); +const internal_pattern_1 = __nccwpck_require__(1548); +const internal_search_state_1 = __nccwpck_require__(5935); +const IS_WINDOWS = process.platform === 'win32'; +class DefaultGlobber { + constructor(options) { + this.patterns = []; + this.searchPaths = []; + this.options = globOptionsHelper.getOptions(options); } - readBody() { - return __awaiter(this, void 0, void 0, function* () { - return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () { - let output = Buffer.alloc(0); - this.message.on('data', (chunk) => { - output = Buffer.concat([output, chunk]); - }); - this.message.on('end', () => { - resolve(output.toString()); - }); - })); - }); + getSearchPaths() { + // Return a copy + return this.searchPaths.slice(); } - readBodyBuffer() { + glob() { + var e_1, _a; 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) { - const parsedUrl = new URL(requestUrl); - return parsedUrl.protocol === 'https:'; -} -exports.isHttps = isHttps; -class HttpClient { - constructor(userAgent, handlers, requestOptions) { - this._ignoreSslError = false; - this._allowRedirects = true; - this._allowRedirectDowngrade = false; - this._maxRedirects = 50; - this._allowRetries = false; - this._maxRetries = 1; - this._keepAlive = false; - this._disposed = false; - this.userAgent = userAgent; - this.handlers = handlers || []; - this.requestOptions = requestOptions; - if (requestOptions) { - if (requestOptions.ignoreSslError != null) { - this._ignoreSslError = requestOptions.ignoreSslError; - } - this._socketTimeout = requestOptions.socketTimeout; - if (requestOptions.allowRedirects != null) { - this._allowRedirects = requestOptions.allowRedirects; - } - if (requestOptions.allowRedirectDowngrade != null) { - this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; + const result = []; + try { + for (var _b = __asyncValues(this.globGenerator()), _c; _c = yield _b.next(), !_c.done;) { + const itemPath = _c.value; + result.push(itemPath); + } } - if (requestOptions.maxRedirects != null) { - this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (_c && !_c.done && (_a = _b.return)) yield _a.call(_b); + } + finally { if (e_1) throw e_1.error; } } - if (requestOptions.keepAlive != null) { - this._keepAlive = requestOptions.keepAlive; + return result; + }); + } + globGenerator() { + return __asyncGenerator(this, arguments, function* globGenerator_1() { + // Fill in defaults options + const options = globOptionsHelper.getOptions(this.options); + // Implicit descendants? + const patterns = []; + for (const pattern of this.patterns) { + patterns.push(pattern); + if (options.implicitDescendants && + (pattern.trailingSeparator || + pattern.segments[pattern.segments.length - 1] !== '**')) { + patterns.push(new internal_pattern_1.Pattern(pattern.negate, true, pattern.segments.concat('**'))); + } } - if (requestOptions.allowRetries != null) { - this._allowRetries = requestOptions.allowRetries; + // Push the search paths + const stack = []; + for (const searchPath of patternHelper.getSearchPaths(patterns)) { + core.debug(`Search path '${searchPath}'`); + // Exists? + try { + // Intentionally using lstat. Detection for broken symlink + // will be performed later (if following symlinks). + yield __await(fs.promises.lstat(searchPath)); + } + catch (err) { + if (err.code === 'ENOENT') { + continue; + } + throw err; + } + stack.unshift(new internal_search_state_1.SearchState(searchPath, 1)); } - if (requestOptions.maxRetries != null) { - this._maxRetries = requestOptions.maxRetries; + // Search + const traversalChain = []; // used to detect cycles + while (stack.length) { + // Pop + const item = stack.pop(); + // Match? + const match = patternHelper.match(patterns, item.path); + const partialMatch = !!match || patternHelper.partialMatch(patterns, item.path); + if (!match && !partialMatch) { + continue; + } + // Stat + const stats = yield __await(DefaultGlobber.stat(item, options, traversalChain) + // Broken symlink, or symlink cycle detected, or no longer exists + ); + // Broken symlink, or symlink cycle detected, or no longer exists + if (!stats) { + continue; + } + // Directory + if (stats.isDirectory()) { + // Matched + if (match & internal_match_kind_1.MatchKind.Directory) { + yield yield __await(item.path); + } + // Descend? + else if (!partialMatch) { + continue; + } + // Push the child items in reverse + const childLevel = item.level + 1; + const childItems = (yield __await(fs.promises.readdir(item.path))).map(x => new internal_search_state_1.SearchState(path.join(item.path, x), childLevel)); + stack.push(...childItems.reverse()); + } + // File + else if (match & internal_match_kind_1.MatchKind.File) { + yield yield __await(item.path); + } } - } - } - options(requestUrl, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('OPTIONS', requestUrl, null, additionalHeaders || {}); - }); - } - get(requestUrl, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('GET', requestUrl, null, additionalHeaders || {}); - }); - } - del(requestUrl, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('DELETE', requestUrl, null, additionalHeaders || {}); - }); - } - post(requestUrl, data, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('POST', requestUrl, data, additionalHeaders || {}); - }); - } - patch(requestUrl, data, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('PATCH', requestUrl, data, additionalHeaders || {}); - }); - } - put(requestUrl, data, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('PUT', requestUrl, data, additionalHeaders || {}); - }); - } - head(requestUrl, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('HEAD', requestUrl, null, additionalHeaders || {}); - }); - } - sendStream(verb, requestUrl, stream, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request(verb, requestUrl, stream, additionalHeaders); }); } /** - * Gets a typed object from an endpoint - * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + * Constructs a DefaultGlobber */ - getJson(requestUrl, additionalHeaders = {}) { + static create(patterns, options) { return __awaiter(this, void 0, void 0, function* () { - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - const res = yield this.get(requestUrl, additionalHeaders); - return this._processResponse(res, this.requestOptions); + const result = new DefaultGlobber(options); + if (IS_WINDOWS) { + patterns = patterns.replace(/\r\n/g, '\n'); + patterns = patterns.replace(/\r/g, '\n'); + } + const lines = patterns.split('\n').map(x => x.trim()); + for (const line of lines) { + // Empty or comment + if (!line || line.startsWith('#')) { + continue; + } + // Pattern + else { + result.patterns.push(new internal_pattern_1.Pattern(line)); + } + } + result.searchPaths.push(...patternHelper.getSearchPaths(result.patterns)); + return result; }); } - postJson(requestUrl, obj, additionalHeaders = {}) { + static stat(item, options, traversalChain) { return __awaiter(this, void 0, void 0, function* () { - const data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); - const res = yield this.post(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); + // Note: + // `stat` returns info about the target of a symlink (or symlink chain) + // `lstat` returns info about a symlink itself + let stats; + if (options.followSymbolicLinks) { + try { + // Use `stat` (following symlinks) + stats = yield fs.promises.stat(item.path); + } + catch (err) { + if (err.code === 'ENOENT') { + if (options.omitBrokenSymbolicLinks) { + core.debug(`Broken symlink '${item.path}'`); + return undefined; + } + throw new Error(`No information found for the path '${item.path}'. This may indicate a broken symbolic link.`); + } + throw err; + } + } + else { + // Use `lstat` (not following symlinks) + stats = yield fs.promises.lstat(item.path); + } + // Note, isDirectory() returns false for the lstat of a symlink + if (stats.isDirectory() && options.followSymbolicLinks) { + // Get the realpath + const realPath = yield fs.promises.realpath(item.path); + // Fixup the traversal chain to match the item level + while (traversalChain.length >= item.level) { + traversalChain.pop(); + } + // Test for a cycle + if (traversalChain.some((x) => x === realPath)) { + core.debug(`Symlink cycle detected for path '${item.path}' and realpath '${realPath}'`); + return undefined; + } + // Update the traversal chain + traversalChain.push(realPath); + } + return stats; }); } - putJson(requestUrl, obj, additionalHeaders = {}) { - return __awaiter(this, void 0, void 0, function* () { - const data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); - const res = yield this.put(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - }); +} +exports.DefaultGlobber = DefaultGlobber; +//# sourceMappingURL=internal-globber.js.map + +/***/ }), + +/***/ 4195: +/***/ ((__unused_webpack_module, exports) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.MatchKind = void 0; +/** + * Indicates whether a pattern matches a path + */ +var MatchKind; +(function (MatchKind) { + /** Not matched */ + MatchKind[MatchKind["None"] = 0] = "None"; + /** Matched if the path is a directory */ + MatchKind[MatchKind["Directory"] = 1] = "Directory"; + /** Matched if the path is a regular file */ + MatchKind[MatchKind["File"] = 2] = "File"; + /** Matched */ + MatchKind[MatchKind["All"] = 3] = "All"; +})(MatchKind = exports.MatchKind || (exports.MatchKind = {})); +//# sourceMappingURL=internal-match-kind.js.map + +/***/ }), + +/***/ 8155: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + +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.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": 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__(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. + * + * For example, on Linux/macOS: + * - `/ => /` + * - `/hello => /` + * + * For example, on Windows: + * - `C:\ => C:\` + * - `C:\hello => C:\` + * - `C: => C:` + * - `C:hello => C:` + * - `\ => \` + * - `\hello => \` + * - `\\hello => \\hello` + * - `\\hello\world => \\hello\world` + */ +function dirname(p) { + // Normalize slashes and trim unnecessary trailing slash + p = safeTrimTrailingSeparator(p); + // Windows UNC root, e.g. \\hello or \\hello\world + if (IS_WINDOWS && /^\\\\[^\\]+(\\[^\\]+)?$/.test(p)) { + return p; } - patchJson(requestUrl, obj, additionalHeaders = {}) { - return __awaiter(this, void 0, void 0, function* () { - const data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); - const res = yield this.patch(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - }); + // Get dirname + let result = path.dirname(p); + // Trim trailing slash for Windows UNC root, e.g. \\hello\world\ + if (IS_WINDOWS && /^\\\\[^\\]+\\[^\\]+\\$/.test(result)) { + result = safeTrimTrailingSeparator(result); } - /** - * Makes a raw http request. - * All other methods such as get, post, patch, and request ultimately call this. - * Prefer get, del, post and patch - */ - request(verb, requestUrl, data, headers) { - return __awaiter(this, void 0, void 0, function* () { - if (this._disposed) { - throw new Error('Client has already been disposed.'); - } - const parsedUrl = new URL(requestUrl); - let info = this._prepareRequest(verb, parsedUrl, headers); - // Only perform retries on reads since writes may not be idempotent. - const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) - ? this._maxRetries + 1 - : 1; - let numTries = 0; - let response; - do { - response = yield this.requestRaw(info, data); - // Check if it's an authentication challenge - if (response && - response.message && - response.message.statusCode === HttpCodes.Unauthorized) { - let authenticationHandler; - for (const handler of this.handlers) { - if (handler.canHandleAuthentication(response)) { - authenticationHandler = handler; - break; - } - } - if (authenticationHandler) { - return authenticationHandler.handleAuthentication(this, info, data); - } - else { - // We have received an unauthorized response but have no handlers to handle it. - // Let the response return to the caller. - return response; - } + return result; +} +exports.dirname = dirname; +/** + * Roots the path if not already rooted. On Windows, relative roots like `\` + * or `C:` are expanded based on the current working directory. + */ +function ensureAbsoluteRoot(root, itemPath) { + assert_1.default(root, `ensureAbsoluteRoot parameter 'root' must not be empty`); + assert_1.default(itemPath, `ensureAbsoluteRoot parameter 'itemPath' must not be empty`); + // Already rooted + if (hasAbsoluteRoot(itemPath)) { + return itemPath; + } + // Windows + if (IS_WINDOWS) { + // Check for itemPath like C: or C:foo + if (itemPath.match(/^[A-Z]:[^\\/]|^[A-Z]:$/i)) { + let cwd = process.cwd(); + assert_1.default(cwd.match(/^[A-Z]:\\/i), `Expected current directory to start with an absolute drive root. Actual '${cwd}'`); + // Drive letter matches cwd? Expand to cwd + if (itemPath[0].toUpperCase() === cwd[0].toUpperCase()) { + // Drive only, e.g. C: + if (itemPath.length === 2) { + // Preserve specified drive letter case (upper or lower) + return `${itemPath[0]}:\\${cwd.substr(3)}`; } - let redirectsRemaining = this._maxRedirects; - while (response.message.statusCode && - HttpRedirectCodes.includes(response.message.statusCode) && - this._allowRedirects && - redirectsRemaining > 0) { - const redirectUrl = response.message.headers['location']; - if (!redirectUrl) { - // if there's no location to redirect to, we won't - break; - } - const parsedRedirectUrl = new URL(redirectUrl); - if (parsedUrl.protocol === 'https:' && - parsedUrl.protocol !== parsedRedirectUrl.protocol && - !this._allowRedirectDowngrade) { - throw new Error('Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.'); - } - // we need to finish reading the response before reassigning response - // which will leak the open socket. - yield response.readBody(); - // strip authorization header if redirected to a different hostname - if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { - for (const header in headers) { - // header names are case insensitive - if (header.toLowerCase() === 'authorization') { - delete headers[header]; - } - } + // Drive + path, e.g. C:foo + else { + if (!cwd.endsWith('\\')) { + cwd += '\\'; } - // let's make the request with the new redirectUrl - info = this._prepareRequest(verb, parsedRedirectUrl, headers); - response = yield this.requestRaw(info, data); - redirectsRemaining--; - } - if (!response.message.statusCode || - !HttpResponseRetryCodes.includes(response.message.statusCode)) { - // If not a retry code, return immediately instead of retrying - return response; - } - numTries += 1; - if (numTries < maxTries) { - yield response.readBody(); - yield this._performExponentialBackoff(numTries); + // Preserve specified drive letter case (upper or lower) + return `${itemPath[0]}:\\${cwd.substr(3)}${itemPath.substr(2)}`; } - } while (numTries < maxTries); - return response; - }); - } - /** - * Needs to be called if keepAlive is set to true in request options. - */ - dispose() { - if (this._agent) { - this._agent.destroy(); + } + // Different drive + else { + return `${itemPath[0]}:\\${itemPath.substr(2)}`; + } + } + // Check for itemPath like \ or \foo + else if (normalizeSeparators(itemPath).match(/^\\$|^\\[^\\]/)) { + const cwd = process.cwd(); + assert_1.default(cwd.match(/^[A-Z]:\\/i), `Expected current directory to start with an absolute drive root. Actual '${cwd}'`); + return `${cwd[0]}:\\${itemPath.substr(1)}`; } - this._disposed = true; } - /** - * Raw request. - * @param info - * @param data - */ - requestRaw(info, data) { - return __awaiter(this, void 0, void 0, function* () { - return new Promise((resolve, reject) => { - function callbackForResult(err, res) { - if (err) { - reject(err); - } - else if (!res) { - // If `err` is not passed, then `res` must be passed. - reject(new Error('Unknown error')); - } - else { - resolve(res); - } - } - this.requestRawWithCallback(info, data, callbackForResult); - }); - }); + assert_1.default(hasAbsoluteRoot(root), `ensureAbsoluteRoot parameter 'root' must have an absolute root`); + // Otherwise ensure root ends with a separator + if (root.endsWith('/') || (IS_WINDOWS && root.endsWith('\\'))) { + // Intentionally empty + } + else { + // Append separator + root += path.sep; + } + return root + itemPath; +} +exports.ensureAbsoluteRoot = ensureAbsoluteRoot; +/** + * On Linux/macOS, true if path starts with `/`. On Windows, true for paths like: + * `\\hello\share` and `C:\hello` (and using alternate separator). + */ +function hasAbsoluteRoot(itemPath) { + assert_1.default(itemPath, `hasAbsoluteRoot parameter 'itemPath' must not be empty`); + // Normalize separators + itemPath = normalizeSeparators(itemPath); + // Windows + if (IS_WINDOWS) { + // E.g. \\hello\share or C:\hello + return itemPath.startsWith('\\\\') || /^[A-Z]:\\/i.test(itemPath); + } + // E.g. /hello + return itemPath.startsWith('/'); +} +exports.hasAbsoluteRoot = hasAbsoluteRoot; +/** + * On Linux/macOS, true if path starts with `/`. On Windows, true for paths like: + * `\`, `\hello`, `\\hello\share`, `C:`, and `C:\hello` (and using alternate separator). + */ +function hasRoot(itemPath) { + assert_1.default(itemPath, `isRooted parameter 'itemPath' must not be empty`); + // Normalize separators + itemPath = normalizeSeparators(itemPath); + // Windows + if (IS_WINDOWS) { + // E.g. \ or \hello or \\hello + // E.g. C: or C:\hello + return itemPath.startsWith('\\') || /^[A-Z]:/i.test(itemPath); + } + // E.g. /hello + return itemPath.startsWith('/'); +} +exports.hasRoot = hasRoot; +/** + * Removes redundant slashes and converts `/` to `\` on Windows + */ +function normalizeSeparators(p) { + p = p || ''; + // Windows + if (IS_WINDOWS) { + // Convert slashes on Windows + p = p.replace(/\//g, '\\'); + // Remove redundant slashes + const isUnc = /^\\\\+[^\\]/.test(p); // e.g. \\hello + return (isUnc ? '\\' : '') + p.replace(/\\\\+/g, '\\'); // preserve leading \\ for UNC } + // Remove redundant slashes + return p.replace(/\/\/+/g, '/'); +} +exports.normalizeSeparators = normalizeSeparators; +/** + * Normalizes the path separators and trims the trailing separator (when safe). + * For example, `/foo/ => /foo` but `/ => /` + */ +function safeTrimTrailingSeparator(p) { + // Short-circuit if empty + if (!p) { + return ''; + } + // Normalize separators + p = normalizeSeparators(p); + // No trailing slash + if (!p.endsWith(path.sep)) { + return p; + } + // Check '/' on Linux/macOS and '\' on Windows + if (p === path.sep) { + return p; + } + // On Windows check if drive root. E.g. C:\ + if (IS_WINDOWS && /^[A-Z]:\\$/i.test(p)) { + return p; + } + // Otherwise trim trailing slash + return p.substr(0, p.length - 1); +} +exports.safeTrimTrailingSeparator = safeTrimTrailingSeparator; +//# sourceMappingURL=internal-path-helper.js.map + +/***/ }), + +/***/ 4674: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + +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.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Path = void 0; +const path = __importStar(__nccwpck_require__(1017)); +const pathHelper = __importStar(__nccwpck_require__(8155)); +const assert_1 = __importDefault(__nccwpck_require__(9491)); +const IS_WINDOWS = process.platform === 'win32'; +/** + * Helper class for parsing paths into segments + */ +class Path { /** - * Raw request with callback. - * @param info - * @param data - * @param onResult + * Constructs a Path + * @param itemPath Path or array of segments */ - requestRawWithCallback(info, data, onResult) { - if (typeof data === 'string') { - if (!info.options.headers) { - info.options.headers = {}; - } - info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8'); - } - let callbackCalled = false; - function handleResult(err, res) { - if (!callbackCalled) { - callbackCalled = true; - onResult(err, res); + constructor(itemPath) { + this.segments = []; + // String + if (typeof itemPath === 'string') { + assert_1.default(itemPath, `Parameter 'itemPath' must not be empty`); + // Normalize slashes and trim unnecessary trailing slash + itemPath = pathHelper.safeTrimTrailingSeparator(itemPath); + // Not rooted + if (!pathHelper.hasRoot(itemPath)) { + this.segments = itemPath.split(path.sep); } - } - const req = info.httpModule.request(info.options, (msg) => { - const res = new HttpClientResponse(msg); - handleResult(undefined, res); - }); - let socket; - req.on('socket', sock => { - socket = sock; - }); - // If we ever get disconnected, we want the socket to timeout eventually - req.setTimeout(this._socketTimeout || 3 * 60000, () => { - if (socket) { - socket.end(); + // Rooted + else { + // Add all segments, while not at the root + let remaining = itemPath; + let dir = pathHelper.dirname(remaining); + while (dir !== remaining) { + // Add the segment + const basename = path.basename(remaining); + this.segments.unshift(basename); + // Truncate the last segment + remaining = dir; + dir = pathHelper.dirname(remaining); + } + // Remainder is the root + this.segments.unshift(remaining); } - handleResult(new Error(`Request timeout: ${info.options.path}`)); - }); - req.on('error', function (err) { - // err has statusCode property - // res should have headers - handleResult(err); - }); - if (data && typeof data === 'string') { - req.write(data, 'utf8'); - } - if (data && typeof data !== 'string') { - data.on('close', function () { - req.end(); - }); - data.pipe(req); } + // Array else { - req.end(); + // Must not be empty + assert_1.default(itemPath.length > 0, `Parameter 'itemPath' must not be an empty array`); + // Each segment + for (let i = 0; i < itemPath.length; i++) { + let segment = itemPath[i]; + // Must not be empty + assert_1.default(segment, `Parameter 'itemPath' must not contain any empty segments`); + // Normalize slashes + segment = pathHelper.normalizeSeparators(itemPath[i]); + // Root segment + if (i === 0 && pathHelper.hasRoot(segment)) { + segment = pathHelper.safeTrimTrailingSeparator(segment); + assert_1.default(segment === pathHelper.dirname(segment), `Parameter 'itemPath' root segment contains information for multiple segments`); + this.segments.push(segment); + } + // All other segments + else { + // Must not contain slash + assert_1.default(!segment.includes(path.sep), `Parameter 'itemPath' contains unexpected path separators`); + this.segments.push(segment); + } + } } } /** - * Gets an http agent. This function is useful when you need an http agent that handles - * routing through a proxy server - depending upon the url and proxy environment variables. - * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + * Converts the path to it's string representation */ - getAgent(serverUrl) { - 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; - const usingSsl = info.parsedUrl.protocol === 'https:'; - info.httpModule = usingSsl ? https : http; - const defaultPort = usingSsl ? 443 : 80; - info.options = {}; - info.options.host = info.parsedUrl.hostname; - info.options.port = info.parsedUrl.port - ? parseInt(info.parsedUrl.port) - : defaultPort; - info.options.path = - (info.parsedUrl.pathname || '') + (info.parsedUrl.search || ''); - info.options.method = method; - info.options.headers = this._mergeHeaders(headers); - if (this.userAgent != null) { - info.options.headers['user-agent'] = this.userAgent; - } - info.options.agent = this._getAgent(info.parsedUrl); - // gives handlers an opportunity to participate - if (this.handlers) { - for (const handler of this.handlers) { - handler.prepareRequest(info.options); - } - } - return info; - } - _mergeHeaders(headers) { - if (this.requestOptions && this.requestOptions.headers) { - return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); - } - return lowercaseKeys(headers || {}); - } - _getExistingOrDefaultHeader(additionalHeaders, header, _default) { - let clientHeader; - if (this.requestOptions && this.requestOptions.headers) { - clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; - } - return additionalHeaders[header] || clientHeader || _default; - } - _getAgent(parsedUrl) { - let agent; - const proxyUrl = pm.getProxyUrl(parsedUrl); - const useProxy = proxyUrl && proxyUrl.hostname; - if (this._keepAlive && useProxy) { - agent = this._proxyAgent; - } - if (!useProxy) { - agent = this._agent; - } - // if agent is already assigned use that agent. - if (agent) { - return agent; - } - const usingSsl = parsedUrl.protocol === 'https:'; - let maxSockets = 100; - if (this.requestOptions) { - maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; - } - // This is `useProxy` again, but we need to check `proxyURl` directly for TypeScripts's flow analysis. - if (proxyUrl && proxyUrl.hostname) { - const agentOptions = { - maxSockets, - keepAlive: this._keepAlive, - proxy: Object.assign(Object.assign({}, ((proxyUrl.username || proxyUrl.password) && { - proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` - })), { host: proxyUrl.hostname, port: proxyUrl.port }) - }; - let tunnelAgent; - const overHttps = proxyUrl.protocol === 'https:'; - if (usingSsl) { - tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; - } - else { - tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; - } - agent = tunnelAgent(agentOptions); - this._proxyAgent = agent; - } - // if tunneling agent isn't assigned create a new agent - if (!agent) { - const options = { keepAlive: this._keepAlive, maxSockets }; - agent = usingSsl ? new https.Agent(options) : new http.Agent(options); - this._agent = agent; - } - 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 - agent.options = Object.assign(agent.options || {}, { - rejectUnauthorized: false - }); - } - 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); - const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); - return new Promise(resolve => setTimeout(() => resolve(), ms)); - }); - } - _processResponse(res, options) { - return __awaiter(this, void 0, void 0, function* () { - return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { - const statusCode = res.message.statusCode || 0; - const response = { - statusCode, - result: null, - headers: {} - }; - // not found leads to null obj returned - if (statusCode === HttpCodes.NotFound) { - resolve(response); - } - // get the result from the body - function dateTimeDeserializer(key, value) { - if (typeof value === 'string') { - const a = new Date(value); - if (!isNaN(a.valueOf())) { - return a; - } - } - return value; - } - let obj; - let contents; - try { - contents = yield res.readBody(); - if (contents && contents.length > 0) { - if (options && options.deserializeDates) { - obj = JSON.parse(contents, dateTimeDeserializer); - } - else { - obj = JSON.parse(contents); - } - response.result = obj; - } - response.headers = res.message.headers; - } - catch (err) { - // Invalid resource (contents not json); leaving result obj null - } - // note that 3xx redirects are handled by the http layer. - if (statusCode > 299) { - let msg; - // if exception/error in body, attempt to get better error - if (obj && obj.message) { - msg = obj.message; - } - else if (contents && contents.length > 0) { - // it may be the case that the exception is in the body message as string - msg = contents; - } - else { - msg = `Failed request: (${statusCode})`; - } - const err = new HttpClientError(msg, statusCode); - err.result = response.result; - reject(err); - } - else { - resolve(response); - } - })); - }); + toString() { + // First segment + let result = this.segments[0]; + // All others + let skipSlash = result.endsWith(path.sep) || (IS_WINDOWS && /^[A-Z]:$/i.test(result)); + for (let i = 1; i < this.segments.length; i++) { + if (skipSlash) { + skipSlash = false; + } + else { + result += path.sep; + } + result += this.segments[i]; + } + return result; } } -exports.HttpClient = HttpClient; -const lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); -//# sourceMappingURL=index.js.map +exports.Path = Path; +//# sourceMappingURL=internal-path.js.map /***/ }), -/***/ 2067: -/***/ ((__unused_webpack_module, exports) => { +/***/ 5677: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +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.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.checkBypass = exports.getProxyUrl = void 0; -function getProxyUrl(reqUrl) { - const usingSsl = reqUrl.protocol === 'https:'; - if (checkBypass(reqUrl)) { - return undefined; +exports.partialMatch = exports.match = exports.getSearchPaths = void 0; +const pathHelper = __importStar(__nccwpck_require__(8155)); +const internal_match_kind_1 = __nccwpck_require__(4195); +const IS_WINDOWS = process.platform === 'win32'; +/** + * Given an array of patterns, returns an array of paths to search. + * Duplicates and paths under other included paths are filtered out. + */ +function getSearchPaths(patterns) { + // Ignore negate patterns + patterns = patterns.filter(x => !x.negate); + // Create a map of all search paths + const searchPathMap = {}; + for (const pattern of patterns) { + const key = IS_WINDOWS + ? pattern.searchPath.toUpperCase() + : pattern.searchPath; + searchPathMap[key] = 'candidate'; } - const proxyVar = (() => { - if (usingSsl) { - return process.env['https_proxy'] || process.env['HTTPS_PROXY']; - } - else { - return process.env['http_proxy'] || process.env['HTTP_PROXY']; - } - })(); - if (proxyVar) { - try { - return new URL(proxyVar); + const result = []; + for (const pattern of patterns) { + // Check if already included + const key = IS_WINDOWS + ? pattern.searchPath.toUpperCase() + : pattern.searchPath; + if (searchPathMap[key] === 'included') { + continue; } - catch (_a) { - if (!proxyVar.startsWith('http://') && !proxyVar.startsWith('https://')) - return new URL(`http://${proxyVar}`); + // Check for an ancestor search path + let foundAncestor = false; + let tempKey = key; + let parent = pathHelper.dirname(tempKey); + while (parent !== tempKey) { + if (searchPathMap[parent]) { + foundAncestor = true; + break; + } + tempKey = parent; + parent = pathHelper.dirname(tempKey); } - } - else { - return undefined; - } -} -exports.getProxyUrl = getProxyUrl; -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; - } - // Determine the request port - let reqPort; - if (reqUrl.port) { - reqPort = Number(reqUrl.port); - } - else if (reqUrl.protocol === 'http:') { - reqPort = 80; - } - else if (reqUrl.protocol === 'https:') { - reqPort = 443; - } - // Format the request hostname and hostname with port - const upperReqHosts = [reqUrl.hostname.toUpperCase()]; - if (typeof reqPort === 'number') { - upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); - } - // Compare request host against noproxy - for (const upperNoProxyItem of noProxy - .split(',') - .map(x => x.trim().toUpperCase()) - .filter(x => x)) { - if (upperNoProxyItem === '*' || - upperReqHosts.some(x => x === upperNoProxyItem || - x.endsWith(`.${upperNoProxyItem}`) || - (upperNoProxyItem.startsWith('.') && - x.endsWith(`${upperNoProxyItem}`)))) { - return true; + // Include the search pattern in the result + if (!foundAncestor) { + result.push(pattern.searchPath); + searchPathMap[key] = 'included'; } } - 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]')); + return result; } -//# sourceMappingURL=proxy.js.map - -/***/ }), - -/***/ 2177: -/***/ (function(__unused_webpack_module, exports) { - - -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.PersonalAccessTokenCredentialHandler = exports.BearerCredentialHandler = exports.BasicCredentialHandler = void 0; -class BasicCredentialHandler { - constructor(username, password) { - this.username = username; - this.password = password; - } - prepareRequest(options) { - if (!options.headers) { - throw Error('The request has no headers'); +exports.getSearchPaths = getSearchPaths; +/** + * Matches the patterns against the path + */ +function match(patterns, itemPath) { + let result = internal_match_kind_1.MatchKind.None; + for (const pattern of patterns) { + if (pattern.negate) { + result &= ~pattern.match(itemPath); } - options.headers['Authorization'] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString('base64')}`; - } - // This handler cannot handle 401 - canHandleAuthentication() { - return false; - } - handleAuthentication() { - return __awaiter(this, void 0, void 0, function* () { - throw new Error('not implemented'); - }); - } -} -exports.BasicCredentialHandler = BasicCredentialHandler; -class BearerCredentialHandler { - constructor(token) { - this.token = token; - } - // currently implements pre-authorization - // TODO: support preAuth = false where it hooks on 401 - prepareRequest(options) { - if (!options.headers) { - throw Error('The request has no headers'); + else { + result |= pattern.match(itemPath); } - options.headers['Authorization'] = `Bearer ${this.token}`; - } - // This handler cannot handle 401 - canHandleAuthentication() { - return false; - } - handleAuthentication() { - return __awaiter(this, void 0, void 0, function* () { - throw new Error('not implemented'); - }); } + return result; } -exports.BearerCredentialHandler = BearerCredentialHandler; -class PersonalAccessTokenCredentialHandler { - constructor(token) { - this.token = token; - } - // currently implements pre-authorization - // TODO: support preAuth = false where it hooks on 401 - prepareRequest(options) { - if (!options.headers) { - throw Error('The request has no headers'); - } - options.headers['Authorization'] = `Basic ${Buffer.from(`PAT:${this.token}`).toString('base64')}`; - } - // This handler cannot handle 401 - canHandleAuthentication() { - return false; - } - handleAuthentication() { - return __awaiter(this, void 0, void 0, function* () { - throw new Error('not implemented'); - }); - } +exports.match = match; +/** + * Checks whether to descend further into the directory + */ +function partialMatch(patterns, itemPath) { + return patterns.some(x => !x.negate && x.partialMatch(itemPath)); } -exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler; -//# sourceMappingURL=auth.js.map +exports.partialMatch = partialMatch; +//# sourceMappingURL=internal-pattern-helper.js.map /***/ }), -/***/ 6634: +/***/ 1548: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { -/* eslint-disable @typescript-eslint/no-explicit-any */ 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); + 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]; @@ -5384,69 +5287,439 @@ 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.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + if (mod != null) for (var k in mod) if (k !== "default" && Object.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()); - }); +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; }; 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__(3685)); -const https = __importStar(__nccwpck_require__(5687)); -const pm = __importStar(__nccwpck_require__(4318)); -const tunnel = __importStar(__nccwpck_require__(4225)); -const undici_1 = __nccwpck_require__(7181); -var HttpCodes; -(function (HttpCodes) { - HttpCodes[HttpCodes["OK"] = 200] = "OK"; - HttpCodes[HttpCodes["MultipleChoices"] = 300] = "MultipleChoices"; - HttpCodes[HttpCodes["MovedPermanently"] = 301] = "MovedPermanently"; - HttpCodes[HttpCodes["ResourceMoved"] = 302] = "ResourceMoved"; - HttpCodes[HttpCodes["SeeOther"] = 303] = "SeeOther"; - HttpCodes[HttpCodes["NotModified"] = 304] = "NotModified"; - HttpCodes[HttpCodes["UseProxy"] = 305] = "UseProxy"; - HttpCodes[HttpCodes["SwitchProxy"] = 306] = "SwitchProxy"; - HttpCodes[HttpCodes["TemporaryRedirect"] = 307] = "TemporaryRedirect"; - HttpCodes[HttpCodes["PermanentRedirect"] = 308] = "PermanentRedirect"; - HttpCodes[HttpCodes["BadRequest"] = 400] = "BadRequest"; - HttpCodes[HttpCodes["Unauthorized"] = 401] = "Unauthorized"; - HttpCodes[HttpCodes["PaymentRequired"] = 402] = "PaymentRequired"; - HttpCodes[HttpCodes["Forbidden"] = 403] = "Forbidden"; - HttpCodes[HttpCodes["NotFound"] = 404] = "NotFound"; - HttpCodes[HttpCodes["MethodNotAllowed"] = 405] = "MethodNotAllowed"; - HttpCodes[HttpCodes["NotAcceptable"] = 406] = "NotAcceptable"; - HttpCodes[HttpCodes["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; - HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout"; - HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict"; - HttpCodes[HttpCodes["Gone"] = 410] = "Gone"; - HttpCodes[HttpCodes["TooManyRequests"] = 429] = "TooManyRequests"; - HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError"; - HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented"; - HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway"; - HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable"; - HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout"; -})(HttpCodes || (exports.HttpCodes = HttpCodes = {})); -var Headers; -(function (Headers) { - Headers["Accept"] = "accept"; - Headers["ContentType"] = "content-type"; -})(Headers || (exports.Headers = Headers = {})); -var MediaTypes; -(function (MediaTypes) { - MediaTypes["ApplicationJson"] = "application/json"; -})(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 - */ +exports.Pattern = void 0; +const os = __importStar(__nccwpck_require__(2037)); +const path = __importStar(__nccwpck_require__(1017)); +const pathHelper = __importStar(__nccwpck_require__(8155)); +const assert_1 = __importDefault(__nccwpck_require__(9491)); +const minimatch_1 = __nccwpck_require__(7151); +const internal_match_kind_1 = __nccwpck_require__(4195); +const internal_path_1 = __nccwpck_require__(4674); +const IS_WINDOWS = process.platform === 'win32'; +class Pattern { + constructor(patternOrNegate, isImplicitPattern = false, segments, homedir) { + /** + * Indicates whether matches should be excluded from the result set + */ + this.negate = false; + // Pattern overload + let pattern; + if (typeof patternOrNegate === 'string') { + pattern = patternOrNegate.trim(); + } + // Segments overload + else { + // Convert to pattern + segments = segments || []; + assert_1.default(segments.length, `Parameter 'segments' must not empty`); + const root = Pattern.getLiteral(segments[0]); + assert_1.default(root && pathHelper.hasAbsoluteRoot(root), `Parameter 'segments' first element must be a root path`); + pattern = new internal_path_1.Path(segments).toString().trim(); + if (patternOrNegate) { + pattern = `!${pattern}`; + } + } + // Negate + while (pattern.startsWith('!')) { + this.negate = !this.negate; + pattern = pattern.substr(1).trim(); + } + // Normalize slashes and ensures absolute root + pattern = Pattern.fixupPattern(pattern, homedir); + // Segments + this.segments = new internal_path_1.Path(pattern).segments; + // Trailing slash indicates the pattern should only match directories, not regular files + this.trailingSeparator = pathHelper + .normalizeSeparators(pattern) + .endsWith(path.sep); + pattern = pathHelper.safeTrimTrailingSeparator(pattern); + // Search path (literal path prior to the first glob segment) + let foundGlob = false; + const searchSegments = this.segments + .map(x => Pattern.getLiteral(x)) + .filter(x => !foundGlob && !(foundGlob = x === '')); + this.searchPath = new internal_path_1.Path(searchSegments).toString(); + // Root RegExp (required when determining partial match) + this.rootRegExp = new RegExp(Pattern.regExpEscape(searchSegments[0]), IS_WINDOWS ? 'i' : ''); + this.isImplicitPattern = isImplicitPattern; + // Create minimatch + const minimatchOptions = { + dot: true, + nobrace: true, + nocase: IS_WINDOWS, + nocomment: true, + noext: true, + nonegate: true + }; + pattern = IS_WINDOWS ? pattern.replace(/\\/g, '/') : pattern; + this.minimatch = new minimatch_1.Minimatch(pattern, minimatchOptions); + } + /** + * Matches the pattern against the specified path + */ + match(itemPath) { + // Last segment is globstar? + if (this.segments[this.segments.length - 1] === '**') { + // Normalize slashes + itemPath = pathHelper.normalizeSeparators(itemPath); + // Append a trailing slash. Otherwise Minimatch will not match the directory immediately + // preceding the globstar. For example, given the pattern `/foo/**`, Minimatch returns + // false for `/foo` but returns true for `/foo/`. Append a trailing slash to handle that quirk. + if (!itemPath.endsWith(path.sep) && this.isImplicitPattern === false) { + // Note, this is safe because the constructor ensures the pattern has an absolute root. + // For example, formats like C: and C:foo on Windows are resolved to an absolute root. + itemPath = `${itemPath}${path.sep}`; + } + } + else { + // Normalize slashes and trim unnecessary trailing slash + itemPath = pathHelper.safeTrimTrailingSeparator(itemPath); + } + // Match + if (this.minimatch.match(itemPath)) { + return this.trailingSeparator ? internal_match_kind_1.MatchKind.Directory : internal_match_kind_1.MatchKind.All; + } + return internal_match_kind_1.MatchKind.None; + } + /** + * Indicates whether the pattern may match descendants of the specified path + */ + partialMatch(itemPath) { + // Normalize slashes and trim unnecessary trailing slash + itemPath = pathHelper.safeTrimTrailingSeparator(itemPath); + // matchOne does not handle root path correctly + if (pathHelper.dirname(itemPath) === itemPath) { + return this.rootRegExp.test(itemPath); + } + return this.minimatch.matchOne(itemPath.split(IS_WINDOWS ? /\\+/ : /\/+/), this.minimatch.set[0], true); + } + /** + * Escapes glob patterns within a path + */ + static globEscape(s) { + return (IS_WINDOWS ? s : s.replace(/\\/g, '\\\\')) // escape '\' on Linux/macOS + .replace(/(\[)(?=[^/]+\])/g, '[[]') // escape '[' when ']' follows within the path segment + .replace(/\?/g, '[?]') // escape '?' + .replace(/\*/g, '[*]'); // escape '*' + } + /** + * Normalizes slashes and ensures absolute root + */ + static fixupPattern(pattern, homedir) { + // Empty + assert_1.default(pattern, 'pattern cannot be empty'); + // Must not contain `.` segment, unless first segment + // Must not contain `..` segment + const literalSegments = new internal_path_1.Path(pattern).segments.map(x => Pattern.getLiteral(x)); + assert_1.default(literalSegments.every((x, i) => (x !== '.' || i === 0) && x !== '..'), `Invalid pattern '${pattern}'. Relative pathing '.' and '..' is not allowed.`); + // Must not contain globs in root, e.g. Windows UNC path \\foo\b*r + assert_1.default(!pathHelper.hasRoot(pattern) || literalSegments[0], `Invalid pattern '${pattern}'. Root segment must not contain globs.`); + // Normalize slashes + pattern = pathHelper.normalizeSeparators(pattern); + // Replace leading `.` segment + if (pattern === '.' || pattern.startsWith(`.${path.sep}`)) { + pattern = Pattern.globEscape(process.cwd()) + pattern.substr(1); + } + // Replace leading `~` segment + else if (pattern === '~' || pattern.startsWith(`~${path.sep}`)) { + homedir = homedir || os.homedir(); + assert_1.default(homedir, 'Unable to determine HOME directory'); + assert_1.default(pathHelper.hasAbsoluteRoot(homedir), `Expected HOME directory to be a rooted path. Actual '${homedir}'`); + pattern = Pattern.globEscape(homedir) + pattern.substr(1); + } + // Replace relative drive root, e.g. pattern is C: or C:foo + else if (IS_WINDOWS && + (pattern.match(/^[A-Z]:$/i) || pattern.match(/^[A-Z]:[^\\]/i))) { + let root = pathHelper.ensureAbsoluteRoot('C:\\dummy-root', pattern.substr(0, 2)); + if (pattern.length > 2 && !root.endsWith('\\')) { + root += '\\'; + } + pattern = Pattern.globEscape(root) + pattern.substr(2); + } + // Replace relative root, e.g. pattern is \ or \foo + else if (IS_WINDOWS && (pattern === '\\' || pattern.match(/^\\[^\\]/))) { + let root = pathHelper.ensureAbsoluteRoot('C:\\dummy-root', '\\'); + if (!root.endsWith('\\')) { + root += '\\'; + } + pattern = Pattern.globEscape(root) + pattern.substr(1); + } + // Otherwise ensure absolute root + else { + pattern = pathHelper.ensureAbsoluteRoot(Pattern.globEscape(process.cwd()), pattern); + } + return pathHelper.normalizeSeparators(pattern); + } + /** + * Attempts to unescape a pattern segment to create a literal path segment. + * Otherwise returns empty string. + */ + static getLiteral(segment) { + let literal = ''; + for (let i = 0; i < segment.length; i++) { + const c = segment[i]; + // Escape + if (c === '\\' && !IS_WINDOWS && i + 1 < segment.length) { + literal += segment[++i]; + continue; + } + // Wildcard + else if (c === '*' || c === '?') { + return ''; + } + // Character set + else if (c === '[' && i + 1 < segment.length) { + let set = ''; + let closed = -1; + for (let i2 = i + 1; i2 < segment.length; i2++) { + const c2 = segment[i2]; + // Escape + if (c2 === '\\' && !IS_WINDOWS && i2 + 1 < segment.length) { + set += segment[++i2]; + continue; + } + // Closed + else if (c2 === ']') { + closed = i2; + break; + } + // Otherwise + else { + set += c2; + } + } + // Closed? + if (closed >= 0) { + // Cannot convert + if (set.length > 1) { + return ''; + } + // Convert to literal + if (set) { + literal += set; + i = closed; + continue; + } + } + // Otherwise fall thru + } + // Append + literal += c; + } + return literal; + } + /** + * Escapes regexp special characters + * https://javascript.info/regexp-escaping + */ + static regExpEscape(s) { + return s.replace(/[[\\^$.|?*+()]/g, '\\$&'); + } +} +exports.Pattern = Pattern; +//# sourceMappingURL=internal-pattern.js.map + +/***/ }), + +/***/ 5935: +/***/ ((__unused_webpack_module, exports) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SearchState = void 0; +class SearchState { + constructor(path, level) { + this.path = path; + this.level = level; + } +} +exports.SearchState = SearchState; +//# sourceMappingURL=internal-search-state.js.map + +/***/ }), + +/***/ 8603: +/***/ (function(__unused_webpack_module, exports) { + + +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.PersonalAccessTokenCredentialHandler = exports.BearerCredentialHandler = exports.BasicCredentialHandler = void 0; +class BasicCredentialHandler { + constructor(username, password) { + this.username = username; + this.password = password; + } + prepareRequest(options) { + if (!options.headers) { + throw Error('The request has no headers'); + } + options.headers['Authorization'] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString('base64')}`; + } + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { + return __awaiter(this, void 0, void 0, function* () { + throw new Error('not implemented'); + }); + } +} +exports.BasicCredentialHandler = BasicCredentialHandler; +class BearerCredentialHandler { + constructor(token) { + this.token = token; + } + // currently implements pre-authorization + // TODO: support preAuth = false where it hooks on 401 + prepareRequest(options) { + if (!options.headers) { + throw Error('The request has no headers'); + } + options.headers['Authorization'] = `Bearer ${this.token}`; + } + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { + return __awaiter(this, void 0, void 0, function* () { + throw new Error('not implemented'); + }); + } +} +exports.BearerCredentialHandler = BearerCredentialHandler; +class PersonalAccessTokenCredentialHandler { + constructor(token) { + this.token = token; + } + // currently implements pre-authorization + // TODO: support preAuth = false where it hooks on 401 + prepareRequest(options) { + if (!options.headers) { + throw Error('The request has no headers'); + } + options.headers['Authorization'] = `Basic ${Buffer.from(`PAT:${this.token}`).toString('base64')}`; + } + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { + return __awaiter(this, void 0, void 0, function* () { + throw new Error('not implemented'); + }); + } +} +exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler; +//# sourceMappingURL=auth.js.map + +/***/ }), + +/***/ 6372: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + +/* eslint-disable @typescript-eslint/no-explicit-any */ +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.HttpClient = exports.isHttps = exports.HttpClientResponse = exports.HttpClientError = exports.getProxyUrl = exports.MediaTypes = exports.Headers = exports.HttpCodes = void 0; +const http = __importStar(__nccwpck_require__(3685)); +const https = __importStar(__nccwpck_require__(5687)); +const pm = __importStar(__nccwpck_require__(2067)); +const tunnel = __importStar(__nccwpck_require__(4225)); +const undici_1 = __nccwpck_require__(7181); +var HttpCodes; +(function (HttpCodes) { + HttpCodes[HttpCodes["OK"] = 200] = "OK"; + HttpCodes[HttpCodes["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes[HttpCodes["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes[HttpCodes["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes[HttpCodes["SeeOther"] = 303] = "SeeOther"; + HttpCodes[HttpCodes["NotModified"] = 304] = "NotModified"; + HttpCodes[HttpCodes["UseProxy"] = 305] = "UseProxy"; + HttpCodes[HttpCodes["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes[HttpCodes["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes[HttpCodes["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes[HttpCodes["BadRequest"] = 400] = "BadRequest"; + HttpCodes[HttpCodes["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes[HttpCodes["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes[HttpCodes["Forbidden"] = 403] = "Forbidden"; + HttpCodes[HttpCodes["NotFound"] = 404] = "NotFound"; + HttpCodes[HttpCodes["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes[HttpCodes["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes[HttpCodes["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict"; + HttpCodes[HttpCodes["Gone"] = 410] = "Gone"; + HttpCodes[HttpCodes["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway"; + HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout"; +})(HttpCodes || (exports.HttpCodes = HttpCodes = {})); +var Headers; +(function (Headers) { + Headers["Accept"] = "accept"; + Headers["ContentType"] = "content-type"; +})(Headers || (exports.Headers = Headers = {})); +var MediaTypes; +(function (MediaTypes) { + MediaTypes["ApplicationJson"] = "application/json"; +})(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 + */ function getProxyUrl(serverUrl) { const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); return proxyUrl ? proxyUrl.href : ''; @@ -5926,7 +6199,7 @@ class HttpClient { } 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: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString('base64')}` + token: `${proxyUrl.username}:${proxyUrl.password}` }))); this._proxyAgentDispatcher = proxyAgent; if (usingSsl && this._ignoreSslError) { @@ -6018,7 +6291,7 @@ const lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCa /***/ }), -/***/ 4318: +/***/ 2067: /***/ ((__unused_webpack_module, exports) => { @@ -6039,11 +6312,11 @@ function getProxyUrl(reqUrl) { })(); if (proxyVar) { try { - return new DecodedURL(proxyVar); + return new URL(proxyVar); } catch (_a) { if (!proxyVar.startsWith('http://') && !proxyVar.startsWith('https://')) - return new DecodedURL(`http://${proxyVar}`); + return new URL(`http://${proxyVar}`); } } else { @@ -6102,46 +6375,14 @@ function isLoopbackAddress(host) { hostLower.startsWith('[::1]') || hostLower.startsWith('[0:0:0:0:0:0:0:1]')); } -class DecodedURL extends URL { - constructor(url, base) { - super(url, base); - this._decodedUsername = decodeURIComponent(super.username); - this._decodedPassword = decodeURIComponent(super.password); - } - get username() { - return this._decodedUsername; - } - get password() { - return this._decodedPassword; - } -} //# sourceMappingURL=proxy.js.map /***/ }), -/***/ 3446: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 2177: +/***/ (function(__unused_webpack_module, exports) { -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.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) { @@ -6151,170 +6392,92 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; -var _a; Object.defineProperty(exports, "__esModule", ({ value: true })); -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 { - yield exports.stat(fsPath); - } - catch (err) { - if (err.code === 'ENOENT') { - return false; - } - throw err; +exports.PersonalAccessTokenCredentialHandler = exports.BearerCredentialHandler = exports.BasicCredentialHandler = void 0; +class BasicCredentialHandler { + constructor(username, password) { + this.username = username; + this.password = password; + } + prepareRequest(options) { + if (!options.headers) { + throw Error('The request has no headers'); } - return true; - }); -} -exports.exists = exists; -function isDirectory(fsPath, useStat = false) { - return __awaiter(this, void 0, void 0, function* () { - const stats = useStat ? yield exports.stat(fsPath) : yield exports.lstat(fsPath); - return stats.isDirectory(); - }); -} -exports.isDirectory = isDirectory; -/** - * On OSX/Linux, true if path starts with '/'. On Windows, true for paths like: - * \, \hello, \\hello\share, C:, and C:\hello (and corresponding alternate separator cases). - */ -function isRooted(p) { - p = normalizeSeparators(p); - if (!p) { - throw new Error('isRooted() parameter "p" cannot be empty'); + options.headers['Authorization'] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString('base64')}`; } - if (exports.IS_WINDOWS) { - return (p.startsWith('\\') || /^[A-Z]:/i.test(p) // e.g. \ or \hello or \\hello - ); // e.g. C: or C:\hello + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { + return __awaiter(this, void 0, void 0, function* () { + throw new Error('not implemented'); + }); } - return p.startsWith('/'); } -exports.isRooted = isRooted; -/** - * Best effort attempt to determine whether a file exists and is executable. - * @param filePath file path to check - * @param extensions additional file extensions to try - * @return if file exists and is executable, returns the file path. otherwise empty string. - */ -function tryGetExecutablePath(filePath, extensions) { - return __awaiter(this, void 0, void 0, function* () { - let stats = undefined; - try { - // test file exists - stats = yield exports.stat(filePath); - } - catch (err) { - if (err.code !== 'ENOENT') { - // eslint-disable-next-line no-console - console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`); - } - } - if (stats && stats.isFile()) { - if (exports.IS_WINDOWS) { - // on Windows, test for valid extension - const upperExt = path.extname(filePath).toUpperCase(); - if (extensions.some(validExt => validExt.toUpperCase() === upperExt)) { - return filePath; - } - } - else { - if (isUnixExecutable(stats)) { - return filePath; - } - } - } - // try each extension - const originalFilePath = filePath; - for (const extension of extensions) { - filePath = originalFilePath + extension; - stats = undefined; - try { - stats = yield exports.stat(filePath); - } - catch (err) { - if (err.code !== 'ENOENT') { - // eslint-disable-next-line no-console - console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`); - } - } - if (stats && stats.isFile()) { - if (exports.IS_WINDOWS) { - // preserve the case of the actual file (since an extension was appended) - try { - const directory = path.dirname(filePath); - const upperName = path.basename(filePath).toUpperCase(); - for (const actualName of yield exports.readdir(directory)) { - if (upperName === actualName.toUpperCase()) { - filePath = path.join(directory, actualName); - break; - } - } - } - catch (err) { - // eslint-disable-next-line no-console - console.log(`Unexpected error attempting to determine the actual case of the file '${filePath}': ${err}`); - } - return filePath; - } - else { - if (isUnixExecutable(stats)) { - return filePath; - } - } - } +exports.BasicCredentialHandler = BasicCredentialHandler; +class BearerCredentialHandler { + constructor(token) { + this.token = token; + } + // currently implements pre-authorization + // TODO: support preAuth = false where it hooks on 401 + prepareRequest(options) { + if (!options.headers) { + throw Error('The request has no headers'); } - return ''; - }); -} -exports.tryGetExecutablePath = tryGetExecutablePath; -function normalizeSeparators(p) { - p = p || ''; - if (exports.IS_WINDOWS) { - // convert slashes on Windows - p = p.replace(/\//g, '\\'); - // remove redundant slashes - return p.replace(/\\\\+/g, '\\'); + options.headers['Authorization'] = `Bearer ${this.token}`; + } + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { + return __awaiter(this, void 0, void 0, function* () { + throw new Error('not implemented'); + }); } - // remove redundant slashes - return p.replace(/\/\/+/g, '/'); -} -// on Mac/Linux, test the execute bit -// R W X R W X R W X -// 256 128 64 32 16 8 4 2 1 -function isUnixExecutable(stats) { - return ((stats.mode & 1) > 0 || - ((stats.mode & 8) > 0 && stats.gid === process.getgid()) || - ((stats.mode & 64) > 0 && stats.uid === process.getuid())); } -// Get the path of cmd.exe in windows -function getCmdPath() { - var _a; - return (_a = process.env['COMSPEC']) !== null && _a !== void 0 ? _a : `cmd.exe`; +exports.BearerCredentialHandler = BearerCredentialHandler; +class PersonalAccessTokenCredentialHandler { + constructor(token) { + this.token = token; + } + // currently implements pre-authorization + // TODO: support preAuth = false where it hooks on 401 + prepareRequest(options) { + if (!options.headers) { + throw Error('The request has no headers'); + } + options.headers['Authorization'] = `Basic ${Buffer.from(`PAT:${this.token}`).toString('base64')}`; + } + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { + return __awaiter(this, void 0, void 0, function* () { + throw new Error('not implemented'); + }); + } } -exports.getCmdPath = getCmdPath; -//# sourceMappingURL=io-util.js.map +exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler; +//# sourceMappingURL=auth.js.map /***/ }), -/***/ 2826: +/***/ 6634: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/* 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]; @@ -6327,7 +6490,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; }; @@ -6341,2987 +6504,3930 @@ 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__(9491); -const path = __importStar(__nccwpck_require__(1017)); -const ioUtil = __importStar(__nccwpck_require__(3446)); +exports.HttpClient = exports.isHttps = exports.HttpClientResponse = exports.HttpClientError = exports.getProxyUrl = exports.MediaTypes = exports.Headers = exports.HttpCodes = void 0; +const http = __importStar(__nccwpck_require__(3685)); +const https = __importStar(__nccwpck_require__(5687)); +const pm = __importStar(__nccwpck_require__(4318)); +const tunnel = __importStar(__nccwpck_require__(4225)); +const undici_1 = __nccwpck_require__(7181); +var HttpCodes; +(function (HttpCodes) { + HttpCodes[HttpCodes["OK"] = 200] = "OK"; + HttpCodes[HttpCodes["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes[HttpCodes["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes[HttpCodes["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes[HttpCodes["SeeOther"] = 303] = "SeeOther"; + HttpCodes[HttpCodes["NotModified"] = 304] = "NotModified"; + HttpCodes[HttpCodes["UseProxy"] = 305] = "UseProxy"; + HttpCodes[HttpCodes["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes[HttpCodes["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes[HttpCodes["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes[HttpCodes["BadRequest"] = 400] = "BadRequest"; + HttpCodes[HttpCodes["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes[HttpCodes["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes[HttpCodes["Forbidden"] = 403] = "Forbidden"; + HttpCodes[HttpCodes["NotFound"] = 404] = "NotFound"; + HttpCodes[HttpCodes["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes[HttpCodes["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes[HttpCodes["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict"; + HttpCodes[HttpCodes["Gone"] = 410] = "Gone"; + HttpCodes[HttpCodes["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway"; + HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout"; +})(HttpCodes || (exports.HttpCodes = HttpCodes = {})); +var Headers; +(function (Headers) { + Headers["Accept"] = "accept"; + Headers["ContentType"] = "content-type"; +})(Headers || (exports.Headers = Headers = {})); +var MediaTypes; +(function (MediaTypes) { + MediaTypes["ApplicationJson"] = "application/json"; +})(MediaTypes || (exports.MediaTypes = MediaTypes = {})); /** - * Copies a file or folder. - * Based off of shelljs - https://github.com/shelljs/shelljs/blob/9237f66c52e5daa40458f94f9565e18e8132f5a6/src/cp.js - * - * @param source source path - * @param dest destination path - * @param options optional. See CopyOptions. + * 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 */ -function cp(source, dest, options = {}) { - return __awaiter(this, void 0, void 0, function* () { - const { force, recursive, copySourceDirectory } = readCopyOptions(options); - const destStat = (yield ioUtil.exists(dest)) ? yield ioUtil.stat(dest) : null; - // Dest is an existing file, but not forcing - if (destStat && destStat.isFile() && !force) { - return; - } - // If dest is an existing directory, should copy inside. - const newDest = destStat && destStat.isDirectory() && copySourceDirectory - ? path.join(dest, path.basename(source)) - : dest; - if (!(yield ioUtil.exists(source))) { - throw new Error(`no such file or directory: ${source}`); - } - const sourceStat = yield ioUtil.stat(source); - if (sourceStat.isDirectory()) { - if (!recursive) { - throw new Error(`Failed to copy. ${source} is a directory, but tried to copy without recursive flag.`); - } - else { - yield cpDirRecursive(source, newDest, 0, force); - } - } - else { - if (path.relative(source, newDest) === '') { - // a file cannot be copied to itself - throw new Error(`'${newDest}' and '${source}' are the same file`); - } - yield copyFile(source, newDest, force); - } - }); +function getProxyUrl(serverUrl) { + const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ''; } -exports.cp = cp; -/** - * Moves a path. - * - * @param source source path - * @param dest destination path - * @param options optional. See MoveOptions. - */ -function mv(source, dest, options = {}) { - return __awaiter(this, void 0, void 0, function* () { - if (yield ioUtil.exists(dest)) { - let destExists = true; - if (yield ioUtil.isDirectory(dest)) { - // If dest is directory copy src into dest - dest = path.join(dest, path.basename(source)); - destExists = yield ioUtil.exists(dest); - } - if (destExists) { - if (options.force == null || options.force) { - yield rmRF(dest); - } - else { - throw new Error('Destination already exists'); - } - } - } - yield mkdirP(path.dirname(dest)); - yield ioUtil.rename(source, dest); - }); +exports.getProxyUrl = getProxyUrl; +const HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect +]; +const HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout +]; +const RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD']; +const ExponentialBackoffCeiling = 10; +const ExponentialBackoffTimeSlice = 5; +class HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = 'HttpClientError'; + this.statusCode = statusCode; + Object.setPrototypeOf(this, HttpClientError.prototype); + } } -exports.mv = mv; -/** - * Remove a path recursively with force - * - * @param inputPath path to remove - */ -function rmRF(inputPath) { - return __awaiter(this, void 0, void 0, function* () { - if (ioUtil.IS_WINDOWS) { - // 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 { - // 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}`); - } - }); +exports.HttpClientError = HttpClientError; +class HttpClientResponse { + constructor(message) { + this.message = message; + } + readBody() { + return __awaiter(this, void 0, void 0, function* () { + return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () { + let output = Buffer.alloc(0); + this.message.on('data', (chunk) => { + output = Buffer.concat([output, chunk]); + }); + this.message.on('end', () => { + resolve(output.toString()); + }); + })); + }); + } + 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.rmRF = rmRF; -/** - * Make a directory. Creates the full path with folders in between - * Will throw if it fails - * - * @param fsPath path to create - * @returns Promise - */ -function mkdirP(fsPath) { - return __awaiter(this, void 0, void 0, function* () { - assert_1.ok(fsPath, 'a path argument must be provided'); - yield ioUtil.mkdir(fsPath, { recursive: true }); - }); +exports.HttpClientResponse = HttpClientResponse; +function isHttps(requestUrl) { + const parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === 'https:'; } -exports.mkdirP = mkdirP; -/** - * Returns path of a tool had the tool actually been invoked. Resolves via paths. - * If you check and the tool does not exist, it will throw. - * - * @param tool name of the tool - * @param check whether to check if tool exists - * @returns Promise path to tool - */ -function which(tool, check) { - return __awaiter(this, void 0, void 0, function* () { - if (!tool) { - throw new Error("parameter 'tool' is required"); - } - // recursive when check=true - if (check) { - const result = yield which(tool, false); - if (!result) { - if (ioUtil.IS_WINDOWS) { - throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also verify the file has a valid extension for an executable file.`); - } - else { - throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also check the file mode to verify the file is executable.`); - } +exports.isHttps = isHttps; +class HttpClient { + constructor(userAgent, handlers, requestOptions) { + this._ignoreSslError = false; + this._allowRedirects = true; + this._allowRedirectDowngrade = false; + this._maxRedirects = 50; + this._allowRetries = false; + this._maxRetries = 1; + this._keepAlive = false; + this._disposed = false; + this.userAgent = userAgent; + this.handlers = handlers || []; + this.requestOptions = requestOptions; + if (requestOptions) { + if (requestOptions.ignoreSslError != null) { + this._ignoreSslError = requestOptions.ignoreSslError; } - return result; - } - const matches = yield findInPath(tool); - if (matches && matches.length > 0) { - return matches[0]; - } - return ''; - }); -} -exports.which = which; -/** - * Returns a list of all occurrences of the given tool on the system path. - * - * @returns Promise the paths of the tool - */ -function findInPath(tool) { - return __awaiter(this, void 0, void 0, function* () { - if (!tool) { - throw new Error("parameter 'tool' is required"); - } - // build the list of extensions to try - const extensions = []; - if (ioUtil.IS_WINDOWS && process.env['PATHEXT']) { - for (const extension of process.env['PATHEXT'].split(path.delimiter)) { - if (extension) { - extensions.push(extension); - } + this._socketTimeout = requestOptions.socketTimeout; + if (requestOptions.allowRedirects != null) { + this._allowRedirects = requestOptions.allowRedirects; } - } - // if it's rooted, return it if exists. otherwise return empty. - if (ioUtil.isRooted(tool)) { - const filePath = yield ioUtil.tryGetExecutablePath(tool, extensions); - if (filePath) { - return [filePath]; + if (requestOptions.allowRedirectDowngrade != null) { + this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; } - return []; - } - // if any path separators, return empty - if (tool.includes(path.sep)) { - return []; - } - // build the list of directories - // - // Note, technically "where" checks the current directory on Windows. From a toolkit perspective, - // it feels like we should not do this. Checking the current directory seems like more of a use - // case of a shell, and the which() function exposed by the toolkit should strive for consistency - // across platforms. - const directories = []; - if (process.env.PATH) { - for (const p of process.env.PATH.split(path.delimiter)) { - if (p) { - directories.push(p); - } + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); } - } - // find all matches - const matches = []; - for (const directory of directories) { - const filePath = yield ioUtil.tryGetExecutablePath(path.join(directory, tool), extensions); - if (filePath) { - matches.push(filePath); + if (requestOptions.keepAlive != null) { + this._keepAlive = requestOptions.keepAlive; + } + if (requestOptions.allowRetries != null) { + this._allowRetries = requestOptions.allowRetries; + } + if (requestOptions.maxRetries != null) { + this._maxRetries = requestOptions.maxRetries; } } - return matches; - }); -} -exports.findInPath = findInPath; -function readCopyOptions(options) { - const force = options.force == null ? true : options.force; - const recursive = Boolean(options.recursive); - const copySourceDirectory = options.copySourceDirectory == null - ? true - : Boolean(options.copySourceDirectory); - return { force, recursive, copySourceDirectory }; -} -function cpDirRecursive(sourceDir, destDir, currentDepth, force) { - return __awaiter(this, void 0, void 0, function* () { - // Ensure there is not a run away recursive copy - if (currentDepth >= 255) - return; - currentDepth++; - yield mkdirP(destDir); - const files = yield ioUtil.readdir(sourceDir); - for (const fileName of files) { - const srcFile = `${sourceDir}/${fileName}`; - const destFile = `${destDir}/${fileName}`; - const srcFileStat = yield ioUtil.lstat(srcFile); - if (srcFileStat.isDirectory()) { - // Recurse - yield cpDirRecursive(srcFile, destFile, currentDepth, force); - } - else { - yield copyFile(srcFile, destFile, force); - } - } - // Change the mode for the newly created directory - yield ioUtil.chmod(destDir, (yield ioUtil.stat(sourceDir)).mode); - }); -} -// Buffered file copy -function copyFile(srcFile, destFile, force) { - return __awaiter(this, void 0, void 0, function* () { - if ((yield ioUtil.lstat(srcFile)).isSymbolicLink()) { - // unlink/re-link it - try { - yield ioUtil.lstat(destFile); - yield ioUtil.unlink(destFile); - } - catch (e) { - // Try to override file permission - if (e.code === 'EPERM') { - yield ioUtil.chmod(destFile, '0666'); - yield ioUtil.unlink(destFile); - } - // other errors = it doesn't exist, no work to do - } - // Copy over symlink - const symlinkFull = yield ioUtil.readlink(srcFile); - yield ioUtil.symlink(symlinkFull, destFile, ioUtil.IS_WINDOWS ? 'junction' : null); - } - else if (!(yield ioUtil.exists(destFile)) || force) { - yield ioUtil.copyFile(srcFile, destFile); - } - }); -} -//# sourceMappingURL=io.js.map - -/***/ }), - -/***/ 4732: -/***/ ((__unused_webpack_module, exports) => { - - - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. -/// -const listenersMap = new WeakMap(); -const abortedMap = new WeakMap(); -/** - * An aborter instance implements AbortSignal interface, can abort HTTP requests. - * - * - Call AbortSignal.none to create a new AbortSignal instance that cannot be cancelled. - * Use `AbortSignal.none` when you are required to pass a cancellation token but the operation - * cannot or will not ever be cancelled. - * - * @example - * Abort without timeout - * ```ts - * await doAsyncWork(AbortSignal.none); - * ``` - */ -class AbortSignal { - constructor() { - /** - * onabort event listener. - */ - this.onabort = null; - listenersMap.set(this, []); - abortedMap.set(this, false); } - /** - * Status of whether aborted or not. - * - * @readonly - */ - get aborted() { - if (!abortedMap.has(this)) { - throw new TypeError("Expected `this` to be an instance of AbortSignal."); - } - return abortedMap.get(this); + options(requestUrl, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('OPTIONS', requestUrl, null, additionalHeaders || {}); + }); } - /** - * Creates a new AbortSignal instance that will never be aborted. - * - * @readonly - */ - static get none() { - return new AbortSignal(); + get(requestUrl, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('GET', requestUrl, null, additionalHeaders || {}); + }); } - /** - * Added new "abort" event listener, only support "abort" event. - * - * @param _type - Only support "abort" event - * @param listener - The listener to be added - */ - addEventListener( - // tslint:disable-next-line:variable-name - _type, listener) { - if (!listenersMap.has(this)) { - throw new TypeError("Expected `this` to be an instance of AbortSignal."); - } - const listeners = listenersMap.get(this); - listeners.push(listener); + del(requestUrl, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('DELETE', requestUrl, null, additionalHeaders || {}); + }); } - /** - * Remove "abort" event listener, only support "abort" event. - * - * @param _type - Only support "abort" event - * @param listener - The listener to be removed - */ - removeEventListener( - // tslint:disable-next-line:variable-name - _type, listener) { - if (!listenersMap.has(this)) { - throw new TypeError("Expected `this` to be an instance of AbortSignal."); - } - const listeners = listenersMap.get(this); - const index = listeners.indexOf(listener); - if (index > -1) { - listeners.splice(index, 1); - } + post(requestUrl, data, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('POST', requestUrl, data, additionalHeaders || {}); + }); + } + patch(requestUrl, data, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('PATCH', requestUrl, data, additionalHeaders || {}); + }); + } + put(requestUrl, data, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('PUT', requestUrl, data, additionalHeaders || {}); + }); + } + head(requestUrl, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('HEAD', requestUrl, null, additionalHeaders || {}); + }); + } + sendStream(verb, requestUrl, stream, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request(verb, requestUrl, stream, additionalHeaders); + }); } /** - * Dispatches a synthetic event to the AbortSignal. + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise */ - dispatchEvent(_event) { - throw new Error("This is a stub dispatchEvent implementation that should not be used. It only exists for type-checking purposes."); - } -} -/** - * Helper to trigger an abort event immediately, the onabort and all abort event listeners will be triggered. - * Will try to trigger abort event for all linked AbortSignal nodes. - * - * - If there is a timeout, the timer will be cancelled. - * - If aborted is true, nothing will happen. - * - * @internal - */ -// eslint-disable-next-line @azure/azure-sdk/ts-use-interface-parameters -function abortSignal(signal) { - if (signal.aborted) { - return; + getJson(requestUrl, additionalHeaders = {}) { + return __awaiter(this, void 0, void 0, function* () { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + const res = yield this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - if (signal.onabort) { - signal.onabort.call(signal); + postJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.post(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - const listeners = listenersMap.get(signal); - if (listeners) { - // Create a copy of listeners so mutations to the array - // (e.g. via removeListener calls) don't affect the listeners - // we invoke. - listeners.slice().forEach((listener) => { - listener.call(signal, { type: "abort" }); + putJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); }); } - abortedMap.set(signal, true); -} - -// Copyright (c) Microsoft Corporation. -/** - * This error is thrown when an asynchronous operation has been aborted. - * Check for this error by testing the `name` that the name property of the - * error matches `"AbortError"`. - * - * @example - * ```ts - * const controller = new AbortController(); - * controller.abort(); - * try { - * doAsyncWork(controller.signal) - * } catch (e) { - * if (e.name === 'AbortError') { - * // handle abort error here. - * } - * } - * ``` - */ -class AbortError extends Error { - constructor(message) { - super(message); - this.name = "AbortError"; + patchJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } -} -/** - * An AbortController provides an AbortSignal and the associated controls to signal - * that an asynchronous operation should be aborted. - * - * @example - * Abort an operation when another event fires - * ```ts - * const controller = new AbortController(); - * const signal = controller.signal; - * doAsyncWork(signal); - * button.addEventListener('click', () => controller.abort()); - * ``` - * - * @example - * Share aborter cross multiple operations in 30s - * ```ts - * // Upload the same data to 2 different data centers at the same time, - * // abort another when any of them is finished - * const controller = AbortController.withTimeout(30 * 1000); - * doAsyncWork(controller.signal).then(controller.abort); - * doAsyncWork(controller.signal).then(controller.abort); - *``` - * - * @example - * Cascaded aborting - * ```ts - * // All operations can't take more than 30 seconds - * const aborter = Aborter.timeout(30 * 1000); - * - * // Following 2 operations can't take more than 25 seconds - * await doAsyncWork(aborter.withTimeout(25 * 1000)); - * await doAsyncWork(aborter.withTimeout(25 * 1000)); - * ``` - */ -class AbortController { - // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types - constructor(parentSignals) { - this._signal = new AbortSignal(); - if (!parentSignals) { - return; - } - // coerce parentSignals into an array - if (!Array.isArray(parentSignals)) { - // eslint-disable-next-line prefer-rest-params - parentSignals = arguments; - } - for (const parentSignal of parentSignals) { - // if the parent signal has already had abort() called, - // then call abort on this signal as well. - if (parentSignal.aborted) { - this.abort(); - } - else { - // when the parent signal aborts, this signal should as well. - parentSignal.addEventListener("abort", () => { - this.abort(); - }); + /** + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch + */ + request(verb, requestUrl, data, headers) { + return __awaiter(this, void 0, void 0, function* () { + if (this._disposed) { + throw new Error('Client has already been disposed.'); } - } + const parsedUrl = new URL(requestUrl); + let info = this._prepareRequest(verb, parsedUrl, headers); + // Only perform retries on reads since writes may not be idempotent. + const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) + ? this._maxRetries + 1 + : 1; + let numTries = 0; + let response; + do { + response = yield this.requestRaw(info, data); + // Check if it's an authentication challenge + if (response && + response.message && + response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (const handler of this.handlers) { + if (handler.canHandleAuthentication(response)) { + authenticationHandler = handler; + break; + } + } + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info, data); + } + else { + // We have received an unauthorized response but have no handlers to handle it. + // Let the response return to the caller. + return response; + } + } + let redirectsRemaining = this._maxRedirects; + while (response.message.statusCode && + HttpRedirectCodes.includes(response.message.statusCode) && + this._allowRedirects && + redirectsRemaining > 0) { + const redirectUrl = response.message.headers['location']; + if (!redirectUrl) { + // if there's no location to redirect to, we won't + break; + } + const parsedRedirectUrl = new URL(redirectUrl); + if (parsedUrl.protocol === 'https:' && + parsedUrl.protocol !== parsedRedirectUrl.protocol && + !this._allowRedirectDowngrade) { + throw new Error('Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.'); + } + // we need to finish reading the response before reassigning response + // which will leak the open socket. + yield response.readBody(); + // strip authorization header if redirected to a different hostname + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (const header in headers) { + // header names are case insensitive + if (header.toLowerCase() === 'authorization') { + delete headers[header]; + } + } + } + // let's make the request with the new redirectUrl + info = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = yield this.requestRaw(info, data); + redirectsRemaining--; + } + if (!response.message.statusCode || + !HttpResponseRetryCodes.includes(response.message.statusCode)) { + // If not a retry code, return immediately instead of retrying + return response; + } + numTries += 1; + if (numTries < maxTries) { + yield response.readBody(); + yield this._performExponentialBackoff(numTries); + } + } while (numTries < maxTries); + return response; + }); } /** - * The AbortSignal associated with this controller that will signal aborted - * when the abort method is called on this controller. - * - * @readonly + * Needs to be called if keepAlive is set to true in request options. */ - get signal() { - return this._signal; + dispose() { + if (this._agent) { + this._agent.destroy(); + } + this._disposed = true; } /** - * Signal that any operations passed this controller's associated abort signal - * to cancel any remaining work and throw an `AbortError`. + * Raw request. + * @param info + * @param data */ - abort() { - abortSignal(this._signal); + requestRaw(info, data) { + return __awaiter(this, void 0, void 0, function* () { + return new Promise((resolve, reject) => { + function callbackForResult(err, res) { + if (err) { + reject(err); + } + else if (!res) { + // If `err` is not passed, then `res` must be passed. + reject(new Error('Unknown error')); + } + else { + resolve(res); + } + } + this.requestRawWithCallback(info, data, callbackForResult); + }); + }); } /** - * Creates a new AbortSignal instance that will abort after the provided ms. - * @param ms - Elapsed time in milliseconds to trigger an abort. + * Raw request with callback. + * @param info + * @param data + * @param onResult */ - static timeout(ms) { - const signal = new AbortSignal(); - const timer = setTimeout(abortSignal, ms, signal); - // Prevent the active Timer from keeping the Node.js event loop active. - if (typeof timer.unref === "function") { - timer.unref(); + requestRawWithCallback(info, data, onResult) { + if (typeof data === 'string') { + if (!info.options.headers) { + info.options.headers = {}; + } + info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8'); } - return signal; - } -} - -exports.AbortController = AbortController; -exports.AbortError = AbortError; -exports.AbortSignal = AbortSignal; -//# sourceMappingURL=index.js.map - - -/***/ }), - -/***/ 3626: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -var coreRestPipeline = __nccwpck_require__(7314); -var tslib = __nccwpck_require__(9236); -var coreAuth = __nccwpck_require__(9334); -var coreUtil = __nccwpck_require__(8143); -var coreHttpCompat = __nccwpck_require__(7050); -var coreClient = __nccwpck_require__(2026); -var coreXml = __nccwpck_require__(5182); -var logger$1 = __nccwpck_require__(2208); -var abortController = __nccwpck_require__(4732); -var crypto = __nccwpck_require__(6113); -var coreTracing = __nccwpck_require__(7423); -var stream = __nccwpck_require__(2781); -var coreLro = __nccwpck_require__(2045); -var events = __nccwpck_require__(2361); -var fs = __nccwpck_require__(7147); -var util = __nccwpck_require__(3837); -var buffer = __nccwpck_require__(4300); - -function _interopNamespaceDefault(e) { - var n = Object.create(null); - if (e) { - Object.keys(e).forEach(function (k) { - if (k !== 'default') { - var d = Object.getOwnPropertyDescriptor(e, k); - Object.defineProperty(n, k, d.get ? d : { - enumerable: true, - get: function () { return e[k]; } - }); + let callbackCalled = false; + function handleResult(err, res) { + if (!callbackCalled) { + callbackCalled = true; + onResult(err, res); } + } + const req = info.httpModule.request(info.options, (msg) => { + const res = new HttpClientResponse(msg); + handleResult(undefined, res); }); - } - n.default = e; - return Object.freeze(n); -} - -var coreHttpCompat__namespace = /*#__PURE__*/_interopNamespaceDefault(coreHttpCompat); -var coreClient__namespace = /*#__PURE__*/_interopNamespaceDefault(coreClient); -var fs__namespace = /*#__PURE__*/_interopNamespaceDefault(fs); -var util__namespace = /*#__PURE__*/_interopNamespaceDefault(util); - -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. -/** - * The `@azure/logger` configuration for this package. - */ -const logger = logger$1.createClientLogger("storage-blob"); - -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. -/** - * The base class from which all request policies derive. - */ -class BaseRequestPolicy { - /** - * The main method to implement that manipulates a request/response. - */ - constructor( - /** - * The next policy in the pipeline. Each policy is responsible for executing the next one if the request is to continue through the pipeline. - */ - _nextPolicy, - /** - * The options that can be passed to a given request policy. - */ - _options) { - this._nextPolicy = _nextPolicy; - this._options = _options; - } - /** - * Get whether or not a log with the provided log level should be logged. - * @param logLevel - The log level of the log that will be logged. - * @returns Whether or not a log with the provided log level should be logged. - */ - shouldLog(logLevel) { - return this._options.shouldLog(logLevel); + let socket; + req.on('socket', sock => { + socket = sock; + }); + // If we ever get disconnected, we want the socket to timeout eventually + req.setTimeout(this._socketTimeout || 3 * 60000, () => { + if (socket) { + socket.end(); + } + handleResult(new Error(`Request timeout: ${info.options.path}`)); + }); + req.on('error', function (err) { + // err has statusCode property + // res should have headers + handleResult(err); + }); + if (data && typeof data === 'string') { + req.write(data, 'utf8'); + } + if (data && typeof data !== 'string') { + data.on('close', function () { + req.end(); + }); + data.pipe(req); + } + else { + req.end(); + } } /** - * Attempt to log the provided message to the provided logger. If no logger was provided or if - * the log level does not meat the logger's threshold, then nothing will be logged. - * @param logLevel - The log level of this log. - * @param message - The message of this log. + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com */ - log(logLevel, message) { - this._options.log(logLevel, message); + getAgent(serverUrl) { + const parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); } -} - -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. -const SDK_VERSION = "12.24.0"; -const SERVICE_VERSION = "2024-08-04"; -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. - */ -const StorageOAuthScopes = "https://storage.azure.com/.default"; -const URLConstants = { - Parameters: { - FORCE_BROWSER_NO_CACHE: "_", - SIGNATURE: "sig", - SNAPSHOT: "snapshot", - VERSIONID: "versionid", - TIMEOUT: "timeout", - }, -}; -const HTTPURLConnection = { - HTTP_ACCEPTED: 202, - HTTP_CONFLICT: 409, - HTTP_NOT_FOUND: 404, - HTTP_PRECON_FAILED: 412, - HTTP_RANGE_NOT_SATISFIABLE: 416, -}; -const HeaderConstants = { - AUTHORIZATION: "Authorization", - AUTHORIZATION_SCHEME: "Bearer", - CONTENT_ENCODING: "Content-Encoding", - CONTENT_ID: "Content-ID", - CONTENT_LANGUAGE: "Content-Language", - CONTENT_LENGTH: "Content-Length", - CONTENT_MD5: "Content-Md5", - CONTENT_TRANSFER_ENCODING: "Content-Transfer-Encoding", - CONTENT_TYPE: "Content-Type", - COOKIE: "Cookie", - DATE: "date", - IF_MATCH: "if-match", - IF_MODIFIED_SINCE: "if-modified-since", - IF_NONE_MATCH: "if-none-match", - IF_UNMODIFIED_SINCE: "if-unmodified-since", - PREFIX_FOR_STORAGE: "x-ms-", - RANGE: "Range", - USER_AGENT: "User-Agent", - X_MS_CLIENT_REQUEST_ID: "x-ms-client-request-id", - X_MS_COPY_SOURCE: "x-ms-copy-source", - X_MS_DATE: "x-ms-date", - X_MS_ERROR_CODE: "x-ms-error-code", - X_MS_VERSION: "x-ms-version", - X_MS_CopySourceErrorCode: "x-ms-copy-source-error-code", -}; -const ETagNone = ""; -const ETagAny = "*"; -const SIZE_1_MB = 1 * 1024 * 1024; -const BATCH_MAX_REQUEST = 256; -const BATCH_MAX_PAYLOAD_IN_BYTES = 4 * SIZE_1_MB; -const HTTP_LINE_ENDING = "\r\n"; -const HTTP_VERSION_1_1 = "HTTP/1.1"; -const EncryptionAlgorithmAES25 = "AES256"; -const DevelopmentConnectionString = `DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;BlobEndpoint=http://127.0.0.1:10000/devstoreaccount1;`; -const StorageBlobLoggingAllowedHeaderNames = [ - "Access-Control-Allow-Origin", - "Cache-Control", - "Content-Length", - "Content-Type", - "Date", - "Request-Id", - "traceparent", - "Transfer-Encoding", - "User-Agent", - "x-ms-client-request-id", - "x-ms-date", - "x-ms-error-code", - "x-ms-request-id", - "x-ms-return-client-request-id", - "x-ms-version", - "Accept-Ranges", - "Content-Disposition", - "Content-Encoding", - "Content-Language", - "Content-MD5", - "Content-Range", - "ETag", - "Last-Modified", - "Server", - "Vary", - "x-ms-content-crc64", - "x-ms-copy-action", - "x-ms-copy-completion-time", - "x-ms-copy-id", - "x-ms-copy-progress", - "x-ms-copy-status", - "x-ms-has-immutability-policy", - "x-ms-has-legal-hold", - "x-ms-lease-state", - "x-ms-lease-status", - "x-ms-range", - "x-ms-request-server-encrypted", - "x-ms-server-encrypted", - "x-ms-snapshot", - "x-ms-source-range", - "If-Match", - "If-Modified-Since", - "If-None-Match", - "If-Unmodified-Since", - "x-ms-access-tier", - "x-ms-access-tier-change-time", - "x-ms-access-tier-inferred", - "x-ms-account-kind", - "x-ms-archive-status", - "x-ms-blob-append-offset", - "x-ms-blob-cache-control", - "x-ms-blob-committed-block-count", - "x-ms-blob-condition-appendpos", - "x-ms-blob-condition-maxsize", - "x-ms-blob-content-disposition", - "x-ms-blob-content-encoding", - "x-ms-blob-content-language", - "x-ms-blob-content-length", - "x-ms-blob-content-md5", - "x-ms-blob-content-type", - "x-ms-blob-public-access", - "x-ms-blob-sequence-number", - "x-ms-blob-type", - "x-ms-copy-destination-snapshot", - "x-ms-creation-time", - "x-ms-default-encryption-scope", - "x-ms-delete-snapshots", - "x-ms-delete-type-permanent", - "x-ms-deny-encryption-scope-override", - "x-ms-encryption-algorithm", - "x-ms-if-sequence-number-eq", - "x-ms-if-sequence-number-le", - "x-ms-if-sequence-number-lt", - "x-ms-incremental-copy", - "x-ms-lease-action", - "x-ms-lease-break-period", - "x-ms-lease-duration", - "x-ms-lease-id", - "x-ms-lease-time", - "x-ms-page-write", - "x-ms-proposed-lease-id", - "x-ms-range-get-content-md5", - "x-ms-rehydrate-priority", - "x-ms-sequence-number-action", - "x-ms-sku-name", - "x-ms-source-content-md5", - "x-ms-source-if-match", - "x-ms-source-if-modified-since", - "x-ms-source-if-none-match", - "x-ms-source-if-unmodified-since", - "x-ms-tag-count", - "x-ms-encryption-key-sha256", - "x-ms-copy-source-error-code", - "x-ms-copy-source-status-code", - "x-ms-if-tags", - "x-ms-source-if-tags", -]; -const StorageBlobLoggingAllowedQueryParameters = [ - "comp", - "maxresults", - "rscc", - "rscd", - "rsce", - "rscl", - "rsct", - "se", - "si", - "sip", - "sp", - "spr", - "sr", - "srt", - "ss", - "st", - "sv", - "include", - "marker", - "prefix", - "copyid", - "restype", - "blockid", - "blocklisttype", - "delimiter", - "prevsnapshot", - "ske", - "skoid", - "sks", - "skt", - "sktid", - "skv", - "snapshot", -]; -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. -// Licensed under the MIT license. -/** - * Reserved URL characters must be properly escaped for Storage services like Blob or File. - * - * ## URL encode and escape strategy for JS SDKs - * - * When customers pass a URL string into XxxClient classes constructor, the URL string may already be URL encoded or not. - * But before sending to Azure Storage server, the URL must be encoded. However, it's hard for a SDK to guess whether the URL - * string has been encoded or not. We have 2 potential strategies, and chose strategy two for the XxxClient constructors. - * - * ### Strategy One: Assume the customer URL string is not encoded, and always encode URL string in SDK. - * - * This is what legacy V2 SDK does, simple and works for most of the cases. - * - When customer URL string is "http://account.blob.core.windows.net/con/b:", - * SDK will encode it to "http://account.blob.core.windows.net/con/b%3A" and send to server. A blob named "b:" will be created. - * - When customer URL string is "http://account.blob.core.windows.net/con/b%3A", - * SDK will encode it to "http://account.blob.core.windows.net/con/b%253A" and send to server. A blob named "b%3A" will be created. - * - * But this strategy will make it not possible to create a blob with "?" in it's name. Because when customer URL string is - * "http://account.blob.core.windows.net/con/blob?name", the "?name" will be treated as URL paramter instead of blob name. - * If customer URL string is "http://account.blob.core.windows.net/con/blob%3Fname", a blob named "blob%3Fname" will be created. - * V2 SDK doesn't have this issue because it doesn't allow customer pass in a full URL, it accepts a separate blob name and encodeURIComponent for it. - * We cannot accept a SDK cannot create a blob name with "?". So we implement strategy two: - * - * ### Strategy Two: SDK doesn't assume the URL has been encoded or not. It will just escape the special characters. - * - * This is what V10 Blob Go SDK does. It accepts a URL type in Go, and call url.EscapedPath() to escape the special chars unescaped. - * - When customer URL string is "http://account.blob.core.windows.net/con/b:", - * SDK will escape ":" like "http://account.blob.core.windows.net/con/b%3A" and send to server. A blob named "b:" will be created. - * - When customer URL string is "http://account.blob.core.windows.net/con/b%3A", - * There is no special characters, so send "http://account.blob.core.windows.net/con/b%3A" to server. A blob named "b:" will be created. - * - When customer URL string is "http://account.blob.core.windows.net/con/b%253A", - * There is no special characters, so send "http://account.blob.core.windows.net/con/b%253A" to server. A blob named "b%3A" will be created. - * - * This strategy gives us flexibility to create with any special characters. But "%" will be treated as a special characters, if the URL string - * is not encoded, there shouldn't a "%" in the URL string, otherwise the URL is not a valid URL. - * If customer needs to create a blob with "%" in it's blob name, use "%25" instead of "%". Just like above 3rd sample. - * And following URL strings are invalid: - * - "http://account.blob.core.windows.net/con/b%" - * - "http://account.blob.core.windows.net/con/b%2" - * - "http://account.blob.core.windows.net/con/b%G" - * - * Another special character is "?", use "%2F" to represent a blob name with "?" in a URL string. - * - * ### Strategy for containerName, blobName or other specific XXXName parameters in methods such as `containerClient.getBlobClient(blobName)` - * - * We will apply strategy one, and call encodeURIComponent for these parameters like blobName. Because what customers passes in is a plain name instead of a URL. - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/naming-and-referencing-containers--blobs--and-metadata - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/naming-and-referencing-shares--directories--files--and-metadata - * - * @param url - - */ -function escapeURLPath(url) { - const urlParsed = new URL(url); - let path = urlParsed.pathname; - path = path || "/"; - path = escape(path); - urlParsed.pathname = path; - return urlParsed.toString(); -} -function getProxyUriFromDevConnString(connectionString) { - // Development Connection String - // https://docs.microsoft.com/en-us/azure/storage/common/storage-configure-connection-string#connect-to-the-emulator-account-using-the-well-known-account-name-and-key - let proxyUri = ""; - if (connectionString.search("DevelopmentStorageProxyUri=") !== -1) { - // CONNECTION_STRING=UseDevelopmentStorage=true;DevelopmentStorageProxyUri=http://myProxyUri - const matchCredentials = connectionString.split(";"); - for (const element of matchCredentials) { - if (element.trim().startsWith("DevelopmentStorageProxyUri=")) { - proxyUri = element.trim().match("DevelopmentStorageProxyUri=(.*)")[1]; - } + 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); } - return proxyUri; -} -function getValueInConnString(connectionString, argument) { - const elements = connectionString.split(";"); - for (const element of elements) { - if (element.trim().startsWith(argument)) { - return element.trim().match(argument + "=(.*)")[1]; + _prepareRequest(method, requestUrl, headers) { + const info = {}; + info.parsedUrl = requestUrl; + const usingSsl = info.parsedUrl.protocol === 'https:'; + info.httpModule = usingSsl ? https : http; + const defaultPort = usingSsl ? 443 : 80; + info.options = {}; + info.options.host = info.parsedUrl.hostname; + info.options.port = info.parsedUrl.port + ? parseInt(info.parsedUrl.port) + : defaultPort; + info.options.path = + (info.parsedUrl.pathname || '') + (info.parsedUrl.search || ''); + info.options.method = method; + info.options.headers = this._mergeHeaders(headers); + if (this.userAgent != null) { + info.options.headers['user-agent'] = this.userAgent; } - } - return ""; -} -/** - * Extracts the parts of an Azure Storage account connection string. - * - * @param connectionString - Connection string. - * @returns String key value pairs of the storage account's url and credentials. - */ -function extractConnectionStringParts(connectionString) { - let proxyUri = ""; - if (connectionString.startsWith("UseDevelopmentStorage=true")) { - // Development connection string - proxyUri = getProxyUriFromDevConnString(connectionString); - connectionString = DevelopmentConnectionString; - } - // Matching BlobEndpoint in the Account connection string - let blobEndpoint = getValueInConnString(connectionString, "BlobEndpoint"); - // Slicing off '/' at the end if exists - // (The methods that use `extractConnectionStringParts` expect the url to not have `/` at the end) - blobEndpoint = blobEndpoint.endsWith("/") ? blobEndpoint.slice(0, -1) : blobEndpoint; - if (connectionString.search("DefaultEndpointsProtocol=") !== -1 && - connectionString.search("AccountKey=") !== -1) { - // Account connection string - let defaultEndpointsProtocol = ""; - let accountName = ""; - let accountKey = Buffer.from("accountKey", "base64"); - let endpointSuffix = ""; - // Get account name and key - accountName = getValueInConnString(connectionString, "AccountName"); - accountKey = Buffer.from(getValueInConnString(connectionString, "AccountKey"), "base64"); - if (!blobEndpoint) { - // BlobEndpoint is not present in the Account connection string - // Can be obtained from `${defaultEndpointsProtocol}://${accountName}.blob.${endpointSuffix}` - defaultEndpointsProtocol = getValueInConnString(connectionString, "DefaultEndpointsProtocol"); - const protocol = defaultEndpointsProtocol.toLowerCase(); - if (protocol !== "https" && protocol !== "http") { - throw new Error("Invalid DefaultEndpointsProtocol in the provided Connection String. Expecting 'https' or 'http'"); - } - endpointSuffix = getValueInConnString(connectionString, "EndpointSuffix"); - if (!endpointSuffix) { - throw new Error("Invalid EndpointSuffix in the provided Connection String"); + info.options.agent = this._getAgent(info.parsedUrl); + // gives handlers an opportunity to participate + if (this.handlers) { + for (const handler of this.handlers) { + handler.prepareRequest(info.options); } - blobEndpoint = `${defaultEndpointsProtocol}://${accountName}.blob.${endpointSuffix}`; - } - if (!accountName) { - throw new Error("Invalid AccountName in the provided Connection String"); } - else if (accountKey.length === 0) { - throw new Error("Invalid AccountKey in the provided Connection String"); + return info; + } + _mergeHeaders(headers) { + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); } - return { - kind: "AccountConnString", - url: blobEndpoint, - accountName, - accountKey, - proxyUri, - }; + return lowercaseKeys(headers || {}); } - else { - // SAS connection string - let accountSas = getValueInConnString(connectionString, "SharedAccessSignature"); - let accountName = getValueInConnString(connectionString, "AccountName"); - // if accountName is empty, try to read it from BlobEndpoint - if (!accountName) { - accountName = getAccountNameFromUrl(blobEndpoint); + _getExistingOrDefaultHeader(additionalHeaders, header, _default) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; } - if (!blobEndpoint) { - throw new Error("Invalid BlobEndpoint in the provided SAS Connection String"); + return additionalHeaders[header] || clientHeader || _default; + } + _getAgent(parsedUrl) { + let agent; + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (this._keepAlive && useProxy) { + agent = this._proxyAgent; } - else if (!accountSas) { - throw new Error("Invalid SharedAccessSignature in the provided SAS Connection String"); + if (!useProxy) { + agent = this._agent; } - // client constructors assume accountSas does *not* start with ? - if (accountSas.startsWith("?")) { - accountSas = accountSas.substring(1); + // if agent is already assigned use that agent. + if (agent) { + return agent; } - return { kind: "SASConnString", url: blobEndpoint, accountName, accountSas }; - } -} -/** - * Internal escape method implemented Strategy Two mentioned in escapeURL() description. - * - * @param text - - */ -function escape(text) { - return encodeURIComponent(text) - .replace(/%2F/g, "/") // Don't escape for "/" - .replace(/'/g, "%27") // Escape for "'" - .replace(/\+/g, "%20") - .replace(/%25/g, "%"); // Revert encoded "%" -} -/** - * Append a string to URL path. Will remove duplicated "/" in front of the string - * when URL path ends with a "/". - * - * @param url - Source URL string - * @param name - String to be appended to URL - * @returns An updated URL string - */ -function appendToURLPath(url, name) { - const urlParsed = new URL(url); - let path = urlParsed.pathname; - path = path ? (path.endsWith("/") ? `${path}${name}` : `${path}/${name}`) : name; - urlParsed.pathname = path; - return urlParsed.toString(); -} -/** - * Set URL parameter name and value. If name exists in URL parameters, old value - * will be replaced by name key. If not provide value, the parameter will be deleted. - * - * @param url - Source URL string - * @param name - Parameter name - * @param value - Parameter value - * @returns An updated URL string - */ -function setURLParameter(url, name, value) { - const urlParsed = new URL(url); - const encodedName = encodeURIComponent(name); - const encodedValue = value ? encodeURIComponent(value) : undefined; - // mutating searchParams will change the encoding, so we have to do this ourselves - const searchString = urlParsed.search === "" ? "?" : urlParsed.search; - const searchPieces = []; - for (const pair of searchString.slice(1).split("&")) { - if (pair) { - const [key] = pair.split("=", 2); - if (key !== encodedName) { - searchPieces.push(pair); + const usingSsl = parsedUrl.protocol === 'https:'; + let maxSockets = 100; + if (this.requestOptions) { + maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; + } + // This is `useProxy` again, but we need to check `proxyURl` directly for TypeScripts's flow analysis. + if (proxyUrl && proxyUrl.hostname) { + const agentOptions = { + maxSockets, + keepAlive: this._keepAlive, + proxy: Object.assign(Object.assign({}, ((proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + })), { host: proxyUrl.hostname, port: proxyUrl.port }) + }; + let tunnelAgent; + const overHttps = proxyUrl.protocol === 'https:'; + if (usingSsl) { + tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; } + else { + tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; + } + agent = tunnelAgent(agentOptions); + this._proxyAgent = agent; + } + // if tunneling agent isn't assigned create a new agent + if (!agent) { + const options = { keepAlive: this._keepAlive, maxSockets }; + agent = usingSsl ? new https.Agent(options) : new http.Agent(options); + this._agent = agent; + } + 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 + agent.options = Object.assign(agent.options || {}, { + rejectUnauthorized: false + }); } + return agent; } - if (encodedValue) { - searchPieces.push(`${encodedName}=${encodedValue}`); + _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: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString('base64')}` + }))); + 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; } - urlParsed.search = searchPieces.length ? `?${searchPieces.join("&")}` : ""; - return urlParsed.toString(); -} -/** - * Get URL parameter by name. - * - * @param url - - * @param name - - */ -function getURLParameter(url, name) { - var _a; - const urlParsed = new URL(url); - return (_a = urlParsed.searchParams.get(name)) !== null && _a !== void 0 ? _a : undefined; -} -/** - * Set URL host. - * - * @param url - Source URL string - * @param host - New host string - * @returns An updated URL string - */ -function setURLHost(url, host) { - const urlParsed = new URL(url); - urlParsed.hostname = host; - return urlParsed.toString(); -} -/** - * Get URL path from an URL string. - * - * @param url - Source URL string - */ -function getURLPath(url) { - try { - const urlParsed = new URL(url); - return urlParsed.pathname; + _performExponentialBackoff(retryNumber) { + return __awaiter(this, void 0, void 0, function* () { + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise(resolve => setTimeout(() => resolve(), ms)); + }); } - catch (e) { - return undefined; + _processResponse(res, options) { + return __awaiter(this, void 0, void 0, function* () { + return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { + const statusCode = res.message.statusCode || 0; + const response = { + statusCode, + result: null, + headers: {} + }; + // not found leads to null obj returned + if (statusCode === HttpCodes.NotFound) { + resolve(response); + } + // get the result from the body + function dateTimeDeserializer(key, value) { + if (typeof value === 'string') { + const a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; + } + } + return value; + } + let obj; + let contents; + try { + contents = yield res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, dateTimeDeserializer); + } + else { + obj = JSON.parse(contents); + } + response.result = obj; + } + response.headers = res.message.headers; + } + catch (err) { + // Invalid resource (contents not json); leaving result obj null + } + // note that 3xx redirects are handled by the http layer. + if (statusCode > 299) { + let msg; + // if exception/error in body, attempt to get better error + if (obj && obj.message) { + msg = obj.message; + } + else if (contents && contents.length > 0) { + // it may be the case that the exception is in the body message as string + msg = contents; + } + else { + msg = `Failed request: (${statusCode})`; + } + const err = new HttpClientError(msg, statusCode); + err.result = response.result; + reject(err); + } + else { + resolve(response); + } + })); + }); } } -/** - * Get URL scheme from an URL string. - * - * @param url - Source URL string - */ -function getURLScheme(url) { - try { - const urlParsed = new URL(url); - return urlParsed.protocol.endsWith(":") ? urlParsed.protocol.slice(0, -1) : urlParsed.protocol; +exports.HttpClient = HttpClient; +const lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 4318: +/***/ ((__unused_webpack_module, exports) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.checkBypass = exports.getProxyUrl = void 0; +function getProxyUrl(reqUrl) { + const usingSsl = reqUrl.protocol === 'https:'; + if (checkBypass(reqUrl)) { + return undefined; } - catch (e) { + const proxyVar = (() => { + if (usingSsl) { + return process.env['https_proxy'] || process.env['HTTPS_PROXY']; + } + else { + return process.env['http_proxy'] || process.env['HTTP_PROXY']; + } + })(); + if (proxyVar) { + try { + return new DecodedURL(proxyVar); + } + catch (_a) { + if (!proxyVar.startsWith('http://') && !proxyVar.startsWith('https://')) + return new DecodedURL(`http://${proxyVar}`); + } + } + else { return undefined; } } -/** - * Get URL path and query from an URL string. - * - * @param url - Source URL string - */ -function getURLPathAndQuery(url) { - const urlParsed = new URL(url); - const pathString = urlParsed.pathname; - if (!pathString) { - throw new RangeError("Invalid url without valid path."); +exports.getProxyUrl = getProxyUrl; +function checkBypass(reqUrl) { + if (!reqUrl.hostname) { + return false; } - let queryString = urlParsed.search || ""; - queryString = queryString.trim(); - if (queryString !== "") { - queryString = queryString.startsWith("?") ? queryString : `?${queryString}`; // Ensure query string start with '?' + const reqHost = reqUrl.hostname; + if (isLoopbackAddress(reqHost)) { + return true; } - return `${pathString}${queryString}`; -} -/** - * Get URL query key value pairs from an URL string. - * - * @param url - - */ -function getURLQueries(url) { - let queryString = new URL(url).search; - if (!queryString) { - return {}; + const noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || ''; + if (!noProxy) { + return false; } - queryString = queryString.trim(); - queryString = queryString.startsWith("?") ? queryString.substring(1) : queryString; - let querySubStrings = queryString.split("&"); - querySubStrings = querySubStrings.filter((value) => { - const indexOfEqual = value.indexOf("="); - const lastIndexOfEqual = value.lastIndexOf("="); - return (indexOfEqual > 0 && indexOfEqual === lastIndexOfEqual && lastIndexOfEqual < value.length - 1); - }); - const queries = {}; - for (const querySubString of querySubStrings) { - const splitResults = querySubString.split("="); - const key = splitResults[0]; - const value = splitResults[1]; - queries[key] = value; + // Determine the request port + let reqPort; + if (reqUrl.port) { + reqPort = Number(reqUrl.port); } - return queries; + else if (reqUrl.protocol === 'http:') { + reqPort = 80; + } + else if (reqUrl.protocol === 'https:') { + reqPort = 443; + } + // Format the request hostname and hostname with port + const upperReqHosts = [reqUrl.hostname.toUpperCase()]; + if (typeof reqPort === 'number') { + upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); + } + // Compare request host against noproxy + for (const upperNoProxyItem of noProxy + .split(',') + .map(x => x.trim().toUpperCase()) + .filter(x => x)) { + if (upperNoProxyItem === '*' || + upperReqHosts.some(x => x === upperNoProxyItem || + x.endsWith(`.${upperNoProxyItem}`) || + (upperNoProxyItem.startsWith('.') && + x.endsWith(`${upperNoProxyItem}`)))) { + return true; + } + } + return false; } -/** - * Append a string to URL query. - * - * @param url - Source URL string. - * @param queryParts - String to be appended to the URL query. - * @returns An updated URL string. - */ -function appendToURLQuery(url, queryParts) { - const urlParsed = new URL(url); - let query = urlParsed.search; - if (query) { - query += "&" + queryParts; +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]')); +} +class DecodedURL extends URL { + constructor(url, base) { + super(url, base); + this._decodedUsername = decodeURIComponent(super.username); + this._decodedPassword = decodeURIComponent(super.password); } - else { - query = queryParts; + get username() { + return this._decodedUsername; + } + get password() { + return this._decodedPassword; } - urlParsed.search = query; - return urlParsed.toString(); } -/** - * Rounds a date off to seconds. - * - * @param date - - * @param withMilliseconds - If true, YYYY-MM-DDThh:mm:ss.fffffffZ will be returned; - * If false, YYYY-MM-DDThh:mm:ssZ will be returned. - * @returns Date string in ISO8061 format, with or without 7 milliseconds component - */ -function truncatedISO8061Date(date, withMilliseconds = true) { - // Date.toISOString() will return like "2018-10-29T06:34:36.139Z" - const dateString = date.toISOString(); - return withMilliseconds - ? dateString.substring(0, dateString.length - 1) + "0000" + "Z" - : dateString.substring(0, dateString.length - 5) + "Z"; +//# sourceMappingURL=proxy.js.map + +/***/ }), + +/***/ 3446: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + +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.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()); + }); +}; +var _a; +Object.defineProperty(exports, "__esModule", ({ value: true })); +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 { + yield exports.stat(fsPath); + } + catch (err) { + if (err.code === 'ENOENT') { + return false; + } + throw err; + } + return true; + }); } -/** - * Base64 encode. - * - * @param content - - */ -function base64encode(content) { - return !coreUtil.isNode ? btoa(content) : Buffer.from(content).toString("base64"); +exports.exists = exists; +function isDirectory(fsPath, useStat = false) { + return __awaiter(this, void 0, void 0, function* () { + const stats = useStat ? yield exports.stat(fsPath) : yield exports.lstat(fsPath); + return stats.isDirectory(); + }); } +exports.isDirectory = isDirectory; /** - * Generate a 64 bytes base64 block ID string. - * - * @param blockIndex - + * On OSX/Linux, true if path starts with '/'. On Windows, true for paths like: + * \, \hello, \\hello\share, C:, and C:\hello (and corresponding alternate separator cases). */ -function generateBlockID(blockIDPrefix, blockIndex) { - // To generate a 64 bytes base64 string, source string should be 48 - const maxSourceStringLength = 48; - // A blob can have a maximum of 100,000 uncommitted blocks at any given time - const maxBlockIndexLength = 6; - const maxAllowedBlockIDPrefixLength = maxSourceStringLength - maxBlockIndexLength; - if (blockIDPrefix.length > maxAllowedBlockIDPrefixLength) { - blockIDPrefix = blockIDPrefix.slice(0, maxAllowedBlockIDPrefixLength); +function isRooted(p) { + p = normalizeSeparators(p); + if (!p) { + throw new Error('isRooted() parameter "p" cannot be empty'); } - const res = blockIDPrefix + - padStart(blockIndex.toString(), maxSourceStringLength - blockIDPrefix.length, "0"); - return base64encode(res); + if (exports.IS_WINDOWS) { + return (p.startsWith('\\') || /^[A-Z]:/i.test(p) // e.g. \ or \hello or \\hello + ); // e.g. C: or C:\hello + } + return p.startsWith('/'); } +exports.isRooted = isRooted; /** - * Delay specified time interval. - * - * @param timeInMs - - * @param aborter - - * @param abortError - + * Best effort attempt to determine whether a file exists and is executable. + * @param filePath file path to check + * @param extensions additional file extensions to try + * @return if file exists and is executable, returns the file path. otherwise empty string. */ -async function delay(timeInMs, aborter, abortError) { - return new Promise((resolve, reject) => { - /* eslint-disable-next-line prefer-const */ - let timeout; - const abortHandler = () => { - if (timeout !== undefined) { - clearTimeout(timeout); - } - reject(abortError); - }; - const resolveHandler = () => { - if (aborter !== undefined) { - aborter.removeEventListener("abort", abortHandler); +function tryGetExecutablePath(filePath, extensions) { + return __awaiter(this, void 0, void 0, function* () { + let stats = undefined; + try { + // test file exists + stats = yield exports.stat(filePath); + } + catch (err) { + if (err.code !== 'ENOENT') { + // eslint-disable-next-line no-console + console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`); + } + } + if (stats && stats.isFile()) { + if (exports.IS_WINDOWS) { + // on Windows, test for valid extension + const upperExt = path.extname(filePath).toUpperCase(); + if (extensions.some(validExt => validExt.toUpperCase() === upperExt)) { + return filePath; + } + } + else { + if (isUnixExecutable(stats)) { + return filePath; + } + } + } + // try each extension + const originalFilePath = filePath; + for (const extension of extensions) { + filePath = originalFilePath + extension; + stats = undefined; + try { + stats = yield exports.stat(filePath); + } + catch (err) { + if (err.code !== 'ENOENT') { + // eslint-disable-next-line no-console + console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`); + } + } + if (stats && stats.isFile()) { + if (exports.IS_WINDOWS) { + // preserve the case of the actual file (since an extension was appended) + try { + const directory = path.dirname(filePath); + const upperName = path.basename(filePath).toUpperCase(); + for (const actualName of yield exports.readdir(directory)) { + if (upperName === actualName.toUpperCase()) { + filePath = path.join(directory, actualName); + break; + } + } + } + catch (err) { + // eslint-disable-next-line no-console + console.log(`Unexpected error attempting to determine the actual case of the file '${filePath}': ${err}`); + } + return filePath; + } + else { + if (isUnixExecutable(stats)) { + return filePath; + } + } } - resolve(); - }; - timeout = setTimeout(resolveHandler, timeInMs); - if (aborter !== undefined) { - aborter.addEventListener("abort", abortHandler); } + return ''; }); } -/** - * String.prototype.padStart() - * - * @param currentString - - * @param targetLength - - * @param padString - - */ -function padStart(currentString, targetLength, padString = " ") { - // @ts-expect-error: TS doesn't know this code needs to run downlevel sometimes - if (String.prototype.padStart) { - return currentString.padStart(targetLength, padString); - } - padString = padString || " "; - if (currentString.length > targetLength) { - return currentString; - } - else { - targetLength = targetLength - currentString.length; - if (targetLength > padString.length) { - padString += padString.repeat(targetLength / padString.length); - } - return padString.slice(0, targetLength) + currentString; +exports.tryGetExecutablePath = tryGetExecutablePath; +function normalizeSeparators(p) { + p = p || ''; + if (exports.IS_WINDOWS) { + // convert slashes on Windows + p = p.replace(/\//g, '\\'); + // remove redundant slashes + return p.replace(/\\\\+/g, '\\'); } + // remove redundant slashes + return p.replace(/\/\/+/g, '/'); } -/** - * If two strings are equal when compared case insensitive. - * - * @param str1 - - * @param str2 - - */ -function iEqual(str1, str2) { - return str1.toLocaleLowerCase() === str2.toLocaleLowerCase(); +// on Mac/Linux, test the execute bit +// R W X R W X R W X +// 256 128 64 32 16 8 4 2 1 +function isUnixExecutable(stats) { + return ((stats.mode & 1) > 0 || + ((stats.mode & 8) > 0 && stats.gid === process.getgid()) || + ((stats.mode & 64) > 0 && stats.uid === process.getuid())); +} +// Get the path of cmd.exe in windows +function getCmdPath() { + var _a; + return (_a = process.env['COMSPEC']) !== null && _a !== void 0 ? _a : `cmd.exe`; } +exports.getCmdPath = getCmdPath; +//# sourceMappingURL=io-util.js.map + +/***/ }), + +/***/ 2826: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + +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.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.findInPath = exports.which = exports.mkdirP = exports.rmRF = exports.mv = exports.cp = void 0; +const assert_1 = __nccwpck_require__(9491); +const path = __importStar(__nccwpck_require__(1017)); +const ioUtil = __importStar(__nccwpck_require__(3446)); /** - * Extracts account name from the url - * @param url - url to extract the account name from - * @returns with the account name + * Copies a file or folder. + * Based off of shelljs - https://github.com/shelljs/shelljs/blob/9237f66c52e5daa40458f94f9565e18e8132f5a6/src/cp.js + * + * @param source source path + * @param dest destination path + * @param options optional. See CopyOptions. */ -function getAccountNameFromUrl(url) { - const parsedUrl = new URL(url); - let accountName; - try { - if (parsedUrl.hostname.split(".")[1] === "blob") { - // `${defaultEndpointsProtocol}://${accountName}.blob.${endpointSuffix}`; - accountName = parsedUrl.hostname.split(".")[0]; +function cp(source, dest, options = {}) { + return __awaiter(this, void 0, void 0, function* () { + const { force, recursive, copySourceDirectory } = readCopyOptions(options); + const destStat = (yield ioUtil.exists(dest)) ? yield ioUtil.stat(dest) : null; + // Dest is an existing file, but not forcing + if (destStat && destStat.isFile() && !force) { + return; } - else if (isIpEndpointStyle(parsedUrl)) { - // IPv4/IPv6 address hosts... Example - http://192.0.0.10:10001/devstoreaccount1/ - // Single word domain without a [dot] in the endpoint... Example - http://localhost:10001/devstoreaccount1/ - // .getPath() -> /devstoreaccount1/ - accountName = parsedUrl.pathname.split("/")[1]; + // If dest is an existing directory, should copy inside. + const newDest = destStat && destStat.isDirectory() && copySourceDirectory + ? path.join(dest, path.basename(source)) + : dest; + if (!(yield ioUtil.exists(source))) { + throw new Error(`no such file or directory: ${source}`); + } + const sourceStat = yield ioUtil.stat(source); + if (sourceStat.isDirectory()) { + if (!recursive) { + throw new Error(`Failed to copy. ${source} is a directory, but tried to copy without recursive flag.`); + } + else { + yield cpDirRecursive(source, newDest, 0, force); + } } else { - // Custom domain case: "https://customdomain.com/containername/blob". - accountName = ""; + if (path.relative(source, newDest) === '') { + // a file cannot be copied to itself + throw new Error(`'${newDest}' and '${source}' are the same file`); + } + yield copyFile(source, newDest, force); } - return accountName; - } - catch (error) { - throw new Error("Unable to extract accountName with provided information."); - } -} -function isIpEndpointStyle(parsedUrl) { - const host = parsedUrl.host; - // Case 1: Ipv6, use a broad regex to find out candidates whose host contains two ':'. - // 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|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) || - (Boolean(parsedUrl.port) && PathStylePorts.includes(parsedUrl.port))); + }); } +exports.cp = cp; /** - * Convert Tags to encoded string. + * Moves a path. * - * @param tags - + * @param source source path + * @param dest destination path + * @param options optional. See MoveOptions. */ -function toBlobTagsString(tags) { - if (tags === undefined) { - return undefined; - } - const tagPairs = []; - for (const key in tags) { - if (Object.prototype.hasOwnProperty.call(tags, key)) { - const value = tags[key]; - tagPairs.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`); +function mv(source, dest, options = {}) { + return __awaiter(this, void 0, void 0, function* () { + if (yield ioUtil.exists(dest)) { + let destExists = true; + if (yield ioUtil.isDirectory(dest)) { + // If dest is directory copy src into dest + dest = path.join(dest, path.basename(source)); + destExists = yield ioUtil.exists(dest); + } + if (destExists) { + if (options.force == null || options.force) { + yield rmRF(dest); + } + else { + throw new Error('Destination already exists'); + } + } } - } - return tagPairs.join("&"); + yield mkdirP(path.dirname(dest)); + yield ioUtil.rename(source, dest); + }); } +exports.mv = mv; /** - * Convert Tags type to BlobTags. + * Remove a path recursively with force * - * @param tags - + * @param inputPath path to remove */ -function toBlobTags(tags) { - if (tags === undefined) { - return undefined; - } - const res = { - blobTagSet: [], - }; - for (const key in tags) { - if (Object.prototype.hasOwnProperty.call(tags, key)) { - const value = tags[key]; - res.blobTagSet.push({ - key, - value, +function rmRF(inputPath) { + return __awaiter(this, void 0, void 0, function* () { + if (ioUtil.IS_WINDOWS) { + // 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 { + // note if path does not exist, error is silent + yield ioUtil.rm(inputPath, { + force: true, + maxRetries: 3, + recursive: true, + retryDelay: 300 }); } - } - return res; + catch (err) { + throw new Error(`File was unable to be removed ${err}`); + } + }); } +exports.rmRF = rmRF; /** - * Covert BlobTags to Tags type. + * Make a directory. Creates the full path with folders in between + * Will throw if it fails * - * @param tags - + * @param fsPath path to create + * @returns Promise */ -function toTags(tags) { - if (tags === undefined) { - return undefined; - } - const res = {}; - for (const blobTag of tags.blobTagSet) { - res[blobTag.key] = blobTag.value; - } - return res; +function mkdirP(fsPath) { + return __awaiter(this, void 0, void 0, function* () { + assert_1.ok(fsPath, 'a path argument must be provided'); + yield ioUtil.mkdir(fsPath, { recursive: true }); + }); } +exports.mkdirP = mkdirP; /** - * Convert BlobQueryTextConfiguration to QuerySerialization type. + * Returns path of a tool had the tool actually been invoked. Resolves via paths. + * If you check and the tool does not exist, it will throw. * - * @param textConfiguration - + * @param tool name of the tool + * @param check whether to check if tool exists + * @returns Promise path to tool */ -function toQuerySerialization(textConfiguration) { - if (textConfiguration === undefined) { - return undefined; - } - switch (textConfiguration.kind) { - case "csv": - return { - format: { - type: "delimited", - delimitedTextConfiguration: { - columnSeparator: textConfiguration.columnSeparator || ",", - fieldQuote: textConfiguration.fieldQuote || "", - recordSeparator: textConfiguration.recordSeparator, - escapeChar: textConfiguration.escapeCharacter || "", - headersPresent: textConfiguration.hasHeaders || false, - }, - }, - }; - case "json": - return { - format: { - type: "json", - jsonTextConfiguration: { - recordSeparator: textConfiguration.recordSeparator, - }, - }, - }; - case "arrow": - return { - format: { - type: "arrow", - arrowConfiguration: { - schema: textConfiguration.schema, - }, - }, - }; - case "parquet": - return { - format: { - type: "parquet", - }, - }; - default: - throw Error("Invalid BlobQueryTextConfiguration."); - } -} -function parseObjectReplicationRecord(objectReplicationRecord) { - if (!objectReplicationRecord) { - return undefined; - } - if ("policy-id" in objectReplicationRecord) { - // If the dictionary contains a key with policy id, we are not required to do any parsing since - // the policy id should already be stored in the ObjectReplicationDestinationPolicyId. - return undefined; - } - const orProperties = []; - for (const key in objectReplicationRecord) { - const ids = key.split("_"); - const policyPrefix = "or-"; - if (ids[0].startsWith(policyPrefix)) { - ids[0] = ids[0].substring(policyPrefix.length); +function which(tool, check) { + return __awaiter(this, void 0, void 0, function* () { + if (!tool) { + throw new Error("parameter 'tool' is required"); } - const rule = { - ruleId: ids[1], - replicationStatus: objectReplicationRecord[key], - }; - const policyIndex = orProperties.findIndex((policy) => policy.policyId === ids[0]); - if (policyIndex > -1) { - orProperties[policyIndex].rules.push(rule); + // recursive when check=true + if (check) { + const result = yield which(tool, false); + if (!result) { + if (ioUtil.IS_WINDOWS) { + throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also verify the file has a valid extension for an executable file.`); + } + else { + throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also check the file mode to verify the file is executable.`); + } + } + return result; } - else { - orProperties.push({ - policyId: ids[0], - rules: [rule], - }); + const matches = yield findInPath(tool); + if (matches && matches.length > 0) { + return matches[0]; } - } - return orProperties; -} -function httpAuthorizationToString(httpAuthorization) { - return httpAuthorization ? httpAuthorization.scheme + " " + httpAuthorization.value : undefined; -} -function BlobNameToString(name) { - if (name.encoded) { - return decodeURIComponent(name.content); - } - else { - return name.content; - } -} -function ConvertInternalResponseOfListBlobFlat(internalResponse) { - return Object.assign(Object.assign({}, internalResponse), { segment: { - blobItems: internalResponse.segment.blobItems.map((blobItemInteral) => { - const blobItem = Object.assign(Object.assign({}, blobItemInteral), { name: BlobNameToString(blobItemInteral.name) }); - return blobItem; - }), - } }); -} -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 = Object.assign(Object.assign({}, blobPrefixInternal), { name: BlobNameToString(blobPrefixInternal.name) }); - return blobPrefix; - }), - blobItems: internalResponse.segment.blobItems.map((blobItemInteral) => { - const blobItem = Object.assign(Object.assign({}, blobItemInteral), { name: BlobNameToString(blobItemInteral.name) }); - return blobItem; - }), - } }); + return ''; + }); } -function* ExtractPageRangeInfoItems(getPageRangesSegment) { - let pageRange = []; - let clearRange = []; - if (getPageRangesSegment.pageRange) - pageRange = getPageRangesSegment.pageRange; - if (getPageRangesSegment.clearRange) - clearRange = getPageRangesSegment.clearRange; - let pageRangeIndex = 0; - let clearRangeIndex = 0; - while (pageRangeIndex < pageRange.length && clearRangeIndex < clearRange.length) { - if (pageRange[pageRangeIndex].start < clearRange[clearRangeIndex].start) { - yield { - start: pageRange[pageRangeIndex].start, - end: pageRange[pageRangeIndex].end, - isClear: false, - }; - ++pageRangeIndex; +exports.which = which; +/** + * Returns a list of all occurrences of the given tool on the system path. + * + * @returns Promise the paths of the tool + */ +function findInPath(tool) { + return __awaiter(this, void 0, void 0, function* () { + if (!tool) { + throw new Error("parameter 'tool' is required"); } - else { - yield { - start: clearRange[clearRangeIndex].start, - end: clearRange[clearRangeIndex].end, - isClear: true, - }; - ++clearRangeIndex; + // build the list of extensions to try + const extensions = []; + if (ioUtil.IS_WINDOWS && process.env['PATHEXT']) { + for (const extension of process.env['PATHEXT'].split(path.delimiter)) { + if (extension) { + extensions.push(extension); + } + } } - } - for (; pageRangeIndex < pageRange.length; ++pageRangeIndex) { - yield { - start: pageRange[pageRangeIndex].start, - end: pageRange[pageRangeIndex].end, - isClear: false, - }; - } - for (; clearRangeIndex < clearRange.length; ++clearRangeIndex) { - yield { - start: clearRange[clearRangeIndex].start, - end: clearRange[clearRangeIndex].end, - isClear: true, - }; - } + // if it's rooted, return it if exists. otherwise return empty. + if (ioUtil.isRooted(tool)) { + const filePath = yield ioUtil.tryGetExecutablePath(tool, extensions); + if (filePath) { + return [filePath]; + } + return []; + } + // if any path separators, return empty + if (tool.includes(path.sep)) { + return []; + } + // build the list of directories + // + // Note, technically "where" checks the current directory on Windows. From a toolkit perspective, + // it feels like we should not do this. Checking the current directory seems like more of a use + // case of a shell, and the which() function exposed by the toolkit should strive for consistency + // across platforms. + const directories = []; + if (process.env.PATH) { + for (const p of process.env.PATH.split(path.delimiter)) { + if (p) { + directories.push(p); + } + } + } + // find all matches + const matches = []; + for (const directory of directories) { + const filePath = yield ioUtil.tryGetExecutablePath(path.join(directory, tool), extensions); + if (filePath) { + matches.push(filePath); + } + } + return matches; + }); } -/** - * 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("/"); +exports.findInPath = findInPath; +function readCopyOptions(options) { + const force = options.force == null ? true : options.force; + const recursive = Boolean(options.recursive); + const copySourceDirectory = options.copySourceDirectory == null + ? true + : Boolean(options.copySourceDirectory); + return { force, recursive, copySourceDirectory }; } -/** - * A typesafe helper for ensuring that a given response object has - * the original _response attached. - * @param response - A response object from calling a client operation - * @returns The same object, but with known _response property - */ -function assertResponse(response) { - if (`_response` in response) { - return response; - } - throw new TypeError(`Unexpected response object ${response}`); +function cpDirRecursive(sourceDir, destDir, currentDepth, force) { + return __awaiter(this, void 0, void 0, function* () { + // Ensure there is not a run away recursive copy + if (currentDepth >= 255) + return; + currentDepth++; + yield mkdirP(destDir); + const files = yield ioUtil.readdir(sourceDir); + for (const fileName of files) { + const srcFile = `${sourceDir}/${fileName}`; + const destFile = `${destDir}/${fileName}`; + const srcFileStat = yield ioUtil.lstat(srcFile); + if (srcFileStat.isDirectory()) { + // Recurse + yield cpDirRecursive(srcFile, destFile, currentDepth, force); + } + else { + yield copyFile(srcFile, destFile, force); + } + } + // Change the mode for the newly created directory + yield ioUtil.chmod(destDir, (yield ioUtil.stat(sourceDir)).mode); + }); +} +// Buffered file copy +function copyFile(srcFile, destFile, force) { + return __awaiter(this, void 0, void 0, function* () { + if ((yield ioUtil.lstat(srcFile)).isSymbolicLink()) { + // unlink/re-link it + try { + yield ioUtil.lstat(destFile); + yield ioUtil.unlink(destFile); + } + catch (e) { + // Try to override file permission + if (e.code === 'EPERM') { + yield ioUtil.chmod(destFile, '0666'); + yield ioUtil.unlink(destFile); + } + // other errors = it doesn't exist, no work to do + } + // Copy over symlink + const symlinkFull = yield ioUtil.readlink(srcFile); + yield ioUtil.symlink(symlinkFull, destFile, ioUtil.IS_WINDOWS ? 'junction' : null); + } + else if (!(yield ioUtil.exists(destFile)) || force) { + yield ioUtil.copyFile(srcFile, destFile); + } + }); } +//# sourceMappingURL=io.js.map + +/***/ }), + +/***/ 4732: +/***/ ((__unused_webpack_module, exports) => { + + + +Object.defineProperty(exports, "__esModule", ({ value: true })); // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. +/// +const listenersMap = new WeakMap(); +const abortedMap = new WeakMap(); /** - * RetryPolicy types. - */ -exports.StorageRetryPolicyType = void 0; -(function (StorageRetryPolicyType) { - /** - * Exponential retry. Retry time delay grows exponentially. - */ - StorageRetryPolicyType[StorageRetryPolicyType["EXPONENTIAL"] = 0] = "EXPONENTIAL"; - /** - * Linear retry. Retry time delay grows linearly. - */ - StorageRetryPolicyType[StorageRetryPolicyType["FIXED"] = 1] = "FIXED"; -})(exports.StorageRetryPolicyType || (exports.StorageRetryPolicyType = {})); -// Default values of StorageRetryOptions -const DEFAULT_RETRY_OPTIONS$1 = { - maxRetryDelayInMs: 120 * 1000, - maxTries: 4, - retryDelayInMs: 4 * 1000, - retryPolicyType: exports.StorageRetryPolicyType.EXPONENTIAL, - secondaryHost: "", - tryTimeoutInMs: undefined, // Use server side default timeout strategy -}; -const RETRY_ABORT_ERROR$1 = new abortController.AbortError("The operation was aborted."); -/** - * Retry policy with exponential retry and linear retry implemented. + * An aborter instance implements AbortSignal interface, can abort HTTP requests. + * + * - Call AbortSignal.none to create a new AbortSignal instance that cannot be cancelled. + * Use `AbortSignal.none` when you are required to pass a cancellation token but the operation + * cannot or will not ever be cancelled. + * + * @example + * Abort without timeout + * ```ts + * await doAsyncWork(AbortSignal.none); + * ``` */ -class StorageRetryPolicy extends BaseRequestPolicy { +class AbortSignal { + constructor() { + /** + * onabort event listener. + */ + this.onabort = null; + listenersMap.set(this, []); + abortedMap.set(this, false); + } /** - * Creates an instance of RetryPolicy. + * Status of whether aborted or not. * - * @param nextPolicy - - * @param options - - * @param retryOptions - + * @readonly */ - constructor(nextPolicy, options, retryOptions = DEFAULT_RETRY_OPTIONS$1) { - super(nextPolicy, options); - // Initialize retry options - this.retryOptions = { - retryPolicyType: retryOptions.retryPolicyType - ? retryOptions.retryPolicyType - : DEFAULT_RETRY_OPTIONS$1.retryPolicyType, - maxTries: retryOptions.maxTries && retryOptions.maxTries >= 1 - ? Math.floor(retryOptions.maxTries) - : DEFAULT_RETRY_OPTIONS$1.maxTries, - tryTimeoutInMs: retryOptions.tryTimeoutInMs && retryOptions.tryTimeoutInMs >= 0 - ? retryOptions.tryTimeoutInMs - : DEFAULT_RETRY_OPTIONS$1.tryTimeoutInMs, - retryDelayInMs: retryOptions.retryDelayInMs && retryOptions.retryDelayInMs >= 0 - ? Math.min(retryOptions.retryDelayInMs, retryOptions.maxRetryDelayInMs - ? retryOptions.maxRetryDelayInMs - : DEFAULT_RETRY_OPTIONS$1.maxRetryDelayInMs) - : DEFAULT_RETRY_OPTIONS$1.retryDelayInMs, - maxRetryDelayInMs: retryOptions.maxRetryDelayInMs && retryOptions.maxRetryDelayInMs >= 0 - ? retryOptions.maxRetryDelayInMs - : DEFAULT_RETRY_OPTIONS$1.maxRetryDelayInMs, - secondaryHost: retryOptions.secondaryHost - ? retryOptions.secondaryHost - : DEFAULT_RETRY_OPTIONS$1.secondaryHost, - }; + get aborted() { + if (!abortedMap.has(this)) { + throw new TypeError("Expected `this` to be an instance of AbortSignal."); + } + return abortedMap.get(this); } /** - * Sends request. + * Creates a new AbortSignal instance that will never be aborted. * - * @param request - + * @readonly */ - async sendRequest(request) { - return this.attemptSendRequest(request, false, 1); + static get none() { + return new AbortSignal(); } /** - * Decide and perform next retry. Won't mutate request parameter. + * Added new "abort" event listener, only support "abort" event. * - * @param request - - * @param secondaryHas404 - If attempt was against the secondary & it returned a StatusNotFound (404), then - * the resource was not found. This may be due to replication delay. So, in this - * case, we'll never try the secondary again for this operation. - * @param attempt - How many retries has been attempted to performed, starting from 1, which includes - * the attempt will be performed by this method call. + * @param _type - Only support "abort" event + * @param listener - The listener to be added */ - async attemptSendRequest(request, secondaryHas404, attempt) { - const newRequest = request.clone(); - const isPrimaryRetry = secondaryHas404 || - !this.retryOptions.secondaryHost || - !(request.method === "GET" || request.method === "HEAD" || request.method === "OPTIONS") || - attempt % 2 === 1; - if (!isPrimaryRetry) { - newRequest.url = setURLHost(newRequest.url, this.retryOptions.secondaryHost); - } - // Set the server-side timeout query parameter "timeout=[seconds]" - if (this.retryOptions.tryTimeoutInMs) { - newRequest.url = setURLParameter(newRequest.url, URLConstants.Parameters.TIMEOUT, Math.floor(this.retryOptions.tryTimeoutInMs / 1000).toString()); - } - let response; - try { - logger.info(`RetryPolicy: =====> Try=${attempt} ${isPrimaryRetry ? "Primary" : "Secondary"}`); - response = await this._nextPolicy.sendRequest(newRequest); - if (!this.shouldRetry(isPrimaryRetry, attempt, response)) { - return response; - } - secondaryHas404 = secondaryHas404 || (!isPrimaryRetry && response.status === 404); - } - catch (err) { - logger.error(`RetryPolicy: Caught error, message: ${err.message}, code: ${err.code}`); - if (!this.shouldRetry(isPrimaryRetry, attempt, response, err)) { - throw err; - } + addEventListener( + // tslint:disable-next-line:variable-name + _type, listener) { + if (!listenersMap.has(this)) { + throw new TypeError("Expected `this` to be an instance of AbortSignal."); } - await this.delay(isPrimaryRetry, attempt, request.abortSignal); - return this.attemptSendRequest(request, secondaryHas404, ++attempt); + const listeners = listenersMap.get(this); + listeners.push(listener); } /** - * Decide whether to retry according to last HTTP response and retry counters. + * Remove "abort" event listener, only support "abort" event. * - * @param isPrimaryRetry - - * @param attempt - - * @param response - - * @param err - + * @param _type - Only support "abort" event + * @param listener - The listener to be removed */ - shouldRetry(isPrimaryRetry, attempt, response, err) { - if (attempt >= this.retryOptions.maxTries) { - logger.info(`RetryPolicy: Attempt(s) ${attempt} >= maxTries ${this.retryOptions - .maxTries}, no further try.`); - return false; - } - // Handle network failures, you may need to customize the list when you implement - // your own http client - const retriableErrors = [ - "ETIMEDOUT", - "ESOCKETTIMEDOUT", - "ECONNREFUSED", - "ECONNRESET", - "ENOENT", - "ENOTFOUND", - "TIMEOUT", - "EPIPE", - "REQUEST_SEND_ERROR", // For default xhr based http client provided in ms-rest-js - ]; - if (err) { - for (const retriableError of retriableErrors) { - if (err.name.toUpperCase().includes(retriableError) || - err.message.toUpperCase().includes(retriableError) || - (err.code && err.code.toString().toUpperCase() === retriableError)) { - logger.info(`RetryPolicy: Network error ${retriableError} found, will retry.`); - return true; - } - } - } - // If attempt was against the secondary & it returned a StatusNotFound (404), then - // the resource was not found. This may be due to replication delay. So, in this - // case, we'll never try the secondary again for this operation. - if (response || err) { - const statusCode = response ? response.status : err ? err.statusCode : 0; - if (!isPrimaryRetry && statusCode === 404) { - logger.info(`RetryPolicy: Secondary access with 404, will retry.`); - return true; - } - // Server internal error or server timeout - if (statusCode === 503 || statusCode === 500) { - logger.info(`RetryPolicy: Will retry for status code ${statusCode}.`); - return true; - } + removeEventListener( + // tslint:disable-next-line:variable-name + _type, listener) { + if (!listenersMap.has(this)) { + throw new TypeError("Expected `this` to be an instance of AbortSignal."); } - // [Copy source error code] Feature is pending on service side, skip retry on copy source error for now. - // if (response) { - // // Retry select Copy Source Error Codes. - // if (response?.status >= 400) { - // const copySourceError = response.headers.get(HeaderConstants.X_MS_CopySourceErrorCode); - // if (copySourceError !== undefined) { - // switch (copySourceError) { - // case "InternalError": - // case "OperationTimedOut": - // case "ServerBusy": - // return true; - // } - // } - // } - // } - if ((err === null || err === void 0 ? void 0 : err.code) === "PARSE_ERROR" && (err === null || err === void 0 ? void 0 : err.message.startsWith(`Error "Error: Unclosed root tag`))) { - logger.info("RetryPolicy: Incomplete XML response likely due to service timeout, will retry."); - return true; + const listeners = listenersMap.get(this); + const index = listeners.indexOf(listener); + if (index > -1) { + listeners.splice(index, 1); } - return false; } /** - * Delay a calculated time between retries. - * - * @param isPrimaryRetry - - * @param attempt - - * @param abortSignal - + * Dispatches a synthetic event to the AbortSignal. */ - async delay(isPrimaryRetry, attempt, abortSignal) { - let delayTimeInMs = 0; - if (isPrimaryRetry) { - switch (this.retryOptions.retryPolicyType) { - case exports.StorageRetryPolicyType.EXPONENTIAL: - delayTimeInMs = Math.min((Math.pow(2, attempt - 1) - 1) * this.retryOptions.retryDelayInMs, this.retryOptions.maxRetryDelayInMs); - break; - case exports.StorageRetryPolicyType.FIXED: - delayTimeInMs = this.retryOptions.retryDelayInMs; - break; - } - } - else { - delayTimeInMs = Math.random() * 1000; - } - logger.info(`RetryPolicy: Delay for ${delayTimeInMs}ms`); - return delay(delayTimeInMs, abortSignal, RETRY_ABORT_ERROR$1); + dispatchEvent(_event) { + throw new Error("This is a stub dispatchEvent implementation that should not be used. It only exists for type-checking purposes."); } } - -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. /** - * StorageRetryPolicyFactory is a factory class helping generating {@link StorageRetryPolicy} objects. + * Helper to trigger an abort event immediately, the onabort and all abort event listeners will be triggered. + * Will try to trigger abort event for all linked AbortSignal nodes. + * + * - If there is a timeout, the timer will be cancelled. + * - If aborted is true, nothing will happen. + * + * @internal */ -class StorageRetryPolicyFactory { - /** - * Creates an instance of StorageRetryPolicyFactory. - * @param retryOptions - - */ - constructor(retryOptions) { - this.retryOptions = retryOptions; +// eslint-disable-next-line @azure/azure-sdk/ts-use-interface-parameters +function abortSignal(signal) { + if (signal.aborted) { + return; } - /** - * Creates a StorageRetryPolicy object. - * - * @param nextPolicy - - * @param options - - */ - create(nextPolicy, options) { - return new StorageRetryPolicy(nextPolicy, options, this.retryOptions); + if (signal.onabort) { + signal.onabort.call(signal); + } + const listeners = listenersMap.get(signal); + if (listeners) { + // Create a copy of listeners so mutations to the array + // (e.g. via removeListener calls) don't affect the listeners + // we invoke. + listeners.slice().forEach((listener) => { + listener.call(signal, { type: "abort" }); + }); } + abortedMap.set(signal, true); } // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. /** - * Credential policy used to sign HTTP(S) requests before sending. This is an - * abstract class. + * This error is thrown when an asynchronous operation has been aborted. + * Check for this error by testing the `name` that the name property of the + * error matches `"AbortError"`. + * + * @example + * ```ts + * const controller = new AbortController(); + * controller.abort(); + * try { + * doAsyncWork(controller.signal) + * } catch (e) { + * if (e.name === 'AbortError') { + * // handle abort error here. + * } + * } + * ``` */ -class CredentialPolicy extends BaseRequestPolicy { - /** - * Sends out request. - * - * @param request - - */ - sendRequest(request) { - return this._nextPolicy.sendRequest(this.signRequest(request)); - } - /** - * Child classes must implement this method with request signing. This method - * will be executed in {@link sendRequest}. - * - * @param request - - */ - signRequest(request) { - // Child classes must override this method with request signing. This method - // will be executed in sendRequest(). - return request; +class AbortError extends Error { + constructor(message) { + super(message); + this.name = "AbortError"; } } - -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. -/* - * We need to imitate .Net culture-aware sorting, which is used in storage service. - * Below tables contain sort-keys for en-US culture. +/** + * An AbortController provides an AbortSignal and the associated controls to signal + * that an asynchronous operation should be aborted. + * + * @example + * Abort an operation when another event fires + * ```ts + * const controller = new AbortController(); + * const signal = controller.signal; + * doAsyncWork(signal); + * button.addEventListener('click', () => controller.abort()); + * ``` + * + * @example + * Share aborter cross multiple operations in 30s + * ```ts + * // Upload the same data to 2 different data centers at the same time, + * // abort another when any of them is finished + * const controller = AbortController.withTimeout(30 * 1000); + * doAsyncWork(controller.signal).then(controller.abort); + * doAsyncWork(controller.signal).then(controller.abort); + *``` + * + * @example + * Cascaded aborting + * ```ts + * // All operations can't take more than 30 seconds + * const aborter = Aborter.timeout(30 * 1000); + * + * // Following 2 operations can't take more than 25 seconds + * await doAsyncWork(aborter.withTimeout(25 * 1000)); + * await doAsyncWork(aborter.withTimeout(25 * 1000)); + * ``` */ -const table_lv0 = new Uint32Array([ - 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, - 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x71c, 0x0, 0x71f, 0x721, - 0x723, 0x725, 0x0, 0x0, 0x0, 0x72d, 0x803, 0x0, 0x0, 0x733, 0x0, 0xd03, 0xd1a, 0xd1c, 0xd1e, - 0xd20, 0xd22, 0xd24, 0xd26, 0xd28, 0xd2a, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xe02, 0xe09, 0xe0a, - 0xe1a, 0xe21, 0xe23, 0xe25, 0xe2c, 0xe32, 0xe35, 0xe36, 0xe48, 0xe51, 0xe70, 0xe7c, 0xe7e, 0xe89, - 0xe8a, 0xe91, 0xe99, 0xe9f, 0xea2, 0xea4, 0xea6, 0xea7, 0xea9, 0x0, 0x0, 0x0, 0x743, 0x744, 0x748, - 0xe02, 0xe09, 0xe0a, 0xe1a, 0xe21, 0xe23, 0xe25, 0xe2c, 0xe32, 0xe35, 0xe36, 0xe48, 0xe51, 0xe70, - 0xe7c, 0xe7e, 0xe89, 0xe8a, 0xe91, 0xe99, 0xe9f, 0xea2, 0xea4, 0xea6, 0xea7, 0xea9, 0x0, 0x74c, - 0x0, 0x750, 0x0, -]); -const table_lv2 = new Uint32Array([ - 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, - 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, - 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, - 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, - 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, - 0x12, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, - 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, -]); -const table_lv4 = new Uint32Array([ - 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, - 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, - 0x0, 0x8012, 0x0, 0x0, 0x0, 0x0, 0x0, 0x8212, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, - 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, - 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, - 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, - 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, -]); -function compareHeader(lhs, rhs) { - if (isLessThan(lhs, rhs)) - return -1; - return 1; -} -function isLessThan(lhs, rhs) { - const tables = [table_lv0, table_lv2, table_lv4]; - let curr_level = 0; - let i = 0; - let j = 0; - while (curr_level < tables.length) { - if (curr_level === tables.length - 1 && i !== j) { - return i > j; - } - const weight1 = i < lhs.length ? tables[curr_level][lhs[i].charCodeAt(0)] : 0x1; - const weight2 = j < rhs.length ? tables[curr_level][rhs[j].charCodeAt(0)] : 0x1; - if (weight1 === 0x1 && weight2 === 0x1) { - i = 0; - j = 0; - ++curr_level; - } - else if (weight1 === weight2) { - ++i; - ++j; - } - else if (weight1 === 0) { - ++i; +class AbortController { + // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types + constructor(parentSignals) { + this._signal = new AbortSignal(); + if (!parentSignals) { + return; } - else if (weight2 === 0) { - ++j; + // coerce parentSignals into an array + if (!Array.isArray(parentSignals)) { + // eslint-disable-next-line prefer-rest-params + parentSignals = arguments; } - else { - return weight1 < weight2; + for (const parentSignal of parentSignals) { + // if the parent signal has already had abort() called, + // then call abort on this signal as well. + if (parentSignal.aborted) { + this.abort(); + } + else { + // when the parent signal aborts, this signal should as well. + parentSignal.addEventListener("abort", () => { + this.abort(); + }); + } } } - return false; -} - -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. -/** - * StorageSharedKeyCredentialPolicy is a policy used to sign HTTP request with a shared key. - */ -class StorageSharedKeyCredentialPolicy extends CredentialPolicy { /** - * Creates an instance of StorageSharedKeyCredentialPolicy. - * @param nextPolicy - - * @param options - - * @param factory - + * The AbortSignal associated with this controller that will signal aborted + * when the abort method is called on this controller. + * + * @readonly */ - constructor(nextPolicy, options, factory) { - super(nextPolicy, options); - this.factory = factory; + get signal() { + return this._signal; } /** - * Signs request. - * - * @param request - + * Signal that any operations passed this controller's associated abort signal + * to cancel any remaining work and throw an `AbortError`. */ - signRequest(request) { - request.headers.set(HeaderConstants.X_MS_DATE, new Date().toUTCString()); - if (request.body && - (typeof request.body === "string" || request.body !== undefined) && - request.body.length > 0) { - request.headers.set(HeaderConstants.CONTENT_LENGTH, Buffer.byteLength(request.body)); - } - const stringToSign = [ - request.method.toUpperCase(), - this.getHeaderValueToSign(request, HeaderConstants.CONTENT_LANGUAGE), - this.getHeaderValueToSign(request, HeaderConstants.CONTENT_ENCODING), - this.getHeaderValueToSign(request, HeaderConstants.CONTENT_LENGTH), - this.getHeaderValueToSign(request, HeaderConstants.CONTENT_MD5), - this.getHeaderValueToSign(request, HeaderConstants.CONTENT_TYPE), - this.getHeaderValueToSign(request, HeaderConstants.DATE), - this.getHeaderValueToSign(request, HeaderConstants.IF_MODIFIED_SINCE), - this.getHeaderValueToSign(request, HeaderConstants.IF_MATCH), - this.getHeaderValueToSign(request, HeaderConstants.IF_NONE_MATCH), - this.getHeaderValueToSign(request, HeaderConstants.IF_UNMODIFIED_SINCE), - this.getHeaderValueToSign(request, HeaderConstants.RANGE), - ].join("\n") + - "\n" + - this.getCanonicalizedHeadersString(request) + - this.getCanonicalizedResourceString(request); - const signature = this.factory.computeHMACSHA256(stringToSign); - request.headers.set(HeaderConstants.AUTHORIZATION, `SharedKey ${this.factory.accountName}:${signature}`); - // console.log(`[URL]:${request.url}`); - // console.log(`[HEADERS]:${request.headers.toString()}`); - // console.log(`[STRING TO SIGN]:${JSON.stringify(stringToSign)}`); - // console.log(`[KEY]: ${request.headers.get(HeaderConstants.AUTHORIZATION)}`); - return request; + abort() { + abortSignal(this._signal); } /** - * Retrieve header value according to shared key sign rules. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/authenticate-with-shared-key - * - * @param request - - * @param headerName - + * Creates a new AbortSignal instance that will abort after the provided ms. + * @param ms - Elapsed time in milliseconds to trigger an abort. */ - getHeaderValueToSign(request, headerName) { - const value = request.headers.get(headerName); - if (!value) { - return ""; - } - // When using version 2015-02-21 or later, if Content-Length is zero, then - // set the Content-Length part of the StringToSign to an empty string. - // https://docs.microsoft.com/en-us/rest/api/storageservices/authenticate-with-shared-key - if (headerName === HeaderConstants.CONTENT_LENGTH && value === "0") { - return ""; + static timeout(ms) { + const signal = new AbortSignal(); + const timer = setTimeout(abortSignal, ms, signal); + // Prevent the active Timer from keeping the Node.js event loop active. + if (typeof timer.unref === "function") { + timer.unref(); } - return value; + return signal; } - /** - * To construct the CanonicalizedHeaders portion of the signature string, follow these steps: - * 1. Retrieve all headers for the resource that begin with x-ms-, including the x-ms-date header. - * 2. Convert each HTTP header name to lowercase. - * 3. Sort the headers lexicographically by header name, in ascending order. - * Each header may appear only once in the string. - * 4. Replace any linear whitespace in the header value with a single space. - * 5. Trim any whitespace around the colon in the header. - * 6. Finally, append a new-line character to each canonicalized header in the resulting list. - * Construct the CanonicalizedHeaders string by concatenating all headers in this list into a single string. - * - * @param request - - */ - getCanonicalizedHeadersString(request) { - let headersArray = request.headers.headersArray().filter((value) => { - return value.name.toLowerCase().startsWith(HeaderConstants.PREFIX_FOR_STORAGE); - }); - headersArray.sort((a, b) => { - return compareHeader(a.name.toLowerCase(), b.name.toLowerCase()); - }); - // Remove duplicate headers - headersArray = headersArray.filter((value, index, array) => { - if (index > 0 && value.name.toLowerCase() === array[index - 1].name.toLowerCase()) { - return false; +} + +exports.AbortController = AbortController; +exports.AbortError = AbortError; +exports.AbortSignal = AbortSignal; +//# sourceMappingURL=index.js.map + + +/***/ }), + +/***/ 1758: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +var coreRestPipeline = __nccwpck_require__(903); +var tslib = __nccwpck_require__(1772); +var coreAuth = __nccwpck_require__(3728); +var coreUtil = __nccwpck_require__(1910); +var coreHttpCompat = __nccwpck_require__(7050); +var coreClient = __nccwpck_require__(2026); +var coreXml = __nccwpck_require__(9542); +var logger$1 = __nccwpck_require__(2208); +var abortController = __nccwpck_require__(5964); +var crypto = __nccwpck_require__(6113); +var coreTracing = __nccwpck_require__(3810); +var stream = __nccwpck_require__(2781); +var coreLro = __nccwpck_require__(2045); +var events = __nccwpck_require__(2361); +var fs = __nccwpck_require__(7147); +var util = __nccwpck_require__(3837); +var buffer = __nccwpck_require__(4300); + +function _interopNamespaceDefault(e) { + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); } - return true; - }); - let canonicalizedHeadersStringToSign = ""; - headersArray.forEach((header) => { - canonicalizedHeadersStringToSign += `${header.name - .toLowerCase() - .trimRight()}:${header.value.trimLeft()}\n`; }); - return canonicalizedHeadersStringToSign; - } - /** - * Retrieves the webResource canonicalized resource string. - * - * @param request - - */ - getCanonicalizedResourceString(request) { - const path = getURLPath(request.url) || "/"; - let canonicalizedResourceString = ""; - canonicalizedResourceString += `/${this.factory.accountName}${path}`; - const queries = getURLQueries(request.url); - const lowercaseQueries = {}; - if (queries) { - const queryKeys = []; - for (const key in queries) { - if (Object.prototype.hasOwnProperty.call(queries, key)) { - const lowercaseKey = key.toLowerCase(); - lowercaseQueries[lowercaseKey] = queries[key]; - queryKeys.push(lowercaseKey); - } - } - queryKeys.sort(); - for (const key of queryKeys) { - canonicalizedResourceString += `\n${key}:${decodeURIComponent(lowercaseQueries[key])}`; - } - } - return canonicalizedResourceString; } + n.default = e; + return Object.freeze(n); } +var coreHttpCompat__namespace = /*#__PURE__*/_interopNamespaceDefault(coreHttpCompat); +var coreClient__namespace = /*#__PURE__*/_interopNamespaceDefault(coreClient); +var fs__namespace = /*#__PURE__*/_interopNamespaceDefault(fs); +var util__namespace = /*#__PURE__*/_interopNamespaceDefault(util); + // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. /** - * Credential is an abstract class for Azure Storage HTTP requests signing. This - * class will host an credentialPolicyCreator factory which generates CredentialPolicy. + * The `@azure/logger` configuration for this package. */ -class Credential { - /** - * Creates a RequestPolicy object. - * - * @param _nextPolicy - - * @param _options - - */ - create(_nextPolicy, _options) { - throw new Error("Method should be implemented in children classes."); - } -} +const logger = logger$1.createClientLogger("storage-blob"); // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. /** - * ONLY AVAILABLE IN NODE.JS RUNTIME. - * - * StorageSharedKeyCredential for account key authorization of Azure Storage service. + * The base class from which all request policies derive. */ -class StorageSharedKeyCredential extends Credential { +class BaseRequestPolicy { /** - * Creates an instance of StorageSharedKeyCredential. - * @param accountName - - * @param accountKey - + * The main method to implement that manipulates a request/response. */ - constructor(accountName, accountKey) { - super(); - this.accountName = accountName; - this.accountKey = Buffer.from(accountKey, "base64"); - } + constructor( /** - * Creates a StorageSharedKeyCredentialPolicy object. - * - * @param nextPolicy - - * @param options - + * The next policy in the pipeline. Each policy is responsible for executing the next one if the request is to continue through the pipeline. */ - create(nextPolicy, options) { - return new StorageSharedKeyCredentialPolicy(nextPolicy, options, this); - } + _nextPolicy, /** - * Generates a hash signature for an HTTP request or for a SAS. - * - * @param stringToSign - + * The options that can be passed to a given request policy. */ - computeHMACSHA256(stringToSign) { - return crypto.createHmac("sha256", this.accountKey).update(stringToSign, "utf8").digest("base64"); + _options) { + this._nextPolicy = _nextPolicy; + this._options = _options; } -} - -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. -/** - * AnonymousCredentialPolicy is used with HTTP(S) requests that read public resources - * or for use with Shared Access Signatures (SAS). - */ -class AnonymousCredentialPolicy extends CredentialPolicy { /** - * Creates an instance of AnonymousCredentialPolicy. - * @param nextPolicy - - * @param options - + * Get whether or not a log with the provided log level should be logged. + * @param logLevel - The log level of the log that will be logged. + * @returns Whether or not a log with the provided log level should be logged. */ - // The base class has a protected constructor. Adding a public one to enable constructing of this class. - /* eslint-disable-next-line @typescript-eslint/no-useless-constructor*/ - constructor(nextPolicy, options) { - super(nextPolicy, options); + shouldLog(logLevel) { + return this._options.shouldLog(logLevel); } -} - -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. -/** - * AnonymousCredential provides a credentialPolicyCreator member used to create - * AnonymousCredentialPolicy objects. AnonymousCredentialPolicy is used with - * HTTP(S) requests that read public resources or for use with Shared Access - * Signatures (SAS). - */ -class AnonymousCredential extends Credential { /** - * Creates an {@link AnonymousCredentialPolicy} object. - * - * @param nextPolicy - - * @param options - + * Attempt to log the provided message to the provided logger. If no logger was provided or if + * the log level does not meat the logger's threshold, then nothing will be logged. + * @param logLevel - The log level of this log. + * @param message - The message of this log. */ - create(nextPolicy, options) { - return new AnonymousCredentialPolicy(nextPolicy, options); - } -} - -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. -let _defaultHttpClient; -function getCachedDefaultHttpClient() { - if (!_defaultHttpClient) { - _defaultHttpClient = coreRestPipeline.createDefaultHttpClient(); + log(logLevel, message) { + this._options.log(logLevel, message); } - return _defaultHttpClient; -} - -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. -/** - * The programmatic identifier of the StorageBrowserPolicy. - */ -const storageBrowserPolicyName = "storageBrowserPolicy"; -/** - * storageBrowserPolicy is a policy used to prevent browsers from caching requests - * and to remove cookies and explicit content-length headers. - */ -function storageBrowserPolicy() { - return { - name: storageBrowserPolicyName, - async sendRequest(request, next) { - if (coreUtil.isNode) { - return next(request); - } - if (request.method === "GET" || request.method === "HEAD") { - request.url = setURLParameter(request.url, URLConstants.Parameters.FORCE_BROWSER_NO_CACHE, new Date().getTime().toString()); - } - request.headers.delete(HeaderConstants.COOKIE); - // According to XHR standards, content-length should be fully controlled by browsers - request.headers.delete(HeaderConstants.CONTENT_LENGTH); - return next(request); - }, - }; } // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. -/** - * Name of the {@link storageRetryPolicy} - */ -const storageRetryPolicyName = "storageRetryPolicy"; +// Licensed under the MIT License. +const SDK_VERSION = "12.25.0"; +const SERVICE_VERSION = "2024-11-04"; +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 /** - * RetryPolicy types. + * The OAuth scope to use with Azure Storage. */ -var StorageRetryPolicyType; -(function (StorageRetryPolicyType) { - /** - * Exponential retry. Retry time delay grows exponentially. - */ - StorageRetryPolicyType[StorageRetryPolicyType["EXPONENTIAL"] = 0] = "EXPONENTIAL"; - /** - * Linear retry. Retry time delay grows linearly. - */ - StorageRetryPolicyType[StorageRetryPolicyType["FIXED"] = 1] = "FIXED"; -})(StorageRetryPolicyType || (StorageRetryPolicyType = {})); -// Default values of StorageRetryOptions -const DEFAULT_RETRY_OPTIONS = { - maxRetryDelayInMs: 120 * 1000, - maxTries: 4, - retryDelayInMs: 4 * 1000, - retryPolicyType: StorageRetryPolicyType.EXPONENTIAL, - secondaryHost: "", - tryTimeoutInMs: undefined, // Use server side default timeout strategy +const StorageOAuthScopes = "https://storage.azure.com/.default"; +const URLConstants = { + Parameters: { + FORCE_BROWSER_NO_CACHE: "_", + SIGNATURE: "sig", + SNAPSHOT: "snapshot", + VERSIONID: "versionid", + TIMEOUT: "timeout", + }, }; -const retriableErrors = [ - "ETIMEDOUT", - "ESOCKETTIMEDOUT", - "ECONNREFUSED", - "ECONNRESET", - "ENOENT", - "ENOTFOUND", - "TIMEOUT", - "EPIPE", - "REQUEST_SEND_ERROR", -]; -const RETRY_ABORT_ERROR = new abortController.AbortError("The operation was aborted."); -/** - * Retry policy with exponential retry and linear retry implemented. - */ -function storageRetryPolicy(options = {}) { - var _a, _b, _c, _d, _e, _f; - const retryPolicyType = (_a = options.retryPolicyType) !== null && _a !== void 0 ? _a : DEFAULT_RETRY_OPTIONS.retryPolicyType; - const maxTries = (_b = options.maxTries) !== null && _b !== void 0 ? _b : DEFAULT_RETRY_OPTIONS.maxTries; - const retryDelayInMs = (_c = options.retryDelayInMs) !== null && _c !== void 0 ? _c : DEFAULT_RETRY_OPTIONS.retryDelayInMs; - const maxRetryDelayInMs = (_d = options.maxRetryDelayInMs) !== null && _d !== void 0 ? _d : DEFAULT_RETRY_OPTIONS.maxRetryDelayInMs; - const secondaryHost = (_e = options.secondaryHost) !== null && _e !== void 0 ? _e : DEFAULT_RETRY_OPTIONS.secondaryHost; - const tryTimeoutInMs = (_f = options.tryTimeoutInMs) !== null && _f !== void 0 ? _f : DEFAULT_RETRY_OPTIONS.tryTimeoutInMs; - function shouldRetry({ isPrimaryRetry, attempt, response, error, }) { - var _a, _b; - if (attempt >= maxTries) { - logger.info(`RetryPolicy: Attempt(s) ${attempt} >= maxTries ${maxTries}, no further try.`); - return false; - } - if (error) { - for (const retriableError of retriableErrors) { - if (error.name.toUpperCase().includes(retriableError) || - error.message.toUpperCase().includes(retriableError) || - (error.code && error.code.toString().toUpperCase() === retriableError)) { - logger.info(`RetryPolicy: Network error ${retriableError} found, will retry.`); - return true; - } - } - if ((error === null || error === void 0 ? void 0 : error.code) === "PARSE_ERROR" && - (error === null || error === void 0 ? void 0 : error.message.startsWith(`Error "Error: Unclosed root tag`))) { - logger.info("RetryPolicy: Incomplete XML response likely due to service timeout, will retry."); - return true; - } - } - // If attempt was against the secondary & it returned a StatusNotFound (404), then - // the resource was not found. This may be due to replication delay. So, in this - // case, we'll never try the secondary again for this operation. - if (response || error) { - const statusCode = (_b = (_a = response === null || response === void 0 ? void 0 : response.status) !== null && _a !== void 0 ? _a : error === null || error === void 0 ? void 0 : error.statusCode) !== null && _b !== void 0 ? _b : 0; - if (!isPrimaryRetry && statusCode === 404) { - logger.info(`RetryPolicy: Secondary access with 404, will retry.`); - return true; - } - // Server internal error or server timeout - if (statusCode === 503 || statusCode === 500) { - logger.info(`RetryPolicy: Will retry for status code ${statusCode}.`); - return true; - } - } - // [Copy source error code] Feature is pending on service side, skip retry on copy source error for now. - // if (response) { - // // Retry select Copy Source Error Codes. - // if (response?.status >= 400) { - // const copySourceError = response.headers.get(HeaderConstants.X_MS_CopySourceErrorCode); - // if (copySourceError !== undefined) { - // switch (copySourceError) { - // case "InternalError": - // case "OperationTimedOut": - // case "ServerBusy": - // return true; - // } - // } - // } - // } - return false; - } - function calculateDelay(isPrimaryRetry, attempt) { - let delayTimeInMs = 0; - if (isPrimaryRetry) { - switch (retryPolicyType) { - case StorageRetryPolicyType.EXPONENTIAL: - delayTimeInMs = Math.min((Math.pow(2, attempt - 1) - 1) * retryDelayInMs, maxRetryDelayInMs); - break; - case StorageRetryPolicyType.FIXED: - delayTimeInMs = retryDelayInMs; - break; - } - } - else { - delayTimeInMs = Math.random() * 1000; - } - logger.info(`RetryPolicy: Delay for ${delayTimeInMs}ms`); - return delayTimeInMs; - } - return { - name: storageRetryPolicyName, - async sendRequest(request, next) { - // Set the server-side timeout query parameter "timeout=[seconds]" - if (tryTimeoutInMs) { - request.url = setURLParameter(request.url, URLConstants.Parameters.TIMEOUT, String(Math.floor(tryTimeoutInMs / 1000))); - } - const primaryUrl = request.url; - const secondaryUrl = secondaryHost ? setURLHost(request.url, secondaryHost) : undefined; - let secondaryHas404 = false; - let attempt = 1; - let retryAgain = true; - let response; - let error; - while (retryAgain) { - const isPrimaryRetry = secondaryHas404 || - !secondaryUrl || - !["GET", "HEAD", "OPTIONS"].includes(request.method) || - attempt % 2 === 1; - request.url = isPrimaryRetry ? primaryUrl : secondaryUrl; - response = undefined; - error = undefined; - try { - logger.info(`RetryPolicy: =====> Try=${attempt} ${isPrimaryRetry ? "Primary" : "Secondary"}`); - response = await next(request); - secondaryHas404 = secondaryHas404 || (!isPrimaryRetry && response.status === 404); - } - catch (e) { - if (coreRestPipeline.isRestError(e)) { - logger.error(`RetryPolicy: Caught error, message: ${e.message}, code: ${e.code}`); - error = e; - } - else { - logger.error(`RetryPolicy: Caught error, message: ${coreUtil.getErrorMessage(e)}`); - throw e; - } - } - retryAgain = shouldRetry({ isPrimaryRetry, attempt, response, error }); - if (retryAgain) { - await delay(calculateDelay(isPrimaryRetry, attempt), request.abortSignal, RETRY_ABORT_ERROR); - } - attempt++; - } - if (response) { - return response; - } - throw error !== null && error !== void 0 ? error : new coreRestPipeline.RestError("RetryPolicy failed without known error."); - }, - }; -} +const HTTPURLConnection = { + HTTP_ACCEPTED: 202, + HTTP_CONFLICT: 409, + HTTP_NOT_FOUND: 404, + HTTP_PRECON_FAILED: 412, + HTTP_RANGE_NOT_SATISFIABLE: 416, +}; +const HeaderConstants = { + AUTHORIZATION: "Authorization", + AUTHORIZATION_SCHEME: "Bearer", + CONTENT_ENCODING: "Content-Encoding", + CONTENT_ID: "Content-ID", + CONTENT_LANGUAGE: "Content-Language", + CONTENT_LENGTH: "Content-Length", + CONTENT_MD5: "Content-Md5", + CONTENT_TRANSFER_ENCODING: "Content-Transfer-Encoding", + CONTENT_TYPE: "Content-Type", + COOKIE: "Cookie", + DATE: "date", + IF_MATCH: "if-match", + IF_MODIFIED_SINCE: "if-modified-since", + IF_NONE_MATCH: "if-none-match", + IF_UNMODIFIED_SINCE: "if-unmodified-since", + PREFIX_FOR_STORAGE: "x-ms-", + RANGE: "Range", + USER_AGENT: "User-Agent", + X_MS_CLIENT_REQUEST_ID: "x-ms-client-request-id", + X_MS_COPY_SOURCE: "x-ms-copy-source", + X_MS_DATE: "x-ms-date", + X_MS_ERROR_CODE: "x-ms-error-code", + X_MS_VERSION: "x-ms-version", + X_MS_CopySourceErrorCode: "x-ms-copy-source-error-code", +}; +const ETagNone = ""; +const ETagAny = "*"; +const SIZE_1_MB = 1 * 1024 * 1024; +const BATCH_MAX_REQUEST = 256; +const BATCH_MAX_PAYLOAD_IN_BYTES = 4 * SIZE_1_MB; +const HTTP_LINE_ENDING = "\r\n"; +const HTTP_VERSION_1_1 = "HTTP/1.1"; +const EncryptionAlgorithmAES25 = "AES256"; +const DevelopmentConnectionString = `DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;BlobEndpoint=http://127.0.0.1:10000/devstoreaccount1;`; +const StorageBlobLoggingAllowedHeaderNames = [ + "Access-Control-Allow-Origin", + "Cache-Control", + "Content-Length", + "Content-Type", + "Date", + "Request-Id", + "traceparent", + "Transfer-Encoding", + "User-Agent", + "x-ms-client-request-id", + "x-ms-date", + "x-ms-error-code", + "x-ms-request-id", + "x-ms-return-client-request-id", + "x-ms-version", + "Accept-Ranges", + "Content-Disposition", + "Content-Encoding", + "Content-Language", + "Content-MD5", + "Content-Range", + "ETag", + "Last-Modified", + "Server", + "Vary", + "x-ms-content-crc64", + "x-ms-copy-action", + "x-ms-copy-completion-time", + "x-ms-copy-id", + "x-ms-copy-progress", + "x-ms-copy-status", + "x-ms-has-immutability-policy", + "x-ms-has-legal-hold", + "x-ms-lease-state", + "x-ms-lease-status", + "x-ms-range", + "x-ms-request-server-encrypted", + "x-ms-server-encrypted", + "x-ms-snapshot", + "x-ms-source-range", + "If-Match", + "If-Modified-Since", + "If-None-Match", + "If-Unmodified-Since", + "x-ms-access-tier", + "x-ms-access-tier-change-time", + "x-ms-access-tier-inferred", + "x-ms-account-kind", + "x-ms-archive-status", + "x-ms-blob-append-offset", + "x-ms-blob-cache-control", + "x-ms-blob-committed-block-count", + "x-ms-blob-condition-appendpos", + "x-ms-blob-condition-maxsize", + "x-ms-blob-content-disposition", + "x-ms-blob-content-encoding", + "x-ms-blob-content-language", + "x-ms-blob-content-length", + "x-ms-blob-content-md5", + "x-ms-blob-content-type", + "x-ms-blob-public-access", + "x-ms-blob-sequence-number", + "x-ms-blob-type", + "x-ms-copy-destination-snapshot", + "x-ms-creation-time", + "x-ms-default-encryption-scope", + "x-ms-delete-snapshots", + "x-ms-delete-type-permanent", + "x-ms-deny-encryption-scope-override", + "x-ms-encryption-algorithm", + "x-ms-if-sequence-number-eq", + "x-ms-if-sequence-number-le", + "x-ms-if-sequence-number-lt", + "x-ms-incremental-copy", + "x-ms-lease-action", + "x-ms-lease-break-period", + "x-ms-lease-duration", + "x-ms-lease-id", + "x-ms-lease-time", + "x-ms-page-write", + "x-ms-proposed-lease-id", + "x-ms-range-get-content-md5", + "x-ms-rehydrate-priority", + "x-ms-sequence-number-action", + "x-ms-sku-name", + "x-ms-source-content-md5", + "x-ms-source-if-match", + "x-ms-source-if-modified-since", + "x-ms-source-if-none-match", + "x-ms-source-if-unmodified-since", + "x-ms-tag-count", + "x-ms-encryption-key-sha256", + "x-ms-copy-source-error-code", + "x-ms-copy-source-status-code", + "x-ms-if-tags", + "x-ms-source-if-tags", +]; +const StorageBlobLoggingAllowedQueryParameters = [ + "comp", + "maxresults", + "rscc", + "rscd", + "rsce", + "rscl", + "rsct", + "se", + "si", + "sip", + "sp", + "spr", + "sr", + "srt", + "ss", + "st", + "sv", + "include", + "marker", + "prefix", + "copyid", + "restype", + "blockid", + "blocklisttype", + "delimiter", + "prevsnapshot", + "ske", + "skoid", + "sks", + "skt", + "sktid", + "skv", + "snapshot", +]; +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. -// Licensed under the MIT license. -/** - * The programmatic identifier of the storageSharedKeyCredentialPolicy. - */ -const storageSharedKeyCredentialPolicyName = "storageSharedKeyCredentialPolicy"; +// Licensed under the MIT License. /** - * storageSharedKeyCredentialPolicy handles signing requests using storage account keys. + * Reserved URL characters must be properly escaped for Storage services like Blob or File. + * + * ## URL encode and escape strategy for JS SDKs + * + * When customers pass a URL string into XxxClient classes constructor, the URL string may already be URL encoded or not. + * But before sending to Azure Storage server, the URL must be encoded. However, it's hard for a SDK to guess whether the URL + * string has been encoded or not. We have 2 potential strategies, and chose strategy two for the XxxClient constructors. + * + * ### Strategy One: Assume the customer URL string is not encoded, and always encode URL string in SDK. + * + * This is what legacy V2 SDK does, simple and works for most of the cases. + * - When customer URL string is "http://account.blob.core.windows.net/con/b:", + * SDK will encode it to "http://account.blob.core.windows.net/con/b%3A" and send to server. A blob named "b:" will be created. + * - When customer URL string is "http://account.blob.core.windows.net/con/b%3A", + * SDK will encode it to "http://account.blob.core.windows.net/con/b%253A" and send to server. A blob named "b%3A" will be created. + * + * But this strategy will make it not possible to create a blob with "?" in it's name. Because when customer URL string is + * "http://account.blob.core.windows.net/con/blob?name", the "?name" will be treated as URL paramter instead of blob name. + * If customer URL string is "http://account.blob.core.windows.net/con/blob%3Fname", a blob named "blob%3Fname" will be created. + * V2 SDK doesn't have this issue because it doesn't allow customer pass in a full URL, it accepts a separate blob name and encodeURIComponent for it. + * We cannot accept a SDK cannot create a blob name with "?". So we implement strategy two: + * + * ### Strategy Two: SDK doesn't assume the URL has been encoded or not. It will just escape the special characters. + * + * This is what V10 Blob Go SDK does. It accepts a URL type in Go, and call url.EscapedPath() to escape the special chars unescaped. + * - When customer URL string is "http://account.blob.core.windows.net/con/b:", + * SDK will escape ":" like "http://account.blob.core.windows.net/con/b%3A" and send to server. A blob named "b:" will be created. + * - When customer URL string is "http://account.blob.core.windows.net/con/b%3A", + * There is no special characters, so send "http://account.blob.core.windows.net/con/b%3A" to server. A blob named "b:" will be created. + * - When customer URL string is "http://account.blob.core.windows.net/con/b%253A", + * There is no special characters, so send "http://account.blob.core.windows.net/con/b%253A" to server. A blob named "b%3A" will be created. + * + * This strategy gives us flexibility to create with any special characters. But "%" will be treated as a special characters, if the URL string + * is not encoded, there shouldn't a "%" in the URL string, otherwise the URL is not a valid URL. + * If customer needs to create a blob with "%" in it's blob name, use "%25" instead of "%". Just like above 3rd sample. + * And following URL strings are invalid: + * - "http://account.blob.core.windows.net/con/b%" + * - "http://account.blob.core.windows.net/con/b%2" + * - "http://account.blob.core.windows.net/con/b%G" + * + * Another special character is "?", use "%2F" to represent a blob name with "?" in a URL string. + * + * ### Strategy for containerName, blobName or other specific XXXName parameters in methods such as `containerClient.getBlobClient(blobName)` + * + * We will apply strategy one, and call encodeURIComponent for these parameters like blobName. Because what customers passes in is a plain name instead of a URL. + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/naming-and-referencing-containers--blobs--and-metadata + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/naming-and-referencing-shares--directories--files--and-metadata + * + * @param url - */ -function storageSharedKeyCredentialPolicy(options) { - function signRequest(request) { - request.headers.set(HeaderConstants.X_MS_DATE, new Date().toUTCString()); - if (request.body && - (typeof request.body === "string" || Buffer.isBuffer(request.body)) && - request.body.length > 0) { - request.headers.set(HeaderConstants.CONTENT_LENGTH, Buffer.byteLength(request.body)); - } - const stringToSign = [ - request.method.toUpperCase(), - getHeaderValueToSign(request, HeaderConstants.CONTENT_LANGUAGE), - getHeaderValueToSign(request, HeaderConstants.CONTENT_ENCODING), - getHeaderValueToSign(request, HeaderConstants.CONTENT_LENGTH), - getHeaderValueToSign(request, HeaderConstants.CONTENT_MD5), - getHeaderValueToSign(request, HeaderConstants.CONTENT_TYPE), - getHeaderValueToSign(request, HeaderConstants.DATE), - getHeaderValueToSign(request, HeaderConstants.IF_MODIFIED_SINCE), - getHeaderValueToSign(request, HeaderConstants.IF_MATCH), - getHeaderValueToSign(request, HeaderConstants.IF_NONE_MATCH), - getHeaderValueToSign(request, HeaderConstants.IF_UNMODIFIED_SINCE), - getHeaderValueToSign(request, HeaderConstants.RANGE), - ].join("\n") + - "\n" + - getCanonicalizedHeadersString(request) + - getCanonicalizedResourceString(request); - const signature = crypto.createHmac("sha256", options.accountKey) - .update(stringToSign, "utf8") - .digest("base64"); - request.headers.set(HeaderConstants.AUTHORIZATION, `SharedKey ${options.accountName}:${signature}`); - // console.log(`[URL]:${request.url}`); - // console.log(`[HEADERS]:${request.headers.toString()}`); - // console.log(`[STRING TO SIGN]:${JSON.stringify(stringToSign)}`); - // console.log(`[KEY]: ${request.headers.get(HeaderConstants.AUTHORIZATION)}`); - } - /** - * Retrieve header value according to shared key sign rules. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/authenticate-with-shared-key - */ - function getHeaderValueToSign(request, headerName) { - const value = request.headers.get(headerName); - if (!value) { - return ""; - } - // When using version 2015-02-21 or later, if Content-Length is zero, then - // set the Content-Length part of the StringToSign to an empty string. - // https://docs.microsoft.com/en-us/rest/api/storageservices/authenticate-with-shared-key - if (headerName === HeaderConstants.CONTENT_LENGTH && value === "0") { - return ""; - } - return value; - } - /** - * To construct the CanonicalizedHeaders portion of the signature string, follow these steps: - * 1. Retrieve all headers for the resource that begin with x-ms-, including the x-ms-date header. - * 2. Convert each HTTP header name to lowercase. - * 3. Sort the headers lexicographically by header name, in ascending order. - * Each header may appear only once in the string. - * 4. Replace any linear whitespace in the header value with a single space. - * 5. Trim any whitespace around the colon in the header. - * 6. Finally, append a new-line character to each canonicalized header in the resulting list. - * Construct the CanonicalizedHeaders string by concatenating all headers in this list into a single string. - * - */ - function getCanonicalizedHeadersString(request) { - let headersArray = []; - for (const [name, value] of request.headers) { - if (name.toLowerCase().startsWith(HeaderConstants.PREFIX_FOR_STORAGE)) { - headersArray.push({ name, value }); +function escapeURLPath(url) { + const urlParsed = new URL(url); + let path = urlParsed.pathname; + path = path || "/"; + path = escape(path); + urlParsed.pathname = path; + return urlParsed.toString(); +} +function getProxyUriFromDevConnString(connectionString) { + // Development Connection String + // https://docs.microsoft.com/en-us/azure/storage/common/storage-configure-connection-string#connect-to-the-emulator-account-using-the-well-known-account-name-and-key + let proxyUri = ""; + if (connectionString.search("DevelopmentStorageProxyUri=") !== -1) { + // CONNECTION_STRING=UseDevelopmentStorage=true;DevelopmentStorageProxyUri=http://myProxyUri + const matchCredentials = connectionString.split(";"); + for (const element of matchCredentials) { + if (element.trim().startsWith("DevelopmentStorageProxyUri=")) { + proxyUri = element.trim().match("DevelopmentStorageProxyUri=(.*)")[1]; } } - headersArray.sort((a, b) => { - return compareHeader(a.name.toLowerCase(), b.name.toLowerCase()); - }); - // Remove duplicate headers - headersArray = headersArray.filter((value, index, array) => { - if (index > 0 && value.name.toLowerCase() === array[index - 1].name.toLowerCase()) { - return false; - } - return true; - }); - let canonicalizedHeadersStringToSign = ""; - headersArray.forEach((header) => { - canonicalizedHeadersStringToSign += `${header.name - .toLowerCase() - .trimRight()}:${header.value.trimLeft()}\n`; - }); - return canonicalizedHeadersStringToSign; } - function getCanonicalizedResourceString(request) { - const path = getURLPath(request.url) || "/"; - let canonicalizedResourceString = ""; - canonicalizedResourceString += `/${options.accountName}${path}`; - const queries = getURLQueries(request.url); - const lowercaseQueries = {}; - if (queries) { - const queryKeys = []; - for (const key in queries) { - if (Object.prototype.hasOwnProperty.call(queries, key)) { - const lowercaseKey = key.toLowerCase(); - lowercaseQueries[lowercaseKey] = queries[key]; - queryKeys.push(lowercaseKey); - } - } - queryKeys.sort(); - for (const key of queryKeys) { - canonicalizedResourceString += `\n${key}:${decodeURIComponent(lowercaseQueries[key])}`; - } + return proxyUri; +} +function getValueInConnString(connectionString, argument) { + const elements = connectionString.split(";"); + for (const element of elements) { + if (element.trim().startsWith(argument)) { + return element.trim().match(argument + "=(.*)")[1]; } - return canonicalizedResourceString; } - return { - name: storageSharedKeyCredentialPolicyName, - async sendRequest(request, next) { - signRequest(request); - return next(request); - }, - }; + return ""; } - -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. /** - * StorageBrowserPolicy will handle differences between Node.js and browser runtime, including: - * - * 1. Browsers cache GET/HEAD requests by adding conditional headers such as 'IF_MODIFIED_SINCE'. - * StorageBrowserPolicy is a policy used to add a timestamp query to GET/HEAD request URL - * thus avoid the browser cache. - * - * 2. Remove cookie header for security + * Extracts the parts of an Azure Storage account connection string. * - * 3. Remove content-length header to avoid browsers warning + * @param connectionString - Connection string. + * @returns String key value pairs of the storage account's url and credentials. */ -class StorageBrowserPolicy extends BaseRequestPolicy { - /** - * Creates an instance of StorageBrowserPolicy. - * @param nextPolicy - - * @param options - - */ - // The base class has a protected constructor. Adding a public one to enable constructing of this class. - /* eslint-disable-next-line @typescript-eslint/no-useless-constructor*/ - constructor(nextPolicy, options) { - super(nextPolicy, options); - } - /** - * Sends out request. - * - * @param request - - */ - async sendRequest(request) { - if (coreUtil.isNode) { - return this._nextPolicy.sendRequest(request); - } - if (request.method.toUpperCase() === "GET" || request.method.toUpperCase() === "HEAD") { - request.url = setURLParameter(request.url, URLConstants.Parameters.FORCE_BROWSER_NO_CACHE, new Date().getTime().toString()); - } - request.headers.remove(HeaderConstants.COOKIE); - // According to XHR standards, content-length should be fully controlled by browsers - request.headers.remove(HeaderConstants.CONTENT_LENGTH); - return this._nextPolicy.sendRequest(request); +function extractConnectionStringParts(connectionString) { + let proxyUri = ""; + if (connectionString.startsWith("UseDevelopmentStorage=true")) { + // Development connection string + proxyUri = getProxyUriFromDevConnString(connectionString); + connectionString = DevelopmentConnectionString; } -} - -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. + // Matching BlobEndpoint in the Account connection string + let blobEndpoint = getValueInConnString(connectionString, "BlobEndpoint"); + // Slicing off '/' at the end if exists + // (The methods that use `extractConnectionStringParts` expect the url to not have `/` at the end) + blobEndpoint = blobEndpoint.endsWith("/") ? blobEndpoint.slice(0, -1) : blobEndpoint; + if (connectionString.search("DefaultEndpointsProtocol=") !== -1 && + connectionString.search("AccountKey=") !== -1) { + // Account connection string + let defaultEndpointsProtocol = ""; + let accountName = ""; + let accountKey = Buffer.from("accountKey", "base64"); + let endpointSuffix = ""; + // Get account name and key + accountName = getValueInConnString(connectionString, "AccountName"); + accountKey = Buffer.from(getValueInConnString(connectionString, "AccountKey"), "base64"); + if (!blobEndpoint) { + // BlobEndpoint is not present in the Account connection string + // Can be obtained from `${defaultEndpointsProtocol}://${accountName}.blob.${endpointSuffix}` + defaultEndpointsProtocol = getValueInConnString(connectionString, "DefaultEndpointsProtocol"); + const protocol = defaultEndpointsProtocol.toLowerCase(); + if (protocol !== "https" && protocol !== "http") { + throw new Error("Invalid DefaultEndpointsProtocol in the provided Connection String. Expecting 'https' or 'http'"); + } + endpointSuffix = getValueInConnString(connectionString, "EndpointSuffix"); + if (!endpointSuffix) { + throw new Error("Invalid EndpointSuffix in the provided Connection String"); + } + blobEndpoint = `${defaultEndpointsProtocol}://${accountName}.blob.${endpointSuffix}`; + } + if (!accountName) { + throw new Error("Invalid AccountName in the provided Connection String"); + } + else if (accountKey.length === 0) { + throw new Error("Invalid AccountKey in the provided Connection String"); + } + return { + kind: "AccountConnString", + url: blobEndpoint, + accountName, + accountKey, + proxyUri, + }; + } + else { + // SAS connection string + let accountSas = getValueInConnString(connectionString, "SharedAccessSignature"); + 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"); + } + else if (!accountSas) { + throw new Error("Invalid SharedAccessSignature in the provided SAS Connection String"); + } + // client constructors assume accountSas does *not* start with ? + if (accountSas.startsWith("?")) { + accountSas = accountSas.substring(1); + } + return { kind: "SASConnString", url: blobEndpoint, accountName, accountSas }; + } +} /** - * StorageBrowserPolicyFactory is a factory class helping generating StorageBrowserPolicy objects. + * Internal escape method implemented Strategy Two mentioned in escapeURL() description. + * + * @param text - */ -class StorageBrowserPolicyFactory { - /** - * Creates a StorageBrowserPolicyFactory object. - * - * @param nextPolicy - - * @param options - - */ - create(nextPolicy, options) { - return new StorageBrowserPolicy(nextPolicy, options); - } +function escape(text) { + return encodeURIComponent(text) + .replace(/%2F/g, "/") // Don't escape for "/" + .replace(/'/g, "%27") // Escape for "'" + .replace(/\+/g, "%20") + .replace(/%25/g, "%"); // Revert encoded "%" } - -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. /** - * The programmatic identifier of the storageCorrectContentLengthPolicy. + * Append a string to URL path. Will remove duplicated "/" in front of the string + * when URL path ends with a "/". + * + * @param url - Source URL string + * @param name - String to be appended to URL + * @returns An updated URL string */ -const storageCorrectContentLengthPolicyName = "StorageCorrectContentLengthPolicy"; +function appendToURLPath(url, name) { + const urlParsed = new URL(url); + let path = urlParsed.pathname; + path = path ? (path.endsWith("/") ? `${path}${name}` : `${path}/${name}`) : name; + urlParsed.pathname = path; + return urlParsed.toString(); +} /** - * storageCorrectContentLengthPolicy to correctly set Content-Length header with request body length. + * Set URL parameter name and value. If name exists in URL parameters, old value + * will be replaced by name key. If not provide value, the parameter will be deleted. + * + * @param url - Source URL string + * @param name - Parameter name + * @param value - Parameter value + * @returns An updated URL string */ -function storageCorrectContentLengthPolicy() { - function correctContentLength(request) { - if (request.body && - (typeof request.body === "string" || Buffer.isBuffer(request.body)) && - request.body.length > 0) { - request.headers.set(HeaderConstants.CONTENT_LENGTH, Buffer.byteLength(request.body)); +function setURLParameter(url, name, value) { + const urlParsed = new URL(url); + const encodedName = encodeURIComponent(name); + const encodedValue = value ? encodeURIComponent(value) : undefined; + // mutating searchParams will change the encoding, so we have to do this ourselves + const searchString = urlParsed.search === "" ? "?" : urlParsed.search; + const searchPieces = []; + for (const pair of searchString.slice(1).split("&")) { + if (pair) { + const [key] = pair.split("=", 2); + if (key !== encodedName) { + searchPieces.push(pair); + } } } - return { - name: storageCorrectContentLengthPolicyName, - async sendRequest(request, next) { - correctContentLength(request); - return next(request); - }, - }; + if (encodedValue) { + searchPieces.push(`${encodedName}=${encodedValue}`); + } + urlParsed.search = searchPieces.length ? `?${searchPieces.join("&")}` : ""; + return urlParsed.toString(); } - -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. /** - * A helper to decide if a given argument satisfies the Pipeline contract - * @param pipeline - An argument that may be a Pipeline - * @returns true when the argument satisfies the Pipeline contract + * Get URL parameter by name. + * + * @param url - + * @param name - */ -function isPipelineLike(pipeline) { - if (!pipeline || typeof pipeline !== "object") { - return false; - } - const castPipeline = pipeline; - return (Array.isArray(castPipeline.factories) && - typeof castPipeline.options === "object" && - typeof castPipeline.toServiceClientOptions === "function"); +function getURLParameter(url, name) { + var _a; + const urlParsed = new URL(url); + return (_a = urlParsed.searchParams.get(name)) !== null && _a !== void 0 ? _a : undefined; } /** - * A Pipeline class containing HTTP request policies. - * You can create a default Pipeline by calling {@link newPipeline}. - * Or you can create a Pipeline with your own policies by the constructor of Pipeline. + * Set URL host. * - * Refer to {@link newPipeline} and provided policies before implementing your - * customized Pipeline. + * @param url - Source URL string + * @param host - New host string + * @returns An updated URL string */ -class Pipeline { - /** - * Creates an instance of Pipeline. Customize HTTPClient by implementing IHttpClient interface. - * - * @param factories - - * @param options - - */ - constructor(factories, options = {}) { - this.factories = factories; - this.options = options; - } - /** - * Transfer Pipeline object to ServiceClientOptions object which is required by - * ServiceClient constructor. - * - * @returns The ServiceClientOptions object from this Pipeline. - */ - toServiceClientOptions() { - return { - httpClient: this.options.httpClient, - requestPolicyFactories: this.factories, - }; - } +function setURLHost(url, host) { + const urlParsed = new URL(url); + urlParsed.hostname = host; + return urlParsed.toString(); } /** - * Creates a new Pipeline object with Credential provided. + * Get URL path from an URL string. * - * @param credential - Such as AnonymousCredential, StorageSharedKeyCredential or any credential from the `@azure/identity` package to authenticate requests to the service. You can also provide an object that implements the TokenCredential interface. If not specified, AnonymousCredential is used. - * @param pipelineOptions - Optional. Options. - * @returns A new Pipeline object. + * @param url - Source URL string */ -function newPipeline(credential, pipelineOptions = {}) { - if (!credential) { - credential = new AnonymousCredential(); +function getURLPath(url) { + try { + const urlParsed = new URL(url); + return urlParsed.pathname; } - const pipeline = new Pipeline([], pipelineOptions); - pipeline._credential = credential; - return pipeline; -} -function processDownlevelPipeline(pipeline) { - const knownFactoryFunctions = [ - isAnonymousCredential, - isStorageSharedKeyCredential, - isCoreHttpBearerTokenFactory, - isStorageBrowserPolicyFactory, - isStorageRetryPolicyFactory, - isStorageTelemetryPolicyFactory, - isCoreHttpPolicyFactory, - ]; - if (pipeline.factories.length) { - const novelFactories = pipeline.factories.filter((factory) => { - return !knownFactoryFunctions.some((knownFactory) => knownFactory(factory)); - }); - if (novelFactories.length) { - const hasInjector = novelFactories.some((factory) => isInjectorPolicyFactory(factory)); - // if there are any left over, wrap in a requestPolicyFactoryPolicy - return { - wrappedPolicies: coreHttpCompat.createRequestPolicyFactoryPolicy(novelFactories), - afterRetry: hasInjector, - }; - } + catch (e) { + return undefined; } - return undefined; } -function getCoreClientOptions(pipeline) { - var _a; - const _b = pipeline.options, { httpClient: v1Client } = _b, restOptions = tslib.__rest(_b, ["httpClient"]); - let httpClient = pipeline._coreHttpClient; - if (!httpClient) { - httpClient = v1Client ? coreHttpCompat.convertHttpClient(v1Client) : getCachedDefaultHttpClient(); - pipeline._coreHttpClient = httpClient; +/** + * Get URL scheme from an URL string. + * + * @param url - Source URL string + */ +function getURLScheme(url) { + try { + const urlParsed = new URL(url); + return urlParsed.protocol.endsWith(":") ? urlParsed.protocol.slice(0, -1) : urlParsed.protocol; } - let corePipeline = pipeline._corePipeline; - if (!corePipeline) { - const packageDetails = `azsdk-js-azure-storage-blob/${SDK_VERSION}`; - const userAgentPrefix = restOptions.userAgentOptions && restOptions.userAgentOptions.userAgentPrefix - ? `${restOptions.userAgentOptions.userAgentPrefix} ${packageDetails}` - : `${packageDetails}`; - corePipeline = coreClient.createClientPipeline(Object.assign(Object.assign({}, restOptions), { loggingOptions: { - additionalAllowedHeaderNames: StorageBlobLoggingAllowedHeaderNames, - additionalAllowedQueryParameters: StorageBlobLoggingAllowedQueryParameters, - logger: logger.info, - }, userAgentOptions: { - userAgentPrefix, - }, serializationOptions: { - stringifyXML: coreXml.stringifyXML, - serializerOptions: { - xml: { - // Use customized XML char key of "#" so we can deserialize metadata - // with "_" key - xmlCharKey: "#", - }, - }, - }, deserializationOptions: { - parseXML: coreXml.parseXML, - serializerOptions: { - xml: { - // Use customized XML char key of "#" so we can deserialize metadata - // with "_" key - xmlCharKey: "#", - }, - }, - } })); - corePipeline.removePolicy({ phase: "Retry" }); - corePipeline.removePolicy({ name: coreRestPipeline.decompressResponsePolicyName }); - corePipeline.addPolicy(storageCorrectContentLengthPolicy()); - corePipeline.addPolicy(storageRetryPolicy(restOptions.retryOptions), { phase: "Retry" }); - corePipeline.addPolicy(storageBrowserPolicy()); - const downlevelResults = processDownlevelPipeline(pipeline); - if (downlevelResults) { - corePipeline.addPolicy(downlevelResults.wrappedPolicies, downlevelResults.afterRetry ? { afterPhase: "Retry" } : undefined); - } - const credential = getCredentialFromPipeline(pipeline); - if (coreAuth.isTokenCredential(credential)) { - corePipeline.addPolicy(coreRestPipeline.bearerTokenAuthenticationPolicy({ - credential, - scopes: (_a = restOptions.audience) !== null && _a !== void 0 ? _a : StorageOAuthScopes, - challengeCallbacks: { authorizeRequestOnChallenge: coreClient.authorizeRequestOnTenantChallenge }, - }), { phase: "Sign" }); - } - else if (credential instanceof StorageSharedKeyCredential) { - corePipeline.addPolicy(storageSharedKeyCredentialPolicy({ - accountName: credential.accountName, - accountKey: credential.accountKey, - }), { phase: "Sign" }); - } - pipeline._corePipeline = corePipeline; + catch (e) { + return undefined; } - return Object.assign(Object.assign({}, restOptions), { allowInsecureConnection: true, httpClient, pipeline: corePipeline }); } -function getCredentialFromPipeline(pipeline) { - // see if we squirreled one away on the type itself - if (pipeline._credential) { - return pipeline._credential; +/** + * Get URL path and query from an URL string. + * + * @param url - Source URL string + */ +function getURLPathAndQuery(url) { + const urlParsed = new URL(url); + const pathString = urlParsed.pathname; + if (!pathString) { + throw new RangeError("Invalid url without valid path."); } - // if it came from another package, loop over the factories and look for one like before - let credential = new AnonymousCredential(); - for (const factory of pipeline.factories) { - if (coreAuth.isTokenCredential(factory.credential)) { - // Only works if the factory has been attached a "credential" property. - // We do that in newPipeline() when using TokenCredential. - credential = factory.credential; - } - else if (isStorageSharedKeyCredential(factory)) { - return factory; - } + let queryString = urlParsed.search || ""; + queryString = queryString.trim(); + if (queryString !== "") { + queryString = queryString.startsWith("?") ? queryString : `?${queryString}`; // Ensure query string start with '?' } - return credential; + return `${pathString}${queryString}`; } -function isStorageSharedKeyCredential(factory) { - if (factory instanceof StorageSharedKeyCredential) { - return true; +/** + * Get URL query key value pairs from an URL string. + * + * @param url - + */ +function getURLQueries(url) { + let queryString = new URL(url).search; + if (!queryString) { + return {}; } - return factory.constructor.name === "StorageSharedKeyCredential"; -} -function isAnonymousCredential(factory) { - if (factory instanceof AnonymousCredential) { - return true; + queryString = queryString.trim(); + queryString = queryString.startsWith("?") ? queryString.substring(1) : queryString; + let querySubStrings = queryString.split("&"); + querySubStrings = querySubStrings.filter((value) => { + const indexOfEqual = value.indexOf("="); + const lastIndexOfEqual = value.lastIndexOf("="); + return (indexOfEqual > 0 && indexOfEqual === lastIndexOfEqual && lastIndexOfEqual < value.length - 1); + }); + const queries = {}; + for (const querySubString of querySubStrings) { + const splitResults = querySubString.split("="); + const key = splitResults[0]; + const value = splitResults[1]; + queries[key] = value; } - return factory.constructor.name === "AnonymousCredential"; -} -function isCoreHttpBearerTokenFactory(factory) { - return coreAuth.isTokenCredential(factory.credential); + return queries; } -function isStorageBrowserPolicyFactory(factory) { - if (factory instanceof StorageBrowserPolicyFactory) { - return true; +/** + * Append a string to URL query. + * + * @param url - Source URL string. + * @param queryParts - String to be appended to the URL query. + * @returns An updated URL string. + */ +function appendToURLQuery(url, queryParts) { + const urlParsed = new URL(url); + let query = urlParsed.search; + if (query) { + query += "&" + queryParts; } - return factory.constructor.name === "StorageBrowserPolicyFactory"; -} -function isStorageRetryPolicyFactory(factory) { - if (factory instanceof StorageRetryPolicyFactory) { - return true; + else { + query = queryParts; } - return factory.constructor.name === "StorageRetryPolicyFactory"; + urlParsed.search = query; + return urlParsed.toString(); } -function isStorageTelemetryPolicyFactory(factory) { - return factory.constructor.name === "TelemetryPolicyFactory"; +/** + * Rounds a date off to seconds. + * + * @param date - + * @param withMilliseconds - If true, YYYY-MM-DDThh:mm:ss.fffffffZ will be returned; + * If false, YYYY-MM-DDThh:mm:ssZ will be returned. + * @returns Date string in ISO8061 format, with or without 7 milliseconds component + */ +function truncatedISO8061Date(date, withMilliseconds = true) { + // Date.toISOString() will return like "2018-10-29T06:34:36.139Z" + const dateString = date.toISOString(); + return withMilliseconds + ? dateString.substring(0, dateString.length - 1) + "0000" + "Z" + : dateString.substring(0, dateString.length - 5) + "Z"; } -function isInjectorPolicyFactory(factory) { - return factory.constructor.name === "InjectorPolicyFactory"; +/** + * Base64 encode. + * + * @param content - + */ +function base64encode(content) { + return !coreUtil.isNode ? btoa(content) : Buffer.from(content).toString("base64"); } -function isCoreHttpPolicyFactory(factory) { - const knownPolicies = [ - "GenerateClientRequestIdPolicy", - "TracingPolicy", - "LogPolicy", - "ProxyPolicy", - "DisableResponseDecompressionPolicy", - "KeepAlivePolicy", - "DeserializationPolicy", - ]; - const mockHttpClient = { - sendRequest: async (request) => { - return { - request, - headers: request.headers.clone(), - status: 500, - }; - }, - }; - const mockRequestPolicyOptions = { - log(_logLevel, _message) { - /* do nothing */ - }, - shouldLog(_logLevel) { - return false; - }, - }; - const policyInstance = factory.create(mockHttpClient, mockRequestPolicyOptions); - const policyName = policyInstance.constructor.name; - // bundlers sometimes add a custom suffix to the class name to make it unique - return knownPolicies.some((knownPolicyName) => { - return policyName.startsWith(knownPolicyName); - }); +/** + * Generate a 64 bytes base64 block ID string. + * + * @param blockIndex - + */ +function generateBlockID(blockIDPrefix, blockIndex) { + // To generate a 64 bytes base64 string, source string should be 48 + const maxSourceStringLength = 48; + // A blob can have a maximum of 100,000 uncommitted blocks at any given time + const maxBlockIndexLength = 6; + const maxAllowedBlockIDPrefixLength = maxSourceStringLength - maxBlockIndexLength; + if (blockIDPrefix.length > maxAllowedBlockIDPrefixLength) { + blockIDPrefix = blockIDPrefix.slice(0, maxAllowedBlockIDPrefixLength); + } + const res = blockIDPrefix + + padStart(blockIndex.toString(), maxSourceStringLength - blockIDPrefix.length, "0"); + return base64encode(res); } - -/* - * Copyright (c) Microsoft Corporation. - * Licensed under the MIT License. +/** + * Delay specified time interval. * - * Code generated by Microsoft (R) AutoRest Code Generator. - * Changes may cause incorrect behavior and will be lost if the code is regenerated. + * @param timeInMs - + * @param aborter - + * @param abortError - */ -const BlobServiceProperties = { - serializedName: "BlobServiceProperties", - xmlName: "StorageServiceProperties", - type: { - name: "Composite", - className: "BlobServiceProperties", - modelProperties: { - blobAnalyticsLogging: { - serializedName: "Logging", - xmlName: "Logging", - type: { - name: "Composite", - className: "Logging", - }, - }, - hourMetrics: { - serializedName: "HourMetrics", - xmlName: "HourMetrics", - type: { - name: "Composite", - className: "Metrics", - }, - }, - minuteMetrics: { - serializedName: "MinuteMetrics", - xmlName: "MinuteMetrics", - type: { - name: "Composite", - className: "Metrics", - }, - }, - cors: { - serializedName: "Cors", - xmlName: "Cors", - xmlIsWrapped: true, - xmlElementName: "CorsRule", - type: { - name: "Sequence", - element: { - type: { - name: "Composite", - className: "CorsRule", - }, +async function delay(timeInMs, aborter, abortError) { + return new Promise((resolve, reject) => { + /* eslint-disable-next-line prefer-const */ + let timeout; + const abortHandler = () => { + if (timeout !== undefined) { + clearTimeout(timeout); + } + reject(abortError); + }; + const resolveHandler = () => { + if (aborter !== undefined) { + aborter.removeEventListener("abort", abortHandler); + } + resolve(); + }; + timeout = setTimeout(resolveHandler, timeInMs); + if (aborter !== undefined) { + aborter.addEventListener("abort", abortHandler); + } + }); +} +/** + * String.prototype.padStart() + * + * @param currentString - + * @param targetLength - + * @param padString - + */ +function padStart(currentString, targetLength, padString = " ") { + // @ts-expect-error: TS doesn't know this code needs to run downlevel sometimes + if (String.prototype.padStart) { + return currentString.padStart(targetLength, padString); + } + padString = padString || " "; + if (currentString.length > targetLength) { + return currentString; + } + else { + targetLength = targetLength - currentString.length; + if (targetLength > padString.length) { + padString += padString.repeat(targetLength / padString.length); + } + return padString.slice(0, targetLength) + currentString; + } +} +/** + * If two strings are equal when compared case insensitive. + * + * @param str1 - + * @param str2 - + */ +function iEqual(str1, str2) { + return str1.toLocaleLowerCase() === str2.toLocaleLowerCase(); +} +/** + * Extracts account name from the url + * @param url - url to extract the account name from + * @returns with the account name + */ +function getAccountNameFromUrl(url) { + const parsedUrl = new URL(url); + let accountName; + try { + if (parsedUrl.hostname.split(".")[1] === "blob") { + // `${defaultEndpointsProtocol}://${accountName}.blob.${endpointSuffix}`; + accountName = parsedUrl.hostname.split(".")[0]; + } + else if (isIpEndpointStyle(parsedUrl)) { + // IPv4/IPv6 address hosts... Example - http://192.0.0.10:10001/devstoreaccount1/ + // Single word domain without a [dot] in the endpoint... Example - http://localhost:10001/devstoreaccount1/ + // .getPath() -> /devstoreaccount1/ + accountName = parsedUrl.pathname.split("/")[1]; + } + else { + // Custom domain case: "https://customdomain.com/containername/blob". + accountName = ""; + } + return accountName; + } + catch (error) { + throw new Error("Unable to extract accountName with provided information."); + } +} +function isIpEndpointStyle(parsedUrl) { + const host = parsedUrl.host; + // Case 1: Ipv6, use a broad regex to find out candidates whose host contains two ':'. + // 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|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) || + (Boolean(parsedUrl.port) && PathStylePorts.includes(parsedUrl.port))); +} +/** + * Convert Tags to encoded string. + * + * @param tags - + */ +function toBlobTagsString(tags) { + if (tags === undefined) { + return undefined; + } + const tagPairs = []; + for (const key in tags) { + if (Object.prototype.hasOwnProperty.call(tags, key)) { + const value = tags[key]; + tagPairs.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`); + } + } + return tagPairs.join("&"); +} +/** + * Convert Tags type to BlobTags. + * + * @param tags - + */ +function toBlobTags(tags) { + if (tags === undefined) { + return undefined; + } + const res = { + blobTagSet: [], + }; + for (const key in tags) { + if (Object.prototype.hasOwnProperty.call(tags, key)) { + const value = tags[key]; + res.blobTagSet.push({ + key, + value, + }); + } + } + return res; +} +/** + * Covert BlobTags to Tags type. + * + * @param tags - + */ +function toTags(tags) { + if (tags === undefined) { + return undefined; + } + const res = {}; + for (const blobTag of tags.blobTagSet) { + res[blobTag.key] = blobTag.value; + } + return res; +} +/** + * Convert BlobQueryTextConfiguration to QuerySerialization type. + * + * @param textConfiguration - + */ +function toQuerySerialization(textConfiguration) { + if (textConfiguration === undefined) { + return undefined; + } + switch (textConfiguration.kind) { + case "csv": + return { + format: { + type: "delimited", + delimitedTextConfiguration: { + columnSeparator: textConfiguration.columnSeparator || ",", + fieldQuote: textConfiguration.fieldQuote || "", + recordSeparator: textConfiguration.recordSeparator, + escapeChar: textConfiguration.escapeCharacter || "", + headersPresent: textConfiguration.hasHeaders || false, }, }, - }, - defaultServiceVersion: { - serializedName: "DefaultServiceVersion", - xmlName: "DefaultServiceVersion", - type: { - name: "String", - }, - }, - deleteRetentionPolicy: { - serializedName: "DeleteRetentionPolicy", - xmlName: "DeleteRetentionPolicy", - type: { - name: "Composite", - className: "RetentionPolicy", - }, - }, - staticWebsite: { - serializedName: "StaticWebsite", - xmlName: "StaticWebsite", - type: { - name: "Composite", - className: "StaticWebsite", - }, - }, - }, - }, -}; -const Logging = { - serializedName: "Logging", - type: { - name: "Composite", - className: "Logging", - modelProperties: { - version: { - serializedName: "Version", - required: true, - xmlName: "Version", - type: { - name: "String", - }, - }, - deleteProperty: { - serializedName: "Delete", - required: true, - xmlName: "Delete", - type: { - name: "Boolean", - }, - }, - read: { - serializedName: "Read", - required: true, - xmlName: "Read", - type: { - name: "Boolean", - }, - }, - write: { - serializedName: "Write", - required: true, - xmlName: "Write", - type: { - name: "Boolean", - }, - }, - retentionPolicy: { - serializedName: "RetentionPolicy", - xmlName: "RetentionPolicy", - type: { - name: "Composite", - className: "RetentionPolicy", - }, - }, - }, - }, -}; -const RetentionPolicy = { - serializedName: "RetentionPolicy", - type: { - name: "Composite", - className: "RetentionPolicy", - modelProperties: { - enabled: { - serializedName: "Enabled", - required: true, - xmlName: "Enabled", - type: { - name: "Boolean", - }, - }, - days: { - constraints: { - InclusiveMinimum: 1, - }, - serializedName: "Days", - xmlName: "Days", - type: { - name: "Number", - }, - }, - }, - }, -}; -const Metrics = { - serializedName: "Metrics", - type: { - name: "Composite", - className: "Metrics", - modelProperties: { - version: { - serializedName: "Version", - xmlName: "Version", - type: { - name: "String", - }, - }, - enabled: { - serializedName: "Enabled", - required: true, - xmlName: "Enabled", - type: { - name: "Boolean", + }; + case "json": + return { + format: { + type: "json", + jsonTextConfiguration: { + recordSeparator: textConfiguration.recordSeparator, + }, }, - }, - includeAPIs: { - serializedName: "IncludeAPIs", - xmlName: "IncludeAPIs", - type: { - name: "Boolean", + }; + case "arrow": + return { + format: { + type: "arrow", + arrowConfiguration: { + schema: textConfiguration.schema, + }, }, - }, - retentionPolicy: { - serializedName: "RetentionPolicy", - xmlName: "RetentionPolicy", - type: { - name: "Composite", - className: "RetentionPolicy", + }; + case "parquet": + return { + format: { + type: "parquet", }, - }, - }, - }, + }; + default: + throw Error("Invalid BlobQueryTextConfiguration."); + } +} +function parseObjectReplicationRecord(objectReplicationRecord) { + if (!objectReplicationRecord) { + return undefined; + } + if ("policy-id" in objectReplicationRecord) { + // If the dictionary contains a key with policy id, we are not required to do any parsing since + // the policy id should already be stored in the ObjectReplicationDestinationPolicyId. + return undefined; + } + const orProperties = []; + for (const key in objectReplicationRecord) { + const ids = key.split("_"); + const policyPrefix = "or-"; + if (ids[0].startsWith(policyPrefix)) { + ids[0] = ids[0].substring(policyPrefix.length); + } + const rule = { + ruleId: ids[1], + replicationStatus: objectReplicationRecord[key], + }; + const policyIndex = orProperties.findIndex((policy) => policy.policyId === ids[0]); + if (policyIndex > -1) { + orProperties[policyIndex].rules.push(rule); + } + else { + orProperties.push({ + policyId: ids[0], + rules: [rule], + }); + } + } + return orProperties; +} +function httpAuthorizationToString(httpAuthorization) { + return httpAuthorization ? httpAuthorization.scheme + " " + httpAuthorization.value : undefined; +} +function BlobNameToString(name) { + if (name.encoded) { + return decodeURIComponent(name.content); + } + else { + return name.content; + } +} +function ConvertInternalResponseOfListBlobFlat(internalResponse) { + return Object.assign(Object.assign({}, internalResponse), { segment: { + blobItems: internalResponse.segment.blobItems.map((blobItemInteral) => { + const blobItem = Object.assign(Object.assign({}, blobItemInteral), { name: BlobNameToString(blobItemInteral.name) }); + return blobItem; + }), + } }); +} +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 = Object.assign(Object.assign({}, blobPrefixInternal), { name: BlobNameToString(blobPrefixInternal.name) }); + return blobPrefix; + }), + blobItems: internalResponse.segment.blobItems.map((blobItemInteral) => { + const blobItem = Object.assign(Object.assign({}, blobItemInteral), { name: BlobNameToString(blobItemInteral.name) }); + return blobItem; + }), + } }); +} +function* ExtractPageRangeInfoItems(getPageRangesSegment) { + let pageRange = []; + let clearRange = []; + if (getPageRangesSegment.pageRange) + pageRange = getPageRangesSegment.pageRange; + if (getPageRangesSegment.clearRange) + clearRange = getPageRangesSegment.clearRange; + let pageRangeIndex = 0; + let clearRangeIndex = 0; + while (pageRangeIndex < pageRange.length && clearRangeIndex < clearRange.length) { + if (pageRange[pageRangeIndex].start < clearRange[clearRangeIndex].start) { + yield { + start: pageRange[pageRangeIndex].start, + end: pageRange[pageRangeIndex].end, + isClear: false, + }; + ++pageRangeIndex; + } + else { + yield { + start: clearRange[clearRangeIndex].start, + end: clearRange[clearRangeIndex].end, + isClear: true, + }; + ++clearRangeIndex; + } + } + for (; pageRangeIndex < pageRange.length; ++pageRangeIndex) { + yield { + start: pageRange[pageRangeIndex].start, + end: pageRange[pageRangeIndex].end, + isClear: false, + }; + } + for (; clearRangeIndex < clearRange.length; ++clearRangeIndex) { + yield { + start: clearRange[clearRangeIndex].start, + end: clearRange[clearRangeIndex].end, + isClear: true, + }; + } +} +/** + * 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("/"); +} +/** + * A typesafe helper for ensuring that a given response object has + * the original _response attached. + * @param response - A response object from calling a client operation + * @returns The same object, but with known _response property + */ +function assertResponse(response) { + if (`_response` in response) { + return response; + } + throw new TypeError(`Unexpected response object ${response}`); +} + +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +/** + * RetryPolicy types. + */ +exports.StorageRetryPolicyType = void 0; +(function (StorageRetryPolicyType) { + /** + * Exponential retry. Retry time delay grows exponentially. + */ + StorageRetryPolicyType[StorageRetryPolicyType["EXPONENTIAL"] = 0] = "EXPONENTIAL"; + /** + * Linear retry. Retry time delay grows linearly. + */ + StorageRetryPolicyType[StorageRetryPolicyType["FIXED"] = 1] = "FIXED"; +})(exports.StorageRetryPolicyType || (exports.StorageRetryPolicyType = {})); +// Default values of StorageRetryOptions +const DEFAULT_RETRY_OPTIONS$1 = { + maxRetryDelayInMs: 120 * 1000, + maxTries: 4, + retryDelayInMs: 4 * 1000, + retryPolicyType: exports.StorageRetryPolicyType.EXPONENTIAL, + secondaryHost: "", + tryTimeoutInMs: undefined, // Use server side default timeout strategy }; -const CorsRule = { +const RETRY_ABORT_ERROR$1 = new abortController.AbortError("The operation was aborted."); +/** + * Retry policy with exponential retry and linear retry implemented. + */ +class StorageRetryPolicy extends BaseRequestPolicy { + /** + * Creates an instance of RetryPolicy. + * + * @param nextPolicy - + * @param options - + * @param retryOptions - + */ + constructor(nextPolicy, options, retryOptions = DEFAULT_RETRY_OPTIONS$1) { + super(nextPolicy, options); + // Initialize retry options + this.retryOptions = { + retryPolicyType: retryOptions.retryPolicyType + ? retryOptions.retryPolicyType + : DEFAULT_RETRY_OPTIONS$1.retryPolicyType, + maxTries: retryOptions.maxTries && retryOptions.maxTries >= 1 + ? Math.floor(retryOptions.maxTries) + : DEFAULT_RETRY_OPTIONS$1.maxTries, + tryTimeoutInMs: retryOptions.tryTimeoutInMs && retryOptions.tryTimeoutInMs >= 0 + ? retryOptions.tryTimeoutInMs + : DEFAULT_RETRY_OPTIONS$1.tryTimeoutInMs, + retryDelayInMs: retryOptions.retryDelayInMs && retryOptions.retryDelayInMs >= 0 + ? Math.min(retryOptions.retryDelayInMs, retryOptions.maxRetryDelayInMs + ? retryOptions.maxRetryDelayInMs + : DEFAULT_RETRY_OPTIONS$1.maxRetryDelayInMs) + : DEFAULT_RETRY_OPTIONS$1.retryDelayInMs, + maxRetryDelayInMs: retryOptions.maxRetryDelayInMs && retryOptions.maxRetryDelayInMs >= 0 + ? retryOptions.maxRetryDelayInMs + : DEFAULT_RETRY_OPTIONS$1.maxRetryDelayInMs, + secondaryHost: retryOptions.secondaryHost + ? retryOptions.secondaryHost + : DEFAULT_RETRY_OPTIONS$1.secondaryHost, + }; + } + /** + * Sends request. + * + * @param request - + */ + async sendRequest(request) { + return this.attemptSendRequest(request, false, 1); + } + /** + * Decide and perform next retry. Won't mutate request parameter. + * + * @param request - + * @param secondaryHas404 - If attempt was against the secondary & it returned a StatusNotFound (404), then + * the resource was not found. This may be due to replication delay. So, in this + * case, we'll never try the secondary again for this operation. + * @param attempt - How many retries has been attempted to performed, starting from 1, which includes + * the attempt will be performed by this method call. + */ + async attemptSendRequest(request, secondaryHas404, attempt) { + const newRequest = request.clone(); + const isPrimaryRetry = secondaryHas404 || + !this.retryOptions.secondaryHost || + !(request.method === "GET" || request.method === "HEAD" || request.method === "OPTIONS") || + attempt % 2 === 1; + if (!isPrimaryRetry) { + newRequest.url = setURLHost(newRequest.url, this.retryOptions.secondaryHost); + } + // Set the server-side timeout query parameter "timeout=[seconds]" + if (this.retryOptions.tryTimeoutInMs) { + newRequest.url = setURLParameter(newRequest.url, URLConstants.Parameters.TIMEOUT, Math.floor(this.retryOptions.tryTimeoutInMs / 1000).toString()); + } + let response; + try { + logger.info(`RetryPolicy: =====> Try=${attempt} ${isPrimaryRetry ? "Primary" : "Secondary"}`); + response = await this._nextPolicy.sendRequest(newRequest); + if (!this.shouldRetry(isPrimaryRetry, attempt, response)) { + return response; + } + secondaryHas404 = secondaryHas404 || (!isPrimaryRetry && response.status === 404); + } + catch (err) { + logger.error(`RetryPolicy: Caught error, message: ${err.message}, code: ${err.code}`); + if (!this.shouldRetry(isPrimaryRetry, attempt, response, err)) { + throw err; + } + } + await this.delay(isPrimaryRetry, attempt, request.abortSignal); + return this.attemptSendRequest(request, secondaryHas404, ++attempt); + } + /** + * Decide whether to retry according to last HTTP response and retry counters. + * + * @param isPrimaryRetry - + * @param attempt - + * @param response - + * @param err - + */ + shouldRetry(isPrimaryRetry, attempt, response, err) { + if (attempt >= this.retryOptions.maxTries) { + logger.info(`RetryPolicy: Attempt(s) ${attempt} >= maxTries ${this.retryOptions + .maxTries}, no further try.`); + return false; + } + // Handle network failures, you may need to customize the list when you implement + // your own http client + const retriableErrors = [ + "ETIMEDOUT", + "ESOCKETTIMEDOUT", + "ECONNREFUSED", + "ECONNRESET", + "ENOENT", + "ENOTFOUND", + "TIMEOUT", + "EPIPE", + "REQUEST_SEND_ERROR", // For default xhr based http client provided in ms-rest-js + ]; + if (err) { + for (const retriableError of retriableErrors) { + if (err.name.toUpperCase().includes(retriableError) || + err.message.toUpperCase().includes(retriableError) || + (err.code && err.code.toString().toUpperCase() === retriableError)) { + logger.info(`RetryPolicy: Network error ${retriableError} found, will retry.`); + return true; + } + } + } + // If attempt was against the secondary & it returned a StatusNotFound (404), then + // the resource was not found. This may be due to replication delay. So, in this + // case, we'll never try the secondary again for this operation. + if (response || err) { + const statusCode = response ? response.status : err ? err.statusCode : 0; + if (!isPrimaryRetry && statusCode === 404) { + logger.info(`RetryPolicy: Secondary access with 404, will retry.`); + return true; + } + // Server internal error or server timeout + if (statusCode === 503 || statusCode === 500) { + logger.info(`RetryPolicy: Will retry for status code ${statusCode}.`); + return true; + } + } + // [Copy source error code] Feature is pending on service side, skip retry on copy source error for now. + // if (response) { + // // Retry select Copy Source Error Codes. + // if (response?.status >= 400) { + // const copySourceError = response.headers.get(HeaderConstants.X_MS_CopySourceErrorCode); + // if (copySourceError !== undefined) { + // switch (copySourceError) { + // case "InternalError": + // case "OperationTimedOut": + // case "ServerBusy": + // return true; + // } + // } + // } + // } + if ((err === null || err === void 0 ? void 0 : err.code) === "PARSE_ERROR" && (err === null || err === void 0 ? void 0 : err.message.startsWith(`Error "Error: Unclosed root tag`))) { + logger.info("RetryPolicy: Incomplete XML response likely due to service timeout, will retry."); + return true; + } + return false; + } + /** + * Delay a calculated time between retries. + * + * @param isPrimaryRetry - + * @param attempt - + * @param abortSignal - + */ + async delay(isPrimaryRetry, attempt, abortSignal) { + let delayTimeInMs = 0; + if (isPrimaryRetry) { + switch (this.retryOptions.retryPolicyType) { + case exports.StorageRetryPolicyType.EXPONENTIAL: + delayTimeInMs = Math.min((Math.pow(2, attempt - 1) - 1) * this.retryOptions.retryDelayInMs, this.retryOptions.maxRetryDelayInMs); + break; + case exports.StorageRetryPolicyType.FIXED: + delayTimeInMs = this.retryOptions.retryDelayInMs; + break; + } + } + else { + delayTimeInMs = Math.random() * 1000; + } + logger.info(`RetryPolicy: Delay for ${delayTimeInMs}ms`); + return delay(delayTimeInMs, abortSignal, RETRY_ABORT_ERROR$1); + } +} + +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +/** + * StorageRetryPolicyFactory is a factory class helping generating {@link StorageRetryPolicy} objects. + */ +class StorageRetryPolicyFactory { + /** + * Creates an instance of StorageRetryPolicyFactory. + * @param retryOptions - + */ + constructor(retryOptions) { + this.retryOptions = retryOptions; + } + /** + * Creates a StorageRetryPolicy object. + * + * @param nextPolicy - + * @param options - + */ + create(nextPolicy, options) { + return new StorageRetryPolicy(nextPolicy, options, this.retryOptions); + } +} + +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +/** + * Credential policy used to sign HTTP(S) requests before sending. This is an + * abstract class. + */ +class CredentialPolicy extends BaseRequestPolicy { + /** + * Sends out request. + * + * @param request - + */ + sendRequest(request) { + return this._nextPolicy.sendRequest(this.signRequest(request)); + } + /** + * Child classes must implement this method with request signing. This method + * will be executed in {@link sendRequest}. + * + * @param request - + */ + signRequest(request) { + // Child classes must override this method with request signing. This method + // will be executed in sendRequest(). + return request; + } +} + +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +/* + * We need to imitate .Net culture-aware sorting, which is used in storage service. + * Below tables contain sort-keys for en-US culture. + */ +const table_lv0 = new Uint32Array([ + 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, + 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x71c, 0x0, 0x71f, 0x721, + 0x723, 0x725, 0x0, 0x0, 0x0, 0x72d, 0x803, 0x0, 0x0, 0x733, 0x0, 0xd03, 0xd1a, 0xd1c, 0xd1e, + 0xd20, 0xd22, 0xd24, 0xd26, 0xd28, 0xd2a, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xe02, 0xe09, 0xe0a, + 0xe1a, 0xe21, 0xe23, 0xe25, 0xe2c, 0xe32, 0xe35, 0xe36, 0xe48, 0xe51, 0xe70, 0xe7c, 0xe7e, 0xe89, + 0xe8a, 0xe91, 0xe99, 0xe9f, 0xea2, 0xea4, 0xea6, 0xea7, 0xea9, 0x0, 0x0, 0x0, 0x743, 0x744, 0x748, + 0xe02, 0xe09, 0xe0a, 0xe1a, 0xe21, 0xe23, 0xe25, 0xe2c, 0xe32, 0xe35, 0xe36, 0xe48, 0xe51, 0xe70, + 0xe7c, 0xe7e, 0xe89, 0xe8a, 0xe91, 0xe99, 0xe9f, 0xea2, 0xea4, 0xea6, 0xea7, 0xea9, 0x0, 0x74c, + 0x0, 0x750, 0x0, +]); +const table_lv2 = new Uint32Array([ + 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, + 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, + 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, + 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, + 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, 0x12, + 0x12, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, + 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, +]); +const table_lv4 = new Uint32Array([ + 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, + 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, + 0x0, 0x8012, 0x0, 0x0, 0x0, 0x0, 0x0, 0x8212, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, + 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, + 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, + 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, + 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, +]); +function compareHeader(lhs, rhs) { + if (isLessThan(lhs, rhs)) + return -1; + return 1; +} +function isLessThan(lhs, rhs) { + const tables = [table_lv0, table_lv2, table_lv4]; + let curr_level = 0; + let i = 0; + let j = 0; + while (curr_level < tables.length) { + if (curr_level === tables.length - 1 && i !== j) { + return i > j; + } + const weight1 = i < lhs.length ? tables[curr_level][lhs[i].charCodeAt(0)] : 0x1; + const weight2 = j < rhs.length ? tables[curr_level][rhs[j].charCodeAt(0)] : 0x1; + if (weight1 === 0x1 && weight2 === 0x1) { + i = 0; + j = 0; + ++curr_level; + } + else if (weight1 === weight2) { + ++i; + ++j; + } + else if (weight1 === 0) { + ++i; + } + else if (weight2 === 0) { + ++j; + } + else { + return weight1 < weight2; + } + } + return false; +} + +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +/** + * StorageSharedKeyCredentialPolicy is a policy used to sign HTTP request with a shared key. + */ +class StorageSharedKeyCredentialPolicy extends CredentialPolicy { + /** + * Creates an instance of StorageSharedKeyCredentialPolicy. + * @param nextPolicy - + * @param options - + * @param factory - + */ + constructor(nextPolicy, options, factory) { + super(nextPolicy, options); + this.factory = factory; + } + /** + * Signs request. + * + * @param request - + */ + signRequest(request) { + request.headers.set(HeaderConstants.X_MS_DATE, new Date().toUTCString()); + if (request.body && + (typeof request.body === "string" || request.body !== undefined) && + request.body.length > 0) { + request.headers.set(HeaderConstants.CONTENT_LENGTH, Buffer.byteLength(request.body)); + } + const stringToSign = [ + request.method.toUpperCase(), + this.getHeaderValueToSign(request, HeaderConstants.CONTENT_LANGUAGE), + this.getHeaderValueToSign(request, HeaderConstants.CONTENT_ENCODING), + this.getHeaderValueToSign(request, HeaderConstants.CONTENT_LENGTH), + this.getHeaderValueToSign(request, HeaderConstants.CONTENT_MD5), + this.getHeaderValueToSign(request, HeaderConstants.CONTENT_TYPE), + this.getHeaderValueToSign(request, HeaderConstants.DATE), + this.getHeaderValueToSign(request, HeaderConstants.IF_MODIFIED_SINCE), + this.getHeaderValueToSign(request, HeaderConstants.IF_MATCH), + this.getHeaderValueToSign(request, HeaderConstants.IF_NONE_MATCH), + this.getHeaderValueToSign(request, HeaderConstants.IF_UNMODIFIED_SINCE), + this.getHeaderValueToSign(request, HeaderConstants.RANGE), + ].join("\n") + + "\n" + + this.getCanonicalizedHeadersString(request) + + this.getCanonicalizedResourceString(request); + const signature = this.factory.computeHMACSHA256(stringToSign); + request.headers.set(HeaderConstants.AUTHORIZATION, `SharedKey ${this.factory.accountName}:${signature}`); + // console.log(`[URL]:${request.url}`); + // console.log(`[HEADERS]:${request.headers.toString()}`); + // console.log(`[STRING TO SIGN]:${JSON.stringify(stringToSign)}`); + // console.log(`[KEY]: ${request.headers.get(HeaderConstants.AUTHORIZATION)}`); + return request; + } + /** + * Retrieve header value according to shared key sign rules. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/authenticate-with-shared-key + * + * @param request - + * @param headerName - + */ + getHeaderValueToSign(request, headerName) { + const value = request.headers.get(headerName); + if (!value) { + return ""; + } + // When using version 2015-02-21 or later, if Content-Length is zero, then + // set the Content-Length part of the StringToSign to an empty string. + // https://docs.microsoft.com/en-us/rest/api/storageservices/authenticate-with-shared-key + if (headerName === HeaderConstants.CONTENT_LENGTH && value === "0") { + return ""; + } + return value; + } + /** + * To construct the CanonicalizedHeaders portion of the signature string, follow these steps: + * 1. Retrieve all headers for the resource that begin with x-ms-, including the x-ms-date header. + * 2. Convert each HTTP header name to lowercase. + * 3. Sort the headers lexicographically by header name, in ascending order. + * Each header may appear only once in the string. + * 4. Replace any linear whitespace in the header value with a single space. + * 5. Trim any whitespace around the colon in the header. + * 6. Finally, append a new-line character to each canonicalized header in the resulting list. + * Construct the CanonicalizedHeaders string by concatenating all headers in this list into a single string. + * + * @param request - + */ + getCanonicalizedHeadersString(request) { + let headersArray = request.headers.headersArray().filter((value) => { + return value.name.toLowerCase().startsWith(HeaderConstants.PREFIX_FOR_STORAGE); + }); + headersArray.sort((a, b) => { + return compareHeader(a.name.toLowerCase(), b.name.toLowerCase()); + }); + // Remove duplicate headers + headersArray = headersArray.filter((value, index, array) => { + if (index > 0 && value.name.toLowerCase() === array[index - 1].name.toLowerCase()) { + return false; + } + return true; + }); + let canonicalizedHeadersStringToSign = ""; + headersArray.forEach((header) => { + canonicalizedHeadersStringToSign += `${header.name + .toLowerCase() + .trimRight()}:${header.value.trimLeft()}\n`; + }); + return canonicalizedHeadersStringToSign; + } + /** + * Retrieves the webResource canonicalized resource string. + * + * @param request - + */ + getCanonicalizedResourceString(request) { + const path = getURLPath(request.url) || "/"; + let canonicalizedResourceString = ""; + canonicalizedResourceString += `/${this.factory.accountName}${path}`; + const queries = getURLQueries(request.url); + const lowercaseQueries = {}; + if (queries) { + const queryKeys = []; + for (const key in queries) { + if (Object.prototype.hasOwnProperty.call(queries, key)) { + const lowercaseKey = key.toLowerCase(); + lowercaseQueries[lowercaseKey] = queries[key]; + queryKeys.push(lowercaseKey); + } + } + queryKeys.sort(); + for (const key of queryKeys) { + canonicalizedResourceString += `\n${key}:${decodeURIComponent(lowercaseQueries[key])}`; + } + } + return canonicalizedResourceString; + } +} + +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +/** + * Credential is an abstract class for Azure Storage HTTP requests signing. This + * class will host an credentialPolicyCreator factory which generates CredentialPolicy. + */ +class Credential { + /** + * Creates a RequestPolicy object. + * + * @param _nextPolicy - + * @param _options - + */ + create(_nextPolicy, _options) { + throw new Error("Method should be implemented in children classes."); + } +} + +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +/** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * + * StorageSharedKeyCredential for account key authorization of Azure Storage service. + */ +class StorageSharedKeyCredential extends Credential { + /** + * Creates an instance of StorageSharedKeyCredential. + * @param accountName - + * @param accountKey - + */ + constructor(accountName, accountKey) { + super(); + this.accountName = accountName; + this.accountKey = Buffer.from(accountKey, "base64"); + } + /** + * Creates a StorageSharedKeyCredentialPolicy object. + * + * @param nextPolicy - + * @param options - + */ + create(nextPolicy, options) { + return new StorageSharedKeyCredentialPolicy(nextPolicy, options, this); + } + /** + * Generates a hash signature for an HTTP request or for a SAS. + * + * @param stringToSign - + */ + computeHMACSHA256(stringToSign) { + return crypto.createHmac("sha256", this.accountKey).update(stringToSign, "utf8").digest("base64"); + } +} + +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +/** + * AnonymousCredentialPolicy is used with HTTP(S) requests that read public resources + * or for use with Shared Access Signatures (SAS). + */ +class AnonymousCredentialPolicy extends CredentialPolicy { + /** + * Creates an instance of AnonymousCredentialPolicy. + * @param nextPolicy - + * @param options - + */ + // The base class has a protected constructor. Adding a public one to enable constructing of this class. + /* eslint-disable-next-line @typescript-eslint/no-useless-constructor*/ + constructor(nextPolicy, options) { + super(nextPolicy, options); + } +} + +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +/** + * AnonymousCredential provides a credentialPolicyCreator member used to create + * AnonymousCredentialPolicy objects. AnonymousCredentialPolicy is used with + * HTTP(S) requests that read public resources or for use with Shared Access + * Signatures (SAS). + */ +class AnonymousCredential extends Credential { + /** + * Creates an {@link AnonymousCredentialPolicy} object. + * + * @param nextPolicy - + * @param options - + */ + create(nextPolicy, options) { + return new AnonymousCredentialPolicy(nextPolicy, options); + } +} + +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +let _defaultHttpClient; +function getCachedDefaultHttpClient() { + if (!_defaultHttpClient) { + _defaultHttpClient = coreRestPipeline.createDefaultHttpClient(); + } + return _defaultHttpClient; +} + +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +/** + * The programmatic identifier of the StorageBrowserPolicy. + */ +const storageBrowserPolicyName = "storageBrowserPolicy"; +/** + * storageBrowserPolicy is a policy used to prevent browsers from caching requests + * and to remove cookies and explicit content-length headers. + */ +function storageBrowserPolicy() { + return { + name: storageBrowserPolicyName, + async sendRequest(request, next) { + if (coreUtil.isNode) { + return next(request); + } + if (request.method === "GET" || request.method === "HEAD") { + request.url = setURLParameter(request.url, URLConstants.Parameters.FORCE_BROWSER_NO_CACHE, new Date().getTime().toString()); + } + request.headers.delete(HeaderConstants.COOKIE); + // According to XHR standards, content-length should be fully controlled by browsers + request.headers.delete(HeaderConstants.CONTENT_LENGTH); + return next(request); + }, + }; +} + +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +/** + * Name of the {@link storageRetryPolicy} + */ +const storageRetryPolicyName = "storageRetryPolicy"; +/** + * RetryPolicy types. + */ +var StorageRetryPolicyType; +(function (StorageRetryPolicyType) { + /** + * Exponential retry. Retry time delay grows exponentially. + */ + StorageRetryPolicyType[StorageRetryPolicyType["EXPONENTIAL"] = 0] = "EXPONENTIAL"; + /** + * Linear retry. Retry time delay grows linearly. + */ + StorageRetryPolicyType[StorageRetryPolicyType["FIXED"] = 1] = "FIXED"; +})(StorageRetryPolicyType || (StorageRetryPolicyType = {})); +// Default values of StorageRetryOptions +const DEFAULT_RETRY_OPTIONS = { + maxRetryDelayInMs: 120 * 1000, + maxTries: 4, + retryDelayInMs: 4 * 1000, + retryPolicyType: StorageRetryPolicyType.EXPONENTIAL, + secondaryHost: "", + tryTimeoutInMs: undefined, // Use server side default timeout strategy +}; +const retriableErrors = [ + "ETIMEDOUT", + "ESOCKETTIMEDOUT", + "ECONNREFUSED", + "ECONNRESET", + "ENOENT", + "ENOTFOUND", + "TIMEOUT", + "EPIPE", + "REQUEST_SEND_ERROR", +]; +const RETRY_ABORT_ERROR = new abortController.AbortError("The operation was aborted."); +/** + * Retry policy with exponential retry and linear retry implemented. + */ +function storageRetryPolicy(options = {}) { + var _a, _b, _c, _d, _e, _f; + const retryPolicyType = (_a = options.retryPolicyType) !== null && _a !== void 0 ? _a : DEFAULT_RETRY_OPTIONS.retryPolicyType; + const maxTries = (_b = options.maxTries) !== null && _b !== void 0 ? _b : DEFAULT_RETRY_OPTIONS.maxTries; + const retryDelayInMs = (_c = options.retryDelayInMs) !== null && _c !== void 0 ? _c : DEFAULT_RETRY_OPTIONS.retryDelayInMs; + const maxRetryDelayInMs = (_d = options.maxRetryDelayInMs) !== null && _d !== void 0 ? _d : DEFAULT_RETRY_OPTIONS.maxRetryDelayInMs; + const secondaryHost = (_e = options.secondaryHost) !== null && _e !== void 0 ? _e : DEFAULT_RETRY_OPTIONS.secondaryHost; + const tryTimeoutInMs = (_f = options.tryTimeoutInMs) !== null && _f !== void 0 ? _f : DEFAULT_RETRY_OPTIONS.tryTimeoutInMs; + function shouldRetry({ isPrimaryRetry, attempt, response, error, }) { + var _a, _b; + if (attempt >= maxTries) { + logger.info(`RetryPolicy: Attempt(s) ${attempt} >= maxTries ${maxTries}, no further try.`); + return false; + } + if (error) { + for (const retriableError of retriableErrors) { + if (error.name.toUpperCase().includes(retriableError) || + error.message.toUpperCase().includes(retriableError) || + (error.code && error.code.toString().toUpperCase() === retriableError)) { + logger.info(`RetryPolicy: Network error ${retriableError} found, will retry.`); + return true; + } + } + if ((error === null || error === void 0 ? void 0 : error.code) === "PARSE_ERROR" && + (error === null || error === void 0 ? void 0 : error.message.startsWith(`Error "Error: Unclosed root tag`))) { + logger.info("RetryPolicy: Incomplete XML response likely due to service timeout, will retry."); + return true; + } + } + // If attempt was against the secondary & it returned a StatusNotFound (404), then + // the resource was not found. This may be due to replication delay. So, in this + // case, we'll never try the secondary again for this operation. + if (response || error) { + const statusCode = (_b = (_a = response === null || response === void 0 ? void 0 : response.status) !== null && _a !== void 0 ? _a : error === null || error === void 0 ? void 0 : error.statusCode) !== null && _b !== void 0 ? _b : 0; + if (!isPrimaryRetry && statusCode === 404) { + logger.info(`RetryPolicy: Secondary access with 404, will retry.`); + return true; + } + // Server internal error or server timeout + if (statusCode === 503 || statusCode === 500) { + logger.info(`RetryPolicy: Will retry for status code ${statusCode}.`); + return true; + } + } + // [Copy source error code] Feature is pending on service side, skip retry on copy source error for now. + // if (response) { + // // Retry select Copy Source Error Codes. + // if (response?.status >= 400) { + // const copySourceError = response.headers.get(HeaderConstants.X_MS_CopySourceErrorCode); + // if (copySourceError !== undefined) { + // switch (copySourceError) { + // case "InternalError": + // case "OperationTimedOut": + // case "ServerBusy": + // return true; + // } + // } + // } + // } + return false; + } + function calculateDelay(isPrimaryRetry, attempt) { + let delayTimeInMs = 0; + if (isPrimaryRetry) { + switch (retryPolicyType) { + case StorageRetryPolicyType.EXPONENTIAL: + delayTimeInMs = Math.min((Math.pow(2, attempt - 1) - 1) * retryDelayInMs, maxRetryDelayInMs); + break; + case StorageRetryPolicyType.FIXED: + delayTimeInMs = retryDelayInMs; + break; + } + } + else { + delayTimeInMs = Math.random() * 1000; + } + logger.info(`RetryPolicy: Delay for ${delayTimeInMs}ms`); + return delayTimeInMs; + } + return { + name: storageRetryPolicyName, + async sendRequest(request, next) { + // Set the server-side timeout query parameter "timeout=[seconds]" + if (tryTimeoutInMs) { + request.url = setURLParameter(request.url, URLConstants.Parameters.TIMEOUT, String(Math.floor(tryTimeoutInMs / 1000))); + } + const primaryUrl = request.url; + const secondaryUrl = secondaryHost ? setURLHost(request.url, secondaryHost) : undefined; + let secondaryHas404 = false; + let attempt = 1; + let retryAgain = true; + let response; + let error; + while (retryAgain) { + const isPrimaryRetry = secondaryHas404 || + !secondaryUrl || + !["GET", "HEAD", "OPTIONS"].includes(request.method) || + attempt % 2 === 1; + request.url = isPrimaryRetry ? primaryUrl : secondaryUrl; + response = undefined; + error = undefined; + try { + logger.info(`RetryPolicy: =====> Try=${attempt} ${isPrimaryRetry ? "Primary" : "Secondary"}`); + response = await next(request); + secondaryHas404 = secondaryHas404 || (!isPrimaryRetry && response.status === 404); + } + catch (e) { + if (coreRestPipeline.isRestError(e)) { + logger.error(`RetryPolicy: Caught error, message: ${e.message}, code: ${e.code}`); + error = e; + } + else { + logger.error(`RetryPolicy: Caught error, message: ${coreUtil.getErrorMessage(e)}`); + throw e; + } + } + retryAgain = shouldRetry({ isPrimaryRetry, attempt, response, error }); + if (retryAgain) { + await delay(calculateDelay(isPrimaryRetry, attempt), request.abortSignal, RETRY_ABORT_ERROR); + } + attempt++; + } + if (response) { + return response; + } + throw error !== null && error !== void 0 ? error : new coreRestPipeline.RestError("RetryPolicy failed without known error."); + }, + }; +} + +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +/** + * The programmatic identifier of the storageSharedKeyCredentialPolicy. + */ +const storageSharedKeyCredentialPolicyName = "storageSharedKeyCredentialPolicy"; +/** + * storageSharedKeyCredentialPolicy handles signing requests using storage account keys. + */ +function storageSharedKeyCredentialPolicy(options) { + function signRequest(request) { + request.headers.set(HeaderConstants.X_MS_DATE, new Date().toUTCString()); + if (request.body && + (typeof request.body === "string" || Buffer.isBuffer(request.body)) && + request.body.length > 0) { + request.headers.set(HeaderConstants.CONTENT_LENGTH, Buffer.byteLength(request.body)); + } + const stringToSign = [ + request.method.toUpperCase(), + getHeaderValueToSign(request, HeaderConstants.CONTENT_LANGUAGE), + getHeaderValueToSign(request, HeaderConstants.CONTENT_ENCODING), + getHeaderValueToSign(request, HeaderConstants.CONTENT_LENGTH), + getHeaderValueToSign(request, HeaderConstants.CONTENT_MD5), + getHeaderValueToSign(request, HeaderConstants.CONTENT_TYPE), + getHeaderValueToSign(request, HeaderConstants.DATE), + getHeaderValueToSign(request, HeaderConstants.IF_MODIFIED_SINCE), + getHeaderValueToSign(request, HeaderConstants.IF_MATCH), + getHeaderValueToSign(request, HeaderConstants.IF_NONE_MATCH), + getHeaderValueToSign(request, HeaderConstants.IF_UNMODIFIED_SINCE), + getHeaderValueToSign(request, HeaderConstants.RANGE), + ].join("\n") + + "\n" + + getCanonicalizedHeadersString(request) + + getCanonicalizedResourceString(request); + const signature = crypto.createHmac("sha256", options.accountKey) + .update(stringToSign, "utf8") + .digest("base64"); + request.headers.set(HeaderConstants.AUTHORIZATION, `SharedKey ${options.accountName}:${signature}`); + // console.log(`[URL]:${request.url}`); + // console.log(`[HEADERS]:${request.headers.toString()}`); + // console.log(`[STRING TO SIGN]:${JSON.stringify(stringToSign)}`); + // console.log(`[KEY]: ${request.headers.get(HeaderConstants.AUTHORIZATION)}`); + } + /** + * Retrieve header value according to shared key sign rules. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/authenticate-with-shared-key + */ + function getHeaderValueToSign(request, headerName) { + const value = request.headers.get(headerName); + if (!value) { + return ""; + } + // When using version 2015-02-21 or later, if Content-Length is zero, then + // set the Content-Length part of the StringToSign to an empty string. + // https://docs.microsoft.com/en-us/rest/api/storageservices/authenticate-with-shared-key + if (headerName === HeaderConstants.CONTENT_LENGTH && value === "0") { + return ""; + } + return value; + } + /** + * To construct the CanonicalizedHeaders portion of the signature string, follow these steps: + * 1. Retrieve all headers for the resource that begin with x-ms-, including the x-ms-date header. + * 2. Convert each HTTP header name to lowercase. + * 3. Sort the headers lexicographically by header name, in ascending order. + * Each header may appear only once in the string. + * 4. Replace any linear whitespace in the header value with a single space. + * 5. Trim any whitespace around the colon in the header. + * 6. Finally, append a new-line character to each canonicalized header in the resulting list. + * Construct the CanonicalizedHeaders string by concatenating all headers in this list into a single string. + * + */ + function getCanonicalizedHeadersString(request) { + let headersArray = []; + for (const [name, value] of request.headers) { + if (name.toLowerCase().startsWith(HeaderConstants.PREFIX_FOR_STORAGE)) { + headersArray.push({ name, value }); + } + } + headersArray.sort((a, b) => { + return compareHeader(a.name.toLowerCase(), b.name.toLowerCase()); + }); + // Remove duplicate headers + headersArray = headersArray.filter((value, index, array) => { + if (index > 0 && value.name.toLowerCase() === array[index - 1].name.toLowerCase()) { + return false; + } + return true; + }); + let canonicalizedHeadersStringToSign = ""; + headersArray.forEach((header) => { + canonicalizedHeadersStringToSign += `${header.name + .toLowerCase() + .trimRight()}:${header.value.trimLeft()}\n`; + }); + return canonicalizedHeadersStringToSign; + } + function getCanonicalizedResourceString(request) { + const path = getURLPath(request.url) || "/"; + let canonicalizedResourceString = ""; + canonicalizedResourceString += `/${options.accountName}${path}`; + const queries = getURLQueries(request.url); + const lowercaseQueries = {}; + if (queries) { + const queryKeys = []; + for (const key in queries) { + if (Object.prototype.hasOwnProperty.call(queries, key)) { + const lowercaseKey = key.toLowerCase(); + lowercaseQueries[lowercaseKey] = queries[key]; + queryKeys.push(lowercaseKey); + } + } + queryKeys.sort(); + for (const key of queryKeys) { + canonicalizedResourceString += `\n${key}:${decodeURIComponent(lowercaseQueries[key])}`; + } + } + return canonicalizedResourceString; + } + return { + name: storageSharedKeyCredentialPolicyName, + async sendRequest(request, next) { + signRequest(request); + return next(request); + }, + }; +} + +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +/** + * StorageBrowserPolicy will handle differences between Node.js and browser runtime, including: + * + * 1. Browsers cache GET/HEAD requests by adding conditional headers such as 'IF_MODIFIED_SINCE'. + * StorageBrowserPolicy is a policy used to add a timestamp query to GET/HEAD request URL + * thus avoid the browser cache. + * + * 2. Remove cookie header for security + * + * 3. Remove content-length header to avoid browsers warning + */ +class StorageBrowserPolicy extends BaseRequestPolicy { + /** + * Creates an instance of StorageBrowserPolicy. + * @param nextPolicy - + * @param options - + */ + // The base class has a protected constructor. Adding a public one to enable constructing of this class. + /* eslint-disable-next-line @typescript-eslint/no-useless-constructor*/ + constructor(nextPolicy, options) { + super(nextPolicy, options); + } + /** + * Sends out request. + * + * @param request - + */ + async sendRequest(request) { + if (coreUtil.isNode) { + return this._nextPolicy.sendRequest(request); + } + if (request.method.toUpperCase() === "GET" || request.method.toUpperCase() === "HEAD") { + request.url = setURLParameter(request.url, URLConstants.Parameters.FORCE_BROWSER_NO_CACHE, new Date().getTime().toString()); + } + request.headers.remove(HeaderConstants.COOKIE); + // According to XHR standards, content-length should be fully controlled by browsers + request.headers.remove(HeaderConstants.CONTENT_LENGTH); + return this._nextPolicy.sendRequest(request); + } +} + +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +/** + * StorageBrowserPolicyFactory is a factory class helping generating StorageBrowserPolicy objects. + */ +class StorageBrowserPolicyFactory { + /** + * Creates a StorageBrowserPolicyFactory object. + * + * @param nextPolicy - + * @param options - + */ + create(nextPolicy, options) { + return new StorageBrowserPolicy(nextPolicy, options); + } +} + +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +/** + * The programmatic identifier of the storageCorrectContentLengthPolicy. + */ +const storageCorrectContentLengthPolicyName = "StorageCorrectContentLengthPolicy"; +/** + * storageCorrectContentLengthPolicy to correctly set Content-Length header with request body length. + */ +function storageCorrectContentLengthPolicy() { + function correctContentLength(request) { + if (request.body && + (typeof request.body === "string" || Buffer.isBuffer(request.body)) && + request.body.length > 0) { + request.headers.set(HeaderConstants.CONTENT_LENGTH, Buffer.byteLength(request.body)); + } + } + return { + name: storageCorrectContentLengthPolicyName, + async sendRequest(request, next) { + correctContentLength(request); + return next(request); + }, + }; +} + +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +/** + * A helper to decide if a given argument satisfies the Pipeline contract + * @param pipeline - An argument that may be a Pipeline + * @returns true when the argument satisfies the Pipeline contract + */ +function isPipelineLike(pipeline) { + if (!pipeline || typeof pipeline !== "object") { + return false; + } + const castPipeline = pipeline; + return (Array.isArray(castPipeline.factories) && + typeof castPipeline.options === "object" && + typeof castPipeline.toServiceClientOptions === "function"); +} +/** + * A Pipeline class containing HTTP request policies. + * You can create a default Pipeline by calling {@link newPipeline}. + * Or you can create a Pipeline with your own policies by the constructor of Pipeline. + * + * Refer to {@link newPipeline} and provided policies before implementing your + * customized Pipeline. + */ +class Pipeline { + /** + * Creates an instance of Pipeline. Customize HTTPClient by implementing IHttpClient interface. + * + * @param factories - + * @param options - + */ + constructor(factories, options = {}) { + this.factories = factories; + this.options = options; + } + /** + * Transfer Pipeline object to ServiceClientOptions object which is required by + * ServiceClient constructor. + * + * @returns The ServiceClientOptions object from this Pipeline. + */ + toServiceClientOptions() { + return { + httpClient: this.options.httpClient, + requestPolicyFactories: this.factories, + }; + } +} +/** + * Creates a new Pipeline object with Credential provided. + * + * @param credential - Such as AnonymousCredential, StorageSharedKeyCredential or any credential from the `@azure/identity` package to authenticate requests to the service. You can also provide an object that implements the TokenCredential interface. If not specified, AnonymousCredential is used. + * @param pipelineOptions - Optional. Options. + * @returns A new Pipeline object. + */ +function newPipeline(credential, pipelineOptions = {}) { + if (!credential) { + credential = new AnonymousCredential(); + } + const pipeline = new Pipeline([], pipelineOptions); + pipeline._credential = credential; + return pipeline; +} +function processDownlevelPipeline(pipeline) { + const knownFactoryFunctions = [ + isAnonymousCredential, + isStorageSharedKeyCredential, + isCoreHttpBearerTokenFactory, + isStorageBrowserPolicyFactory, + isStorageRetryPolicyFactory, + isStorageTelemetryPolicyFactory, + isCoreHttpPolicyFactory, + ]; + if (pipeline.factories.length) { + const novelFactories = pipeline.factories.filter((factory) => { + return !knownFactoryFunctions.some((knownFactory) => knownFactory(factory)); + }); + if (novelFactories.length) { + const hasInjector = novelFactories.some((factory) => isInjectorPolicyFactory(factory)); + // if there are any left over, wrap in a requestPolicyFactoryPolicy + return { + wrappedPolicies: coreHttpCompat.createRequestPolicyFactoryPolicy(novelFactories), + afterRetry: hasInjector, + }; + } + } + return undefined; +} +function getCoreClientOptions(pipeline) { + var _a; + const _b = pipeline.options, { httpClient: v1Client } = _b, restOptions = tslib.__rest(_b, ["httpClient"]); + let httpClient = pipeline._coreHttpClient; + if (!httpClient) { + httpClient = v1Client ? coreHttpCompat.convertHttpClient(v1Client) : getCachedDefaultHttpClient(); + pipeline._coreHttpClient = httpClient; + } + let corePipeline = pipeline._corePipeline; + if (!corePipeline) { + const packageDetails = `azsdk-js-azure-storage-blob/${SDK_VERSION}`; + const userAgentPrefix = restOptions.userAgentOptions && restOptions.userAgentOptions.userAgentPrefix + ? `${restOptions.userAgentOptions.userAgentPrefix} ${packageDetails}` + : `${packageDetails}`; + corePipeline = coreClient.createClientPipeline(Object.assign(Object.assign({}, restOptions), { loggingOptions: { + additionalAllowedHeaderNames: StorageBlobLoggingAllowedHeaderNames, + additionalAllowedQueryParameters: StorageBlobLoggingAllowedQueryParameters, + logger: logger.info, + }, userAgentOptions: { + userAgentPrefix, + }, serializationOptions: { + stringifyXML: coreXml.stringifyXML, + serializerOptions: { + xml: { + // Use customized XML char key of "#" so we can deserialize metadata + // with "_" key + xmlCharKey: "#", + }, + }, + }, deserializationOptions: { + parseXML: coreXml.parseXML, + serializerOptions: { + xml: { + // Use customized XML char key of "#" so we can deserialize metadata + // with "_" key + xmlCharKey: "#", + }, + }, + } })); + corePipeline.removePolicy({ phase: "Retry" }); + corePipeline.removePolicy({ name: coreRestPipeline.decompressResponsePolicyName }); + corePipeline.addPolicy(storageCorrectContentLengthPolicy()); + corePipeline.addPolicy(storageRetryPolicy(restOptions.retryOptions), { phase: "Retry" }); + corePipeline.addPolicy(storageBrowserPolicy()); + const downlevelResults = processDownlevelPipeline(pipeline); + if (downlevelResults) { + corePipeline.addPolicy(downlevelResults.wrappedPolicies, downlevelResults.afterRetry ? { afterPhase: "Retry" } : undefined); + } + const credential = getCredentialFromPipeline(pipeline); + if (coreAuth.isTokenCredential(credential)) { + corePipeline.addPolicy(coreRestPipeline.bearerTokenAuthenticationPolicy({ + credential, + scopes: (_a = restOptions.audience) !== null && _a !== void 0 ? _a : StorageOAuthScopes, + challengeCallbacks: { authorizeRequestOnChallenge: coreClient.authorizeRequestOnTenantChallenge }, + }), { phase: "Sign" }); + } + else if (credential instanceof StorageSharedKeyCredential) { + corePipeline.addPolicy(storageSharedKeyCredentialPolicy({ + accountName: credential.accountName, + accountKey: credential.accountKey, + }), { phase: "Sign" }); + } + pipeline._corePipeline = corePipeline; + } + return Object.assign(Object.assign({}, restOptions), { allowInsecureConnection: true, httpClient, pipeline: corePipeline }); +} +function getCredentialFromPipeline(pipeline) { + // see if we squirreled one away on the type itself + if (pipeline._credential) { + return pipeline._credential; + } + // if it came from another package, loop over the factories and look for one like before + let credential = new AnonymousCredential(); + for (const factory of pipeline.factories) { + if (coreAuth.isTokenCredential(factory.credential)) { + // Only works if the factory has been attached a "credential" property. + // We do that in newPipeline() when using TokenCredential. + credential = factory.credential; + } + else if (isStorageSharedKeyCredential(factory)) { + return factory; + } + } + return credential; +} +function isStorageSharedKeyCredential(factory) { + if (factory instanceof StorageSharedKeyCredential) { + return true; + } + return factory.constructor.name === "StorageSharedKeyCredential"; +} +function isAnonymousCredential(factory) { + if (factory instanceof AnonymousCredential) { + return true; + } + return factory.constructor.name === "AnonymousCredential"; +} +function isCoreHttpBearerTokenFactory(factory) { + return coreAuth.isTokenCredential(factory.credential); +} +function isStorageBrowserPolicyFactory(factory) { + if (factory instanceof StorageBrowserPolicyFactory) { + return true; + } + return factory.constructor.name === "StorageBrowserPolicyFactory"; +} +function isStorageRetryPolicyFactory(factory) { + if (factory instanceof StorageRetryPolicyFactory) { + return true; + } + return factory.constructor.name === "StorageRetryPolicyFactory"; +} +function isStorageTelemetryPolicyFactory(factory) { + return factory.constructor.name === "TelemetryPolicyFactory"; +} +function isInjectorPolicyFactory(factory) { + return factory.constructor.name === "InjectorPolicyFactory"; +} +function isCoreHttpPolicyFactory(factory) { + const knownPolicies = [ + "GenerateClientRequestIdPolicy", + "TracingPolicy", + "LogPolicy", + "ProxyPolicy", + "DisableResponseDecompressionPolicy", + "KeepAlivePolicy", + "DeserializationPolicy", + ]; + const mockHttpClient = { + sendRequest: async (request) => { + return { + request, + headers: request.headers.clone(), + status: 500, + }; + }, + }; + const mockRequestPolicyOptions = { + log(_logLevel, _message) { + /* do nothing */ + }, + shouldLog(_logLevel) { + return false; + }, + }; + const policyInstance = factory.create(mockHttpClient, mockRequestPolicyOptions); + const policyName = policyInstance.constructor.name; + // bundlers sometimes add a custom suffix to the class name to make it unique + return knownPolicies.some((knownPolicyName) => { + return policyName.startsWith(knownPolicyName); + }); +} + +/* + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is regenerated. + */ +const BlobServiceProperties = { + serializedName: "BlobServiceProperties", + xmlName: "StorageServiceProperties", + type: { + name: "Composite", + className: "BlobServiceProperties", + modelProperties: { + blobAnalyticsLogging: { + serializedName: "Logging", + xmlName: "Logging", + type: { + name: "Composite", + className: "Logging", + }, + }, + hourMetrics: { + serializedName: "HourMetrics", + xmlName: "HourMetrics", + type: { + name: "Composite", + className: "Metrics", + }, + }, + minuteMetrics: { + serializedName: "MinuteMetrics", + xmlName: "MinuteMetrics", + type: { + name: "Composite", + className: "Metrics", + }, + }, + cors: { + serializedName: "Cors", + xmlName: "Cors", + xmlIsWrapped: true, + xmlElementName: "CorsRule", + type: { + name: "Sequence", + element: { + type: { + name: "Composite", + className: "CorsRule", + }, + }, + }, + }, + defaultServiceVersion: { + serializedName: "DefaultServiceVersion", + xmlName: "DefaultServiceVersion", + type: { + name: "String", + }, + }, + deleteRetentionPolicy: { + serializedName: "DeleteRetentionPolicy", + xmlName: "DeleteRetentionPolicy", + type: { + name: "Composite", + className: "RetentionPolicy", + }, + }, + staticWebsite: { + serializedName: "StaticWebsite", + xmlName: "StaticWebsite", + type: { + name: "Composite", + className: "StaticWebsite", + }, + }, + }, + }, +}; +const Logging = { + serializedName: "Logging", + type: { + name: "Composite", + className: "Logging", + modelProperties: { + version: { + serializedName: "Version", + required: true, + xmlName: "Version", + type: { + name: "String", + }, + }, + deleteProperty: { + serializedName: "Delete", + required: true, + xmlName: "Delete", + type: { + name: "Boolean", + }, + }, + read: { + serializedName: "Read", + required: true, + xmlName: "Read", + type: { + name: "Boolean", + }, + }, + write: { + serializedName: "Write", + required: true, + xmlName: "Write", + type: { + name: "Boolean", + }, + }, + retentionPolicy: { + serializedName: "RetentionPolicy", + xmlName: "RetentionPolicy", + type: { + name: "Composite", + className: "RetentionPolicy", + }, + }, + }, + }, +}; +const RetentionPolicy = { + serializedName: "RetentionPolicy", + type: { + name: "Composite", + className: "RetentionPolicy", + modelProperties: { + enabled: { + serializedName: "Enabled", + required: true, + xmlName: "Enabled", + type: { + name: "Boolean", + }, + }, + days: { + constraints: { + InclusiveMinimum: 1, + }, + serializedName: "Days", + xmlName: "Days", + type: { + name: "Number", + }, + }, + }, + }, +}; +const Metrics = { + serializedName: "Metrics", + type: { + name: "Composite", + className: "Metrics", + modelProperties: { + version: { + serializedName: "Version", + xmlName: "Version", + type: { + name: "String", + }, + }, + enabled: { + serializedName: "Enabled", + required: true, + xmlName: "Enabled", + type: { + name: "Boolean", + }, + }, + includeAPIs: { + serializedName: "IncludeAPIs", + xmlName: "IncludeAPIs", + type: { + name: "Boolean", + }, + }, + retentionPolicy: { + serializedName: "RetentionPolicy", + xmlName: "RetentionPolicy", + type: { + name: "Composite", + className: "RetentionPolicy", + }, + }, + }, + }, +}; +const CorsRule = { serializedName: "CorsRule", type: { name: "Composite", @@ -17618,7 +18724,7 @@ const timeoutInSeconds = { const version = { parameterPath: "version", mapper: { - defaultValue: "2024-08-04", + defaultValue: "2024-11-04", isConstant: true, serializedName: "x-ms-version", type: { @@ -22235,7 +23341,7 @@ let StorageClient$1 = class StorageClient extends coreHttpCompat__namespace.Exte const defaults = { requestContentType: "application/json; charset=utf-8", }; - const packageDetails = `azsdk-js-azure-storage-blob/12.24.0`; + const packageDetails = `azsdk-js-azure-storage-blob/12.25.0`; const userAgentPrefix = options.userAgentOptions && options.userAgentOptions.userAgentPrefix ? `${options.userAgentOptions.userAgentPrefix} ${packageDetails}` : `${packageDetails}`; @@ -22246,7 +23352,7 @@ let StorageClient$1 = class StorageClient extends coreHttpCompat__namespace.Exte // Parameter assignments this.url = url; // Assigning values to Constant parameters - this.version = options.version || "2024-08-04"; + this.version = options.version || "2024-11-04"; this.service = new ServiceImpl(this); this.container = new ContainerImpl(this); this.blob = new BlobImpl(this); @@ -22257,7 +23363,7 @@ let StorageClient$1 = class StorageClient extends coreHttpCompat__namespace.Exte }; // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. /** * @internal */ @@ -22273,7 +23379,7 @@ class StorageContextClient extends StorageClient$1 { } // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. /** * A StorageClient represents a based URL class for {@link BlobServiceClient}, {@link ContainerClient} * and etc. @@ -22299,7 +23405,7 @@ class StorageClient { } // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. /** * Creates a span using the global tracer. * @internal @@ -22311,7 +23417,7 @@ const tracingClient = coreTracing.createTracingClient({ }); // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * @@ -22506,7 +23612,7 @@ class BlobSASPermissions { } // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. /** * This is a helper class to construct a string representing the permissions granted by a ServiceSAS to a container. * Setting a value to true means that any SAS which uses these permissions will grant permissions for that operation. @@ -22727,7 +23833,7 @@ class ContainerSASPermissions { } // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * @@ -22757,7 +23863,7 @@ class UserDelegationKeyCredential { } // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. /** * Generate SasIPRange format string. For example: * @@ -22770,7 +23876,7 @@ function ipRangeToString(ipRange) { } // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. /** * Protocols for generated SAS. */ @@ -23002,8 +24108,11 @@ class SASQueryParameters { } // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. function generateBlobSASQueryParameters(blobSASSignatureValues, sharedKeyCredentialOrUserDelegationKey, accountName) { + return generateBlobSASQueryParametersInternal(blobSASSignatureValues, sharedKeyCredentialOrUserDelegationKey, accountName).sasQueryParameters; +} +function generateBlobSASQueryParametersInternal(blobSASSignatureValues, sharedKeyCredentialOrUserDelegationKey, accountName) { const version = blobSASSignatureValues.version ? blobSASSignatureValues.version : SERVICE_VERSION; const sharedKeyCredential = sharedKeyCredentialOrUserDelegationKey instanceof StorageSharedKeyCredential ? sharedKeyCredentialOrUserDelegationKey @@ -23108,7 +24217,10 @@ function generateBlobSASQueryParameters20150405(blobSASSignatureValues, sharedKe blobSASSignatureValues.contentType ? blobSASSignatureValues.contentType : "", ].join("\n"); const signature = sharedKeyCredential.computeHMACSHA256(stringToSign); - return new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType); + return { + sasQueryParameters: new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType), + stringToSign: stringToSign, + }; } /** * ONLY AVAILABLE IN NODE.JS RUNTIME. @@ -23177,7 +24289,10 @@ function generateBlobSASQueryParameters20181109(blobSASSignatureValues, sharedKe blobSASSignatureValues.contentType ? blobSASSignatureValues.contentType : "", ].join("\n"); const signature = sharedKeyCredential.computeHMACSHA256(stringToSign); - return new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType); + return { + sasQueryParameters: new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType), + stringToSign: stringToSign, + }; } /** * ONLY AVAILABLE IN NODE.JS RUNTIME. @@ -23247,7 +24362,10 @@ function generateBlobSASQueryParameters20201206(blobSASSignatureValues, sharedKe blobSASSignatureValues.contentType ? blobSASSignatureValues.contentType : "", ].join("\n"); const signature = sharedKeyCredential.computeHMACSHA256(stringToSign); - return new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType, undefined, undefined, undefined, blobSASSignatureValues.encryptionScope); + return { + sasQueryParameters: new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType, undefined, undefined, undefined, blobSASSignatureValues.encryptionScope), + stringToSign: stringToSign, + }; } /** * ONLY AVAILABLE IN NODE.JS RUNTIME. @@ -23323,7 +24441,10 @@ function generateBlobSASQueryParametersUDK20181109(blobSASSignatureValues, userD blobSASSignatureValues.contentType, ].join("\n"); const signature = userDelegationKeyCredential.computeHMACSHA256(stringToSign); - return new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType, userDelegationKeyCredential.userDelegationKey); + return { + sasQueryParameters: new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType, userDelegationKeyCredential.userDelegationKey), + stringToSign: stringToSign, + }; } /** * ONLY AVAILABLE IN NODE.JS RUNTIME. @@ -23402,7 +24523,10 @@ function generateBlobSASQueryParametersUDK20200210(blobSASSignatureValues, userD blobSASSignatureValues.contentType, ].join("\n"); const signature = userDelegationKeyCredential.computeHMACSHA256(stringToSign); - return new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType, userDelegationKeyCredential.userDelegationKey, blobSASSignatureValues.preauthorizedAgentObjectId, blobSASSignatureValues.correlationId); + return { + sasQueryParameters: new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType, userDelegationKeyCredential.userDelegationKey, blobSASSignatureValues.preauthorizedAgentObjectId, blobSASSignatureValues.correlationId), + stringToSign: stringToSign, + }; } /** * ONLY AVAILABLE IN NODE.JS RUNTIME. @@ -23482,7 +24606,10 @@ function generateBlobSASQueryParametersUDK20201206(blobSASSignatureValues, userD blobSASSignatureValues.contentType, ].join("\n"); const signature = userDelegationKeyCredential.computeHMACSHA256(stringToSign); - return new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType, userDelegationKeyCredential.userDelegationKey, blobSASSignatureValues.preauthorizedAgentObjectId, blobSASSignatureValues.correlationId, blobSASSignatureValues.encryptionScope); + return { + sasQueryParameters: new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType, userDelegationKeyCredential.userDelegationKey, blobSASSignatureValues.preauthorizedAgentObjectId, blobSASSignatureValues.correlationId, blobSASSignatureValues.encryptionScope), + stringToSign: stringToSign, + }; } function getCanonicalName(accountName, containerName, blobName) { // Container: "/blob/account/containerName" @@ -23549,7 +24676,7 @@ function SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues) { } // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. /** * A client that manages leases for a {@link ContainerClient} or a {@link BlobClient}. */ @@ -23737,7 +24864,7 @@ class BlobLeaseClient { } // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * @@ -23854,7 +24981,7 @@ class RetriableReadableStream extends stream.Readable { } // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * @@ -24315,14 +25442,14 @@ class BlobDownloadResponse { } // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. const AVRO_SYNC_MARKER_SIZE = 16; const AVRO_INIT_BYTES = new Uint8Array([79, 98, 106, 1]); const AVRO_CODEC_KEY = "avro.codec"; const AVRO_SCHEMA_KEY = "avro.schema"; // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. class AvroParser { /** * Reads a fixed number of bytes from the stream. @@ -24479,6 +25606,7 @@ class AvroType { /** * Determines the AvroType from the Avro Schema. */ + // eslint-disable-next-line @typescript-eslint/no-wrapper-object-types static fromSchema(schema) { if (typeof schema === "string") { return AvroType.fromStringSchema(schema); @@ -24514,7 +25642,7 @@ class AvroType { try { return AvroType.fromStringSchema(type); } - catch (err) { + catch (_a) { // eslint-disable-line no-empty } switch (type) { @@ -24559,6 +25687,7 @@ class AvroPrimitiveType extends AvroType { super(); this._primitive = primitive; } + // eslint-disable-next-line @typescript-eslint/no-wrapper-object-types read(stream, options = {}) { switch (this._primitive) { case AvroPrimitive.NULL: @@ -24587,6 +25716,7 @@ class AvroEnumType extends AvroType { super(); this._symbols = symbols; } + // eslint-disable-next-line @typescript-eslint/no-wrapper-object-types async read(stream, options = {}) { const value = await AvroParser.readInt(stream, options); return this._symbols[value]; @@ -24598,7 +25728,6 @@ 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); } @@ -24608,6 +25737,7 @@ class AvroMapType extends AvroType { super(); this._itemType = itemType; } + // eslint-disable-next-line @typescript-eslint/no-wrapper-object-types read(stream, options = {}) { const readItemMethod = (s, opts) => { return this._itemType.read(s, opts); @@ -24621,7 +25751,9 @@ class AvroRecordType extends AvroType { this._fields = fields; this._name = name; } + // eslint-disable-next-line @typescript-eslint/no-wrapper-object-types async read(stream, options = {}) { + // eslint-disable-next-line @typescript-eslint/no-wrapper-object-types const record = {}; record["$schema"] = this._name; for (const key in this._fields) { @@ -24634,7 +25766,7 @@ class AvroRecordType extends AvroType { } // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. function arraysEqual(a, b) { if (a === b) return true; @@ -24651,7 +25783,7 @@ function arraysEqual(a, b) { } // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. class AvroReader { get blockOffset() { return this._blockOffset; @@ -24735,7 +25867,7 @@ class AvroReader { abortSignal: options.abortSignal, })); } - catch (err) { + catch (_a) { // We hit the end of the stream. this._itemsRemainingInBlock = 0; } @@ -24751,12 +25883,12 @@ class AvroReader { } // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. class AvroReadable { } // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. const ABORT_ERROR = new abortController.AbortError("Reading from the avro stream was aborted."); class AvroReadableFromStream extends AvroReadable { toUint8Array(data) { @@ -24838,7 +25970,7 @@ class AvroReadableFromStream extends AvroReadable { } // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * @@ -24947,7 +26079,7 @@ class BlobQuickQueryStream extends stream.Readable { } // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * @@ -25312,7 +26444,7 @@ class BlobQueryResponse { } // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. /** * Represents the access tier on a blob. * For detailed information about block blob level tiering see {@link https://docs.microsoft.com/azure/storage/blobs/storage-blob-storage-tiers|Hot, cool and archive storage tiers.} @@ -25426,7 +26558,7 @@ function getBlobServiceAccountAudience(storageAccountName) { } // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. /** * Function that converts PageRange and ClearRange to a common Range object. * PageRange and ClearRange have start and end while Range offset and count @@ -25450,7 +26582,7 @@ function rangeResponseFromModel(response) { } // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. /** * This is the poller returned by {@link BlobClient.beginCopyFromURL}. * This can not be instantiated directly outside of this package. @@ -25578,7 +26710,7 @@ function makeBlobBeginCopyFromURLPollOperation(state) { } // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. /** * Generate a range string. For example: * @@ -25599,7 +26731,7 @@ function rangeToString(iRange) { } // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. // In browser, during webpack or browserify bundling, this module will be replaced by 'events' // https://github.com/Gozala/events /** @@ -25720,7 +26852,7 @@ class Batch { } // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. /** * This class generates a readable stream from the data in an array of buffers. */ @@ -25802,7 +26934,7 @@ class BuffersStream extends stream.Readable { } // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. const maxBufferLength = buffer.constants.MAX_LENGTH; /** * This class provides a buffer container which conceptually has no hard size limit. @@ -25884,7 +27016,7 @@ class PooledBuffer { } // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. /** * This class accepts a Node.js Readable stream as input, and keeps reading data * from the stream into the internal buffer structure, until it reaches maxBuffers. @@ -26134,7 +27266,7 @@ class BufferScheduler { } // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. /** * Reads a readable stream into buffer. Fill the buffer from offset to end. * @@ -26244,7 +27376,7 @@ const fsStat = util__namespace.promisify(fs__namespace.stat); const fsCreateReadStream = fs__namespace.createReadStream; // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. /** * A BlobClient represents a URL to an Azure Storage blob; the blob may be a block blob, * append blob, or page blob. @@ -27148,6 +28280,24 @@ class BlobClient extends StorageClient { resolve(appendToURLQuery(this.url, sas)); }); } + /** + * Only available for BlobClient constructed with a shared key credential. + * + * Generates string to sign for a Blob Service Shared Access Signature (SAS) URI based on + * the client properties and parameters passed in. The SAS is signed by the shared key credential of the client. + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas + * + * @param options - Optional parameters. + * @returns The SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. + */ + /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options*/ + generateSasStringToSign(options) { + if (!(this.credential instanceof StorageSharedKeyCredential)) { + throw new RangeError("Can only generate the SAS when the client is initialized with a shared key credential"); + } + return generateBlobSASQueryParametersInternal(Object.assign({ containerName: this._containerName, blobName: this._name, snapshotTime: this._snapshot, versionId: this._versionId }, options), this.credential).stringToSign; + } /** * Delete the immutablility policy on the blob. * @@ -28007,6 +29157,7 @@ class BlockBlobClient extends BlobClient { blockList.push(blockID); blockNum++; await this.stageBlock(blockID, body, length, { + customerProvidedKey: options.customerProvidedKey, conditions: options.conditions, encryptionScope: options.encryptionScope, tracingOptions: updatedOptions.tracingOptions, @@ -28764,7 +29915,7 @@ class PageBlobClient extends BlobClient { } // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. async function getBodyAsText(batchResponse) { let buffer = Buffer.alloc(BATCH_MAX_PAYLOAD_IN_BYTES); const responseLength = await streamToBuffer2(batchResponse.readableStreamBody, buffer); @@ -28777,7 +29928,7 @@ function utf8ByteLength(str) { } // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. const HTTP_HEADER_DELIMITER = ": "; const SPACE_DELIMITER = " "; const NOT_FOUND = -1; @@ -28909,7 +30060,7 @@ class BatchResponseParser { } // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. var MutexLockStatus; (function (MutexLockStatus) { MutexLockStatus[MutexLockStatus["LOCKED"] = 0] = "LOCKED"; @@ -28974,7 +30125,7 @@ Mutex.keys = {}; Mutex.listeners = {}; // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. /** * A BlobBatch represents an aggregated set of operations on blobs. * Currently, only `delete` and `setAccessTier` are supported. @@ -29226,7 +30377,7 @@ function batchHeaderFilterPolicy() { } // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. /** * A BlobBatchClient allows you to make batched requests to the Azure Storage Blob service. * @@ -30493,6 +31644,24 @@ class ContainerClient extends StorageClient { resolve(appendToURLQuery(this.url, sas)); }); } + /** + * Only available for ContainerClient constructed with a shared key credential. + * + * Generates string to sign for a Blob Container Service Shared Access Signature (SAS) URI + * based on the client properties and parameters passed in. The SAS is signed by the shared key credential of the client. + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas + * + * @param options - Optional parameters. + * @returns The SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. + */ + /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options*/ + generateSasStringToSign(options) { + if (!(this.credential instanceof StorageSharedKeyCredential)) { + throw new RangeError("Can only generate the SAS when the client is initialized with a shared key credential"); + } + return generateBlobSASQueryParametersInternal(Object.assign({ containerName: this._containerName }, options), this.credential).stringToSign; + } /** * Creates a BlobBatchClient object to conduct batch operations. * @@ -30506,7 +31675,7 @@ class ContainerClient extends StorageClient { } // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * @@ -30733,7 +31902,7 @@ class AccountSASPermissions { } // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * @@ -30805,7 +31974,7 @@ class AccountSASResourceTypes { } // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * @@ -30885,7 +32054,7 @@ class AccountSASServices { } // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * @@ -30898,6 +32067,10 @@ class AccountSASServices { * @param sharedKeyCredential - */ function generateAccountSASQueryParameters(accountSASSignatureValues, sharedKeyCredential) { + return generateAccountSASQueryParametersInternal(accountSASSignatureValues, sharedKeyCredential) + .sasQueryParameters; +} +function generateAccountSASQueryParametersInternal(accountSASSignatureValues, sharedKeyCredential) { const version = accountSASSignatureValues.version ? accountSASSignatureValues.version : SERVICE_VERSION; @@ -30967,7 +32140,10 @@ function generateAccountSASQueryParameters(accountSASSignatureValues, sharedKeyC ].join("\n"); } const signature = sharedKeyCredential.computeHMACSHA256(stringToSign); - return new SASQueryParameters(version, signature, parsedPermissions.toString(), parsedServices, parsedResourceTypes, accountSASSignatureValues.protocol, accountSASSignatureValues.startsOn, accountSASSignatureValues.expiresOn, accountSASSignatureValues.ipRange, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, accountSASSignatureValues.encryptionScope); + return { + sasQueryParameters: new SASQueryParameters(version, signature, parsedPermissions.toString(), parsedServices, parsedResourceTypes, accountSASSignatureValues.protocol, accountSASSignatureValues.startsOn, accountSASSignatureValues.expiresOn, accountSASSignatureValues.ipRange, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, accountSASSignatureValues.encryptionScope), + stringToSign: stringToSign, + }; } /** @@ -31642,10 +32818,36 @@ class BlobServiceClient extends StorageClient { resourceTypes, services: AccountSASServices.parse("b").toString() }, options), this.credential).toString(); return appendToURLQuery(this.url, sas); } + /** + * Only available for BlobServiceClient constructed with a shared key credential. + * + * Generates string to sign for a Blob account Shared Access Signature (SAS) URI based on + * the client properties and parameters passed in. The SAS is signed by the shared key credential of the client. + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-account-sas + * + * @param expiresOn - Optional. The time at which the shared access signature becomes invalid. Default to an hour later if not provided. + * @param permissions - Specifies the list of permissions to be associated with the SAS. + * @param resourceTypes - Specifies the resource types associated with the shared access signature. + * @param options - Optional parameters. + * @returns An account SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. + */ + generateSasStringToSign(expiresOn, permissions = AccountSASPermissions.parse("r"), resourceTypes = "sco", options = {}) { + if (!(this.credential instanceof StorageSharedKeyCredential)) { + throw RangeError("Can only generate the account SAS when the client is initialized with a shared key credential"); + } + if (expiresOn === undefined) { + const now = new Date(); + expiresOn = new Date(now.getTime() + 3600 * 1000); + } + return generateAccountSASQueryParametersInternal(Object.assign({ permissions, + expiresOn, + resourceTypes, services: AccountSASServices.parse("b").toString() }, options), this.credential).stringToSign; + } } // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. /** Known values of {@link EncryptionAlgorithmType} that the service accepts. */ exports.KnownEncryptionAlgorithmType = void 0; (function (KnownEncryptionAlgorithmType) { @@ -32245,7 +33447,7 @@ var isArray = Array.isArray || function (xs) { /***/ }), -/***/ 9280: +/***/ 4602: /***/ ((module, exports, __nccwpck_require__) => { /* eslint-env browser */ @@ -32504,7 +33706,7 @@ function localstorage() { } } -module.exports = __nccwpck_require__(85)(exports); +module.exports = __nccwpck_require__(8958)(exports); const {formatters} = module.exports; @@ -32523,7 +33725,7 @@ formatters.j = function (v) { /***/ }), -/***/ 85: +/***/ 8958: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { @@ -32539,7 +33741,7 @@ function setup(env) { createDebug.disable = disable; createDebug.enable = enable; createDebug.enabled = enabled; - createDebug.humanize = __nccwpck_require__(5717); + createDebug.humanize = __nccwpck_require__(158); createDebug.destroy = destroy; Object.keys(env).forEach(key => { @@ -32804,7 +34006,7 @@ module.exports = setup; /***/ }), -/***/ 4684: +/***/ 9329: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /** @@ -32813,15 +34015,15 @@ module.exports = setup; */ if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { - module.exports = __nccwpck_require__(9280); + module.exports = __nccwpck_require__(4602); } else { - module.exports = __nccwpck_require__(1240); + module.exports = __nccwpck_require__(6193); } /***/ }), -/***/ 1240: +/***/ 6193: /***/ ((module, exports, __nccwpck_require__) => { /** @@ -33063,7 +34265,7 @@ function init(debug) { } } -module.exports = __nccwpck_require__(85)(exports); +module.exports = __nccwpck_require__(8958)(exports); const {formatters} = module.exports; @@ -35968,7 +37170,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.HttpProxyAgent = void 0; const net = __importStar(__nccwpck_require__(1808)); const tls = __importStar(__nccwpck_require__(4404)); -const debug_1 = __importDefault(__nccwpck_require__(4684)); +const debug_1 = __importDefault(__nccwpck_require__(9329)); const events_1 = __nccwpck_require__(2361); const agent_base_1 = __nccwpck_require__(8247); const url_1 = __nccwpck_require__(7310); @@ -38534,7 +39736,7 @@ exports.HttpsProxyAgent = void 0; const net = __importStar(__nccwpck_require__(1808)); const tls = __importStar(__nccwpck_require__(4404)); const assert_1 = __importDefault(__nccwpck_require__(9491)); -const debug_1 = __importDefault(__nccwpck_require__(4684)); +const debug_1 = __importDefault(__nccwpck_require__(9329)); const agent_base_1 = __nccwpck_require__(8247); const url_1 = __nccwpck_require__(7310); const parse_proxy_response_1 = __nccwpck_require__(7372); @@ -38689,7 +39891,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parseProxyResponse = void 0; -const debug_1 = __importDefault(__nccwpck_require__(4684)); +const debug_1 = __importDefault(__nccwpck_require__(9329)); const debug = (0, debug_1.default)('https-proxy-agent:parse-proxy-response'); function parseProxyResponse(socket) { return new Promise((resolve, reject) => { @@ -40156,7 +41358,7 @@ function regExpEscape (s) { /***/ }), -/***/ 5717: +/***/ 158: /***/ ((module) => { /** @@ -40184,7 +41386,7 @@ var y = d * 365.25; * @api public */ -module.exports = function(val, options) { +module.exports = function (val, options) { options = options || {}; var type = typeof val; if (type === 'string' && val.length > 0) { @@ -42782,7 +43984,7 @@ exports.x = Tail /***/ }), -/***/ 9236: +/***/ 1772: /***/ ((module) => { /****************************************************************************** @@ -42831,6 +44033,7 @@ var __classPrivateFieldIn; var __createBinding; var __addDisposableResource; var __disposeResources; +var __rewriteRelativeImportExtension; (function (factory) { var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {}; if (typeof define === "function" && define.amd) { @@ -43098,10 +44301,19 @@ var __disposeResources; o["default"] = v; }; + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + __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); + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; @@ -43182,6 +44394,15 @@ var __disposeResources; return next(); }; + __rewriteRelativeImportExtension = function (path, preserveJsx) { + if (typeof path === "string" && /^\.\.?\//.test(path)) { + return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) { + return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js"); + }); + } + return path; + }; + exporter("__extends", __extends); exporter("__assign", __assign); exporter("__rest", __rest); @@ -43213,7 +44434,10 @@ var __disposeResources; exporter("__classPrivateFieldIn", __classPrivateFieldIn); exporter("__addDisposableResource", __addDisposableResource); exporter("__disposeResources", __disposeResources); + exporter("__rewriteRelativeImportExtension", __rewriteRelativeImportExtension); }); + +0 && (0); /***/ }), @@ -65583,221 +66807,6 @@ module.exports = { } -/***/ }), - -/***/ 8493: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var v1 = __nccwpck_require__(1311); -var v4 = __nccwpck_require__(7191); - -var uuid = v4; -uuid.v1 = v1; -uuid.v4 = v4; - -module.exports = uuid; - - -/***/ }), - -/***/ 2937: -/***/ ((module) => { - -/** - * Convert array of 16 byte values to UUID string format of the form: - * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX - */ -var byteToHex = []; -for (var i = 0; i < 256; ++i) { - byteToHex[i] = (i + 0x100).toString(16).substr(1); -} - -function bytesToUuid(buf, offset) { - var i = offset || 0; - var bth = byteToHex; - // join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4 - return ([ - bth[buf[i++]], bth[buf[i++]], - bth[buf[i++]], bth[buf[i++]], '-', - bth[buf[i++]], bth[buf[i++]], '-', - bth[buf[i++]], bth[buf[i++]], '-', - bth[buf[i++]], bth[buf[i++]], '-', - bth[buf[i++]], bth[buf[i++]], - bth[buf[i++]], bth[buf[i++]], - bth[buf[i++]], bth[buf[i++]] - ]).join(''); -} - -module.exports = bytesToUuid; - - -/***/ }), - -/***/ 5403: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -// Unique ID creation requires a high quality random # generator. In node.js -// this is pretty straight-forward - we use the crypto API. - -var crypto = __nccwpck_require__(6113); - -module.exports = function nodeRNG() { - return crypto.randomBytes(16); -}; - - -/***/ }), - -/***/ 1311: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var rng = __nccwpck_require__(5403); -var bytesToUuid = __nccwpck_require__(2937); - -// **`v1()` - Generate time-based UUID** -// -// Inspired by https://github.com/LiosK/UUID.js -// and http://docs.python.org/library/uuid.html - -var _nodeId; -var _clockseq; - -// Previous uuid creation time -var _lastMSecs = 0; -var _lastNSecs = 0; - -// See https://github.com/uuidjs/uuid for API details -function v1(options, buf, offset) { - var i = buf && offset || 0; - var b = buf || []; - - options = options || {}; - var node = options.node || _nodeId; - var 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) { - var seedBytes = rng(); - 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. - var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime(); - - // Per 4.2.1.2, use count of uuid's generated during the current clock - // cycle to simulate higher resolution clock - var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; - - // Time since last uuid creation (in msecs) - var 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` - var 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` - var 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 (var n = 0; n < 6; ++n) { - b[i + n] = node[n]; - } - - return buf ? buf : bytesToUuid(b); -} - -module.exports = v1; - - -/***/ }), - -/***/ 7191: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var rng = __nccwpck_require__(5403); -var bytesToUuid = __nccwpck_require__(2937); - -function v4(options, buf, offset) { - var i = buf && offset || 0; - - if (typeof(options) == 'string') { - buf = options === 'binary' ? new Array(16) : null; - options = null; - } - options = options || {}; - - var rnds = options.random || (options.rng || rng)(); - - // 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 - if (buf) { - for (var ii = 0; ii < 16; ++ii) { - buf[i + ii] = rnds[ii]; - } - } - - return buf || bytesToUuid(rnds); -} - -module.exports = v4; - - /***/ }), /***/ 7338: @@ -66734,12 +67743,12 @@ Object.defineProperty(exports, "AbortError", ({ enumerable: true, get: function /***/ }), -/***/ 8935: +/***/ 662: /***/ ((__unused_webpack_module, exports) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.AzureKeyCredential = void 0; /** @@ -66782,15 +67791,16 @@ exports.AzureKeyCredential = AzureKeyCredential; /***/ }), -/***/ 6058: +/***/ 5525: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.isNamedKeyCredential = exports.AzureNamedKeyCredential = void 0; -const core_util_1 = __nccwpck_require__(8143); +exports.AzureNamedKeyCredential = void 0; +exports.isNamedKeyCredential = isNamedKeyCredential; +const core_util_1 = __nccwpck_require__(1910); /** * A static name/key-based credential that supports updating * the underlying name and key values. @@ -66850,20 +67860,20 @@ function isNamedKeyCredential(credential) { typeof credential.key === "string" && typeof credential.name === "string"); } -exports.isNamedKeyCredential = isNamedKeyCredential; //# sourceMappingURL=azureNamedKeyCredential.js.map /***/ }), -/***/ 6512: +/***/ 1446: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.isSASCredential = exports.AzureSASCredential = void 0; -const core_util_1 = __nccwpck_require__(8143); +exports.AzureSASCredential = void 0; +exports.isSASCredential = isSASCredential; +const core_util_1 = __nccwpck_require__(1910); /** * A static-signature-based credential that supports updating * the underlying signature value. @@ -66911,44 +67921,41 @@ exports.AzureSASCredential = AzureSASCredential; function isSASCredential(credential) { return ((0, core_util_1.isObjectWithProperties)(credential, ["signature"]) && typeof credential.signature === "string"); } -exports.isSASCredential = isSASCredential; //# sourceMappingURL=azureSASCredential.js.map /***/ }), -/***/ 9334: +/***/ 3728: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isTokenCredential = exports.isSASCredential = exports.AzureSASCredential = exports.isNamedKeyCredential = exports.AzureNamedKeyCredential = exports.isKeyCredential = exports.AzureKeyCredential = void 0; -var azureKeyCredential_js_1 = __nccwpck_require__(8935); +var azureKeyCredential_js_1 = __nccwpck_require__(662); Object.defineProperty(exports, "AzureKeyCredential", ({ enumerable: true, get: function () { return azureKeyCredential_js_1.AzureKeyCredential; } })); -var keyCredential_js_1 = __nccwpck_require__(3921); +var keyCredential_js_1 = __nccwpck_require__(4770); Object.defineProperty(exports, "isKeyCredential", ({ enumerable: true, get: function () { return keyCredential_js_1.isKeyCredential; } })); -var azureNamedKeyCredential_js_1 = __nccwpck_require__(6058); +var azureNamedKeyCredential_js_1 = __nccwpck_require__(5525); Object.defineProperty(exports, "AzureNamedKeyCredential", ({ enumerable: true, get: function () { return azureNamedKeyCredential_js_1.AzureNamedKeyCredential; } })); Object.defineProperty(exports, "isNamedKeyCredential", ({ enumerable: true, get: function () { return azureNamedKeyCredential_js_1.isNamedKeyCredential; } })); -var azureSASCredential_js_1 = __nccwpck_require__(6512); +var azureSASCredential_js_1 = __nccwpck_require__(1446); Object.defineProperty(exports, "AzureSASCredential", ({ enumerable: true, get: function () { return azureSASCredential_js_1.AzureSASCredential; } })); Object.defineProperty(exports, "isSASCredential", ({ enumerable: true, get: function () { return azureSASCredential_js_1.isSASCredential; } })); -var tokenCredential_js_1 = __nccwpck_require__(8045); +var tokenCredential_js_1 = __nccwpck_require__(9089); Object.defineProperty(exports, "isTokenCredential", ({ enumerable: true, get: function () { return tokenCredential_js_1.isTokenCredential; } })); //# sourceMappingURL=index.js.map /***/ }), -/***/ 3921: +/***/ 4770: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.isKeyCredential = void 0; -const core_util_1 = __nccwpck_require__(8143); +exports.isKeyCredential = isKeyCredential; +const core_util_1 = __nccwpck_require__(1910); /** * Tests an object to determine whether it implements KeyCredential. * @@ -66957,19 +67964,36 @@ const core_util_1 = __nccwpck_require__(8143); function isKeyCredential(credential) { return (0, core_util_1.isObjectWithProperties)(credential, ["key"]) && typeof credential.key === "string"; } -exports.isKeyCredential = isKeyCredential; //# sourceMappingURL=keyCredential.js.map /***/ }), -/***/ 8045: +/***/ 9089: /***/ ((__unused_webpack_module, exports) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.isTokenCredential = void 0; +exports.isBearerToken = isBearerToken; +exports.isPopToken = isPopToken; +exports.isTokenCredential = isTokenCredential; +/** + * @internal + * @param accessToken - Access token + * @returns Whether a token is bearer type or not + */ +function isBearerToken(accessToken) { + return !accessToken.tokenType || accessToken.tokenType === "Bearer"; +} +/** + * @internal + * @param accessToken - Access token + * @returns Whether a token is Pop token or not + */ +function isPopToken(accessToken) { + return accessToken.tokenType === "pop"; +} /** * Tests an object to determine whether it implements TokenCredential. * @@ -66986,7 +68010,6 @@ function isTokenCredential(credential) { typeof castCredential.getToken === "function" && (castCredential.signRequest === undefined || castCredential.getToken.length > 0)); } -exports.isTokenCredential = isTokenCredential; //# sourceMappingURL=tokenCredential.js.map /***/ }), @@ -67252,7 +68275,7 @@ exports.decodeStringToString = decodeStringToString; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.deserializationPolicy = exports.deserializationPolicyName = void 0; const interfaces_js_1 = __nccwpck_require__(5915); -const core_rest_pipeline_1 = __nccwpck_require__(7314); +const core_rest_pipeline_1 = __nccwpck_require__(903); const serializer_js_1 = __nccwpck_require__(8293); const operationHelpers_js_1 = __nccwpck_require__(164); const defaultJsonContentTypes = ["application/json", "text/json"]; @@ -67492,7 +68515,7 @@ async function parse(jsonContentTypes, xmlContentTypes, operationResponse, opts, // Licensed under the MIT license. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getCachedDefaultHttpClient = void 0; -const core_rest_pipeline_1 = __nccwpck_require__(7314); +const core_rest_pipeline_1 = __nccwpck_require__(903); let cachedHttpClient; function getCachedDefaultHttpClient() { if (!cachedHttpClient) { @@ -67735,7 +68758,7 @@ exports.getOperationRequestInfo = getOperationRequestInfo; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createClientPipeline = void 0; const deserializationPolicy_js_1 = __nccwpck_require__(9430); -const core_rest_pipeline_1 = __nccwpck_require__(7314); +const core_rest_pipeline_1 = __nccwpck_require__(903); const serializationPolicy_js_1 = __nccwpck_require__(7709); /** * Creates a new Pipeline for use with a Service Client. @@ -67935,7 +68958,7 @@ function prepareXMLRootList(obj, elementName, xmlNamespaceKey, xmlNamespace) { // Licensed under the MIT license. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.MapperTypeNames = exports.createSerializer = void 0; -const tslib_1 = __nccwpck_require__(9236); +const tslib_1 = __nccwpck_require__(1772); const base64 = tslib_1.__importStar(__nccwpck_require__(447)); const interfaces_js_1 = __nccwpck_require__(5915); const utils_js_1 = __nccwpck_require__(382); @@ -68868,7 +69891,7 @@ exports.MapperTypeNames = { // Licensed under the MIT license. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ServiceClient = void 0; -const core_rest_pipeline_1 = __nccwpck_require__(7314); +const core_rest_pipeline_1 = __nccwpck_require__(903); const pipeline_js_1 = __nccwpck_require__(8381); const utils_js_1 = __nccwpck_require__(382); const httpClientCache_js_1 = __nccwpck_require__(9509); @@ -69420,7 +70443,7 @@ exports.flattenResponse = flattenResponse; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ExtendedServiceClient = void 0; const disableKeepAlivePolicy_js_1 = __nccwpck_require__(5268); -const core_rest_pipeline_1 = __nccwpck_require__(7314); +const core_rest_pipeline_1 = __nccwpck_require__(903); const core_client_1 = __nccwpck_require__(2026); const response_js_1 = __nccwpck_require__(4023); /** @@ -69628,7 +70651,7 @@ exports.createRequestPolicyFactoryPolicy = createRequestPolicyFactoryPolicy; // Licensed under the MIT license. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.toPipelineResponse = exports.toCompatResponse = void 0; -const core_rest_pipeline_1 = __nccwpck_require__(7314); +const core_rest_pipeline_1 = __nccwpck_require__(903); const util_js_1 = __nccwpck_require__(4912); const originalResponse = Symbol("Original FullOperationResponse"); /** @@ -69699,7 +70722,7 @@ exports.toPipelineResponse = toPipelineResponse; // Licensed under the MIT license. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.HttpHeaders = exports.toHttpHeadersLike = exports.toWebResourceLike = exports.toPipelineRequest = void 0; -const core_rest_pipeline_1 = __nccwpck_require__(7314); +const core_rest_pipeline_1 = __nccwpck_require__(903); // We use a custom symbol to cache a reference to the original request without // exposing it on the public interface. const originalRequestSymbol = Symbol("Original PipelineRequest"); @@ -70270,7 +71293,7 @@ exports.pollHttpOperation = pollHttpOperation; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createHttpPoller = void 0; const operation_js_1 = __nccwpck_require__(6562); -const poller_js_1 = __nccwpck_require__(269); +const poller_js_1 = __nccwpck_require__(2233); /** * Creates a poller that can be used to poll a long-running operation. * @param lro - Description of the long-running operation @@ -70323,7 +71346,7 @@ exports.createHttpPoller = createHttpPoller; // Licensed under the MIT license. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createHttpPoller = void 0; -const tslib_1 = __nccwpck_require__(9236); +const tslib_1 = __nccwpck_require__(1772); var poller_js_1 = __nccwpck_require__(8969); Object.defineProperty(exports, "createHttpPoller", ({ enumerable: true, get: function () { return poller_js_1.createHttpPoller; } })); /** @@ -71128,7 +72151,7 @@ exports.pollOperation = pollOperation; /***/ }), -/***/ 269: +/***/ 2233: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { @@ -71138,7 +72161,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.buildCreatePoller = void 0; const operation_js_1 = __nccwpck_require__(5258); const constants_js_1 = __nccwpck_require__(474); -const core_util_1 = __nccwpck_require__(8143); +const core_util_1 = __nccwpck_require__(1910); const createStateProxy = () => ({ /** * The state at this point is created to be of type OperationState. @@ -71308,41 +72331,41 @@ exports.buildCreatePoller = buildCreatePoller; /***/ }), -/***/ 5631: +/***/ 2757: /***/ ((__unused_webpack_module, exports) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DEFAULT_RETRY_POLICY_COUNT = exports.SDK_VERSION = void 0; -exports.SDK_VERSION = "1.16.3"; +exports.SDK_VERSION = "1.17.0"; exports.DEFAULT_RETRY_POLICY_COUNT = 3; //# sourceMappingURL=constants.js.map /***/ }), -/***/ 6881: +/***/ 3891: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createPipelineFromOptions = createPipelineFromOptions; -const logPolicy_js_1 = __nccwpck_require__(8383); -const pipeline_js_1 = __nccwpck_require__(4191); -const redirectPolicy_js_1 = __nccwpck_require__(2960); -const userAgentPolicy_js_1 = __nccwpck_require__(8254); -const multipartPolicy_js_1 = __nccwpck_require__(8807); -const decompressResponsePolicy_js_1 = __nccwpck_require__(9716); -const defaultRetryPolicy_js_1 = __nccwpck_require__(6451); -const formDataPolicy_js_1 = __nccwpck_require__(5204); -const core_util_1 = __nccwpck_require__(8143); -const proxyPolicy_js_1 = __nccwpck_require__(6360); -const setClientRequestIdPolicy_js_1 = __nccwpck_require__(1334); -const tlsPolicy_js_1 = __nccwpck_require__(8422); -const tracingPolicy_js_1 = __nccwpck_require__(6105); +const logPolicy_js_1 = __nccwpck_require__(4560); +const pipeline_js_1 = __nccwpck_require__(9122); +const redirectPolicy_js_1 = __nccwpck_require__(4250); +const userAgentPolicy_js_1 = __nccwpck_require__(9413); +const multipartPolicy_js_1 = __nccwpck_require__(2545); +const decompressResponsePolicy_js_1 = __nccwpck_require__(3007); +const defaultRetryPolicy_js_1 = __nccwpck_require__(9607); +const formDataPolicy_js_1 = __nccwpck_require__(2256); +const core_util_1 = __nccwpck_require__(1910); +const proxyPolicy_js_1 = __nccwpck_require__(7966); +const setClientRequestIdPolicy_js_1 = __nccwpck_require__(5283); +const tlsPolicy_js_1 = __nccwpck_require__(8012); +const tracingPolicy_js_1 = __nccwpck_require__(9817); /** * Create a new pipeline with a default set of customizable policies. * @param options - Options to configure a custom pipeline. @@ -71380,15 +72403,15 @@ function createPipelineFromOptions(options) { /***/ }), -/***/ 1936: +/***/ 4323: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createDefaultHttpClient = createDefaultHttpClient; -const nodeHttpClient_js_1 = __nccwpck_require__(4093); +const nodeHttpClient_js_1 = __nccwpck_require__(2441); /** * Create the correct HttpClient for the current environment. */ @@ -71399,12 +72422,12 @@ function createDefaultHttpClient() { /***/ }), -/***/ 3488: +/***/ 1780: /***/ ((__unused_webpack_module, exports) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createHttpHeaders = createHttpHeaders; function normalizeName(name) { @@ -71497,93 +72520,93 @@ function createHttpHeaders(rawHeaders) { /***/ }), -/***/ 7314: +/***/ 903: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createFileFromStream = exports.createFile = exports.auxiliaryAuthenticationHeaderPolicyName = exports.auxiliaryAuthenticationHeaderPolicy = exports.ndJsonPolicyName = exports.ndJsonPolicy = exports.bearerTokenAuthenticationPolicyName = exports.bearerTokenAuthenticationPolicy = exports.formDataPolicyName = exports.formDataPolicy = exports.tlsPolicyName = exports.tlsPolicy = exports.userAgentPolicyName = exports.userAgentPolicy = exports.defaultRetryPolicy = exports.tracingPolicyName = exports.tracingPolicy = exports.retryPolicy = exports.throttlingRetryPolicyName = exports.throttlingRetryPolicy = exports.systemErrorRetryPolicyName = exports.systemErrorRetryPolicy = exports.redirectPolicyName = exports.redirectPolicy = exports.getDefaultProxySettings = exports.proxyPolicyName = exports.proxyPolicy = exports.multipartPolicyName = exports.multipartPolicy = exports.logPolicyName = exports.logPolicy = exports.setClientRequestIdPolicyName = exports.setClientRequestIdPolicy = exports.exponentialRetryPolicyName = exports.exponentialRetryPolicy = exports.decompressResponsePolicyName = exports.decompressResponsePolicy = exports.isRestError = exports.RestError = exports.createPipelineRequest = exports.createHttpHeaders = exports.createDefaultHttpClient = exports.createPipelineFromOptions = exports.createEmptyPipeline = void 0; -var pipeline_js_1 = __nccwpck_require__(4191); +var pipeline_js_1 = __nccwpck_require__(9122); Object.defineProperty(exports, "createEmptyPipeline", ({ enumerable: true, get: function () { return pipeline_js_1.createEmptyPipeline; } })); -var createPipelineFromOptions_js_1 = __nccwpck_require__(6881); +var createPipelineFromOptions_js_1 = __nccwpck_require__(3891); Object.defineProperty(exports, "createPipelineFromOptions", ({ enumerable: true, get: function () { return createPipelineFromOptions_js_1.createPipelineFromOptions; } })); -var defaultHttpClient_js_1 = __nccwpck_require__(1936); +var defaultHttpClient_js_1 = __nccwpck_require__(4323); Object.defineProperty(exports, "createDefaultHttpClient", ({ enumerable: true, get: function () { return defaultHttpClient_js_1.createDefaultHttpClient; } })); -var httpHeaders_js_1 = __nccwpck_require__(3488); +var httpHeaders_js_1 = __nccwpck_require__(1780); Object.defineProperty(exports, "createHttpHeaders", ({ enumerable: true, get: function () { return httpHeaders_js_1.createHttpHeaders; } })); -var pipelineRequest_js_1 = __nccwpck_require__(3375); +var pipelineRequest_js_1 = __nccwpck_require__(871); Object.defineProperty(exports, "createPipelineRequest", ({ enumerable: true, get: function () { return pipelineRequest_js_1.createPipelineRequest; } })); -var restError_js_1 = __nccwpck_require__(6985); +var restError_js_1 = __nccwpck_require__(690); Object.defineProperty(exports, "RestError", ({ enumerable: true, get: function () { return restError_js_1.RestError; } })); Object.defineProperty(exports, "isRestError", ({ enumerable: true, get: function () { return restError_js_1.isRestError; } })); -var decompressResponsePolicy_js_1 = __nccwpck_require__(9716); +var decompressResponsePolicy_js_1 = __nccwpck_require__(3007); Object.defineProperty(exports, "decompressResponsePolicy", ({ enumerable: true, get: function () { return decompressResponsePolicy_js_1.decompressResponsePolicy; } })); Object.defineProperty(exports, "decompressResponsePolicyName", ({ enumerable: true, get: function () { return decompressResponsePolicy_js_1.decompressResponsePolicyName; } })); -var exponentialRetryPolicy_js_1 = __nccwpck_require__(2233); +var exponentialRetryPolicy_js_1 = __nccwpck_require__(5105); Object.defineProperty(exports, "exponentialRetryPolicy", ({ enumerable: true, get: function () { return exponentialRetryPolicy_js_1.exponentialRetryPolicy; } })); Object.defineProperty(exports, "exponentialRetryPolicyName", ({ enumerable: true, get: function () { return exponentialRetryPolicy_js_1.exponentialRetryPolicyName; } })); -var setClientRequestIdPolicy_js_1 = __nccwpck_require__(1334); +var setClientRequestIdPolicy_js_1 = __nccwpck_require__(5283); Object.defineProperty(exports, "setClientRequestIdPolicy", ({ enumerable: true, get: function () { return setClientRequestIdPolicy_js_1.setClientRequestIdPolicy; } })); Object.defineProperty(exports, "setClientRequestIdPolicyName", ({ enumerable: true, get: function () { return setClientRequestIdPolicy_js_1.setClientRequestIdPolicyName; } })); -var logPolicy_js_1 = __nccwpck_require__(8383); +var logPolicy_js_1 = __nccwpck_require__(4560); Object.defineProperty(exports, "logPolicy", ({ enumerable: true, get: function () { return logPolicy_js_1.logPolicy; } })); Object.defineProperty(exports, "logPolicyName", ({ enumerable: true, get: function () { return logPolicy_js_1.logPolicyName; } })); -var multipartPolicy_js_1 = __nccwpck_require__(8807); +var multipartPolicy_js_1 = __nccwpck_require__(2545); Object.defineProperty(exports, "multipartPolicy", ({ enumerable: true, get: function () { return multipartPolicy_js_1.multipartPolicy; } })); Object.defineProperty(exports, "multipartPolicyName", ({ enumerable: true, get: function () { return multipartPolicy_js_1.multipartPolicyName; } })); -var proxyPolicy_js_1 = __nccwpck_require__(6360); +var proxyPolicy_js_1 = __nccwpck_require__(7966); Object.defineProperty(exports, "proxyPolicy", ({ enumerable: true, get: function () { return proxyPolicy_js_1.proxyPolicy; } })); Object.defineProperty(exports, "proxyPolicyName", ({ enumerable: true, get: function () { return proxyPolicy_js_1.proxyPolicyName; } })); Object.defineProperty(exports, "getDefaultProxySettings", ({ enumerable: true, get: function () { return proxyPolicy_js_1.getDefaultProxySettings; } })); -var redirectPolicy_js_1 = __nccwpck_require__(2960); +var redirectPolicy_js_1 = __nccwpck_require__(4250); Object.defineProperty(exports, "redirectPolicy", ({ enumerable: true, get: function () { return redirectPolicy_js_1.redirectPolicy; } })); Object.defineProperty(exports, "redirectPolicyName", ({ enumerable: true, get: function () { return redirectPolicy_js_1.redirectPolicyName; } })); -var systemErrorRetryPolicy_js_1 = __nccwpck_require__(8009); +var systemErrorRetryPolicy_js_1 = __nccwpck_require__(6626); Object.defineProperty(exports, "systemErrorRetryPolicy", ({ enumerable: true, get: function () { return systemErrorRetryPolicy_js_1.systemErrorRetryPolicy; } })); Object.defineProperty(exports, "systemErrorRetryPolicyName", ({ enumerable: true, get: function () { return systemErrorRetryPolicy_js_1.systemErrorRetryPolicyName; } })); -var throttlingRetryPolicy_js_1 = __nccwpck_require__(3297); +var throttlingRetryPolicy_js_1 = __nccwpck_require__(7823); Object.defineProperty(exports, "throttlingRetryPolicy", ({ enumerable: true, get: function () { return throttlingRetryPolicy_js_1.throttlingRetryPolicy; } })); Object.defineProperty(exports, "throttlingRetryPolicyName", ({ enumerable: true, get: function () { return throttlingRetryPolicy_js_1.throttlingRetryPolicyName; } })); -var retryPolicy_js_1 = __nccwpck_require__(3261); +var retryPolicy_js_1 = __nccwpck_require__(2093); Object.defineProperty(exports, "retryPolicy", ({ enumerable: true, get: function () { return retryPolicy_js_1.retryPolicy; } })); -var tracingPolicy_js_1 = __nccwpck_require__(6105); +var tracingPolicy_js_1 = __nccwpck_require__(9817); Object.defineProperty(exports, "tracingPolicy", ({ enumerable: true, get: function () { return tracingPolicy_js_1.tracingPolicy; } })); Object.defineProperty(exports, "tracingPolicyName", ({ enumerable: true, get: function () { return tracingPolicy_js_1.tracingPolicyName; } })); -var defaultRetryPolicy_js_1 = __nccwpck_require__(6451); +var defaultRetryPolicy_js_1 = __nccwpck_require__(9607); Object.defineProperty(exports, "defaultRetryPolicy", ({ enumerable: true, get: function () { return defaultRetryPolicy_js_1.defaultRetryPolicy; } })); -var userAgentPolicy_js_1 = __nccwpck_require__(8254); +var userAgentPolicy_js_1 = __nccwpck_require__(9413); Object.defineProperty(exports, "userAgentPolicy", ({ enumerable: true, get: function () { return userAgentPolicy_js_1.userAgentPolicy; } })); Object.defineProperty(exports, "userAgentPolicyName", ({ enumerable: true, get: function () { return userAgentPolicy_js_1.userAgentPolicyName; } })); -var tlsPolicy_js_1 = __nccwpck_require__(8422); +var tlsPolicy_js_1 = __nccwpck_require__(8012); Object.defineProperty(exports, "tlsPolicy", ({ enumerable: true, get: function () { return tlsPolicy_js_1.tlsPolicy; } })); Object.defineProperty(exports, "tlsPolicyName", ({ enumerable: true, get: function () { return tlsPolicy_js_1.tlsPolicyName; } })); -var formDataPolicy_js_1 = __nccwpck_require__(5204); +var formDataPolicy_js_1 = __nccwpck_require__(2256); Object.defineProperty(exports, "formDataPolicy", ({ enumerable: true, get: function () { return formDataPolicy_js_1.formDataPolicy; } })); Object.defineProperty(exports, "formDataPolicyName", ({ enumerable: true, get: function () { return formDataPolicy_js_1.formDataPolicyName; } })); -var bearerTokenAuthenticationPolicy_js_1 = __nccwpck_require__(8050); +var bearerTokenAuthenticationPolicy_js_1 = __nccwpck_require__(7693); Object.defineProperty(exports, "bearerTokenAuthenticationPolicy", ({ enumerable: true, get: function () { return bearerTokenAuthenticationPolicy_js_1.bearerTokenAuthenticationPolicy; } })); Object.defineProperty(exports, "bearerTokenAuthenticationPolicyName", ({ enumerable: true, get: function () { return bearerTokenAuthenticationPolicy_js_1.bearerTokenAuthenticationPolicyName; } })); -var ndJsonPolicy_js_1 = __nccwpck_require__(1970); +var ndJsonPolicy_js_1 = __nccwpck_require__(6957); Object.defineProperty(exports, "ndJsonPolicy", ({ enumerable: true, get: function () { return ndJsonPolicy_js_1.ndJsonPolicy; } })); Object.defineProperty(exports, "ndJsonPolicyName", ({ enumerable: true, get: function () { return ndJsonPolicy_js_1.ndJsonPolicyName; } })); -var auxiliaryAuthenticationHeaderPolicy_js_1 = __nccwpck_require__(5864); +var auxiliaryAuthenticationHeaderPolicy_js_1 = __nccwpck_require__(7565); Object.defineProperty(exports, "auxiliaryAuthenticationHeaderPolicy", ({ enumerable: true, get: function () { return auxiliaryAuthenticationHeaderPolicy_js_1.auxiliaryAuthenticationHeaderPolicy; } })); Object.defineProperty(exports, "auxiliaryAuthenticationHeaderPolicyName", ({ enumerable: true, get: function () { return auxiliaryAuthenticationHeaderPolicy_js_1.auxiliaryAuthenticationHeaderPolicyName; } })); -var file_js_1 = __nccwpck_require__(8990); +var file_js_1 = __nccwpck_require__(5328); Object.defineProperty(exports, "createFile", ({ enumerable: true, get: function () { return file_js_1.createFile; } })); Object.defineProperty(exports, "createFileFromStream", ({ enumerable: true, get: function () { return file_js_1.createFileFromStream; } })); //# sourceMappingURL=index.js.map /***/ }), -/***/ 5666: +/***/ 1817: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.logger = void 0; const logger_1 = __nccwpck_require__(2208); @@ -71592,40 +72615,46 @@ exports.logger = (0, logger_1.createClientLogger)("core-rest-pipeline"); /***/ }), -/***/ 4093: +/***/ 2441: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getBodyLength = getBodyLength; exports.createNodeHttpClient = createNodeHttpClient; -const tslib_1 = __nccwpck_require__(9236); +const tslib_1 = __nccwpck_require__(1772); const http = tslib_1.__importStar(__nccwpck_require__(8849)); const https = tslib_1.__importStar(__nccwpck_require__(2286)); const zlib = tslib_1.__importStar(__nccwpck_require__(5628)); const node_stream_1 = __nccwpck_require__(4492); const abort_controller_1 = __nccwpck_require__(5964); -const httpHeaders_js_1 = __nccwpck_require__(3488); -const restError_js_1 = __nccwpck_require__(6985); -const log_js_1 = __nccwpck_require__(5666); +const httpHeaders_js_1 = __nccwpck_require__(1780); +const restError_js_1 = __nccwpck_require__(690); +const log_js_1 = __nccwpck_require__(1817); const DEFAULT_TLS_SETTINGS = {}; function isReadableStream(body) { return body && typeof body.pipe === "function"; } function isStreamComplete(stream) { return new Promise((resolve) => { - stream.on("close", resolve); - stream.on("end", resolve); - stream.on("error", resolve); + const handler = () => { + resolve(); + stream.removeListener("close", handler); + stream.removeListener("end", handler); + stream.removeListener("error", handler); + }; + stream.on("close", handler); + stream.on("end", handler); + stream.on("error", handler); }); } function isArrayBuffer(body) { return body && typeof body.byteLength === "number"; } class ReportTransform extends node_stream_1.Transform { - // eslint-disable-next-line @typescript-eslint/ban-types + // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type _transform(chunk, _encoding, callback) { this.push(chunk); this.loadedBytes += chunk.length; @@ -71935,12 +72964,12 @@ function createNodeHttpClient() { /***/ }), -/***/ 4191: +/***/ 9122: /***/ ((__unused_webpack_module, exports) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createEmptyPipeline = createEmptyPipeline; const ValidPhaseNames = new Set(["Deserialize", "Serialize", "Retry", "Sign"]); @@ -72206,16 +73235,16 @@ function createEmptyPipeline() { /***/ }), -/***/ 3375: +/***/ 871: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createPipelineRequest = createPipelineRequest; -const httpHeaders_js_1 = __nccwpck_require__(3488); -const core_util_1 = __nccwpck_require__(8143); +const httpHeaders_js_1 = __nccwpck_require__(1780); +const core_util_1 = __nccwpck_require__(1910); class PipelineRequestImpl { constructor(options) { var _a, _b, _c, _d, _e, _f, _g; @@ -72251,17 +73280,17 @@ function createPipelineRequest(options) { /***/ }), -/***/ 5864: +/***/ 7565: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.auxiliaryAuthenticationHeaderPolicyName = void 0; exports.auxiliaryAuthenticationHeaderPolicy = auxiliaryAuthenticationHeaderPolicy; -const tokenCycler_js_1 = __nccwpck_require__(7902); -const log_js_1 = __nccwpck_require__(5666); +const tokenCycler_js_1 = __nccwpck_require__(5821); +const log_js_1 = __nccwpck_require__(1817); /** * The programmatic identifier of the auxiliaryAuthenticationHeaderPolicy. */ @@ -72324,17 +73353,17 @@ function auxiliaryAuthenticationHeaderPolicy(options) { /***/ }), -/***/ 8050: +/***/ 7693: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.bearerTokenAuthenticationPolicyName = void 0; exports.bearerTokenAuthenticationPolicy = bearerTokenAuthenticationPolicy; -const tokenCycler_js_1 = __nccwpck_require__(7902); -const log_js_1 = __nccwpck_require__(5666); +const tokenCycler_js_1 = __nccwpck_require__(5821); +const log_js_1 = __nccwpck_require__(1817); /** * The programmatic identifier of the bearerTokenAuthenticationPolicy. */ @@ -72442,12 +73471,12 @@ function bearerTokenAuthenticationPolicy(options) { /***/ }), -/***/ 9716: +/***/ 3007: /***/ ((__unused_webpack_module, exports) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.decompressResponsePolicyName = void 0; exports.decompressResponsePolicy = decompressResponsePolicy; @@ -72475,19 +73504,19 @@ function decompressResponsePolicy() { /***/ }), -/***/ 6451: +/***/ 9607: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.defaultRetryPolicyName = void 0; exports.defaultRetryPolicy = defaultRetryPolicy; -const exponentialRetryStrategy_js_1 = __nccwpck_require__(3901); -const throttlingRetryStrategy_js_1 = __nccwpck_require__(6922); -const retryPolicy_js_1 = __nccwpck_require__(3261); -const constants_js_1 = __nccwpck_require__(5631); +const exponentialRetryStrategy_js_1 = __nccwpck_require__(7345); +const throttlingRetryStrategy_js_1 = __nccwpck_require__(7885); +const retryPolicy_js_1 = __nccwpck_require__(2093); +const constants_js_1 = __nccwpck_require__(2757); /** * Name of the {@link defaultRetryPolicy} */ @@ -72511,18 +73540,18 @@ function defaultRetryPolicy(options = {}) { /***/ }), -/***/ 2233: +/***/ 5105: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.exponentialRetryPolicyName = void 0; exports.exponentialRetryPolicy = exponentialRetryPolicy; -const exponentialRetryStrategy_js_1 = __nccwpck_require__(3901); -const retryPolicy_js_1 = __nccwpck_require__(3261); -const constants_js_1 = __nccwpck_require__(5631); +const exponentialRetryStrategy_js_1 = __nccwpck_require__(7345); +const retryPolicy_js_1 = __nccwpck_require__(2093); +const constants_js_1 = __nccwpck_require__(2757); /** * The programmatic identifier of the exponentialRetryPolicy. */ @@ -72543,17 +73572,17 @@ function exponentialRetryPolicy(options = {}) { /***/ }), -/***/ 5204: +/***/ 2256: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.formDataPolicyName = void 0; exports.formDataPolicy = formDataPolicy; -const core_util_1 = __nccwpck_require__(8143); -const httpHeaders_js_1 = __nccwpck_require__(3488); +const core_util_1 = __nccwpck_require__(1910); +const httpHeaders_js_1 = __nccwpck_require__(1780); /** * The programmatic identifier of the formDataPolicy. */ @@ -72649,17 +73678,17 @@ async function prepareFormData(formData, request) { /***/ }), -/***/ 8383: +/***/ 4560: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.logPolicyName = void 0; exports.logPolicy = logPolicy; -const log_js_1 = __nccwpck_require__(5666); -const sanitizer_js_1 = __nccwpck_require__(8464); +const log_js_1 = __nccwpck_require__(1817); +const sanitizer_js_1 = __nccwpck_require__(1040); /** * The programmatic identifier of the logPolicy. */ @@ -72693,18 +73722,18 @@ function logPolicy(options = {}) { /***/ }), -/***/ 8807: +/***/ 2545: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.multipartPolicyName = void 0; exports.multipartPolicy = multipartPolicy; -const core_util_1 = __nccwpck_require__(8143); -const concat_js_1 = __nccwpck_require__(2694); -const typeGuards_js_1 = __nccwpck_require__(7734); +const core_util_1 = __nccwpck_require__(1910); +const concat_js_1 = __nccwpck_require__(5489); +const typeGuards_js_1 = __nccwpck_require__(1479); function generateBoundary() { return `----AzSDKFormBoundary${(0, core_util_1.randomUUID)()}`; } @@ -72814,12 +73843,12 @@ function multipartPolicy() { /***/ }), -/***/ 1970: +/***/ 6957: /***/ ((__unused_webpack_module, exports) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ndJsonPolicyName = void 0; exports.ndJsonPolicy = ndJsonPolicy; @@ -72849,12 +73878,12 @@ function ndJsonPolicy() { /***/ }), -/***/ 6360: +/***/ 7966: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.globalNoProxyList = exports.proxyPolicyName = void 0; exports.loadNoProxy = loadNoProxy; @@ -72862,7 +73891,7 @@ exports.getDefaultProxySettings = getDefaultProxySettings; exports.proxyPolicy = proxyPolicy; const https_proxy_agent_1 = __nccwpck_require__(2838); const http_proxy_agent_1 = __nccwpck_require__(6628); -const log_js_1 = __nccwpck_require__(5666); +const log_js_1 = __nccwpck_require__(1817); const HTTPS_PROXY = "HTTPS_PROXY"; const HTTP_PROXY = "HTTP_PROXY"; const ALL_PROXY = "ALL_PROXY"; @@ -72980,7 +74009,7 @@ function getUrlFromProxySettings(settings) { try { parsedProxyUrl = new URL(settings.host); } - catch (_error) { + catch (_a) { throw new Error(`Expecting a valid host string in proxy settings, but found "${settings.host}".`); } parsedProxyUrl.port = String(settings.port); @@ -73052,12 +74081,12 @@ function proxyPolicy(proxySettings, options) { /***/ }), -/***/ 2960: +/***/ 4250: /***/ ((__unused_webpack_module, exports) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.redirectPolicyName = void 0; exports.redirectPolicy = redirectPolicy; @@ -73114,18 +74143,18 @@ async function handleRedirect(next, response, maxRetries, currentRetries = 0) { /***/ }), -/***/ 3261: +/***/ 2093: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.retryPolicy = retryPolicy; -const helpers_js_1 = __nccwpck_require__(7714); +const helpers_js_1 = __nccwpck_require__(7101); const logger_1 = __nccwpck_require__(2208); const abort_controller_1 = __nccwpck_require__(5964); -const constants_js_1 = __nccwpck_require__(5631); +const constants_js_1 = __nccwpck_require__(2757); const retryPolicyLogger = (0, logger_1.createClientLogger)("core-rest-pipeline retryPolicy"); /** * The programmatic identifier of the retryPolicy. @@ -73229,12 +74258,12 @@ function retryPolicy(strategies, options = { maxRetries: constants_js_1.DEFAULT_ /***/ }), -/***/ 1334: +/***/ 5283: /***/ ((__unused_webpack_module, exports) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.setClientRequestIdPolicyName = void 0; exports.setClientRequestIdPolicy = setClientRequestIdPolicy; @@ -73263,18 +74292,18 @@ function setClientRequestIdPolicy(requestIdHeaderName = "x-ms-client-request-id" /***/ }), -/***/ 8009: +/***/ 6626: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.systemErrorRetryPolicyName = void 0; exports.systemErrorRetryPolicy = systemErrorRetryPolicy; -const exponentialRetryStrategy_js_1 = __nccwpck_require__(3901); -const retryPolicy_js_1 = __nccwpck_require__(3261); -const constants_js_1 = __nccwpck_require__(5631); +const exponentialRetryStrategy_js_1 = __nccwpck_require__(7345); +const retryPolicy_js_1 = __nccwpck_require__(2093); +const constants_js_1 = __nccwpck_require__(2757); /** * Name of the {@link systemErrorRetryPolicy} */ @@ -73300,18 +74329,18 @@ function systemErrorRetryPolicy(options = {}) { /***/ }), -/***/ 3297: +/***/ 7823: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.throttlingRetryPolicyName = void 0; exports.throttlingRetryPolicy = throttlingRetryPolicy; -const throttlingRetryStrategy_js_1 = __nccwpck_require__(6922); -const retryPolicy_js_1 = __nccwpck_require__(3261); -const constants_js_1 = __nccwpck_require__(5631); +const throttlingRetryStrategy_js_1 = __nccwpck_require__(7885); +const retryPolicy_js_1 = __nccwpck_require__(2093); +const constants_js_1 = __nccwpck_require__(2757); /** * Name of the {@link throttlingRetryPolicy} */ @@ -73339,12 +74368,12 @@ function throttlingRetryPolicy(options = {}) { /***/ }), -/***/ 8422: +/***/ 8012: /***/ ((__unused_webpack_module, exports) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.tlsPolicyName = void 0; exports.tlsPolicy = tlsPolicy; @@ -73371,22 +74400,22 @@ function tlsPolicy(tlsSettings) { /***/ }), -/***/ 6105: +/***/ 9817: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.tracingPolicyName = void 0; exports.tracingPolicy = tracingPolicy; -const core_tracing_1 = __nccwpck_require__(7423); -const constants_js_1 = __nccwpck_require__(5631); -const userAgent_js_1 = __nccwpck_require__(8478); -const log_js_1 = __nccwpck_require__(5666); -const core_util_1 = __nccwpck_require__(8143); -const restError_js_1 = __nccwpck_require__(6985); -const sanitizer_js_1 = __nccwpck_require__(8464); +const core_tracing_1 = __nccwpck_require__(3810); +const constants_js_1 = __nccwpck_require__(2757); +const userAgent_js_1 = __nccwpck_require__(8683); +const log_js_1 = __nccwpck_require__(1817); +const core_util_1 = __nccwpck_require__(1910); +const restError_js_1 = __nccwpck_require__(690); +const sanitizer_js_1 = __nccwpck_require__(1040); /** * The programmatic identifier of the tracingPolicy. */ @@ -73406,8 +74435,8 @@ function tracingPolicy(options = {}) { return { name: exports.tracingPolicyName, async sendRequest(request, next) { - var _a, _b; - if (!tracingClient || !((_a = request.tracingOptions) === null || _a === void 0 ? void 0 : _a.tracingContext)) { + var _a; + if (!tracingClient) { return next(request); } const userAgent = await userAgentPromise; @@ -73420,7 +74449,7 @@ function tracingPolicy(options = {}) { if (userAgent) { spanAttributes["http.user_agent"] = userAgent; } - const { span, tracingContext } = (_b = tryCreateSpan(tracingClient, request, spanAttributes)) !== null && _b !== void 0 ? _b : {}; + const { span, tracingContext } = (_a = tryCreateSpan(tracingClient, request, spanAttributes)) !== null && _a !== void 0 ? _a : {}; if (!span || !tracingContext) { return next(request); } @@ -73508,16 +74537,16 @@ function tryProcessResponse(span, response) { /***/ }), -/***/ 8254: +/***/ 9413: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.userAgentPolicyName = void 0; exports.userAgentPolicy = userAgentPolicy; -const userAgent_js_1 = __nccwpck_require__(8478); +const userAgent_js_1 = __nccwpck_require__(8683); const UserAgentHeaderName = (0, userAgent_js_1.getUserAgentHeaderName)(); /** * The programmatic identifier of the userAgentPolicy. @@ -73544,18 +74573,18 @@ function userAgentPolicy(options = {}) { /***/ }), -/***/ 6985: +/***/ 690: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.RestError = void 0; exports.isRestError = isRestError; -const core_util_1 = __nccwpck_require__(8143); -const inspect_js_1 = __nccwpck_require__(1838); -const sanitizer_js_1 = __nccwpck_require__(8464); +const core_util_1 = __nccwpck_require__(1910); +const inspect_js_1 = __nccwpck_require__(1589); +const sanitizer_js_1 = __nccwpck_require__(1040); const errorSanitizer = new sanitizer_js_1.Sanitizer(); /** * A custom error type for failed pipeline requests. @@ -73609,18 +74638,18 @@ function isRestError(e) { /***/ }), -/***/ 3901: +/***/ 7345: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.exponentialRetryStrategy = exponentialRetryStrategy; exports.isExponentialRetryResponse = isExponentialRetryResponse; exports.isSystemError = isSystemError; -const core_util_1 = __nccwpck_require__(8143); -const throttlingRetryStrategy_js_1 = __nccwpck_require__(6922); +const core_util_1 = __nccwpck_require__(1910); +const throttlingRetryStrategy_js_1 = __nccwpck_require__(7885); // intervals are in milliseconds const DEFAULT_CLIENT_RETRY_INTERVAL = 1000; const DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1000 * 64; @@ -73690,16 +74719,16 @@ function isSystemError(err) { /***/ }), -/***/ 6922: +/***/ 7885: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isThrottlingRetryResponse = isThrottlingRetryResponse; exports.throttlingRetryStrategy = throttlingRetryStrategy; -const helpers_js_1 = __nccwpck_require__(7714); +const helpers_js_1 = __nccwpck_require__(7101); /** * The header that comes back from Azure services representing * the amount of time (minimum) to wait to retry (in seconds or timestamp after which we can retry). @@ -73745,7 +74774,7 @@ function getRetryAfterInMs(response) { // negative diff would mean a date in the past, so retry asap with 0 milliseconds return Number.isFinite(diff) ? Math.max(0, diff) : undefined; } - catch (e) { + catch (_a) { return undefined; } } @@ -73774,18 +74803,18 @@ function throttlingRetryStrategy() { /***/ }), -/***/ 2694: +/***/ 5489: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.concat = concat; -const tslib_1 = __nccwpck_require__(9236); +const tslib_1 = __nccwpck_require__(1772); const node_stream_1 = __nccwpck_require__(4492); -const typeGuards_js_1 = __nccwpck_require__(7734); -const file_js_1 = __nccwpck_require__(8990); +const typeGuards_js_1 = __nccwpck_require__(1479); +const file_js_1 = __nccwpck_require__(5328); function streamAsyncIterator() { return tslib_1.__asyncGenerator(this, arguments, function* streamAsyncIterator_1() { const reader = this.getReader(); @@ -73871,18 +74900,18 @@ async function concat(sources) { /***/ }), -/***/ 8990: +/***/ 5328: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getRawContent = getRawContent; exports.createFileFromStream = createFileFromStream; exports.createFile = createFile; -const core_util_1 = __nccwpck_require__(8143); -const typeGuards_js_1 = __nccwpck_require__(7734); +const core_util_1 = __nccwpck_require__(1910); +const typeGuards_js_1 = __nccwpck_require__(1479); const unimplementedMethods = { arrayBuffer: () => { throw new Error("Not implemented"); @@ -73978,12 +75007,12 @@ function createFile(content, name, options = {}) { /***/ }), -/***/ 7714: +/***/ 7101: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.delay = delay; exports.parseHeaderValueAsNumber = parseHeaderValueAsNumber; @@ -74046,12 +75075,12 @@ function parseHeaderValueAsNumber(response, headerName) { /***/ }), -/***/ 1838: +/***/ 1589: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.custom = void 0; const node_util_1 = __nccwpck_require__(7261); @@ -74060,15 +75089,15 @@ exports.custom = node_util_1.inspect.custom; /***/ }), -/***/ 8464: +/***/ 1040: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Sanitizer = void 0; -const core_util_1 = __nccwpck_require__(8143); +const core_util_1 = __nccwpck_require__(1910); const RedactedString = "REDACTED"; // Make sure this list is up-to-date with the one under core/logger/Readme#Keyconcepts const defaultAllowedHeaderNames = [ @@ -74209,16 +75238,16 @@ exports.Sanitizer = Sanitizer; /***/ }), -/***/ 7902: +/***/ 5821: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DEFAULT_CYCLER_OPTIONS = void 0; exports.createTokenCycler = createTokenCycler; -const helpers_js_1 = __nccwpck_require__(7714); +const helpers_js_1 = __nccwpck_require__(7101); // Default options for the cycler if none are provided exports.DEFAULT_CYCLER_OPTIONS = { forcedRefreshWindowInMs: 1000, // Force waiting for a refresh 1s before the token expires @@ -74299,8 +75328,13 @@ function createTokenCycler(credential, tokenCyclerOptions) { */ get shouldRefresh() { var _a; - return (!cycler.isRefreshing && - ((_a = token === null || token === void 0 ? void 0 : token.expiresOnTimestamp) !== null && _a !== void 0 ? _a : 0) - options.refreshWindowInMs < Date.now()); + if (cycler.isRefreshing) { + return false; + } + if ((token === null || token === void 0 ? void 0 : token.refreshAfterTimestamp) && token.refreshAfterTimestamp < Date.now()) { + return true; + } + return ((_a = token === null || token === void 0 ? void 0 : token.expiresOnTimestamp) !== null && _a !== void 0 ? _a : 0) - options.refreshWindowInMs < Date.now(); }, /** * Produces true if the cycler MUST refresh (null or nearly-expired @@ -74376,12 +75410,12 @@ function createTokenCycler(credential, tokenCyclerOptions) { /***/ }), -/***/ 7734: +/***/ 1479: /***/ ((__unused_webpack_module, exports) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isNodeReadableStream = isNodeReadableStream; exports.isWebReadableStream = isWebReadableStream; @@ -74405,17 +75439,17 @@ function isBlob(x) { /***/ }), -/***/ 8478: +/***/ 8683: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getUserAgentHeaderName = getUserAgentHeaderName; exports.getUserAgentValue = getUserAgentValue; -const userAgentPlatform_js_1 = __nccwpck_require__(5886); -const constants_js_1 = __nccwpck_require__(5631); +const userAgentPlatform_js_1 = __nccwpck_require__(3859); +const constants_js_1 = __nccwpck_require__(2757); function getUserAgentString(telemetryInfo) { const parts = []; for (const [key, value] of telemetryInfo) { @@ -74445,16 +75479,16 @@ async function getUserAgentValue(prefix) { /***/ }), -/***/ 5886: +/***/ 3859: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getHeaderName = getHeaderName; exports.setPlatformSpecificData = setPlatformSpecificData; -const tslib_1 = __nccwpck_require__(9236); +const tslib_1 = __nccwpck_require__(1772); const os = tslib_1.__importStar(__nccwpck_require__(612)); const process = tslib_1.__importStar(__nccwpck_require__(7742)); /** @@ -74485,32 +75519,35 @@ async function setPlatformSpecificData(map) { /***/ }), -/***/ 7423: +/***/ 3810: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createTracingClient = exports.useInstrumenter = void 0; -var instrumenter_js_1 = __nccwpck_require__(4746); +var instrumenter_js_1 = __nccwpck_require__(6912); Object.defineProperty(exports, "useInstrumenter", ({ enumerable: true, get: function () { return instrumenter_js_1.useInstrumenter; } })); -var tracingClient_js_1 = __nccwpck_require__(1291); +var tracingClient_js_1 = __nccwpck_require__(5450); Object.defineProperty(exports, "createTracingClient", ({ enumerable: true, get: function () { return tracingClient_js_1.createTracingClient; } })); //# sourceMappingURL=index.js.map /***/ }), -/***/ 4746: +/***/ 6912: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getInstrumenter = exports.useInstrumenter = exports.createDefaultInstrumenter = exports.createDefaultTracingSpan = void 0; -const tracingContext_js_1 = __nccwpck_require__(2402); -const state_js_1 = __nccwpck_require__(3133); +exports.createDefaultTracingSpan = createDefaultTracingSpan; +exports.createDefaultInstrumenter = createDefaultInstrumenter; +exports.useInstrumenter = useInstrumenter; +exports.getInstrumenter = getInstrumenter; +const tracingContext_js_1 = __nccwpck_require__(7419); +const state_js_1 = __nccwpck_require__(9926); function createDefaultTracingSpan() { return { end: () => { @@ -74526,9 +75563,11 @@ function createDefaultTracingSpan() { setStatus: () => { // noop }, + addEvent: () => { + // noop + }, }; } -exports.createDefaultTracingSpan = createDefaultTracingSpan; function createDefaultInstrumenter() { return { createRequestHeaders: () => { @@ -74548,7 +75587,6 @@ function createDefaultInstrumenter() { }, }; } -exports.createDefaultInstrumenter = createDefaultInstrumenter; /** * Extends the Azure SDK with support for a given instrumenter implementation. * @@ -74557,7 +75595,6 @@ exports.createDefaultInstrumenter = createDefaultInstrumenter; function useInstrumenter(instrumenter) { state_js_1.state.instrumenterImplementation = instrumenter; } -exports.useInstrumenter = useInstrumenter; /** * Gets the currently set instrumenter, a No-Op instrumenter by default. * @@ -74569,17 +75606,16 @@ function getInstrumenter() { } return state_js_1.state.instrumenterImplementation; } -exports.getInstrumenter = getInstrumenter; //# sourceMappingURL=instrumenter.js.map /***/ }), -/***/ 3133: +/***/ 9926: /***/ ((__unused_webpack_module, exports) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.state = void 0; /** @@ -74594,16 +75630,16 @@ exports.state = { /***/ }), -/***/ 1291: +/***/ 5450: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createTracingClient = void 0; -const instrumenter_js_1 = __nccwpck_require__(4746); -const tracingContext_js_1 = __nccwpck_require__(2402); +exports.createTracingClient = createTracingClient; +const instrumenter_js_1 = __nccwpck_require__(6912); +const tracingContext_js_1 = __nccwpck_require__(7419); /** * Creates a new tracing client. * @@ -74673,19 +75709,19 @@ function createTracingClient(options) { createRequestHeaders, }; } -exports.createTracingClient = createTracingClient; //# sourceMappingURL=tracingClient.js.map /***/ }), -/***/ 2402: +/***/ 7419: /***/ ((__unused_webpack_module, exports) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.TracingContextImpl = exports.createTracingContext = exports.knownContextKeys = void 0; +exports.TracingContextImpl = exports.knownContextKeys = void 0; +exports.createTracingContext = createTracingContext; /** @internal */ exports.knownContextKeys = { span: Symbol.for("@azure/core-tracing span"), @@ -74708,7 +75744,6 @@ function createTracingContext(options = {}) { } return context; } -exports.createTracingContext = createTracingContext; /** @internal */ class TracingContextImpl { constructor(initialContext) { @@ -74736,12 +75771,12 @@ exports.TracingContextImpl = TracingContextImpl; /***/ }), -/***/ 3736: +/***/ 2521: /***/ ((__unused_webpack_module, exports) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.cancelablePromiseRace = cancelablePromiseRace; /** @@ -74766,12 +75801,12 @@ async function cancelablePromiseRace(abortablePromiseBuilders, options) { /***/ }), -/***/ 3095: +/***/ 8978: /***/ ((__unused_webpack_module, exports) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.uint8ArrayToString = uint8ArrayToString; exports.stringToUint8Array = stringToUint8Array; @@ -74797,12 +75832,12 @@ function stringToUint8Array(value, format) { /***/ }), -/***/ 5083: +/***/ 2185: /***/ ((__unused_webpack_module, exports) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. var _a, _b, _c, _d; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isReactNative = exports.isNodeRuntime = exports.isNode = exports.isNodeLike = exports.isBun = exports.isDeno = exports.isWebWorker = exports.isBrowser = void 0; @@ -74853,12 +75888,12 @@ exports.isReactNative = typeof navigator !== "undefined" && (navigator === null /***/ }), -/***/ 5361: +/***/ 533: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createAbortablePromise = createAbortablePromise; const abort_controller_1 = __nccwpck_require__(5964); @@ -74904,15 +75939,17 @@ function createAbortablePromise(buildPromise, options) { /***/ }), -/***/ 7030: +/***/ 3986: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.delay = delay; -const createAbortablePromise_js_1 = __nccwpck_require__(5361); +exports.calculateRetryDelay = calculateRetryDelay; +const createAbortablePromise_js_1 = __nccwpck_require__(533); +const random_js_1 = __nccwpck_require__(2234); const StandardAbortMessage = "The delay was aborted."; /** * A wrapper for setTimeout that resolves a promise after timeInMs milliseconds. @@ -74931,20 +75968,36 @@ function delay(timeInMs, options) { abortErrorMsg: abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : StandardAbortMessage, }); } +/** + * Calculates the delay interval for retry attempts using exponential delay with jitter. + * @param retryAttempt - The current retry attempt number. + * @param config - The exponential retry configuration. + * @returns An object containing the calculated retry delay. + */ +function calculateRetryDelay(retryAttempt, config) { + // Exponentially increase the delay each time + const exponentialDelay = config.retryDelayInMs * Math.pow(2, retryAttempt); + // Don't let the delay exceed the maximum + const clampedDelay = Math.min(config.maxRetryDelayInMs, exponentialDelay); + // Allow the final value to have some "jitter" (within 50% of the delay size) so + // that retries across multiple clients don't occur simultaneously. + const retryAfterInMs = clampedDelay / 2 + (0, random_js_1.getRandomIntegerInclusive)(0, clampedDelay / 2); + return { retryAfterInMs }; +} //# sourceMappingURL=delay.js.map /***/ }), -/***/ 2280: +/***/ 8338: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isError = isError; exports.getErrorMessage = getErrorMessage; -const object_js_1 = __nccwpck_require__(7844); +const object_js_1 = __nccwpck_require__(8444); /** * Typeguard for an error object shape (has name and message) * @param e - Something caught by a catch clause. @@ -74987,37 +76040,38 @@ function getErrorMessage(e) { /***/ }), -/***/ 8143: +/***/ 1910: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.stringToUint8Array = exports.uint8ArrayToString = exports.isWebWorker = exports.isReactNative = exports.isDeno = exports.isNodeRuntime = exports.isNodeLike = exports.isNode = exports.isBun = exports.isBrowser = exports.randomUUID = exports.objectHasProperty = exports.isObjectWithProperties = exports.isDefined = exports.computeSha256Hmac = exports.computeSha256Hash = exports.getErrorMessage = exports.isError = exports.isObject = exports.getRandomIntegerInclusive = exports.createAbortablePromise = exports.cancelablePromiseRace = exports.delay = void 0; -var delay_js_1 = __nccwpck_require__(7030); +exports.stringToUint8Array = exports.uint8ArrayToString = exports.isWebWorker = exports.isReactNative = exports.isDeno = exports.isNodeRuntime = exports.isNodeLike = exports.isNode = exports.isBun = exports.isBrowser = exports.randomUUID = exports.objectHasProperty = exports.isObjectWithProperties = exports.isDefined = exports.computeSha256Hmac = exports.computeSha256Hash = exports.getErrorMessage = exports.isError = exports.isObject = exports.getRandomIntegerInclusive = exports.createAbortablePromise = exports.cancelablePromiseRace = exports.calculateRetryDelay = exports.delay = void 0; +var delay_js_1 = __nccwpck_require__(3986); Object.defineProperty(exports, "delay", ({ enumerable: true, get: function () { return delay_js_1.delay; } })); -var aborterUtils_js_1 = __nccwpck_require__(3736); +Object.defineProperty(exports, "calculateRetryDelay", ({ enumerable: true, get: function () { return delay_js_1.calculateRetryDelay; } })); +var aborterUtils_js_1 = __nccwpck_require__(2521); Object.defineProperty(exports, "cancelablePromiseRace", ({ enumerable: true, get: function () { return aborterUtils_js_1.cancelablePromiseRace; } })); -var createAbortablePromise_js_1 = __nccwpck_require__(5361); +var createAbortablePromise_js_1 = __nccwpck_require__(533); Object.defineProperty(exports, "createAbortablePromise", ({ enumerable: true, get: function () { return createAbortablePromise_js_1.createAbortablePromise; } })); -var random_js_1 = __nccwpck_require__(9566); +var random_js_1 = __nccwpck_require__(2234); Object.defineProperty(exports, "getRandomIntegerInclusive", ({ enumerable: true, get: function () { return random_js_1.getRandomIntegerInclusive; } })); -var object_js_1 = __nccwpck_require__(7844); +var object_js_1 = __nccwpck_require__(8444); Object.defineProperty(exports, "isObject", ({ enumerable: true, get: function () { return object_js_1.isObject; } })); -var error_js_1 = __nccwpck_require__(2280); +var error_js_1 = __nccwpck_require__(8338); Object.defineProperty(exports, "isError", ({ enumerable: true, get: function () { return error_js_1.isError; } })); Object.defineProperty(exports, "getErrorMessage", ({ enumerable: true, get: function () { return error_js_1.getErrorMessage; } })); -var sha256_js_1 = __nccwpck_require__(7931); +var sha256_js_1 = __nccwpck_require__(5775); Object.defineProperty(exports, "computeSha256Hash", ({ enumerable: true, get: function () { return sha256_js_1.computeSha256Hash; } })); Object.defineProperty(exports, "computeSha256Hmac", ({ enumerable: true, get: function () { return sha256_js_1.computeSha256Hmac; } })); -var typeGuards_js_1 = __nccwpck_require__(1467); +var typeGuards_js_1 = __nccwpck_require__(1465); Object.defineProperty(exports, "isDefined", ({ enumerable: true, get: function () { return typeGuards_js_1.isDefined; } })); Object.defineProperty(exports, "isObjectWithProperties", ({ enumerable: true, get: function () { return typeGuards_js_1.isObjectWithProperties; } })); Object.defineProperty(exports, "objectHasProperty", ({ enumerable: true, get: function () { return typeGuards_js_1.objectHasProperty; } })); -var uuidUtils_js_1 = __nccwpck_require__(9057); +var uuidUtils_js_1 = __nccwpck_require__(2809); Object.defineProperty(exports, "randomUUID", ({ enumerable: true, get: function () { return uuidUtils_js_1.randomUUID; } })); -var checkEnvironment_js_1 = __nccwpck_require__(5083); +var checkEnvironment_js_1 = __nccwpck_require__(2185); Object.defineProperty(exports, "isBrowser", ({ enumerable: true, get: function () { return checkEnvironment_js_1.isBrowser; } })); Object.defineProperty(exports, "isBun", ({ enumerable: true, get: function () { return checkEnvironment_js_1.isBun; } })); Object.defineProperty(exports, "isNode", ({ enumerable: true, get: function () { return checkEnvironment_js_1.isNode; } })); @@ -75026,19 +76080,19 @@ Object.defineProperty(exports, "isNodeRuntime", ({ enumerable: true, get: functi Object.defineProperty(exports, "isDeno", ({ enumerable: true, get: function () { return checkEnvironment_js_1.isDeno; } })); Object.defineProperty(exports, "isReactNative", ({ enumerable: true, get: function () { return checkEnvironment_js_1.isReactNative; } })); Object.defineProperty(exports, "isWebWorker", ({ enumerable: true, get: function () { return checkEnvironment_js_1.isWebWorker; } })); -var bytesEncoding_js_1 = __nccwpck_require__(3095); +var bytesEncoding_js_1 = __nccwpck_require__(8978); Object.defineProperty(exports, "uint8ArrayToString", ({ enumerable: true, get: function () { return bytesEncoding_js_1.uint8ArrayToString; } })); Object.defineProperty(exports, "stringToUint8Array", ({ enumerable: true, get: function () { return bytesEncoding_js_1.stringToUint8Array; } })); //# sourceMappingURL=index.js.map /***/ }), -/***/ 7844: +/***/ 8444: /***/ ((__unused_webpack_module, exports) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isObject = isObject; /** @@ -75056,12 +76110,12 @@ function isObject(input) { /***/ }), -/***/ 9566: +/***/ 2234: /***/ ((__unused_webpack_module, exports) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getRandomIntegerInclusive = getRandomIntegerInclusive; /** @@ -75086,12 +76140,12 @@ function getRandomIntegerInclusive(min, max) { /***/ }), -/***/ 7931: +/***/ 5775: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.computeSha256Hmac = computeSha256Hmac; exports.computeSha256Hash = computeSha256Hash; @@ -75118,12 +76172,12 @@ async function computeSha256Hash(content, encoding) { /***/ }), -/***/ 1467: +/***/ 1465: /***/ ((__unused_webpack_module, exports) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isDefined = isDefined; exports.isObjectWithProperties = isObjectWithProperties; @@ -75163,12 +76217,12 @@ function objectHasProperty(thing, property) { /***/ }), -/***/ 9057: +/***/ 2809: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. var _a; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.randomUUID = randomUUID; @@ -75189,30 +76243,30 @@ function randomUUID() { /***/ }), -/***/ 5182: +/***/ 9542: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.XML_CHARKEY = exports.XML_ATTRKEY = exports.parseXML = exports.stringifyXML = void 0; -var xml_js_1 = __nccwpck_require__(5795); +var xml_js_1 = __nccwpck_require__(9805); Object.defineProperty(exports, "stringifyXML", ({ enumerable: true, get: function () { return xml_js_1.stringifyXML; } })); Object.defineProperty(exports, "parseXML", ({ enumerable: true, get: function () { return xml_js_1.parseXML; } })); -var xml_common_js_1 = __nccwpck_require__(8917); +var xml_common_js_1 = __nccwpck_require__(9161); Object.defineProperty(exports, "XML_ATTRKEY", ({ enumerable: true, get: function () { return xml_common_js_1.XML_ATTRKEY; } })); Object.defineProperty(exports, "XML_CHARKEY", ({ enumerable: true, get: function () { return xml_common_js_1.XML_CHARKEY; } })); //# sourceMappingURL=index.js.map /***/ }), -/***/ 8917: +/***/ 9161: /***/ ((__unused_webpack_module, exports) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.XML_CHARKEY = exports.XML_ATTRKEY = void 0; /** @@ -75227,17 +76281,17 @@ exports.XML_CHARKEY = "_"; /***/ }), -/***/ 5795: +/***/ 9805: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. +// Licensed under the MIT License. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.stringifyXML = stringifyXML; exports.parseXML = parseXML; const fast_xml_parser_1 = __nccwpck_require__(5542); -const xml_common_js_1 = __nccwpck_require__(8917); +const xml_common_js_1 = __nccwpck_require__(9161); function getCommonOptions(options) { var _a; return { @@ -75412,7 +76466,7 @@ exports.AzureLogger = void 0; exports.setLogLevel = setLogLevel; exports.getLogLevel = getLogLevel; exports.createClientLogger = createClientLogger; -const tslib_1 = __nccwpck_require__(9236); +const tslib_1 = __nccwpck_require__(1772); const debug_js_1 = tslib_1.__importDefault(__nccwpck_require__(8630)); const registeredLoggers = new Set(); const logLevelFromEnv = (typeof process !== "undefined" && process.env && process.env.AZURE_LOG_LEVEL) || undefined; @@ -75520,7 +76574,7 @@ function isAzureLogLevel(logLevel) { // Licensed under the MIT license. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.log = log; -const tslib_1 = __nccwpck_require__(9236); +const tslib_1 = __nccwpck_require__(1772); const node_os_1 = __nccwpck_require__(612); const node_util_1 = tslib_1.__importDefault(__nccwpck_require__(7261)); const process = tslib_1.__importStar(__nccwpck_require__(7742)); @@ -76292,6616 +77346,11380 @@ function Multipart (boy, cfg) { 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) - } + 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.listenerCount('file') === 0) { + 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 + + +/***/ }), + +/***/ 6173: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const Decoder = __nccwpck_require__(9687) +const decodeText = __nccwpck_require__(884) +const getLimit = __nccwpck_require__(2160) + +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 + + +/***/ }), + +/***/ 9687: +/***/ ((module) => { + + + +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 - // 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 - } - } - } - } +/***/ 6504: +/***/ ((module) => { - 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' } +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) +} - 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 +/***/ 884: +/***/ (function(module) { - if (boy.listenerCount('file') === 0) { - 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 } +// Node has always utf-8 +const utf8Decoder = new TextDecoder('utf-8') +const textDecoders = new Map([ + ['utf-8', utf8Decoder], + ['utf8', utf8Decoder] +]) - file.bytesRead = nsize +function getDecoder (charset) { + let lc + while (true) { + switch (charset) { + case 'utf-8': + case 'utf8': + return decoders.utf8 + case 'latin1': + case 'ascii': // TODO: Make these a separate, strict decoder? + case 'us-ascii': + case 'iso-8859-1': + case 'iso8859-1': + case 'iso88591': + case 'iso_8859-1': + case 'windows-1252': + case 'iso_8859-1:1987': + case 'cp1252': + case 'x-cp1252': + return decoders.latin1 + case 'utf16le': + case 'utf-16le': + case 'ucs2': + case 'ucs-2': + return decoders.utf16le + case 'base64': + return decoders.base64 + default: + if (lc === undefined) { + lc = true + charset = charset.toLowerCase() + continue } + return decoders.other.bind(charset) + } + } +} - 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) - } +const decoders = { + utf8: (data, sourceEncoding) => { + if (data.length === 0) { + return '' + } + if (typeof data === 'string') { + data = Buffer.from(data, sourceEncoding) + } + return data.utf8Slice(0, data.length) + }, - ++nfields - ++nends - let buffer = '' - let truncated = false - curField = part + latin1: (data, sourceEncoding) => { + if (data.length === 0) { + return '' + } + if (typeof data === 'string') { + return data + } + return data.latin1Slice(0, data.length) + }, - 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') } - } + utf16le: (data, sourceEncoding) => { + if (data.length === 0) { + return '' + } + if (typeof data === 'string') { + data = Buffer.from(data, sourceEncoding) + } + return data.ucs2Slice(0, data.length) + }, - onEnd = function () { - curField = undefined - if (buffer.length) { buffer = decodeText(buffer, 'binary', charset) } - boy.emit('field', fieldname, buffer, false, truncated, encoding, contype) - --nends - checkFinished() - } - } + base64: (data, sourceEncoding) => { + if (data.length === 0) { + return '' + } + if (typeof data === 'string') { + data = Buffer.from(data, sourceEncoding) + } + return data.base64Slice(0, data.length) + }, - /* 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 + other: (data, sourceEncoding) => { + if (data.length === 0) { + return '' + } + if (typeof data === 'string') { + data = Buffer.from(data, sourceEncoding) + } - 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() - }) + if (textDecoders.has(this.toString())) { + try { + return textDecoders.get(this).decode(data) + } catch {} + } + return typeof data === 'string' + ? data + : data.toString() + } } -Multipart.prototype.write = function (chunk, cb) { - const r = this.parser.write(chunk) - if (r && !this._pause) { - cb() - } else { - this._needDrain = !r - this._cb = cb +function decodeText (text, sourceEncoding, destEncoding) { + if (text) { + return getDecoder(destEncoding)(text, sourceEncoding) } + return text } -Multipart.prototype.end = function () { - const self = this +module.exports = decodeText - 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) +/***/ 2160: +/***/ ((module) => { - this.bytesRead = 0 - this.truncated = false -} -inherits(FileStream, Readable) +module.exports = function getLimit (limits, name, defaultLimit) { + if ( + !limits || + limits[name] === undefined || + limits[name] === null + ) { return defaultLimit } -FileStream.prototype._read = function (n) {} + if ( + typeof limits[name] !== 'number' || + isNaN(limits[name]) + ) { throw new TypeError('Limit ' + name + ' is not a valid number') } -module.exports = Multipart + return limits[name] +} /***/ }), -/***/ 6173: +/***/ 3576: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/* eslint-disable object-property-newline */ -const Decoder = __nccwpck_require__(9687) const decodeText = __nccwpck_require__(884) -const getLimit = __nccwpck_require__(2160) -const RE_CHARSET = /^charset$/i +const RE_ENCODED = /%[a-fA-F0-9][a-fA-F0-9]/g -UrlEncoded.detect = /^application\/x-www-form-urlencoded/i -function UrlEncoded (boy, cfg) { - const limits = cfg.limits - const parsedConType = cfg.parsedConType - this.boy = boy +const EncodedLookup = { + '%00': '\x00', '%01': '\x01', '%02': '\x02', '%03': '\x03', '%04': '\x04', + '%05': '\x05', '%06': '\x06', '%07': '\x07', '%08': '\x08', '%09': '\x09', + '%0a': '\x0a', '%0A': '\x0a', '%0b': '\x0b', '%0B': '\x0b', '%0c': '\x0c', + '%0C': '\x0c', '%0d': '\x0d', '%0D': '\x0d', '%0e': '\x0e', '%0E': '\x0e', + '%0f': '\x0f', '%0F': '\x0f', '%10': '\x10', '%11': '\x11', '%12': '\x12', + '%13': '\x13', '%14': '\x14', '%15': '\x15', '%16': '\x16', '%17': '\x17', + '%18': '\x18', '%19': '\x19', '%1a': '\x1a', '%1A': '\x1a', '%1b': '\x1b', + '%1B': '\x1b', '%1c': '\x1c', '%1C': '\x1c', '%1d': '\x1d', '%1D': '\x1d', + '%1e': '\x1e', '%1E': '\x1e', '%1f': '\x1f', '%1F': '\x1f', '%20': '\x20', + '%21': '\x21', '%22': '\x22', '%23': '\x23', '%24': '\x24', '%25': '\x25', + '%26': '\x26', '%27': '\x27', '%28': '\x28', '%29': '\x29', '%2a': '\x2a', + '%2A': '\x2a', '%2b': '\x2b', '%2B': '\x2b', '%2c': '\x2c', '%2C': '\x2c', + '%2d': '\x2d', '%2D': '\x2d', '%2e': '\x2e', '%2E': '\x2e', '%2f': '\x2f', + '%2F': '\x2f', '%30': '\x30', '%31': '\x31', '%32': '\x32', '%33': '\x33', + '%34': '\x34', '%35': '\x35', '%36': '\x36', '%37': '\x37', '%38': '\x38', + '%39': '\x39', '%3a': '\x3a', '%3A': '\x3a', '%3b': '\x3b', '%3B': '\x3b', + '%3c': '\x3c', '%3C': '\x3c', '%3d': '\x3d', '%3D': '\x3d', '%3e': '\x3e', + '%3E': '\x3e', '%3f': '\x3f', '%3F': '\x3f', '%40': '\x40', '%41': '\x41', + '%42': '\x42', '%43': '\x43', '%44': '\x44', '%45': '\x45', '%46': '\x46', + '%47': '\x47', '%48': '\x48', '%49': '\x49', '%4a': '\x4a', '%4A': '\x4a', + '%4b': '\x4b', '%4B': '\x4b', '%4c': '\x4c', '%4C': '\x4c', '%4d': '\x4d', + '%4D': '\x4d', '%4e': '\x4e', '%4E': '\x4e', '%4f': '\x4f', '%4F': '\x4f', + '%50': '\x50', '%51': '\x51', '%52': '\x52', '%53': '\x53', '%54': '\x54', + '%55': '\x55', '%56': '\x56', '%57': '\x57', '%58': '\x58', '%59': '\x59', + '%5a': '\x5a', '%5A': '\x5a', '%5b': '\x5b', '%5B': '\x5b', '%5c': '\x5c', + '%5C': '\x5c', '%5d': '\x5d', '%5D': '\x5d', '%5e': '\x5e', '%5E': '\x5e', + '%5f': '\x5f', '%5F': '\x5f', '%60': '\x60', '%61': '\x61', '%62': '\x62', + '%63': '\x63', '%64': '\x64', '%65': '\x65', '%66': '\x66', '%67': '\x67', + '%68': '\x68', '%69': '\x69', '%6a': '\x6a', '%6A': '\x6a', '%6b': '\x6b', + '%6B': '\x6b', '%6c': '\x6c', '%6C': '\x6c', '%6d': '\x6d', '%6D': '\x6d', + '%6e': '\x6e', '%6E': '\x6e', '%6f': '\x6f', '%6F': '\x6f', '%70': '\x70', + '%71': '\x71', '%72': '\x72', '%73': '\x73', '%74': '\x74', '%75': '\x75', + '%76': '\x76', '%77': '\x77', '%78': '\x78', '%79': '\x79', '%7a': '\x7a', + '%7A': '\x7a', '%7b': '\x7b', '%7B': '\x7b', '%7c': '\x7c', '%7C': '\x7c', + '%7d': '\x7d', '%7D': '\x7d', '%7e': '\x7e', '%7E': '\x7e', '%7f': '\x7f', + '%7F': '\x7f', '%80': '\x80', '%81': '\x81', '%82': '\x82', '%83': '\x83', + '%84': '\x84', '%85': '\x85', '%86': '\x86', '%87': '\x87', '%88': '\x88', + '%89': '\x89', '%8a': '\x8a', '%8A': '\x8a', '%8b': '\x8b', '%8B': '\x8b', + '%8c': '\x8c', '%8C': '\x8c', '%8d': '\x8d', '%8D': '\x8d', '%8e': '\x8e', + '%8E': '\x8e', '%8f': '\x8f', '%8F': '\x8f', '%90': '\x90', '%91': '\x91', + '%92': '\x92', '%93': '\x93', '%94': '\x94', '%95': '\x95', '%96': '\x96', + '%97': '\x97', '%98': '\x98', '%99': '\x99', '%9a': '\x9a', '%9A': '\x9a', + '%9b': '\x9b', '%9B': '\x9b', '%9c': '\x9c', '%9C': '\x9c', '%9d': '\x9d', + '%9D': '\x9d', '%9e': '\x9e', '%9E': '\x9e', '%9f': '\x9f', '%9F': '\x9f', + '%a0': '\xa0', '%A0': '\xa0', '%a1': '\xa1', '%A1': '\xa1', '%a2': '\xa2', + '%A2': '\xa2', '%a3': '\xa3', '%A3': '\xa3', '%a4': '\xa4', '%A4': '\xa4', + '%a5': '\xa5', '%A5': '\xa5', '%a6': '\xa6', '%A6': '\xa6', '%a7': '\xa7', + '%A7': '\xa7', '%a8': '\xa8', '%A8': '\xa8', '%a9': '\xa9', '%A9': '\xa9', + '%aa': '\xaa', '%Aa': '\xaa', '%aA': '\xaa', '%AA': '\xaa', '%ab': '\xab', + '%Ab': '\xab', '%aB': '\xab', '%AB': '\xab', '%ac': '\xac', '%Ac': '\xac', + '%aC': '\xac', '%AC': '\xac', '%ad': '\xad', '%Ad': '\xad', '%aD': '\xad', + '%AD': '\xad', '%ae': '\xae', '%Ae': '\xae', '%aE': '\xae', '%AE': '\xae', + '%af': '\xaf', '%Af': '\xaf', '%aF': '\xaf', '%AF': '\xaf', '%b0': '\xb0', + '%B0': '\xb0', '%b1': '\xb1', '%B1': '\xb1', '%b2': '\xb2', '%B2': '\xb2', + '%b3': '\xb3', '%B3': '\xb3', '%b4': '\xb4', '%B4': '\xb4', '%b5': '\xb5', + '%B5': '\xb5', '%b6': '\xb6', '%B6': '\xb6', '%b7': '\xb7', '%B7': '\xb7', + '%b8': '\xb8', '%B8': '\xb8', '%b9': '\xb9', '%B9': '\xb9', '%ba': '\xba', + '%Ba': '\xba', '%bA': '\xba', '%BA': '\xba', '%bb': '\xbb', '%Bb': '\xbb', + '%bB': '\xbb', '%BB': '\xbb', '%bc': '\xbc', '%Bc': '\xbc', '%bC': '\xbc', + '%BC': '\xbc', '%bd': '\xbd', '%Bd': '\xbd', '%bD': '\xbd', '%BD': '\xbd', + '%be': '\xbe', '%Be': '\xbe', '%bE': '\xbe', '%BE': '\xbe', '%bf': '\xbf', + '%Bf': '\xbf', '%bF': '\xbf', '%BF': '\xbf', '%c0': '\xc0', '%C0': '\xc0', + '%c1': '\xc1', '%C1': '\xc1', '%c2': '\xc2', '%C2': '\xc2', '%c3': '\xc3', + '%C3': '\xc3', '%c4': '\xc4', '%C4': '\xc4', '%c5': '\xc5', '%C5': '\xc5', + '%c6': '\xc6', '%C6': '\xc6', '%c7': '\xc7', '%C7': '\xc7', '%c8': '\xc8', + '%C8': '\xc8', '%c9': '\xc9', '%C9': '\xc9', '%ca': '\xca', '%Ca': '\xca', + '%cA': '\xca', '%CA': '\xca', '%cb': '\xcb', '%Cb': '\xcb', '%cB': '\xcb', + '%CB': '\xcb', '%cc': '\xcc', '%Cc': '\xcc', '%cC': '\xcc', '%CC': '\xcc', + '%cd': '\xcd', '%Cd': '\xcd', '%cD': '\xcd', '%CD': '\xcd', '%ce': '\xce', + '%Ce': '\xce', '%cE': '\xce', '%CE': '\xce', '%cf': '\xcf', '%Cf': '\xcf', + '%cF': '\xcf', '%CF': '\xcf', '%d0': '\xd0', '%D0': '\xd0', '%d1': '\xd1', + '%D1': '\xd1', '%d2': '\xd2', '%D2': '\xd2', '%d3': '\xd3', '%D3': '\xd3', + '%d4': '\xd4', '%D4': '\xd4', '%d5': '\xd5', '%D5': '\xd5', '%d6': '\xd6', + '%D6': '\xd6', '%d7': '\xd7', '%D7': '\xd7', '%d8': '\xd8', '%D8': '\xd8', + '%d9': '\xd9', '%D9': '\xd9', '%da': '\xda', '%Da': '\xda', '%dA': '\xda', + '%DA': '\xda', '%db': '\xdb', '%Db': '\xdb', '%dB': '\xdb', '%DB': '\xdb', + '%dc': '\xdc', '%Dc': '\xdc', '%dC': '\xdc', '%DC': '\xdc', '%dd': '\xdd', + '%Dd': '\xdd', '%dD': '\xdd', '%DD': '\xdd', '%de': '\xde', '%De': '\xde', + '%dE': '\xde', '%DE': '\xde', '%df': '\xdf', '%Df': '\xdf', '%dF': '\xdf', + '%DF': '\xdf', '%e0': '\xe0', '%E0': '\xe0', '%e1': '\xe1', '%E1': '\xe1', + '%e2': '\xe2', '%E2': '\xe2', '%e3': '\xe3', '%E3': '\xe3', '%e4': '\xe4', + '%E4': '\xe4', '%e5': '\xe5', '%E5': '\xe5', '%e6': '\xe6', '%E6': '\xe6', + '%e7': '\xe7', '%E7': '\xe7', '%e8': '\xe8', '%E8': '\xe8', '%e9': '\xe9', + '%E9': '\xe9', '%ea': '\xea', '%Ea': '\xea', '%eA': '\xea', '%EA': '\xea', + '%eb': '\xeb', '%Eb': '\xeb', '%eB': '\xeb', '%EB': '\xeb', '%ec': '\xec', + '%Ec': '\xec', '%eC': '\xec', '%EC': '\xec', '%ed': '\xed', '%Ed': '\xed', + '%eD': '\xed', '%ED': '\xed', '%ee': '\xee', '%Ee': '\xee', '%eE': '\xee', + '%EE': '\xee', '%ef': '\xef', '%Ef': '\xef', '%eF': '\xef', '%EF': '\xef', + '%f0': '\xf0', '%F0': '\xf0', '%f1': '\xf1', '%F1': '\xf1', '%f2': '\xf2', + '%F2': '\xf2', '%f3': '\xf3', '%F3': '\xf3', '%f4': '\xf4', '%F4': '\xf4', + '%f5': '\xf5', '%F5': '\xf5', '%f6': '\xf6', '%F6': '\xf6', '%f7': '\xf7', + '%F7': '\xf7', '%f8': '\xf8', '%F8': '\xf8', '%f9': '\xf9', '%F9': '\xf9', + '%fa': '\xfa', '%Fa': '\xfa', '%fA': '\xfa', '%FA': '\xfa', '%fb': '\xfb', + '%Fb': '\xfb', '%fB': '\xfb', '%FB': '\xfb', '%fc': '\xfc', '%Fc': '\xfc', + '%fC': '\xfc', '%FC': '\xfc', '%fd': '\xfd', '%Fd': '\xfd', '%fD': '\xfd', + '%FD': '\xfd', '%fe': '\xfe', '%Fe': '\xfe', '%fE': '\xfe', '%FE': '\xfe', + '%ff': '\xff', '%Ff': '\xff', '%fF': '\xff', '%FF': '\xff' +} - this.fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024) - this.fieldNameSizeLimit = getLimit(limits, 'fieldNameSize', 100) - this.fieldsLimit = getLimit(limits, 'fields', Infinity) +function encodedReplacer (match) { + return EncodedLookup[match] +} - 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 +const STATE_KEY = 0 +const STATE_VALUE = 1 +const STATE_CHARSET = 2 +const STATE_LANG = 3 + +function parseParams (str) { + const res = [] + let state = STATE_KEY + let charset = '' + let inquote = false + let escaping = false + let p = 0 + let tmp = '' + const len = str.length + + for (var i = 0; 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 = STATE_KEY + } else { inquote = true } + continue + } else { escaping = false } + } else { + if (escaping && inquote) { tmp += '\\' } + escaping = false + if ((state === STATE_CHARSET || state === STATE_LANG) && char === "'") { + if (state === STATE_CHARSET) { + state = STATE_LANG + charset = tmp.substring(1) + } else { state = STATE_VALUE } + tmp = '' + continue + } else if (state === STATE_KEY && + (char === '*' || char === '=') && + res.length) { + state = char === '*' + ? STATE_CHARSET + : STATE_VALUE + res[p] = [tmp, undefined] + tmp = '' + continue + } else if (!inquote && char === ';') { + state = 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 === 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() + if (charset && tmp.length) { + tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer), + 'binary', + charset) + } else if (tmp) { + tmp = decodeText(tmp, 'binary', 'utf8') } - let idxeq; let idxamp; let i; let p = 0; const len = data.length + if (res[p] === undefined) { + if (tmp) { res[p] = tmp } + } else { res[p][1] = tmp } - 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 } - } + return res +} - if (idxeq !== undefined) { - // key with assignment - if (idxeq > p) { this._key += this.decoder.write(data.toString('binary', p, idxeq)) } - this._state = 'val' +module.exports = parseParams - 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() +/******/ }); +/************************************************************************/ +/******/ // The module cache +/******/ var __webpack_module_cache__ = {}; +/******/ +/******/ // The require function +/******/ function __nccwpck_require__(moduleId) { +/******/ // Check if module is in cache +/******/ var cachedModule = __webpack_module_cache__[moduleId]; +/******/ if (cachedModule !== undefined) { +/******/ return cachedModule.exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = __webpack_module_cache__[moduleId] = { +/******/ // no module.id needed +/******/ // no module.loaded needed +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ var threw = true; +/******/ try { +/******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __nccwpck_require__); +/******/ threw = false; +/******/ } finally { +/******/ if(threw) delete __webpack_module_cache__[moduleId]; +/******/ } +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/************************************************************************/ +/******/ /* webpack/runtime/compat */ +/******/ +/******/ if (typeof __nccwpck_require__ !== 'undefined') __nccwpck_require__.ab = new URL('.', import.meta.url).pathname.slice(import.meta.url.match(/^file:\/\/\/\w:/) ? 1 : 0, -1) + "/"; +/******/ +/************************************************************************/ +var __webpack_exports__ = {}; +// This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk. +(() => { - if (key.length) { - this.boy.emit('field', decodeText(key, 'binary', this.charset), - '', - keyTrunc, - false) +// EXTERNAL MODULE: ./node_modules/.pnpm/@actions+core@1.10.1/node_modules/@actions/core/lib/core.js +var core = __nccwpck_require__(9093); +;// CONCATENATED MODULE: external "node:fs/promises" +const promises_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:fs/promises"); +// EXTERNAL MODULE: external "node:os" +var external_node_os_ = __nccwpck_require__(612); +;// CONCATENATED MODULE: external "node:path" +const external_node_path_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:path"); +// EXTERNAL MODULE: ./node_modules/.pnpm/tail@2.2.6/node_modules/tail/lib/tail.js +var tail = __nccwpck_require__(3707); +;// CONCATENATED MODULE: external "node:fs" +const external_node_fs_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:fs"); +// EXTERNAL MODULE: external "node:util" +var external_node_util_ = __nccwpck_require__(7261); +// EXTERNAL MODULE: ./node_modules/.pnpm/@actions+core@1.11.1/node_modules/@actions/core/lib/core.js +var lib_core = __nccwpck_require__(8407); +// EXTERNAL MODULE: ./node_modules/.pnpm/@actions+exec@1.1.1/node_modules/@actions/exec/lib/exec.js +var exec = __nccwpck_require__(7775); +// EXTERNAL MODULE: external "os" +var external_os_ = __nccwpck_require__(2037); +// EXTERNAL MODULE: external "node:zlib" +var external_node_zlib_ = __nccwpck_require__(5628); +;// CONCATENATED MODULE: external "node:crypto" +const external_node_crypto_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:crypto"); +;// CONCATENATED MODULE: external "node:timers/promises" +const external_node_timers_promises_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:timers/promises"); +;// CONCATENATED MODULE: ./node_modules/.pnpm/@sindresorhus+is@7.0.1/node_modules/@sindresorhus/is/distribution/index.js +const typedArrayTypeNames = [ + 'Int8Array', + 'Uint8Array', + 'Uint8ClampedArray', + 'Int16Array', + 'Uint16Array', + 'Int32Array', + 'Uint32Array', + 'Float32Array', + 'Float64Array', + 'BigInt64Array', + 'BigUint64Array', +]; +function isTypedArrayName(name) { + return typedArrayTypeNames.includes(name); +} +const objectTypeNames = [ + 'Function', + 'Generator', + 'AsyncGenerator', + 'GeneratorFunction', + 'AsyncGeneratorFunction', + 'AsyncFunction', + 'Observable', + 'Array', + 'Buffer', + 'Blob', + 'Object', + 'RegExp', + 'Date', + 'Error', + 'Map', + 'Set', + 'WeakMap', + 'WeakSet', + 'WeakRef', + 'ArrayBuffer', + 'SharedArrayBuffer', + 'DataView', + 'Promise', + 'URL', + 'FormData', + 'URLSearchParams', + 'HTMLElement', + 'NaN', + ...typedArrayTypeNames, +]; +function isObjectTypeName(name) { + return objectTypeNames.includes(name); +} +const primitiveTypeNames = [ + 'null', + 'undefined', + 'string', + 'number', + 'bigint', + 'boolean', + 'symbol', +]; +function isPrimitiveTypeName(name) { + return primitiveTypeNames.includes(name); +} +const assertionTypeDescriptions = [ + 'positive number', + 'negative number', + 'Class', + 'string with a number', + 'null or undefined', + 'Iterable', + 'AsyncIterable', + 'native Promise', + 'EnumCase', + 'string with a URL', + 'truthy', + 'falsy', + 'primitive', + 'integer', + 'plain object', + 'TypedArray', + 'array-like', + 'tuple-like', + 'Node.js Stream', + 'infinite number', + 'empty array', + 'non-empty array', + 'empty string', + 'empty string or whitespace', + 'non-empty string', + 'non-empty string and not whitespace', + 'empty object', + 'non-empty object', + 'empty set', + 'non-empty set', + 'empty map', + 'non-empty map', + 'PropertyKey', + 'even integer', + 'odd integer', + 'T', + 'in range', + 'predicate returns truthy for any value', + 'predicate returns truthy for all values', + 'valid Date', + 'valid length', + 'whitespace string', + ...objectTypeNames, + ...primitiveTypeNames, +]; +const getObjectType = (value) => { + const objectTypeName = Object.prototype.toString.call(value).slice(8, -1); + if (/HTML\w+Element/.test(objectTypeName) && isHtmlElement(value)) { + return 'HTMLElement'; + } + if (isObjectTypeName(objectTypeName)) { + return objectTypeName; + } + return undefined; +}; +function detect(value) { + if (value === null) { + return 'null'; + } + switch (typeof value) { + case 'undefined': { + return 'undefined'; } - - 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 + case 'string': { + return 'string'; } - } 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 + case 'number': { + return Number.isNaN(value) ? 'NaN' : 'number'; } - 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 + case 'boolean': { + return 'boolean'; } - } else { - if (p < len) { this._val += this.decoder.write(data.toString('binary', p)) } - p = len - } + case 'function': { + return 'Function'; + } + case 'bigint': { + return 'bigint'; + } + case 'symbol': { + return 'symbol'; + } + default: } - } - cb() + if (isObservable(value)) { + return 'Observable'; + } + if (isArray(value)) { + return 'Array'; + } + if (isBuffer(value)) { + return 'Buffer'; + } + const tagType = getObjectType(value); + if (tagType) { + return tagType; + } + if (value instanceof String || value instanceof Boolean || value instanceof Number) { + throw new TypeError('Please don\'t use object wrappers for primitive types'); + } + return 'Object'; +} +function hasPromiseApi(value) { + return isFunction(value?.then) && isFunction(value?.catch); +} +const is = Object.assign(detect, { + all: isAll, + any: isAny, + array: isArray, + arrayBuffer: isArrayBuffer, + arrayLike: isArrayLike, + asyncFunction: isAsyncFunction, + asyncGenerator: isAsyncGenerator, + asyncGeneratorFunction: isAsyncGeneratorFunction, + asyncIterable: isAsyncIterable, + bigint: isBigint, + bigInt64Array: isBigInt64Array, + bigUint64Array: isBigUint64Array, + blob: isBlob, + boolean: isBoolean, + boundFunction: isBoundFunction, + buffer: isBuffer, + class: isClass, + dataView: isDataView, + date: isDate, + detect, + directInstanceOf: isDirectInstanceOf, + emptyArray: isEmptyArray, + emptyMap: isEmptyMap, + emptyObject: isEmptyObject, + emptySet: isEmptySet, + emptyString: isEmptyString, + emptyStringOrWhitespace: isEmptyStringOrWhitespace, + enumCase: isEnumCase, + error: isError, + evenInteger: isEvenInteger, + falsy: isFalsy, + float32Array: isFloat32Array, + float64Array: isFloat64Array, + formData: isFormData, + function: isFunction, + generator: isGenerator, + generatorFunction: isGeneratorFunction, + htmlElement: isHtmlElement, + infinite: isInfinite, + inRange: isInRange, + int16Array: isInt16Array, + int32Array: isInt32Array, + int8Array: isInt8Array, + integer: isInteger, + iterable: isIterable, + map: isMap, + nan: isNan, + nativePromise: isNativePromise, + negativeNumber: isNegativeNumber, + nodeStream: isNodeStream, + nonEmptyArray: isNonEmptyArray, + nonEmptyMap: isNonEmptyMap, + nonEmptyObject: isNonEmptyObject, + nonEmptySet: isNonEmptySet, + nonEmptyString: isNonEmptyString, + nonEmptyStringAndNotWhitespace: isNonEmptyStringAndNotWhitespace, + null: isNull, + nullOrUndefined: isNullOrUndefined, + number: isNumber, + numericString: isNumericString, + object: isObject, + observable: isObservable, + oddInteger: isOddInteger, + plainObject: isPlainObject, + positiveNumber: isPositiveNumber, + primitive: isPrimitive, + promise: isPromise, + propertyKey: isPropertyKey, + regExp: isRegExp, + safeInteger: isSafeInteger, + set: isSet, + sharedArrayBuffer: isSharedArrayBuffer, + string: isString, + symbol: isSymbol, + truthy: isTruthy, + tupleLike: isTupleLike, + typedArray: isTypedArray, + uint16Array: isUint16Array, + uint32Array: isUint32Array, + uint8Array: isUint8Array, + uint8ClampedArray: isUint8ClampedArray, + undefined: isUndefined, + urlInstance: isUrlInstance, + urlSearchParams: isUrlSearchParams, + urlString: isUrlString, + validDate: isValidDate, + validLength: isValidLength, + weakMap: isWeakMap, + weakRef: isWeakRef, + weakSet: isWeakSet, + whitespaceString: isWhitespaceString, +}); +function isAbsoluteModule2(remainder) { + return (value) => isInteger(value) && Math.abs(value % 2) === remainder; +} +function isAll(predicate, ...values) { + return predicateOnArray(Array.prototype.every, predicate, values); +} +function isAny(predicate, ...values) { + const predicates = isArray(predicate) ? predicate : [predicate]; + return predicates.some(singlePredicate => predicateOnArray(Array.prototype.some, singlePredicate, values)); +} +function isArray(value, assertion) { + if (!Array.isArray(value)) { + return false; + } + if (!isFunction(assertion)) { + return true; + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument + return value.every(element => assertion(element)); +} +function isArrayBuffer(value) { + return getObjectType(value) === 'ArrayBuffer'; +} +function isArrayLike(value) { + return !isNullOrUndefined(value) && !isFunction(value) && isValidLength(value.length); +} +function isAsyncFunction(value) { + return getObjectType(value) === 'AsyncFunction'; +} +function isAsyncGenerator(value) { + return isAsyncIterable(value) && isFunction(value.next) && isFunction(value.throw); } - -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') +function isAsyncGeneratorFunction(value) { + return getObjectType(value) === 'AsyncGeneratorFunction'; } - -module.exports = UrlEncoded - - -/***/ }), - -/***/ 9687: -/***/ ((module) => { - - - -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 +function isAsyncIterable(value) { + return isFunction(value?.[Symbol.asyncIterator]); } -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 +function isBigint(value) { + return typeof value === 'bigint'; } -Decoder.prototype.reset = function () { - this.buffer = undefined +function isBigInt64Array(value) { + return getObjectType(value) === 'BigInt64Array'; } - -module.exports = Decoder - - -/***/ }), - -/***/ 6504: -/***/ ((module) => { - - - -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) +function isBigUint64Array(value) { + return getObjectType(value) === 'BigUint64Array'; } - - -/***/ }), - -/***/ 884: -/***/ (function(module) { - - - -// Node has always utf-8 -const utf8Decoder = new TextDecoder('utf-8') -const textDecoders = new Map([ - ['utf-8', utf8Decoder], - ['utf8', utf8Decoder] -]) - -function getDecoder (charset) { - let lc - while (true) { - switch (charset) { - case 'utf-8': - case 'utf8': - return decoders.utf8 - case 'latin1': - case 'ascii': // TODO: Make these a separate, strict decoder? - case 'us-ascii': - case 'iso-8859-1': - case 'iso8859-1': - case 'iso88591': - case 'iso_8859-1': - case 'windows-1252': - case 'iso_8859-1:1987': - case 'cp1252': - case 'x-cp1252': - return decoders.latin1 - case 'utf16le': - case 'utf-16le': - case 'ucs2': - case 'ucs-2': - return decoders.utf16le - case 'base64': - return decoders.base64 - default: - if (lc === undefined) { - lc = true - charset = charset.toLowerCase() - continue - } - return decoders.other.bind(charset) - } - } +function isBlob(value) { + return getObjectType(value) === 'Blob'; } - -const decoders = { - utf8: (data, sourceEncoding) => { - if (data.length === 0) { - return '' +function isBoolean(value) { + return value === true || value === false; +} +// eslint-disable-next-line @typescript-eslint/ban-types +function isBoundFunction(value) { + return isFunction(value) && !Object.hasOwn(value, 'prototype'); +} +/** +Note: [Prefer using `Uint8Array` instead of `Buffer`.](https://sindresorhus.com/blog/goodbye-nodejs-buffer) +*/ +function isBuffer(value) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-call + return value?.constructor?.isBuffer?.(value) ?? false; +} +function isClass(value) { + return isFunction(value) && value.toString().startsWith('class '); +} +function isDataView(value) { + return getObjectType(value) === 'DataView'; +} +function isDate(value) { + return getObjectType(value) === 'Date'; +} +function isDirectInstanceOf(instance, class_) { + if (instance === undefined || instance === null) { + return false; } - if (typeof data === 'string') { - data = Buffer.from(data, sourceEncoding) + return Object.getPrototypeOf(instance) === class_.prototype; +} +function isEmptyArray(value) { + return isArray(value) && value.length === 0; +} +function isEmptyMap(value) { + return isMap(value) && value.size === 0; +} +function isEmptyObject(value) { + return isObject(value) && !isMap(value) && !isSet(value) && Object.keys(value).length === 0; +} +function isEmptySet(value) { + return isSet(value) && value.size === 0; +} +function isEmptyString(value) { + return isString(value) && value.length === 0; +} +function isEmptyStringOrWhitespace(value) { + return isEmptyString(value) || isWhitespaceString(value); +} +function isEnumCase(value, targetEnum) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument + return Object.values(targetEnum).includes(value); +} +function isError(value) { + return getObjectType(value) === 'Error'; +} +function isEvenInteger(value) { + return isAbsoluteModule2(0)(value); +} +// Example: `is.falsy = (value: unknown): value is (not true | 0 | '' | undefined | null) => Boolean(value);` +function isFalsy(value) { + return !value; +} +function isFloat32Array(value) { + return getObjectType(value) === 'Float32Array'; +} +function isFloat64Array(value) { + return getObjectType(value) === 'Float64Array'; +} +function isFormData(value) { + return getObjectType(value) === 'FormData'; +} +// eslint-disable-next-line @typescript-eslint/ban-types +function isFunction(value) { + return typeof value === 'function'; +} +function isGenerator(value) { + return isIterable(value) && isFunction(value?.next) && isFunction(value?.throw); +} +function isGeneratorFunction(value) { + return getObjectType(value) === 'GeneratorFunction'; +} +// eslint-disable-next-line @typescript-eslint/naming-convention +const NODE_TYPE_ELEMENT = 1; +// eslint-disable-next-line @typescript-eslint/naming-convention +const DOM_PROPERTIES_TO_CHECK = [ + 'innerHTML', + 'ownerDocument', + 'style', + 'attributes', + 'nodeValue', +]; +function isHtmlElement(value) { + return isObject(value) + && value.nodeType === NODE_TYPE_ELEMENT + && isString(value.nodeName) + && !isPlainObject(value) + && DOM_PROPERTIES_TO_CHECK.every(property => property in value); +} +function isInfinite(value) { + return value === Number.POSITIVE_INFINITY || value === Number.NEGATIVE_INFINITY; +} +function isInRange(value, range) { + if (isNumber(range)) { + return value >= Math.min(0, range) && value <= Math.max(range, 0); } - return data.utf8Slice(0, data.length) - }, - - latin1: (data, sourceEncoding) => { - if (data.length === 0) { - return '' + if (isArray(range) && range.length === 2) { + return value >= Math.min(...range) && value <= Math.max(...range); } - if (typeof data === 'string') { - return data + throw new TypeError(`Invalid range: ${JSON.stringify(range)}`); +} +function isInt16Array(value) { + return getObjectType(value) === 'Int16Array'; +} +function isInt32Array(value) { + return getObjectType(value) === 'Int32Array'; +} +function isInt8Array(value) { + return getObjectType(value) === 'Int8Array'; +} +function isInteger(value) { + return Number.isInteger(value); +} +function isIterable(value) { + return isFunction(value?.[Symbol.iterator]); +} +function isMap(value) { + return getObjectType(value) === 'Map'; +} +function isNan(value) { + return Number.isNaN(value); +} +function isNativePromise(value) { + return getObjectType(value) === 'Promise'; +} +function isNegativeNumber(value) { + return isNumber(value) && value < 0; +} +function isNodeStream(value) { + return isObject(value) && isFunction(value.pipe) && !isObservable(value); +} +function isNonEmptyArray(value) { + return isArray(value) && value.length > 0; +} +function isNonEmptyMap(value) { + return isMap(value) && value.size > 0; +} +// TODO: Use `not` operator here to remove `Map` and `Set` from type guard: +// - https://github.com/Microsoft/TypeScript/pull/29317 +function isNonEmptyObject(value) { + return isObject(value) && !isMap(value) && !isSet(value) && Object.keys(value).length > 0; +} +function isNonEmptySet(value) { + return isSet(value) && value.size > 0; +} +// TODO: Use `not ''` when the `not` operator is available. +function isNonEmptyString(value) { + return isString(value) && value.length > 0; +} +// TODO: Use `not ''` when the `not` operator is available. +function isNonEmptyStringAndNotWhitespace(value) { + return isString(value) && !isEmptyStringOrWhitespace(value); +} +// eslint-disable-next-line @typescript-eslint/ban-types +function isNull(value) { + return value === null; +} +// eslint-disable-next-line @typescript-eslint/ban-types +function isNullOrUndefined(value) { + return isNull(value) || isUndefined(value); +} +function isNumber(value) { + return typeof value === 'number' && !Number.isNaN(value); +} +function isNumericString(value) { + return isString(value) && !isEmptyStringOrWhitespace(value) && !Number.isNaN(Number(value)); +} +// eslint-disable-next-line @typescript-eslint/ban-types +function isObject(value) { + return !isNull(value) && (typeof value === 'object' || isFunction(value)); +} +function isObservable(value) { + if (!value) { + return false; } - return data.latin1Slice(0, data.length) - }, - - utf16le: (data, sourceEncoding) => { - if (data.length === 0) { - return '' + // eslint-disable-next-line no-use-extend-native/no-use-extend-native, @typescript-eslint/no-unsafe-call + if (value === value[Symbol.observable]?.()) { + return true; } - if (typeof data === 'string') { - data = Buffer.from(data, sourceEncoding) + // eslint-disable-next-line @typescript-eslint/no-unsafe-call + if (value === value['@@observable']?.()) { + return true; } - return data.ucs2Slice(0, data.length) - }, - - base64: (data, sourceEncoding) => { - if (data.length === 0) { - return '' + return false; +} +function isOddInteger(value) { + return isAbsoluteModule2(1)(value); +} +function isPlainObject(value) { + // From: https://github.com/sindresorhus/is-plain-obj/blob/main/index.js + if (typeof value !== 'object' || value === null) { + return false; } - if (typeof data === 'string') { - data = Buffer.from(data, sourceEncoding) + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const prototype = Object.getPrototypeOf(value); + return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value) && !(Symbol.iterator in value); +} +function isPositiveNumber(value) { + return isNumber(value) && value > 0; +} +function isPrimitive(value) { + return isNull(value) || isPrimitiveTypeName(typeof value); +} +function isPromise(value) { + return isNativePromise(value) || hasPromiseApi(value); +} +// `PropertyKey` is any value that can be used as an object key (string, number, or symbol) +function isPropertyKey(value) { + return isAny([isString, isNumber, isSymbol], value); +} +function isRegExp(value) { + return getObjectType(value) === 'RegExp'; +} +function isSafeInteger(value) { + return Number.isSafeInteger(value); +} +function isSet(value) { + return getObjectType(value) === 'Set'; +} +function isSharedArrayBuffer(value) { + return getObjectType(value) === 'SharedArrayBuffer'; +} +function isString(value) { + return typeof value === 'string'; +} +function isSymbol(value) { + return typeof value === 'symbol'; +} +// Example: `is.truthy = (value: unknown): value is (not false | not 0 | not '' | not undefined | not null) => Boolean(value);` +// eslint-disable-next-line unicorn/prefer-native-coercion-functions +function isTruthy(value) { + return Boolean(value); +} +function isTupleLike(value, guards) { + if (isArray(guards) && isArray(value) && guards.length === value.length) { + return guards.every((guard, index) => guard(value[index])); } - return data.base64Slice(0, data.length) - }, - - other: (data, sourceEncoding) => { - if (data.length === 0) { - return '' + return false; +} +function isTypedArray(value) { + return isTypedArrayName(getObjectType(value)); +} +function isUint16Array(value) { + return getObjectType(value) === 'Uint16Array'; +} +function isUint32Array(value) { + return getObjectType(value) === 'Uint32Array'; +} +function isUint8Array(value) { + return getObjectType(value) === 'Uint8Array'; +} +function isUint8ClampedArray(value) { + return getObjectType(value) === 'Uint8ClampedArray'; +} +function isUndefined(value) { + return value === undefined; +} +function isUrlInstance(value) { + return getObjectType(value) === 'URL'; +} +// eslint-disable-next-line unicorn/prevent-abbreviations +function isUrlSearchParams(value) { + return getObjectType(value) === 'URLSearchParams'; +} +function isUrlString(value) { + if (!isString(value)) { + return false; } - if (typeof data === 'string') { - data = Buffer.from(data, sourceEncoding) + try { + new URL(value); // eslint-disable-line no-new + return true; } - - if (textDecoders.has(this.toString())) { - try { - return textDecoders.get(this).decode(data) - } catch {} + catch { + return false; } - return typeof data === 'string' - ? data - : data.toString() - } } - -function decodeText (text, sourceEncoding, destEncoding) { - if (text) { - return getDecoder(destEncoding)(text, sourceEncoding) - } - return text -} - -module.exports = decodeText - - -/***/ }), - -/***/ 2160: -/***/ ((module) => { - - - -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] +function isValidDate(value) { + return isDate(value) && !isNan(Number(value)); } - - -/***/ }), - -/***/ 3576: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -/* eslint-disable object-property-newline */ - - -const decodeText = __nccwpck_require__(884) - -const RE_ENCODED = /%[a-fA-F0-9][a-fA-F0-9]/g - -const EncodedLookup = { - '%00': '\x00', '%01': '\x01', '%02': '\x02', '%03': '\x03', '%04': '\x04', - '%05': '\x05', '%06': '\x06', '%07': '\x07', '%08': '\x08', '%09': '\x09', - '%0a': '\x0a', '%0A': '\x0a', '%0b': '\x0b', '%0B': '\x0b', '%0c': '\x0c', - '%0C': '\x0c', '%0d': '\x0d', '%0D': '\x0d', '%0e': '\x0e', '%0E': '\x0e', - '%0f': '\x0f', '%0F': '\x0f', '%10': '\x10', '%11': '\x11', '%12': '\x12', - '%13': '\x13', '%14': '\x14', '%15': '\x15', '%16': '\x16', '%17': '\x17', - '%18': '\x18', '%19': '\x19', '%1a': '\x1a', '%1A': '\x1a', '%1b': '\x1b', - '%1B': '\x1b', '%1c': '\x1c', '%1C': '\x1c', '%1d': '\x1d', '%1D': '\x1d', - '%1e': '\x1e', '%1E': '\x1e', '%1f': '\x1f', '%1F': '\x1f', '%20': '\x20', - '%21': '\x21', '%22': '\x22', '%23': '\x23', '%24': '\x24', '%25': '\x25', - '%26': '\x26', '%27': '\x27', '%28': '\x28', '%29': '\x29', '%2a': '\x2a', - '%2A': '\x2a', '%2b': '\x2b', '%2B': '\x2b', '%2c': '\x2c', '%2C': '\x2c', - '%2d': '\x2d', '%2D': '\x2d', '%2e': '\x2e', '%2E': '\x2e', '%2f': '\x2f', - '%2F': '\x2f', '%30': '\x30', '%31': '\x31', '%32': '\x32', '%33': '\x33', - '%34': '\x34', '%35': '\x35', '%36': '\x36', '%37': '\x37', '%38': '\x38', - '%39': '\x39', '%3a': '\x3a', '%3A': '\x3a', '%3b': '\x3b', '%3B': '\x3b', - '%3c': '\x3c', '%3C': '\x3c', '%3d': '\x3d', '%3D': '\x3d', '%3e': '\x3e', - '%3E': '\x3e', '%3f': '\x3f', '%3F': '\x3f', '%40': '\x40', '%41': '\x41', - '%42': '\x42', '%43': '\x43', '%44': '\x44', '%45': '\x45', '%46': '\x46', - '%47': '\x47', '%48': '\x48', '%49': '\x49', '%4a': '\x4a', '%4A': '\x4a', - '%4b': '\x4b', '%4B': '\x4b', '%4c': '\x4c', '%4C': '\x4c', '%4d': '\x4d', - '%4D': '\x4d', '%4e': '\x4e', '%4E': '\x4e', '%4f': '\x4f', '%4F': '\x4f', - '%50': '\x50', '%51': '\x51', '%52': '\x52', '%53': '\x53', '%54': '\x54', - '%55': '\x55', '%56': '\x56', '%57': '\x57', '%58': '\x58', '%59': '\x59', - '%5a': '\x5a', '%5A': '\x5a', '%5b': '\x5b', '%5B': '\x5b', '%5c': '\x5c', - '%5C': '\x5c', '%5d': '\x5d', '%5D': '\x5d', '%5e': '\x5e', '%5E': '\x5e', - '%5f': '\x5f', '%5F': '\x5f', '%60': '\x60', '%61': '\x61', '%62': '\x62', - '%63': '\x63', '%64': '\x64', '%65': '\x65', '%66': '\x66', '%67': '\x67', - '%68': '\x68', '%69': '\x69', '%6a': '\x6a', '%6A': '\x6a', '%6b': '\x6b', - '%6B': '\x6b', '%6c': '\x6c', '%6C': '\x6c', '%6d': '\x6d', '%6D': '\x6d', - '%6e': '\x6e', '%6E': '\x6e', '%6f': '\x6f', '%6F': '\x6f', '%70': '\x70', - '%71': '\x71', '%72': '\x72', '%73': '\x73', '%74': '\x74', '%75': '\x75', - '%76': '\x76', '%77': '\x77', '%78': '\x78', '%79': '\x79', '%7a': '\x7a', - '%7A': '\x7a', '%7b': '\x7b', '%7B': '\x7b', '%7c': '\x7c', '%7C': '\x7c', - '%7d': '\x7d', '%7D': '\x7d', '%7e': '\x7e', '%7E': '\x7e', '%7f': '\x7f', - '%7F': '\x7f', '%80': '\x80', '%81': '\x81', '%82': '\x82', '%83': '\x83', - '%84': '\x84', '%85': '\x85', '%86': '\x86', '%87': '\x87', '%88': '\x88', - '%89': '\x89', '%8a': '\x8a', '%8A': '\x8a', '%8b': '\x8b', '%8B': '\x8b', - '%8c': '\x8c', '%8C': '\x8c', '%8d': '\x8d', '%8D': '\x8d', '%8e': '\x8e', - '%8E': '\x8e', '%8f': '\x8f', '%8F': '\x8f', '%90': '\x90', '%91': '\x91', - '%92': '\x92', '%93': '\x93', '%94': '\x94', '%95': '\x95', '%96': '\x96', - '%97': '\x97', '%98': '\x98', '%99': '\x99', '%9a': '\x9a', '%9A': '\x9a', - '%9b': '\x9b', '%9B': '\x9b', '%9c': '\x9c', '%9C': '\x9c', '%9d': '\x9d', - '%9D': '\x9d', '%9e': '\x9e', '%9E': '\x9e', '%9f': '\x9f', '%9F': '\x9f', - '%a0': '\xa0', '%A0': '\xa0', '%a1': '\xa1', '%A1': '\xa1', '%a2': '\xa2', - '%A2': '\xa2', '%a3': '\xa3', '%A3': '\xa3', '%a4': '\xa4', '%A4': '\xa4', - '%a5': '\xa5', '%A5': '\xa5', '%a6': '\xa6', '%A6': '\xa6', '%a7': '\xa7', - '%A7': '\xa7', '%a8': '\xa8', '%A8': '\xa8', '%a9': '\xa9', '%A9': '\xa9', - '%aa': '\xaa', '%Aa': '\xaa', '%aA': '\xaa', '%AA': '\xaa', '%ab': '\xab', - '%Ab': '\xab', '%aB': '\xab', '%AB': '\xab', '%ac': '\xac', '%Ac': '\xac', - '%aC': '\xac', '%AC': '\xac', '%ad': '\xad', '%Ad': '\xad', '%aD': '\xad', - '%AD': '\xad', '%ae': '\xae', '%Ae': '\xae', '%aE': '\xae', '%AE': '\xae', - '%af': '\xaf', '%Af': '\xaf', '%aF': '\xaf', '%AF': '\xaf', '%b0': '\xb0', - '%B0': '\xb0', '%b1': '\xb1', '%B1': '\xb1', '%b2': '\xb2', '%B2': '\xb2', - '%b3': '\xb3', '%B3': '\xb3', '%b4': '\xb4', '%B4': '\xb4', '%b5': '\xb5', - '%B5': '\xb5', '%b6': '\xb6', '%B6': '\xb6', '%b7': '\xb7', '%B7': '\xb7', - '%b8': '\xb8', '%B8': '\xb8', '%b9': '\xb9', '%B9': '\xb9', '%ba': '\xba', - '%Ba': '\xba', '%bA': '\xba', '%BA': '\xba', '%bb': '\xbb', '%Bb': '\xbb', - '%bB': '\xbb', '%BB': '\xbb', '%bc': '\xbc', '%Bc': '\xbc', '%bC': '\xbc', - '%BC': '\xbc', '%bd': '\xbd', '%Bd': '\xbd', '%bD': '\xbd', '%BD': '\xbd', - '%be': '\xbe', '%Be': '\xbe', '%bE': '\xbe', '%BE': '\xbe', '%bf': '\xbf', - '%Bf': '\xbf', '%bF': '\xbf', '%BF': '\xbf', '%c0': '\xc0', '%C0': '\xc0', - '%c1': '\xc1', '%C1': '\xc1', '%c2': '\xc2', '%C2': '\xc2', '%c3': '\xc3', - '%C3': '\xc3', '%c4': '\xc4', '%C4': '\xc4', '%c5': '\xc5', '%C5': '\xc5', - '%c6': '\xc6', '%C6': '\xc6', '%c7': '\xc7', '%C7': '\xc7', '%c8': '\xc8', - '%C8': '\xc8', '%c9': '\xc9', '%C9': '\xc9', '%ca': '\xca', '%Ca': '\xca', - '%cA': '\xca', '%CA': '\xca', '%cb': '\xcb', '%Cb': '\xcb', '%cB': '\xcb', - '%CB': '\xcb', '%cc': '\xcc', '%Cc': '\xcc', '%cC': '\xcc', '%CC': '\xcc', - '%cd': '\xcd', '%Cd': '\xcd', '%cD': '\xcd', '%CD': '\xcd', '%ce': '\xce', - '%Ce': '\xce', '%cE': '\xce', '%CE': '\xce', '%cf': '\xcf', '%Cf': '\xcf', - '%cF': '\xcf', '%CF': '\xcf', '%d0': '\xd0', '%D0': '\xd0', '%d1': '\xd1', - '%D1': '\xd1', '%d2': '\xd2', '%D2': '\xd2', '%d3': '\xd3', '%D3': '\xd3', - '%d4': '\xd4', '%D4': '\xd4', '%d5': '\xd5', '%D5': '\xd5', '%d6': '\xd6', - '%D6': '\xd6', '%d7': '\xd7', '%D7': '\xd7', '%d8': '\xd8', '%D8': '\xd8', - '%d9': '\xd9', '%D9': '\xd9', '%da': '\xda', '%Da': '\xda', '%dA': '\xda', - '%DA': '\xda', '%db': '\xdb', '%Db': '\xdb', '%dB': '\xdb', '%DB': '\xdb', - '%dc': '\xdc', '%Dc': '\xdc', '%dC': '\xdc', '%DC': '\xdc', '%dd': '\xdd', - '%Dd': '\xdd', '%dD': '\xdd', '%DD': '\xdd', '%de': '\xde', '%De': '\xde', - '%dE': '\xde', '%DE': '\xde', '%df': '\xdf', '%Df': '\xdf', '%dF': '\xdf', - '%DF': '\xdf', '%e0': '\xe0', '%E0': '\xe0', '%e1': '\xe1', '%E1': '\xe1', - '%e2': '\xe2', '%E2': '\xe2', '%e3': '\xe3', '%E3': '\xe3', '%e4': '\xe4', - '%E4': '\xe4', '%e5': '\xe5', '%E5': '\xe5', '%e6': '\xe6', '%E6': '\xe6', - '%e7': '\xe7', '%E7': '\xe7', '%e8': '\xe8', '%E8': '\xe8', '%e9': '\xe9', - '%E9': '\xe9', '%ea': '\xea', '%Ea': '\xea', '%eA': '\xea', '%EA': '\xea', - '%eb': '\xeb', '%Eb': '\xeb', '%eB': '\xeb', '%EB': '\xeb', '%ec': '\xec', - '%Ec': '\xec', '%eC': '\xec', '%EC': '\xec', '%ed': '\xed', '%Ed': '\xed', - '%eD': '\xed', '%ED': '\xed', '%ee': '\xee', '%Ee': '\xee', '%eE': '\xee', - '%EE': '\xee', '%ef': '\xef', '%Ef': '\xef', '%eF': '\xef', '%EF': '\xef', - '%f0': '\xf0', '%F0': '\xf0', '%f1': '\xf1', '%F1': '\xf1', '%f2': '\xf2', - '%F2': '\xf2', '%f3': '\xf3', '%F3': '\xf3', '%f4': '\xf4', '%F4': '\xf4', - '%f5': '\xf5', '%F5': '\xf5', '%f6': '\xf6', '%F6': '\xf6', '%f7': '\xf7', - '%F7': '\xf7', '%f8': '\xf8', '%F8': '\xf8', '%f9': '\xf9', '%F9': '\xf9', - '%fa': '\xfa', '%Fa': '\xfa', '%fA': '\xfa', '%FA': '\xfa', '%fb': '\xfb', - '%Fb': '\xfb', '%fB': '\xfb', '%FB': '\xfb', '%fc': '\xfc', '%Fc': '\xfc', - '%fC': '\xfc', '%FC': '\xfc', '%fd': '\xfd', '%Fd': '\xfd', '%fD': '\xfd', - '%FD': '\xfd', '%fe': '\xfe', '%Fe': '\xfe', '%fE': '\xfe', '%FE': '\xfe', - '%ff': '\xff', '%Ff': '\xff', '%fF': '\xff', '%FF': '\xff' +function isValidLength(value) { + return isSafeInteger(value) && value >= 0; } - -function encodedReplacer (match) { - return EncodedLookup[match] +// eslint-disable-next-line @typescript-eslint/ban-types +function isWeakMap(value) { + return getObjectType(value) === 'WeakMap'; } - -const STATE_KEY = 0 -const STATE_VALUE = 1 -const STATE_CHARSET = 2 -const STATE_LANG = 3 - -function parseParams (str) { - const res = [] - let state = STATE_KEY - let charset = '' - let inquote = false - let escaping = false - let p = 0 - let tmp = '' - const len = str.length - - for (var i = 0; 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 = STATE_KEY - } else { inquote = true } - continue - } else { escaping = false } - } else { - if (escaping && inquote) { tmp += '\\' } - escaping = false - if ((state === STATE_CHARSET || state === STATE_LANG) && char === "'") { - if (state === STATE_CHARSET) { - state = STATE_LANG - charset = tmp.substring(1) - } else { state = STATE_VALUE } - tmp = '' - continue - } else if (state === STATE_KEY && - (char === '*' || char === '=') && - res.length) { - state = char === '*' - ? STATE_CHARSET - : STATE_VALUE - res[p] = [tmp, undefined] - tmp = '' - continue - } else if (!inquote && char === ';') { - state = 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 } +// eslint-disable-next-line @typescript-eslint/ban-types, unicorn/prevent-abbreviations +function isWeakRef(value) { + return getObjectType(value) === 'WeakRef'; +} +// eslint-disable-next-line @typescript-eslint/ban-types +function isWeakSet(value) { + return getObjectType(value) === 'WeakSet'; +} +function isWhitespaceString(value) { + return isString(value) && /^\s+$/.test(value); +} +function predicateOnArray(method, predicate, values) { + if (!isFunction(predicate)) { + throw new TypeError(`Invalid predicate: ${JSON.stringify(predicate)}`); } - 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 + if (values.length === 0) { + throw new TypeError('Invalid number of values'); + } + return method.call(values, predicate); } - -module.exports = parseParams - - -/***/ }) - -/******/ }); -/************************************************************************/ -/******/ // The module cache -/******/ var __webpack_module_cache__ = {}; -/******/ -/******/ // The require function -/******/ function __nccwpck_require__(moduleId) { -/******/ // Check if module is in cache -/******/ var cachedModule = __webpack_module_cache__[moduleId]; -/******/ if (cachedModule !== undefined) { -/******/ return cachedModule.exports; -/******/ } -/******/ // Create a new module (and put it into the cache) -/******/ var module = __webpack_module_cache__[moduleId] = { -/******/ // no module.id needed -/******/ // no module.loaded needed -/******/ exports: {} -/******/ }; -/******/ -/******/ // Execute the module function -/******/ var threw = true; -/******/ try { -/******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __nccwpck_require__); -/******/ threw = false; -/******/ } finally { -/******/ if(threw) delete __webpack_module_cache__[moduleId]; -/******/ } -/******/ -/******/ // Return the exports of the module -/******/ return module.exports; -/******/ } -/******/ -/************************************************************************/ -/******/ /* webpack/runtime/compat */ -/******/ -/******/ if (typeof __nccwpck_require__ !== 'undefined') __nccwpck_require__.ab = new URL('.', import.meta.url).pathname.slice(import.meta.url.match(/^file:\/\/\/\w:/) ? 1 : 0, -1) + "/"; -/******/ -/************************************************************************/ -var __webpack_exports__ = {}; -// This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk. -(() => { - -// EXTERNAL MODULE: ./node_modules/.pnpm/@actions+core@1.10.1/node_modules/@actions/core/lib/core.js -var core = __nccwpck_require__(9093); -;// CONCATENATED MODULE: external "node:fs/promises" -const promises_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:fs/promises"); -// EXTERNAL MODULE: external "node:os" -var external_node_os_ = __nccwpck_require__(612); -;// CONCATENATED MODULE: external "node:path" -const external_node_path_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:path"); -// EXTERNAL MODULE: ./node_modules/.pnpm/tail@2.2.6/node_modules/tail/lib/tail.js -var tail = __nccwpck_require__(3707); -;// CONCATENATED MODULE: external "node:fs" -const external_node_fs_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:fs"); -// EXTERNAL MODULE: external "node:util" -var external_node_util_ = __nccwpck_require__(7261); -// EXTERNAL MODULE: ./node_modules/.pnpm/@actions+exec@1.1.1/node_modules/@actions/exec/lib/exec.js -var exec = __nccwpck_require__(7775); -// EXTERNAL MODULE: external "os" -var external_os_ = __nccwpck_require__(2037); -// EXTERNAL MODULE: external "node:zlib" -var external_node_zlib_ = __nccwpck_require__(5628); -;// CONCATENATED MODULE: external "node:crypto" -const external_node_crypto_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:crypto"); -;// CONCATENATED MODULE: ./node_modules/.pnpm/@sindresorhus+is@7.0.0/node_modules/@sindresorhus/is/distribution/index.js -const typedArrayTypeNames = [ - 'Int8Array', - 'Uint8Array', - 'Uint8ClampedArray', - 'Int16Array', - 'Uint16Array', - 'Int32Array', - 'Uint32Array', - 'Float32Array', - 'Float64Array', - 'BigInt64Array', - 'BigUint64Array', -]; -function isTypedArrayName(name) { - return typedArrayTypeNames.includes(name); +function typeErrorMessage(description, value) { + return `Expected value which is \`${description}\`, received value of type \`${is(value)}\`.`; } -const objectTypeNames = [ - 'Function', - 'Generator', - 'AsyncGenerator', - 'GeneratorFunction', - 'AsyncGeneratorFunction', - 'AsyncFunction', - 'Observable', - 'Array', - 'Buffer', - 'Blob', - 'Object', - 'RegExp', - 'Date', - 'Error', - 'Map', - 'Set', - 'WeakMap', - 'WeakSet', - 'WeakRef', - 'ArrayBuffer', - 'SharedArrayBuffer', - 'DataView', - 'Promise', - 'URL', - 'FormData', - 'URLSearchParams', - 'HTMLElement', - 'NaN', - ...typedArrayTypeNames, -]; -function isObjectTypeName(name) { - return objectTypeNames.includes(name); +function unique(values) { + // eslint-disable-next-line unicorn/prefer-spread + return Array.from(new Set(values)); +} +const andFormatter = new Intl.ListFormat('en', { style: 'long', type: 'conjunction' }); +const orFormatter = new Intl.ListFormat('en', { style: 'long', type: 'disjunction' }); +function typeErrorMessageMultipleValues(expectedType, values) { + const uniqueExpectedTypes = unique((isArray(expectedType) ? expectedType : [expectedType]).map(value => `\`${value}\``)); + const uniqueValueTypes = unique(values.map(value => `\`${is(value)}\``)); + return `Expected values which are ${orFormatter.format(uniqueExpectedTypes)}. Received values of type${uniqueValueTypes.length > 1 ? 's' : ''} ${andFormatter.format(uniqueValueTypes)}.`; +} +const assert = { + all: assertAll, + any: assertAny, + array: assertArray, + arrayBuffer: assertArrayBuffer, + arrayLike: assertArrayLike, + asyncFunction: assertAsyncFunction, + asyncGenerator: assertAsyncGenerator, + asyncGeneratorFunction: assertAsyncGeneratorFunction, + asyncIterable: assertAsyncIterable, + bigint: assertBigint, + bigInt64Array: assertBigInt64Array, + bigUint64Array: assertBigUint64Array, + blob: assertBlob, + boolean: assertBoolean, + boundFunction: assertBoundFunction, + buffer: assertBuffer, + class: assertClass, + dataView: assertDataView, + date: assertDate, + directInstanceOf: assertDirectInstanceOf, + emptyArray: assertEmptyArray, + emptyMap: assertEmptyMap, + emptyObject: assertEmptyObject, + emptySet: assertEmptySet, + emptyString: assertEmptyString, + emptyStringOrWhitespace: assertEmptyStringOrWhitespace, + enumCase: assertEnumCase, + error: assertError, + evenInteger: assertEvenInteger, + falsy: assertFalsy, + float32Array: assertFloat32Array, + float64Array: assertFloat64Array, + formData: assertFormData, + function: assertFunction, + generator: assertGenerator, + generatorFunction: assertGeneratorFunction, + htmlElement: assertHtmlElement, + infinite: assertInfinite, + inRange: assertInRange, + int16Array: assertInt16Array, + int32Array: assertInt32Array, + int8Array: assertInt8Array, + integer: assertInteger, + iterable: assertIterable, + map: assertMap, + nan: assertNan, + nativePromise: assertNativePromise, + negativeNumber: assertNegativeNumber, + nodeStream: assertNodeStream, + nonEmptyArray: assertNonEmptyArray, + nonEmptyMap: assertNonEmptyMap, + nonEmptyObject: assertNonEmptyObject, + nonEmptySet: assertNonEmptySet, + nonEmptyString: assertNonEmptyString, + nonEmptyStringAndNotWhitespace: assertNonEmptyStringAndNotWhitespace, + null: assertNull, + nullOrUndefined: assertNullOrUndefined, + number: assertNumber, + numericString: assertNumericString, + object: assertObject, + observable: assertObservable, + oddInteger: assertOddInteger, + plainObject: assertPlainObject, + positiveNumber: assertPositiveNumber, + primitive: assertPrimitive, + promise: assertPromise, + propertyKey: assertPropertyKey, + regExp: assertRegExp, + safeInteger: assertSafeInteger, + set: assertSet, + sharedArrayBuffer: assertSharedArrayBuffer, + string: assertString, + symbol: assertSymbol, + truthy: assertTruthy, + tupleLike: assertTupleLike, + typedArray: assertTypedArray, + uint16Array: assertUint16Array, + uint32Array: assertUint32Array, + uint8Array: assertUint8Array, + uint8ClampedArray: assertUint8ClampedArray, + undefined: assertUndefined, + urlInstance: assertUrlInstance, + urlSearchParams: assertUrlSearchParams, + urlString: assertUrlString, + validDate: assertValidDate, + validLength: assertValidLength, + weakMap: assertWeakMap, + weakRef: assertWeakRef, + weakSet: assertWeakSet, + whitespaceString: assertWhitespaceString, +}; +const methodTypeMap = { + isArray: 'Array', + isArrayBuffer: 'ArrayBuffer', + isArrayLike: 'array-like', + isAsyncFunction: 'AsyncFunction', + isAsyncGenerator: 'AsyncGenerator', + isAsyncGeneratorFunction: 'AsyncGeneratorFunction', + isAsyncIterable: 'AsyncIterable', + isBigint: 'bigint', + isBigInt64Array: 'BigInt64Array', + isBigUint64Array: 'BigUint64Array', + isBlob: 'Blob', + isBoolean: 'boolean', + isBoundFunction: 'Function', + isBuffer: 'Buffer', + isClass: 'Class', + isDataView: 'DataView', + isDate: 'Date', + isDirectInstanceOf: 'T', + isEmptyArray: 'empty array', + isEmptyMap: 'empty map', + isEmptyObject: 'empty object', + isEmptySet: 'empty set', + isEmptyString: 'empty string', + isEmptyStringOrWhitespace: 'empty string or whitespace', + isEnumCase: 'EnumCase', + isError: 'Error', + isEvenInteger: 'even integer', + isFalsy: 'falsy', + isFloat32Array: 'Float32Array', + isFloat64Array: 'Float64Array', + isFormData: 'FormData', + isFunction: 'Function', + isGenerator: 'Generator', + isGeneratorFunction: 'GeneratorFunction', + isHtmlElement: 'HTMLElement', + isInfinite: 'infinite number', + isInRange: 'in range', + isInt16Array: 'Int16Array', + isInt32Array: 'Int32Array', + isInt8Array: 'Int8Array', + isInteger: 'integer', + isIterable: 'Iterable', + isMap: 'Map', + isNan: 'NaN', + isNativePromise: 'native Promise', + isNegativeNumber: 'negative number', + isNodeStream: 'Node.js Stream', + isNonEmptyArray: 'non-empty array', + isNonEmptyMap: 'non-empty map', + isNonEmptyObject: 'non-empty object', + isNonEmptySet: 'non-empty set', + isNonEmptyString: 'non-empty string', + isNonEmptyStringAndNotWhitespace: 'non-empty string and not whitespace', + isNull: 'null', + isNullOrUndefined: 'null or undefined', + isNumber: 'number', + isNumericString: 'string with a number', + isObject: 'Object', + isObservable: 'Observable', + isOddInteger: 'odd integer', + isPlainObject: 'plain object', + isPositiveNumber: 'positive number', + isPrimitive: 'primitive', + isPromise: 'Promise', + isPropertyKey: 'PropertyKey', + isRegExp: 'RegExp', + isSafeInteger: 'integer', + isSet: 'Set', + isSharedArrayBuffer: 'SharedArrayBuffer', + isString: 'string', + isSymbol: 'symbol', + isTruthy: 'truthy', + isTupleLike: 'tuple-like', + isTypedArray: 'TypedArray', + isUint16Array: 'Uint16Array', + isUint32Array: 'Uint32Array', + isUint8Array: 'Uint8Array', + isUint8ClampedArray: 'Uint8ClampedArray', + isUndefined: 'undefined', + isUrlInstance: 'URL', + isUrlSearchParams: 'URLSearchParams', + isUrlString: 'string with a URL', + isValidDate: 'valid Date', + isValidLength: 'valid length', + isWeakMap: 'WeakMap', + isWeakRef: 'WeakRef', + isWeakSet: 'WeakSet', + isWhitespaceString: 'whitespace string', +}; +function keysOf(value) { + return Object.keys(value); } -const primitiveTypeNames = [ - 'null', - 'undefined', - 'string', - 'number', - 'bigint', - 'boolean', - 'symbol', -]; -function isPrimitiveTypeName(name) { - return primitiveTypeNames.includes(name); +const isMethodNames = keysOf(methodTypeMap); +function isIsMethodName(value) { + return isMethodNames.includes(value); } -const assertionTypeDescriptions = [ - 'positive number', - 'negative number', - 'Class', - 'string with a number', - 'null or undefined', - 'Iterable', - 'AsyncIterable', - 'native Promise', - 'EnumCase', - 'string with a URL', - 'truthy', - 'falsy', - 'primitive', - 'integer', - 'plain object', - 'TypedArray', - 'array-like', - 'tuple-like', - 'Node.js Stream', - 'infinite number', - 'empty array', - 'non-empty array', - 'empty string', - 'empty string or whitespace', - 'non-empty string', - 'non-empty string and not whitespace', - 'empty object', - 'non-empty object', - 'empty set', - 'non-empty set', - 'empty map', - 'non-empty map', - 'PropertyKey', - 'even integer', - 'odd integer', - 'T', - 'in range', - 'predicate returns truthy for any value', - 'predicate returns truthy for all values', - 'valid Date', - 'valid length', - 'whitespace string', - ...objectTypeNames, - ...primitiveTypeNames, -]; -const getObjectType = (value) => { - const objectTypeName = Object.prototype.toString.call(value).slice(8, -1); - if (/HTML\w+Element/.test(objectTypeName) && isHtmlElement(value)) { - return 'HTMLElement'; +function assertAll(predicate, ...values) { + if (!isAll(predicate, ...values)) { + const expectedType = isIsMethodName(predicate.name) ? methodTypeMap[predicate.name] : 'predicate returns truthy for all values'; + throw new TypeError(typeErrorMessageMultipleValues(expectedType, values)); } - if (isObjectTypeName(objectTypeName)) { - return objectTypeName; +} +function assertAny(predicate, ...values) { + if (!isAny(predicate, ...values)) { + const predicates = isArray(predicate) ? predicate : [predicate]; + const expectedTypes = predicates.map(predicate => isIsMethodName(predicate.name) ? methodTypeMap[predicate.name] : 'predicate returns truthy for any value'); + throw new TypeError(typeErrorMessageMultipleValues(expectedTypes, values)); } - return undefined; -}; -function detect(value) { - if (value === null) { - return 'null'; +} +function assertArray(value, assertion, message) { + if (!isArray(value)) { + throw new TypeError(message ?? typeErrorMessage('Array', value)); } - switch (typeof value) { - case 'undefined': { - return 'undefined'; - } - case 'string': { - return 'string'; - } - case 'number': { - return Number.isNaN(value) ? 'NaN' : 'number'; - } - case 'boolean': { - return 'boolean'; - } - case 'function': { - return 'Function'; - } - case 'bigint': { - return 'bigint'; - } - case 'symbol': { - return 'symbol'; + if (assertion) { + for (const element of value) { + // @ts-expect-error: "Assertions require every name in the call target to be declared with an explicit type annotation." + assertion(element, message); } - default: - } - if (isObservable(value)) { - return 'Observable'; - } - if (isArray(value)) { - return 'Array'; - } - if (isBuffer(value)) { - return 'Buffer'; - } - const tagType = getObjectType(value); - if (tagType) { - return tagType; - } - if (value instanceof String || value instanceof Boolean || value instanceof Number) { - throw new TypeError('Please don\'t use object wrappers for primitive types'); } - return 'Object'; -} -function hasPromiseApi(value) { - return isFunction(value?.then) && isFunction(value?.catch); -} -const is = Object.assign(detect, { - all: isAll, - any: isAny, - array: isArray, - arrayBuffer: isArrayBuffer, - arrayLike: isArrayLike, - asyncFunction: isAsyncFunction, - asyncGenerator: isAsyncGenerator, - asyncGeneratorFunction: isAsyncGeneratorFunction, - asyncIterable: isAsyncIterable, - bigint: isBigint, - bigInt64Array: isBigInt64Array, - bigUint64Array: isBigUint64Array, - blob: isBlob, - boolean: isBoolean, - boundFunction: isBoundFunction, - buffer: isBuffer, - class: isClass, - dataView: isDataView, - date: isDate, - detect, - directInstanceOf: isDirectInstanceOf, - emptyArray: isEmptyArray, - emptyMap: isEmptyMap, - emptyObject: isEmptyObject, - emptySet: isEmptySet, - emptyString: isEmptyString, - emptyStringOrWhitespace: isEmptyStringOrWhitespace, - enumCase: isEnumCase, - error: isError, - evenInteger: isEvenInteger, - falsy: isFalsy, - float32Array: isFloat32Array, - float64Array: isFloat64Array, - formData: isFormData, - function: isFunction, - generator: isGenerator, - generatorFunction: isGeneratorFunction, - htmlElement: isHtmlElement, - infinite: isInfinite, - inRange: isInRange, - int16Array: isInt16Array, - int32Array: isInt32Array, - int8Array: isInt8Array, - integer: isInteger, - iterable: isIterable, - map: isMap, - nan: isNan, - nativePromise: isNativePromise, - negativeNumber: isNegativeNumber, - nodeStream: isNodeStream, - nonEmptyArray: isNonEmptyArray, - nonEmptyMap: isNonEmptyMap, - nonEmptyObject: isNonEmptyObject, - nonEmptySet: isNonEmptySet, - nonEmptyString: isNonEmptyString, - nonEmptyStringAndNotWhitespace: isNonEmptyStringAndNotWhitespace, - null: isNull, - nullOrUndefined: isNullOrUndefined, - number: isNumber, - numericString: isNumericString, - object: isObject, - observable: isObservable, - oddInteger: isOddInteger, - plainObject: isPlainObject, - positiveNumber: isPositiveNumber, - primitive: isPrimitive, - promise: isPromise, - propertyKey: isPropertyKey, - regExp: isRegExp, - safeInteger: isSafeInteger, - set: isSet, - sharedArrayBuffer: isSharedArrayBuffer, - string: isString, - symbol: isSymbol, - truthy: isTruthy, - tupleLike: isTupleLike, - typedArray: isTypedArray, - uint16Array: isUint16Array, - uint32Array: isUint32Array, - uint8Array: isUint8Array, - uint8ClampedArray: isUint8ClampedArray, - undefined: isUndefined, - urlInstance: isUrlInstance, - urlSearchParams: isUrlSearchParams, - urlString: isUrlString, - validDate: isValidDate, - validLength: isValidLength, - weakMap: isWeakMap, - weakRef: isWeakRef, - weakSet: isWeakSet, - whitespaceString: isWhitespaceString, -}); -function isAbsoluteModule2(remainder) { - return (value) => isInteger(value) && Math.abs(value % 2) === remainder; -} -function isAll(predicate, ...values) { - return predicateOnArray(Array.prototype.every, predicate, values); -} -function isAny(predicate, ...values) { - const predicates = isArray(predicate) ? predicate : [predicate]; - return predicates.some(singlePredicate => predicateOnArray(Array.prototype.some, singlePredicate, values)); } -function isArray(value, assertion) { - if (!Array.isArray(value)) { - return false; - } - if (!isFunction(assertion)) { - return true; +function assertArrayBuffer(value, message) { + if (!isArrayBuffer(value)) { + throw new TypeError(message ?? typeErrorMessage('ArrayBuffer', value)); } - // eslint-disable-next-line @typescript-eslint/no-unsafe-argument - return value.every(element => assertion(element)); -} -function isArrayBuffer(value) { - return getObjectType(value) === 'ArrayBuffer'; } -function isArrayLike(value) { - return !isNullOrUndefined(value) && !isFunction(value) && isValidLength(value.length); +function assertArrayLike(value, message) { + if (!isArrayLike(value)) { + throw new TypeError(message ?? typeErrorMessage('array-like', value)); + } } -function isAsyncFunction(value) { - return getObjectType(value) === 'AsyncFunction'; +// eslint-disable-next-line @typescript-eslint/ban-types +function assertAsyncFunction(value, message) { + if (!isAsyncFunction(value)) { + throw new TypeError(message ?? typeErrorMessage('AsyncFunction', value)); + } } -function isAsyncGenerator(value) { - return isAsyncIterable(value) && isFunction(value.next) && isFunction(value.throw); +function assertAsyncGenerator(value, message) { + if (!isAsyncGenerator(value)) { + throw new TypeError(message ?? typeErrorMessage('AsyncGenerator', value)); + } } -function isAsyncGeneratorFunction(value) { - return getObjectType(value) === 'AsyncGeneratorFunction'; +function assertAsyncGeneratorFunction(value, message) { + if (!isAsyncGeneratorFunction(value)) { + throw new TypeError(message ?? typeErrorMessage('AsyncGeneratorFunction', value)); + } } -function isAsyncIterable(value) { - return isFunction(value?.[Symbol.asyncIterator]); +function assertAsyncIterable(value, message) { + if (!isAsyncIterable(value)) { + throw new TypeError(message ?? typeErrorMessage('AsyncIterable', value)); + } } -function isBigint(value) { - return typeof value === 'bigint'; +function assertBigint(value, message) { + if (!isBigint(value)) { + throw new TypeError(message ?? typeErrorMessage('bigint', value)); + } } -function isBigInt64Array(value) { - return getObjectType(value) === 'BigInt64Array'; +function assertBigInt64Array(value, message) { + if (!isBigInt64Array(value)) { + throw new TypeError(message ?? typeErrorMessage('BigInt64Array', value)); + } } -function isBigUint64Array(value) { - return getObjectType(value) === 'BigUint64Array'; +function assertBigUint64Array(value, message) { + if (!isBigUint64Array(value)) { + throw new TypeError(message ?? typeErrorMessage('BigUint64Array', value)); + } } -function isBlob(value) { - return getObjectType(value) === 'Blob'; +function assertBlob(value, message) { + if (!isBlob(value)) { + throw new TypeError(message ?? typeErrorMessage('Blob', value)); + } } -function isBoolean(value) { - return value === true || value === false; +function assertBoolean(value, message) { + if (!isBoolean(value)) { + throw new TypeError(message ?? typeErrorMessage('boolean', value)); + } } // eslint-disable-next-line @typescript-eslint/ban-types -function isBoundFunction(value) { - return isFunction(value) && !Object.hasOwn(value, 'prototype'); +function assertBoundFunction(value, message) { + if (!isBoundFunction(value)) { + throw new TypeError(message ?? typeErrorMessage('Function', value)); + } } /** Note: [Prefer using `Uint8Array` instead of `Buffer`.](https://sindresorhus.com/blog/goodbye-nodejs-buffer) */ -function isBuffer(value) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-call - return value?.constructor?.isBuffer?.(value) ?? false; +function assertBuffer(value, message) { + if (!isBuffer(value)) { + throw new TypeError(message ?? typeErrorMessage('Buffer', value)); + } } -function isClass(value) { - return isFunction(value) && value.toString().startsWith('class '); +function assertClass(value, message) { + if (!isClass(value)) { + throw new TypeError(message ?? typeErrorMessage('Class', value)); + } } -function isDataView(value) { - return getObjectType(value) === 'DataView'; +function assertDataView(value, message) { + if (!isDataView(value)) { + throw new TypeError(message ?? typeErrorMessage('DataView', value)); + } } -function isDate(value) { - return getObjectType(value) === 'Date'; +function assertDate(value, message) { + if (!isDate(value)) { + throw new TypeError(message ?? typeErrorMessage('Date', value)); + } } -function isDirectInstanceOf(instance, class_) { - if (instance === undefined || instance === null) { - return false; +function assertDirectInstanceOf(instance, class_, message) { + if (!isDirectInstanceOf(instance, class_)) { + throw new TypeError(message ?? typeErrorMessage('T', instance)); } - return Object.getPrototypeOf(instance) === class_.prototype; } -function isEmptyArray(value) { - return isArray(value) && value.length === 0; +function assertEmptyArray(value, message) { + if (!isEmptyArray(value)) { + throw new TypeError(message ?? typeErrorMessage('empty array', value)); + } } -function isEmptyMap(value) { - return isMap(value) && value.size === 0; +function assertEmptyMap(value, message) { + if (!isEmptyMap(value)) { + throw new TypeError(message ?? typeErrorMessage('empty map', value)); + } } -function isEmptyObject(value) { - return isObject(value) && !isMap(value) && !isSet(value) && Object.keys(value).length === 0; +function assertEmptyObject(value, message) { + if (!isEmptyObject(value)) { + throw new TypeError(message ?? typeErrorMessage('empty object', value)); + } } -function isEmptySet(value) { - return isSet(value) && value.size === 0; +function assertEmptySet(value, message) { + if (!isEmptySet(value)) { + throw new TypeError(message ?? typeErrorMessage('empty set', value)); + } } -function isEmptyString(value) { - return isString(value) && value.length === 0; +function assertEmptyString(value, message) { + if (!isEmptyString(value)) { + throw new TypeError(message ?? typeErrorMessage('empty string', value)); + } } -function isEmptyStringOrWhitespace(value) { - return isEmptyString(value) || isWhitespaceString(value); +function assertEmptyStringOrWhitespace(value, message) { + if (!isEmptyStringOrWhitespace(value)) { + throw new TypeError(message ?? typeErrorMessage('empty string or whitespace', value)); + } } -function isEnumCase(value, targetEnum) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-argument - return Object.values(targetEnum).includes(value); +function assertEnumCase(value, targetEnum, message) { + if (!isEnumCase(value, targetEnum)) { + throw new TypeError(message ?? typeErrorMessage('EnumCase', value)); + } } -function isError(value) { - return getObjectType(value) === 'Error'; +function assertError(value, message) { + if (!isError(value)) { + throw new TypeError(message ?? typeErrorMessage('Error', value)); + } } -function isEvenInteger(value) { - return isAbsoluteModule2(0)(value); +function assertEvenInteger(value, message) { + if (!isEvenInteger(value)) { + throw new TypeError(message ?? typeErrorMessage('even integer', value)); + } } -// Example: `is.falsy = (value: unknown): value is (not true | 0 | '' | undefined | null) => Boolean(value);` -function isFalsy(value) { - return !value; +function assertFalsy(value, message) { + if (!isFalsy(value)) { + throw new TypeError(message ?? typeErrorMessage('falsy', value)); + } } -function isFloat32Array(value) { - return getObjectType(value) === 'Float32Array'; +function assertFloat32Array(value, message) { + if (!isFloat32Array(value)) { + throw new TypeError(message ?? typeErrorMessage('Float32Array', value)); + } } -function isFloat64Array(value) { - return getObjectType(value) === 'Float64Array'; +function assertFloat64Array(value, message) { + if (!isFloat64Array(value)) { + throw new TypeError(message ?? typeErrorMessage('Float64Array', value)); + } } -function isFormData(value) { - return getObjectType(value) === 'FormData'; +function assertFormData(value, message) { + if (!isFormData(value)) { + throw new TypeError(message ?? typeErrorMessage('FormData', value)); + } } // eslint-disable-next-line @typescript-eslint/ban-types -function isFunction(value) { - return typeof value === 'function'; +function assertFunction(value, message) { + if (!isFunction(value)) { + throw new TypeError(message ?? typeErrorMessage('Function', value)); + } } -function isGenerator(value) { - return isIterable(value) && isFunction(value?.next) && isFunction(value?.throw); +function assertGenerator(value, message) { + if (!isGenerator(value)) { + throw new TypeError(message ?? typeErrorMessage('Generator', value)); + } } -function isGeneratorFunction(value) { - return getObjectType(value) === 'GeneratorFunction'; +function assertGeneratorFunction(value, message) { + if (!isGeneratorFunction(value)) { + throw new TypeError(message ?? typeErrorMessage('GeneratorFunction', value)); + } } -// eslint-disable-next-line @typescript-eslint/naming-convention -const NODE_TYPE_ELEMENT = 1; -// eslint-disable-next-line @typescript-eslint/naming-convention -const DOM_PROPERTIES_TO_CHECK = [ - 'innerHTML', - 'ownerDocument', - 'style', - 'attributes', - 'nodeValue', -]; -function isHtmlElement(value) { - return isObject(value) - && value.nodeType === NODE_TYPE_ELEMENT - && isString(value.nodeName) - && !isPlainObject(value) - && DOM_PROPERTIES_TO_CHECK.every(property => property in value); +function assertHtmlElement(value, message) { + if (!isHtmlElement(value)) { + throw new TypeError(message ?? typeErrorMessage('HTMLElement', value)); + } +} +function assertInfinite(value, message) { + if (!isInfinite(value)) { + throw new TypeError(message ?? typeErrorMessage('infinite number', value)); + } +} +function assertInRange(value, range, message) { + if (!isInRange(value, range)) { + throw new TypeError(message ?? typeErrorMessage('in range', value)); + } +} +function assertInt16Array(value, message) { + if (!isInt16Array(value)) { + throw new TypeError(message ?? typeErrorMessage('Int16Array', value)); + } +} +function assertInt32Array(value, message) { + if (!isInt32Array(value)) { + throw new TypeError(message ?? typeErrorMessage('Int32Array', value)); + } +} +function assertInt8Array(value, message) { + if (!isInt8Array(value)) { + throw new TypeError(message ?? typeErrorMessage('Int8Array', value)); + } } -function isInfinite(value) { - return value === Number.POSITIVE_INFINITY || value === Number.NEGATIVE_INFINITY; +function assertInteger(value, message) { + if (!isInteger(value)) { + throw new TypeError(message ?? typeErrorMessage('integer', value)); + } } -function isInRange(value, range) { - if (isNumber(range)) { - return value >= Math.min(0, range) && value <= Math.max(range, 0); +function assertIterable(value, message) { + if (!isIterable(value)) { + throw new TypeError(message ?? typeErrorMessage('Iterable', value)); } - if (isArray(range) && range.length === 2) { - return value >= Math.min(...range) && value <= Math.max(...range); +} +function assertMap(value, message) { + if (!isMap(value)) { + throw new TypeError(message ?? typeErrorMessage('Map', value)); } - throw new TypeError(`Invalid range: ${JSON.stringify(range)}`); } -function isInt16Array(value) { - return getObjectType(value) === 'Int16Array'; +function assertNan(value, message) { + if (!isNan(value)) { + throw new TypeError(message ?? typeErrorMessage('NaN', value)); + } } -function isInt32Array(value) { - return getObjectType(value) === 'Int32Array'; +function assertNativePromise(value, message) { + if (!isNativePromise(value)) { + throw new TypeError(message ?? typeErrorMessage('native Promise', value)); + } } -function isInt8Array(value) { - return getObjectType(value) === 'Int8Array'; +function assertNegativeNumber(value, message) { + if (!isNegativeNumber(value)) { + throw new TypeError(message ?? typeErrorMessage('negative number', value)); + } } -function isInteger(value) { - return Number.isInteger(value); +function assertNodeStream(value, message) { + if (!isNodeStream(value)) { + throw new TypeError(message ?? typeErrorMessage('Node.js Stream', value)); + } } -function isIterable(value) { - return isFunction(value?.[Symbol.iterator]); +function assertNonEmptyArray(value, message) { + if (!isNonEmptyArray(value)) { + throw new TypeError(message ?? typeErrorMessage('non-empty array', value)); + } } -function isMap(value) { - return getObjectType(value) === 'Map'; +function assertNonEmptyMap(value, message) { + if (!isNonEmptyMap(value)) { + throw new TypeError(message ?? typeErrorMessage('non-empty map', value)); + } } -function isNan(value) { - return Number.isNaN(value); +function assertNonEmptyObject(value, message) { + if (!isNonEmptyObject(value)) { + throw new TypeError(message ?? typeErrorMessage('non-empty object', value)); + } } -function isNativePromise(value) { - return getObjectType(value) === 'Promise'; +function assertNonEmptySet(value, message) { + if (!isNonEmptySet(value)) { + throw new TypeError(message ?? typeErrorMessage('non-empty set', value)); + } } -function isNegativeNumber(value) { - return isNumber(value) && value < 0; +function assertNonEmptyString(value, message) { + if (!isNonEmptyString(value)) { + throw new TypeError(message ?? typeErrorMessage('non-empty string', value)); + } } -function isNodeStream(value) { - return isObject(value) && isFunction(value.pipe) && !isObservable(value); +function assertNonEmptyStringAndNotWhitespace(value, message) { + if (!isNonEmptyStringAndNotWhitespace(value)) { + throw new TypeError(message ?? typeErrorMessage('non-empty string and not whitespace', value)); + } } -function isNonEmptyArray(value) { - return isArray(value) && value.length > 0; +// eslint-disable-next-line @typescript-eslint/ban-types +function assertNull(value, message) { + if (!isNull(value)) { + throw new TypeError(message ?? typeErrorMessage('null', value)); + } } -function isNonEmptyMap(value) { - return isMap(value) && value.size > 0; +// eslint-disable-next-line @typescript-eslint/ban-types +function assertNullOrUndefined(value, message) { + if (!isNullOrUndefined(value)) { + throw new TypeError(message ?? typeErrorMessage('null or undefined', value)); + } } -// TODO: Use `not` operator here to remove `Map` and `Set` from type guard: -// - https://github.com/Microsoft/TypeScript/pull/29317 -function isNonEmptyObject(value) { - return isObject(value) && !isMap(value) && !isSet(value) && Object.keys(value).length > 0; +function assertNumber(value, message) { + if (!isNumber(value)) { + throw new TypeError(message ?? typeErrorMessage('number', value)); + } } -function isNonEmptySet(value) { - return isSet(value) && value.size > 0; +function assertNumericString(value, message) { + if (!isNumericString(value)) { + throw new TypeError(message ?? typeErrorMessage('string with a number', value)); + } } -// TODO: Use `not ''` when the `not` operator is available. -function isNonEmptyString(value) { - return isString(value) && value.length > 0; +// eslint-disable-next-line @typescript-eslint/ban-types +function assertObject(value, message) { + if (!isObject(value)) { + throw new TypeError(message ?? typeErrorMessage('Object', value)); + } } -// TODO: Use `not ''` when the `not` operator is available. -function isNonEmptyStringAndNotWhitespace(value) { - return isString(value) && !isEmptyStringOrWhitespace(value); +function assertObservable(value, message) { + if (!isObservable(value)) { + throw new TypeError(message ?? typeErrorMessage('Observable', value)); + } } -// eslint-disable-next-line @typescript-eslint/ban-types -function isNull(value) { - return value === null; +function assertOddInteger(value, message) { + if (!isOddInteger(value)) { + throw new TypeError(message ?? typeErrorMessage('odd integer', value)); + } } -// eslint-disable-next-line @typescript-eslint/ban-types -function isNullOrUndefined(value) { - return isNull(value) || isUndefined(value); +function assertPlainObject(value, message) { + if (!isPlainObject(value)) { + throw new TypeError(message ?? typeErrorMessage('plain object', value)); + } } -function isNumber(value) { - return typeof value === 'number' && !Number.isNaN(value); +function assertPositiveNumber(value, message) { + if (!isPositiveNumber(value)) { + throw new TypeError(message ?? typeErrorMessage('positive number', value)); + } } -function isNumericString(value) { - return isString(value) && !isEmptyStringOrWhitespace(value) && !Number.isNaN(Number(value)); +function assertPrimitive(value, message) { + if (!isPrimitive(value)) { + throw new TypeError(message ?? typeErrorMessage('primitive', value)); + } } -// eslint-disable-next-line @typescript-eslint/ban-types -function isObject(value) { - return !isNull(value) && (typeof value === 'object' || isFunction(value)); +function assertPromise(value, message) { + if (!isPromise(value)) { + throw new TypeError(message ?? typeErrorMessage('Promise', value)); + } } -function isObservable(value) { - if (!value) { - return false; +function assertPropertyKey(value, message) { + if (!isPropertyKey(value)) { + throw new TypeError(message ?? typeErrorMessage('PropertyKey', value)); } - // eslint-disable-next-line no-use-extend-native/no-use-extend-native, @typescript-eslint/no-unsafe-call - if (value === value[Symbol.observable]?.()) { - return true; +} +function assertRegExp(value, message) { + if (!isRegExp(value)) { + throw new TypeError(message ?? typeErrorMessage('RegExp', value)); } - // eslint-disable-next-line @typescript-eslint/no-unsafe-call - if (value === value['@@observable']?.()) { - return true; +} +function assertSafeInteger(value, message) { + if (!isSafeInteger(value)) { + throw new TypeError(message ?? typeErrorMessage('integer', value)); } - return false; } -function isOddInteger(value) { - return isAbsoluteModule2(1)(value); +function assertSet(value, message) { + if (!isSet(value)) { + throw new TypeError(message ?? typeErrorMessage('Set', value)); + } } -function isPlainObject(value) { - // From: https://github.com/sindresorhus/is-plain-obj/blob/main/index.js - if (typeof value !== 'object' || value === null) { - return false; +function assertSharedArrayBuffer(value, message) { + if (!isSharedArrayBuffer(value)) { + throw new TypeError(message ?? typeErrorMessage('SharedArrayBuffer', value)); } - // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment - const prototype = Object.getPrototypeOf(value); - return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value) && !(Symbol.iterator in value); } -function isPositiveNumber(value) { - return isNumber(value) && value > 0; +function assertString(value, message) { + if (!isString(value)) { + throw new TypeError(message ?? typeErrorMessage('string', value)); + } } -function isPrimitive(value) { - return isNull(value) || isPrimitiveTypeName(typeof value); +function assertSymbol(value, message) { + if (!isSymbol(value)) { + throw new TypeError(message ?? typeErrorMessage('symbol', value)); + } } -function isPromise(value) { - return isNativePromise(value) || hasPromiseApi(value); +function assertTruthy(value, message) { + if (!isTruthy(value)) { + throw new TypeError(message ?? typeErrorMessage('truthy', value)); + } } -// `PropertyKey` is any value that can be used as an object key (string, number, or symbol) -function isPropertyKey(value) { - return isAny([isString, isNumber, isSymbol], value); +function assertTupleLike(value, guards, message) { + if (!isTupleLike(value, guards)) { + throw new TypeError(message ?? typeErrorMessage('tuple-like', value)); + } } -function isRegExp(value) { - return getObjectType(value) === 'RegExp'; +function assertTypedArray(value, message) { + if (!isTypedArray(value)) { + throw new TypeError(message ?? typeErrorMessage('TypedArray', value)); + } } -function isSafeInteger(value) { - return Number.isSafeInteger(value); +function assertUint16Array(value, message) { + if (!isUint16Array(value)) { + throw new TypeError(message ?? typeErrorMessage('Uint16Array', value)); + } } -function isSet(value) { - return getObjectType(value) === 'Set'; +function assertUint32Array(value, message) { + if (!isUint32Array(value)) { + throw new TypeError(message ?? typeErrorMessage('Uint32Array', value)); + } } -function isSharedArrayBuffer(value) { - return getObjectType(value) === 'SharedArrayBuffer'; +function assertUint8Array(value, message) { + if (!isUint8Array(value)) { + throw new TypeError(message ?? typeErrorMessage('Uint8Array', value)); + } } -function isString(value) { - return typeof value === 'string'; +function assertUint8ClampedArray(value, message) { + if (!isUint8ClampedArray(value)) { + throw new TypeError(message ?? typeErrorMessage('Uint8ClampedArray', value)); + } } -function isSymbol(value) { - return typeof value === 'symbol'; +function assertUndefined(value, message) { + if (!isUndefined(value)) { + throw new TypeError(message ?? typeErrorMessage('undefined', value)); + } } -// Example: `is.truthy = (value: unknown): value is (not false | not 0 | not '' | not undefined | not null) => Boolean(value);` -// eslint-disable-next-line unicorn/prefer-native-coercion-functions -function isTruthy(value) { - return Boolean(value); +function assertUrlInstance(value, message) { + if (!isUrlInstance(value)) { + throw new TypeError(message ?? typeErrorMessage('URL', value)); + } } -function isTupleLike(value, guards) { - if (isArray(guards) && isArray(value) && guards.length === value.length) { - return guards.every((guard, index) => guard(value[index])); +// eslint-disable-next-line unicorn/prevent-abbreviations +function assertUrlSearchParams(value, message) { + if (!isUrlSearchParams(value)) { + throw new TypeError(message ?? typeErrorMessage('URLSearchParams', value)); } - return false; } -function isTypedArray(value) { - return isTypedArrayName(getObjectType(value)); +function assertUrlString(value, message) { + if (!isUrlString(value)) { + throw new TypeError(message ?? typeErrorMessage('string with a URL', value)); + } } -function isUint16Array(value) { - return getObjectType(value) === 'Uint16Array'; +function assertValidDate(value, message) { + if (!isValidDate(value)) { + throw new TypeError(message ?? typeErrorMessage('valid Date', value)); + } } -function isUint32Array(value) { - return getObjectType(value) === 'Uint32Array'; +function assertValidLength(value, message) { + if (!isValidLength(value)) { + throw new TypeError(message ?? typeErrorMessage('valid length', value)); + } } -function isUint8Array(value) { - return getObjectType(value) === 'Uint8Array'; +// eslint-disable-next-line @typescript-eslint/ban-types +function assertWeakMap(value, message) { + if (!isWeakMap(value)) { + throw new TypeError(message ?? typeErrorMessage('WeakMap', value)); + } } -function isUint8ClampedArray(value) { - return getObjectType(value) === 'Uint8ClampedArray'; +// eslint-disable-next-line @typescript-eslint/ban-types, unicorn/prevent-abbreviations +function assertWeakRef(value, message) { + if (!isWeakRef(value)) { + throw new TypeError(message ?? typeErrorMessage('WeakRef', value)); + } } -function isUndefined(value) { - return value === undefined; +// eslint-disable-next-line @typescript-eslint/ban-types +function assertWeakSet(value, message) { + if (!isWeakSet(value)) { + throw new TypeError(message ?? typeErrorMessage('WeakSet', value)); + } } -function isUrlInstance(value) { - return getObjectType(value) === 'URL'; +function assertWhitespaceString(value, message) { + if (!isWhitespaceString(value)) { + throw new TypeError(message ?? typeErrorMessage('whitespace string', value)); + } } -// eslint-disable-next-line unicorn/prevent-abbreviations -function isUrlSearchParams(value) { - return getObjectType(value) === 'URLSearchParams'; +/* harmony default export */ const distribution = (is); + +// EXTERNAL MODULE: external "node:events" +var external_node_events_ = __nccwpck_require__(5673); +;// CONCATENATED MODULE: ./node_modules/.pnpm/p-cancelable@4.0.1/node_modules/p-cancelable/index.js +class CancelError extends Error { + constructor(reason) { + super(reason || 'Promise was canceled'); + this.name = 'CancelError'; + } + + get isCanceled() { + return true; + } } -function isUrlString(value) { - if (!isString(value)) { - return false; + +const promiseState = Object.freeze({ + pending: Symbol('pending'), + canceled: Symbol('canceled'), + resolved: Symbol('resolved'), + rejected: Symbol('rejected'), +}); + +class PCancelable { + static fn(userFunction) { + return (...arguments_) => new PCancelable((resolve, reject, onCancel) => { + arguments_.push(onCancel); + userFunction(...arguments_).then(resolve, reject); + }); + } + + #cancelHandlers = []; + #rejectOnCancel = true; + #state = promiseState.pending; + #promise; + #reject; + + constructor(executor) { + this.#promise = new Promise((resolve, reject) => { + this.#reject = reject; + + const onResolve = value => { + if (this.#state !== promiseState.canceled || !onCancel.shouldReject) { + resolve(value); + this.#setState(promiseState.resolved); + } + }; + + const onReject = error => { + if (this.#state !== promiseState.canceled || !onCancel.shouldReject) { + reject(error); + this.#setState(promiseState.rejected); + } + }; + + const onCancel = handler => { + if (this.#state !== promiseState.pending) { + throw new Error(`The \`onCancel\` handler was attached after the promise ${this.#state.description}.`); + } + + this.#cancelHandlers.push(handler); + }; + + Object.defineProperties(onCancel, { + shouldReject: { + get: () => this.#rejectOnCancel, + set: boolean => { + this.#rejectOnCancel = boolean; + }, + }, + }); + + executor(onResolve, onReject, onCancel); + }); + } + + // eslint-disable-next-line unicorn/no-thenable + then(onFulfilled, onRejected) { + return this.#promise.then(onFulfilled, onRejected); + } + + catch(onRejected) { + return this.#promise.catch(onRejected); + } + + finally(onFinally) { + return this.#promise.finally(onFinally); + } + + cancel(reason) { + if (this.#state !== promiseState.pending) { + return; + } + + this.#setState(promiseState.canceled); + + if (this.#cancelHandlers.length > 0) { + try { + for (const handler of this.#cancelHandlers) { + handler(); + } + } catch (error) { + this.#reject(error); + return; + } + } + + if (this.#rejectOnCancel) { + this.#reject(new CancelError(reason)); + } + } + + get isCanceled() { + return this.#state === promiseState.canceled; + } + + #setState(state) { + if (this.#state === promiseState.pending) { + this.#state = state; + } + } +} + +Object.setPrototypeOf(PCancelable.prototype, Promise.prototype); + +;// CONCATENATED MODULE: ./node_modules/.pnpm/got@14.4.4/node_modules/got/dist/source/core/errors.js + +// A hacky check to prevent circular references. +function isRequest(x) { + return distribution.object(x) && '_onResponse' in x; +} +/** +An error to be thrown when a request fails. +Contains a `code` property with error class code, like `ECONNREFUSED`. +*/ +class RequestError extends Error { + input; + code; + stack; + response; + request; + timings; + constructor(message, error, self) { + super(message, { cause: error }); + Error.captureStackTrace(this, this.constructor); + this.name = 'RequestError'; + this.code = error.code ?? 'ERR_GOT_REQUEST_ERROR'; + this.input = error.input; + if (isRequest(self)) { + Object.defineProperty(this, 'request', { + enumerable: false, + value: self, + }); + Object.defineProperty(this, 'response', { + enumerable: false, + value: self.response, + }); + this.options = self.options; + } + else { + this.options = self; + } + this.timings = this.request?.timings; + // Recover the original stacktrace + if (distribution.string(error.stack) && distribution.string(this.stack)) { + const indexOfMessage = this.stack.indexOf(this.message) + this.message.length; + const thisStackTrace = this.stack.slice(indexOfMessage).split('\n').reverse(); + const errorStackTrace = error.stack.slice(error.stack.indexOf(error.message) + error.message.length).split('\n').reverse(); + // Remove duplicated traces + while (errorStackTrace.length > 0 && errorStackTrace[0] === thisStackTrace[0]) { + thisStackTrace.shift(); + } + this.stack = `${this.stack.slice(0, indexOfMessage)}${thisStackTrace.reverse().join('\n')}${errorStackTrace.reverse().join('\n')}`; + } } - try { - new URL(value); // eslint-disable-line no-new - return true; +} +/** +An error to be thrown when the server redirects you more than ten times. +Includes a `response` property. +*/ +class MaxRedirectsError extends RequestError { + constructor(request) { + super(`Redirected ${request.options.maxRedirects} times. Aborting.`, {}, request); + this.name = 'MaxRedirectsError'; + this.code = 'ERR_TOO_MANY_REDIRECTS'; } - catch { - return false; +} +/** +An error to be thrown when the server response code is not 2xx nor 3xx if `options.followRedirect` is `true`, but always except for 304. +Includes a `response` property. +*/ +// TODO: Change `HTTPError` to `HTTPError` in the next major version to enforce type usage. +// eslint-disable-next-line @typescript-eslint/naming-convention +class HTTPError extends RequestError { + constructor(response) { + super(`Response code ${response.statusCode} (${response.statusMessage})`, {}, response.request); + this.name = 'HTTPError'; + this.code = 'ERR_NON_2XX_3XX_RESPONSE'; } } -function isValidDate(value) { - return isDate(value) && !isNan(Number(value)); +/** +An error to be thrown when a cache method fails. +For example, if the database goes down or there's a filesystem error. +*/ +class CacheError extends RequestError { + constructor(error, request) { + super(error.message, error, request); + this.name = 'CacheError'; + this.code = this.code === 'ERR_GOT_REQUEST_ERROR' ? 'ERR_CACHE_ACCESS' : this.code; + } } -function isValidLength(value) { - return isSafeInteger(value) && value >= 0; +/** +An error to be thrown when the request body is a stream and an error occurs while reading from that stream. +*/ +class UploadError extends RequestError { + constructor(error, request) { + super(error.message, error, request); + this.name = 'UploadError'; + this.code = this.code === 'ERR_GOT_REQUEST_ERROR' ? 'ERR_UPLOAD' : this.code; + } } -// eslint-disable-next-line @typescript-eslint/ban-types -function isWeakMap(value) { - return getObjectType(value) === 'WeakMap'; +/** +An error to be thrown when the request is aborted due to a timeout. +Includes an `event` and `timings` property. +*/ +class TimeoutError extends RequestError { + timings; + event; + constructor(error, timings, request) { + super(error.message, error, request); + this.name = 'TimeoutError'; + this.event = error.event; + this.timings = timings; + } } -// eslint-disable-next-line @typescript-eslint/ban-types, unicorn/prevent-abbreviations -function isWeakRef(value) { - return getObjectType(value) === 'WeakRef'; +/** +An error to be thrown when reading from response stream fails. +*/ +class ReadError extends RequestError { + constructor(error, request) { + super(error.message, error, request); + this.name = 'ReadError'; + this.code = this.code === 'ERR_GOT_REQUEST_ERROR' ? 'ERR_READING_RESPONSE_STREAM' : this.code; + } } -// eslint-disable-next-line @typescript-eslint/ban-types -function isWeakSet(value) { - return getObjectType(value) === 'WeakSet'; +/** +An error which always triggers a new retry when thrown. +*/ +class RetryError extends RequestError { + constructor(request) { + super('Retrying', {}, request); + this.name = 'RetryError'; + this.code = 'ERR_RETRYING'; + } } -function isWhitespaceString(value) { - return isString(value) && /^\s+$/.test(value); +/** +An error to be thrown when the request is aborted by AbortController. +*/ +class AbortError extends RequestError { + constructor(request) { + super('This operation was aborted.', {}, request); + this.code = 'ERR_ABORTED'; + this.name = 'AbortError'; + } } -function predicateOnArray(method, predicate, values) { - if (!isFunction(predicate)) { - throw new TypeError(`Invalid predicate: ${JSON.stringify(predicate)}`); + +// EXTERNAL MODULE: external "node:process" +var external_node_process_ = __nccwpck_require__(7742); +;// CONCATENATED MODULE: external "node:buffer" +const external_node_buffer_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:buffer"); +// EXTERNAL MODULE: external "node:stream" +var external_node_stream_ = __nccwpck_require__(4492); +// EXTERNAL MODULE: external "node:http" +var external_node_http_ = __nccwpck_require__(8849); +// EXTERNAL MODULE: external "events" +var external_events_ = __nccwpck_require__(2361); +// EXTERNAL MODULE: external "util" +var external_util_ = __nccwpck_require__(3837); +// EXTERNAL MODULE: ./node_modules/.pnpm/defer-to-connect@2.0.1/node_modules/defer-to-connect/dist/source/index.js +var source = __nccwpck_require__(6906); +;// CONCATENATED MODULE: ./node_modules/.pnpm/@szmarczak+http-timer@5.0.1/node_modules/@szmarczak/http-timer/dist/source/index.js + + + +const timer = (request) => { + if (request.timings) { + return request.timings; } - if (values.length === 0) { - throw new TypeError('Invalid number of values'); + const timings = { + start: Date.now(), + socket: undefined, + lookup: undefined, + connect: undefined, + secureConnect: undefined, + upload: undefined, + response: undefined, + end: undefined, + error: undefined, + abort: undefined, + phases: { + wait: undefined, + dns: undefined, + tcp: undefined, + tls: undefined, + request: undefined, + firstByte: undefined, + download: undefined, + total: undefined, + }, + }; + request.timings = timings; + const handleError = (origin) => { + origin.once(external_events_.errorMonitor, () => { + timings.error = Date.now(); + timings.phases.total = timings.error - timings.start; + }); + }; + handleError(request); + const onAbort = () => { + timings.abort = Date.now(); + timings.phases.total = timings.abort - timings.start; + }; + request.prependOnceListener('abort', onAbort); + const onSocket = (socket) => { + timings.socket = Date.now(); + timings.phases.wait = timings.socket - timings.start; + if (external_util_.types.isProxy(socket)) { + return; + } + const lookupListener = () => { + timings.lookup = Date.now(); + timings.phases.dns = timings.lookup - timings.socket; + }; + socket.prependOnceListener('lookup', lookupListener); + source(socket, { + connect: () => { + timings.connect = Date.now(); + if (timings.lookup === undefined) { + socket.removeListener('lookup', lookupListener); + timings.lookup = timings.connect; + timings.phases.dns = timings.lookup - timings.socket; + } + timings.phases.tcp = timings.connect - timings.lookup; + }, + secureConnect: () => { + timings.secureConnect = Date.now(); + timings.phases.tls = timings.secureConnect - timings.connect; + }, + }); + }; + if (request.socket) { + onSocket(request.socket); } - return method.call(values, predicate); -} -function typeErrorMessage(description, value) { - return `Expected value which is \`${description}\`, received value of type \`${is(value)}\`.`; -} -function unique(values) { - // eslint-disable-next-line unicorn/prefer-spread - return Array.from(new Set(values)); + else { + request.prependOnceListener('socket', onSocket); + } + const onUpload = () => { + timings.upload = Date.now(); + timings.phases.request = timings.upload - (timings.secureConnect ?? timings.connect); + }; + if (request.writableFinished) { + onUpload(); + } + else { + request.prependOnceListener('finish', onUpload); + } + request.prependOnceListener('response', (response) => { + timings.response = Date.now(); + timings.phases.firstByte = timings.response - timings.upload; + response.timings = timings; + handleError(response); + response.prependOnceListener('end', () => { + request.off('abort', onAbort); + response.off('aborted', onAbort); + if (timings.phases.total) { + // Aborted or errored + return; + } + timings.end = Date.now(); + timings.phases.download = timings.end - timings.response; + timings.phases.total = timings.end - timings.start; + }); + response.prependOnceListener('aborted', onAbort); + }); + return timings; +}; +/* harmony default export */ const dist_source = (timer); + +;// CONCATENATED MODULE: external "node:url" +const external_node_url_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:url"); +;// CONCATENATED MODULE: ./node_modules/.pnpm/normalize-url@8.0.1/node_modules/normalize-url/index.js +// https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs +const DATA_URL_DEFAULT_MIME_TYPE = 'text/plain'; +const DATA_URL_DEFAULT_CHARSET = 'us-ascii'; + +const testParameter = (name, filters) => filters.some(filter => filter instanceof RegExp ? filter.test(name) : filter === name); + +const supportedProtocols = new Set([ + 'https:', + 'http:', + 'file:', +]); + +const hasCustomProtocol = urlString => { + try { + const {protocol} = new URL(urlString); + + return protocol.endsWith(':') + && !protocol.includes('.') + && !supportedProtocols.has(protocol); + } catch { + return false; + } +}; + +const normalizeDataURL = (urlString, {stripHash}) => { + const match = /^data:(?[^,]*?),(?[^#]*?)(?:#(?.*))?$/.exec(urlString); + + if (!match) { + throw new Error(`Invalid URL: ${urlString}`); + } + + let {type, data, hash} = match.groups; + const mediaType = type.split(';'); + hash = stripHash ? '' : hash; + + let isBase64 = false; + if (mediaType[mediaType.length - 1] === 'base64') { + mediaType.pop(); + isBase64 = true; + } + + // Lowercase MIME type + const mimeType = mediaType.shift()?.toLowerCase() ?? ''; + const attributes = mediaType + .map(attribute => { + let [key, value = ''] = attribute.split('=').map(string => string.trim()); + + // Lowercase `charset` + if (key === 'charset') { + value = value.toLowerCase(); + + if (value === DATA_URL_DEFAULT_CHARSET) { + return ''; + } + } + + return `${key}${value ? `=${value}` : ''}`; + }) + .filter(Boolean); + + const normalizedMediaType = [ + ...attributes, + ]; + + if (isBase64) { + normalizedMediaType.push('base64'); + } + + if (normalizedMediaType.length > 0 || (mimeType && mimeType !== DATA_URL_DEFAULT_MIME_TYPE)) { + normalizedMediaType.unshift(mimeType); + } + + return `data:${normalizedMediaType.join(';')},${isBase64 ? data.trim() : data}${hash ? `#${hash}` : ''}`; +}; + +function normalizeUrl(urlString, options) { + options = { + defaultProtocol: 'http', + normalizeProtocol: true, + forceHttp: false, + forceHttps: false, + stripAuthentication: true, + stripHash: false, + stripTextFragment: true, + stripWWW: true, + removeQueryParameters: [/^utm_\w+/i], + removeTrailingSlash: true, + removeSingleSlash: true, + removeDirectoryIndex: false, + removeExplicitPort: false, + sortQueryParameters: true, + ...options, + }; + + // Legacy: Append `:` to the protocol if missing. + if (typeof options.defaultProtocol === 'string' && !options.defaultProtocol.endsWith(':')) { + options.defaultProtocol = `${options.defaultProtocol}:`; + } + + urlString = urlString.trim(); + + // Data URL + if (/^data:/i.test(urlString)) { + return normalizeDataURL(urlString, options); + } + + if (hasCustomProtocol(urlString)) { + return urlString; + } + + const hasRelativeProtocol = urlString.startsWith('//'); + const isRelativeUrl = !hasRelativeProtocol && /^\.*\//.test(urlString); + + // Prepend protocol + if (!isRelativeUrl) { + urlString = urlString.replace(/^(?!(?:\w+:)?\/\/)|^\/\//, options.defaultProtocol); + } + + const urlObject = new URL(urlString); + + if (options.forceHttp && options.forceHttps) { + throw new Error('The `forceHttp` and `forceHttps` options cannot be used together'); + } + + if (options.forceHttp && urlObject.protocol === 'https:') { + urlObject.protocol = 'http:'; + } + + if (options.forceHttps && urlObject.protocol === 'http:') { + urlObject.protocol = 'https:'; + } + + // Remove auth + if (options.stripAuthentication) { + urlObject.username = ''; + urlObject.password = ''; + } + + // Remove hash + if (options.stripHash) { + urlObject.hash = ''; + } else if (options.stripTextFragment) { + urlObject.hash = urlObject.hash.replace(/#?:~:text.*?$/i, ''); + } + + // Remove duplicate slashes if not preceded by a protocol + // NOTE: This could be implemented using a single negative lookbehind + // regex, but we avoid that to maintain compatibility with older js engines + // which do not have support for that feature. + if (urlObject.pathname) { + // TODO: Replace everything below with `urlObject.pathname = urlObject.pathname.replace(/(? 0) { + let pathComponents = urlObject.pathname.split('/'); + const lastComponent = pathComponents[pathComponents.length - 1]; + + if (testParameter(lastComponent, options.removeDirectoryIndex)) { + pathComponents = pathComponents.slice(0, -1); + urlObject.pathname = pathComponents.slice(1).join('/') + '/'; + } + } + + if (urlObject.hostname) { + // Remove trailing dot + urlObject.hostname = urlObject.hostname.replace(/\.$/, ''); + + // Remove `www.` + if (options.stripWWW && /^www\.(?!www\.)[a-z\-\d]{1,63}\.[a-z.\-\d]{2,63}$/.test(urlObject.hostname)) { + // Each label should be max 63 at length (min: 1). + // Source: https://en.wikipedia.org/wiki/Hostname#Restrictions_on_valid_host_names + // Each TLD should be up to 63 characters long (min: 2). + // It is technically possible to have a single character TLD, but none currently exist. + urlObject.hostname = urlObject.hostname.replace(/^www\./, ''); + } + } + + // Remove query unwanted parameters + if (Array.isArray(options.removeQueryParameters)) { + // eslint-disable-next-line unicorn/no-useless-spread -- We are intentionally spreading to get a copy. + for (const key of [...urlObject.searchParams.keys()]) { + if (testParameter(key, options.removeQueryParameters)) { + urlObject.searchParams.delete(key); + } + } + } + + if (!Array.isArray(options.keepQueryParameters) && options.removeQueryParameters === true) { + urlObject.search = ''; + } + + // Keep wanted query parameters + if (Array.isArray(options.keepQueryParameters) && options.keepQueryParameters.length > 0) { + // eslint-disable-next-line unicorn/no-useless-spread -- We are intentionally spreading to get a copy. + for (const key of [...urlObject.searchParams.keys()]) { + if (!testParameter(key, options.keepQueryParameters)) { + urlObject.searchParams.delete(key); + } + } + } + + // Sort query parameters + if (options.sortQueryParameters) { + urlObject.searchParams.sort(); + + // Calling `.sort()` encodes the search parameters, so we need to decode them again. + try { + urlObject.search = decodeURIComponent(urlObject.search); + } catch {} + } + + if (options.removeTrailingSlash) { + urlObject.pathname = urlObject.pathname.replace(/\/$/, ''); + } + + // Remove an explicit port number, excluding a default port number, if applicable + if (options.removeExplicitPort && urlObject.port) { + urlObject.port = ''; + } + + const oldUrlString = urlString; + + // Take advantage of many of the Node `url` normalizations + urlString = urlObject.toString(); + + if (!options.removeSingleSlash && urlObject.pathname === '/' && !oldUrlString.endsWith('/') && urlObject.hash === '') { + urlString = urlString.replace(/\/$/, ''); + } + + // Remove ending `/` unless removeSingleSlash is false + if ((options.removeTrailingSlash || urlObject.pathname === '/') && urlObject.hash === '' && options.removeSingleSlash) { + urlString = urlString.replace(/\/$/, ''); + } + + // Restore relative protocol, if applicable + if (hasRelativeProtocol && !options.normalizeProtocol) { + urlString = urlString.replace(/^http:\/\//, '//'); + } + + // Remove http/https + if (options.stripProtocol) { + urlString = urlString.replace(/^(?:https?:)?\/\//, ''); + } + + return urlString; } -const andFormatter = new Intl.ListFormat('en', { style: 'long', type: 'conjunction' }); -const orFormatter = new Intl.ListFormat('en', { style: 'long', type: 'disjunction' }); -function typeErrorMessageMultipleValues(expectedType, values) { - const uniqueExpectedTypes = unique((isArray(expectedType) ? expectedType : [expectedType]).map(value => `\`${value}\``)); - const uniqueValueTypes = unique(values.map(value => `\`${is(value)}\``)); - return `Expected values which are ${orFormatter.format(uniqueExpectedTypes)}. Received values of type${uniqueValueTypes.length > 1 ? 's' : ''} ${andFormatter.format(uniqueValueTypes)}.`; + +;// CONCATENATED MODULE: ./node_modules/.pnpm/is-stream@4.0.1/node_modules/is-stream/index.js +function isStream(stream, {checkOpen = true} = {}) { + return stream !== null + && typeof stream === 'object' + && (stream.writable || stream.readable || !checkOpen || (stream.writable === undefined && stream.readable === undefined)) + && typeof stream.pipe === 'function'; } -const assert = { - all: assertAll, - any: assertAny, - array: assertArray, - arrayBuffer: assertArrayBuffer, - arrayLike: assertArrayLike, - asyncFunction: assertAsyncFunction, - asyncGenerator: assertAsyncGenerator, - asyncGeneratorFunction: assertAsyncGeneratorFunction, - asyncIterable: assertAsyncIterable, - bigint: assertBigint, - bigInt64Array: assertBigInt64Array, - bigUint64Array: assertBigUint64Array, - blob: assertBlob, - boolean: assertBoolean, - boundFunction: assertBoundFunction, - buffer: assertBuffer, - class: assertClass, - dataView: assertDataView, - date: assertDate, - directInstanceOf: assertDirectInstanceOf, - emptyArray: assertEmptyArray, - emptyMap: assertEmptyMap, - emptyObject: assertEmptyObject, - emptySet: assertEmptySet, - emptyString: assertEmptyString, - emptyStringOrWhitespace: assertEmptyStringOrWhitespace, - enumCase: assertEnumCase, - error: assertError, - evenInteger: assertEvenInteger, - falsy: assertFalsy, - float32Array: assertFloat32Array, - float64Array: assertFloat64Array, - formData: assertFormData, - function: assertFunction, - generator: assertGenerator, - generatorFunction: assertGeneratorFunction, - htmlElement: assertHtmlElement, - infinite: assertInfinite, - inRange: assertInRange, - int16Array: assertInt16Array, - int32Array: assertInt32Array, - int8Array: assertInt8Array, - integer: assertInteger, - iterable: assertIterable, - map: assertMap, - nan: assertNan, - nativePromise: assertNativePromise, - negativeNumber: assertNegativeNumber, - nodeStream: assertNodeStream, - nonEmptyArray: assertNonEmptyArray, - nonEmptyMap: assertNonEmptyMap, - nonEmptyObject: assertNonEmptyObject, - nonEmptySet: assertNonEmptySet, - nonEmptyString: assertNonEmptyString, - nonEmptyStringAndNotWhitespace: assertNonEmptyStringAndNotWhitespace, - null: assertNull, - nullOrUndefined: assertNullOrUndefined, - number: assertNumber, - numericString: assertNumericString, - object: assertObject, - observable: assertObservable, - oddInteger: assertOddInteger, - plainObject: assertPlainObject, - positiveNumber: assertPositiveNumber, - primitive: assertPrimitive, - promise: assertPromise, - propertyKey: assertPropertyKey, - regExp: assertRegExp, - safeInteger: assertSafeInteger, - set: assertSet, - sharedArrayBuffer: assertSharedArrayBuffer, - string: assertString, - symbol: assertSymbol, - truthy: assertTruthy, - tupleLike: assertTupleLike, - typedArray: assertTypedArray, - uint16Array: assertUint16Array, - uint32Array: assertUint32Array, - uint8Array: assertUint8Array, - uint8ClampedArray: assertUint8ClampedArray, - undefined: assertUndefined, - urlInstance: assertUrlInstance, - urlSearchParams: assertUrlSearchParams, - urlString: assertUrlString, - validDate: assertValidDate, - validLength: assertValidLength, - weakMap: assertWeakMap, - weakRef: assertWeakRef, - weakSet: assertWeakSet, - whitespaceString: assertWhitespaceString, -}; -const methodTypeMap = { - isArray: 'Array', - isArrayBuffer: 'ArrayBuffer', - isArrayLike: 'array-like', - isAsyncFunction: 'AsyncFunction', - isAsyncGenerator: 'AsyncGenerator', - isAsyncGeneratorFunction: 'AsyncGeneratorFunction', - isAsyncIterable: 'AsyncIterable', - isBigint: 'bigint', - isBigInt64Array: 'BigInt64Array', - isBigUint64Array: 'BigUint64Array', - isBlob: 'Blob', - isBoolean: 'boolean', - isBoundFunction: 'Function', - isBuffer: 'Buffer', - isClass: 'Class', - isDataView: 'DataView', - isDate: 'Date', - isDirectInstanceOf: 'T', - isEmptyArray: 'empty array', - isEmptyMap: 'empty map', - isEmptyObject: 'empty object', - isEmptySet: 'empty set', - isEmptyString: 'empty string', - isEmptyStringOrWhitespace: 'empty string or whitespace', - isEnumCase: 'EnumCase', - isError: 'Error', - isEvenInteger: 'even integer', - isFalsy: 'falsy', - isFloat32Array: 'Float32Array', - isFloat64Array: 'Float64Array', - isFormData: 'FormData', - isFunction: 'Function', - isGenerator: 'Generator', - isGeneratorFunction: 'GeneratorFunction', - isHtmlElement: 'HTMLElement', - isInfinite: 'infinite number', - isInRange: 'in range', - isInt16Array: 'Int16Array', - isInt32Array: 'Int32Array', - isInt8Array: 'Int8Array', - isInteger: 'integer', - isIterable: 'Iterable', - isMap: 'Map', - isNan: 'NaN', - isNativePromise: 'native Promise', - isNegativeNumber: 'negative number', - isNodeStream: 'Node.js Stream', - isNonEmptyArray: 'non-empty array', - isNonEmptyMap: 'non-empty map', - isNonEmptyObject: 'non-empty object', - isNonEmptySet: 'non-empty set', - isNonEmptyString: 'non-empty string', - isNonEmptyStringAndNotWhitespace: 'non-empty string and not whitespace', - isNull: 'null', - isNullOrUndefined: 'null or undefined', - isNumber: 'number', - isNumericString: 'string with a number', - isObject: 'Object', - isObservable: 'Observable', - isOddInteger: 'odd integer', - isPlainObject: 'plain object', - isPositiveNumber: 'positive number', - isPrimitive: 'primitive', - isPromise: 'Promise', - isPropertyKey: 'PropertyKey', - isRegExp: 'RegExp', - isSafeInteger: 'integer', - isSet: 'Set', - isSharedArrayBuffer: 'SharedArrayBuffer', - isString: 'string', - isSymbol: 'symbol', - isTruthy: 'truthy', - isTupleLike: 'tuple-like', - isTypedArray: 'TypedArray', - isUint16Array: 'Uint16Array', - isUint32Array: 'Uint32Array', - isUint8Array: 'Uint8Array', - isUint8ClampedArray: 'Uint8ClampedArray', - isUndefined: 'undefined', - isUrlInstance: 'URL', - isUrlSearchParams: 'URLSearchParams', - isUrlString: 'string with a URL', - isValidDate: 'valid Date', - isValidLength: 'valid length', - isWeakMap: 'WeakMap', - isWeakRef: 'WeakRef', - isWeakSet: 'WeakSet', - isWhitespaceString: 'whitespace string', -}; -function keysOf(value) { - return Object.keys(value); + +function isWritableStream(stream, {checkOpen = true} = {}) { + return isStream(stream, {checkOpen}) + && (stream.writable || !checkOpen) + && typeof stream.write === 'function' + && typeof stream.end === 'function' + && typeof stream.writable === 'boolean' + && typeof stream.writableObjectMode === 'boolean' + && typeof stream.destroy === 'function' + && typeof stream.destroyed === 'boolean'; } -const isMethodNames = keysOf(methodTypeMap); -function isIsMethodName(value) { - return isMethodNames.includes(value); + +function isReadableStream(stream, {checkOpen = true} = {}) { + return isStream(stream, {checkOpen}) + && (stream.readable || !checkOpen) + && typeof stream.read === 'function' + && typeof stream.readable === 'boolean' + && typeof stream.readableObjectMode === 'boolean' + && typeof stream.destroy === 'function' + && typeof stream.destroyed === 'boolean'; } -function assertAll(predicate, ...values) { - if (!isAll(predicate, ...values)) { - const expectedType = isIsMethodName(predicate.name) ? methodTypeMap[predicate.name] : 'predicate returns truthy for all values'; - throw new TypeError(typeErrorMessageMultipleValues(expectedType, values)); - } + +function isDuplexStream(stream, options) { + return isWritableStream(stream, options) + && isReadableStream(stream, options); } -function assertAny(predicate, ...values) { - if (!isAny(predicate, ...values)) { - const predicates = isArray(predicate) ? predicate : [predicate]; - const expectedTypes = predicates.map(predicate => isIsMethodName(predicate.name) ? methodTypeMap[predicate.name] : 'predicate returns truthy for any value'); - throw new TypeError(typeErrorMessageMultipleValues(expectedTypes, values)); - } + +function isTransformStream(stream, options) { + return isDuplexStream(stream, options) + && typeof stream._transform === 'function'; } -function assertArray(value, assertion, message) { - if (!isArray(value)) { - throw new TypeError(message ?? typeErrorMessage('Array', value)); + +;// CONCATENATED MODULE: ./node_modules/.pnpm/@sec-ant+readable-stream@0.4.1/node_modules/@sec-ant/readable-stream/dist/ponyfill/asyncIterator.js +const a = Object.getPrototypeOf( + Object.getPrototypeOf( + /* istanbul ignore next */ + async function* () { } - if (assertion) { - // eslint-disable-next-line unicorn/no-array-for-each, unicorn/no-array-callback-reference - value.forEach(assertion); + ).prototype +); +class c { + #t; + #n; + #r = !1; + #e = void 0; + constructor(e, t) { + this.#t = e, this.#n = t; + } + next() { + const e = () => this.#s(); + return this.#e = this.#e ? this.#e.then(e, e) : e(), this.#e; + } + return(e) { + const t = () => this.#i(e); + return this.#e ? this.#e.then(t, t) : t(); + } + async #s() { + if (this.#r) + return { + done: !0, + value: void 0 + }; + let e; + try { + e = await this.#t.read(); + } catch (t) { + throw this.#e = void 0, this.#r = !0, this.#t.releaseLock(), t; } -} -function assertArrayBuffer(value, message) { - if (!isArrayBuffer(value)) { - throw new TypeError(message ?? typeErrorMessage('ArrayBuffer', value)); + return e.done && (this.#e = void 0, this.#r = !0, this.#t.releaseLock()), e; + } + async #i(e) { + if (this.#r) + return { + done: !0, + value: e + }; + if (this.#r = !0, !this.#n) { + const t = this.#t.cancel(e); + return this.#t.releaseLock(), await t, { + done: !0, + value: e + }; } + return this.#t.releaseLock(), { + done: !0, + value: e + }; + } } -function assertArrayLike(value, message) { - if (!isArrayLike(value)) { - throw new TypeError(message ?? typeErrorMessage('array-like', value)); - } +const n = Symbol(); +function i() { + return this[n].next(); } -// eslint-disable-next-line @typescript-eslint/ban-types -function assertAsyncFunction(value, message) { - if (!isAsyncFunction(value)) { - throw new TypeError(message ?? typeErrorMessage('AsyncFunction', value)); - } +Object.defineProperty(i, "name", { value: "next" }); +function o(r) { + return this[n].return(r); } -function assertAsyncGenerator(value, message) { - if (!isAsyncGenerator(value)) { - throw new TypeError(message ?? typeErrorMessage('AsyncGenerator', value)); - } +Object.defineProperty(o, "name", { value: "return" }); +const u = Object.create(a, { + next: { + enumerable: !0, + configurable: !0, + writable: !0, + value: i + }, + return: { + enumerable: !0, + configurable: !0, + writable: !0, + value: o + } +}); +function h({ preventCancel: r = !1 } = {}) { + const e = this.getReader(), t = new c( + e, + r + ), s = Object.create(u); + return s[n] = t, s; +} + + +;// CONCATENATED MODULE: ./node_modules/.pnpm/@sec-ant+readable-stream@0.4.1/node_modules/@sec-ant/readable-stream/dist/ponyfill/index.js + + + + +;// CONCATENATED MODULE: ./node_modules/.pnpm/get-stream@9.0.1/node_modules/get-stream/source/stream.js + + + +const getAsyncIterable = stream => { + if (isReadableStream(stream, {checkOpen: false}) && nodeImports.on !== undefined) { + return getStreamIterable(stream); + } + + if (typeof stream?.[Symbol.asyncIterator] === 'function') { + return stream; + } + + // `ReadableStream[Symbol.asyncIterator]` support is missing in multiple browsers, so we ponyfill it + if (stream_toString.call(stream) === '[object ReadableStream]') { + return h.call(stream); + } + + throw new TypeError('The first argument must be a Readable, a ReadableStream, or an async iterable.'); +}; + +const {toString: stream_toString} = Object.prototype; + +// The default iterable for Node.js streams does not allow for multiple readers at once, so we re-implement it +const getStreamIterable = async function * (stream) { + const controller = new AbortController(); + const state = {}; + handleStreamEnd(stream, controller, state); + + try { + for await (const [chunk] of nodeImports.on(stream, 'data', {signal: controller.signal})) { + yield chunk; + } + } catch (error) { + // Stream failure, for example due to `stream.destroy(error)` + if (state.error !== undefined) { + throw state.error; + // `error` event directly emitted on stream + } else if (!controller.signal.aborted) { + throw error; + // Otherwise, stream completed successfully + } + // The `finally` block also runs when the caller throws, for example due to the `maxBuffer` option + } finally { + stream.destroy(); + } +}; + +const handleStreamEnd = async (stream, controller, state) => { + try { + await nodeImports.finished(stream, { + cleanup: true, + readable: true, + writable: false, + error: false, + }); + } catch (error) { + state.error = error; + } finally { + controller.abort(); + } +}; + +// Loaded by the Node entrypoint, but not by the browser one. +// This prevents using dynamic imports. +const nodeImports = {}; + +;// CONCATENATED MODULE: ./node_modules/.pnpm/get-stream@9.0.1/node_modules/get-stream/source/contents.js + + +const getStreamContents = async (stream, {init, convertChunk, getSize, truncateChunk, addChunk, getFinalChunk, finalize}, {maxBuffer = Number.POSITIVE_INFINITY} = {}) => { + const asyncIterable = getAsyncIterable(stream); + + const state = init(); + state.length = 0; + + try { + for await (const chunk of asyncIterable) { + const chunkType = getChunkType(chunk); + const convertedChunk = convertChunk[chunkType](chunk, state); + appendChunk({ + convertedChunk, + state, + getSize, + truncateChunk, + addChunk, + maxBuffer, + }); + } + + appendFinalChunk({ + state, + convertChunk, + getSize, + truncateChunk, + addChunk, + getFinalChunk, + maxBuffer, + }); + return finalize(state); + } catch (error) { + const normalizedError = typeof error === 'object' && error !== null ? error : new Error(error); + normalizedError.bufferedData = finalize(state); + throw normalizedError; + } +}; + +const appendFinalChunk = ({state, getSize, truncateChunk, addChunk, getFinalChunk, maxBuffer}) => { + const convertedChunk = getFinalChunk(state); + if (convertedChunk !== undefined) { + appendChunk({ + convertedChunk, + state, + getSize, + truncateChunk, + addChunk, + maxBuffer, + }); + } +}; + +const appendChunk = ({convertedChunk, state, getSize, truncateChunk, addChunk, maxBuffer}) => { + const chunkSize = getSize(convertedChunk); + const newLength = state.length + chunkSize; + + if (newLength <= maxBuffer) { + addNewChunk(convertedChunk, state, addChunk, newLength); + return; + } + + const truncatedChunk = truncateChunk(convertedChunk, maxBuffer - state.length); + + if (truncatedChunk !== undefined) { + addNewChunk(truncatedChunk, state, addChunk, maxBuffer); + } + + throw new MaxBufferError(); +}; + +const addNewChunk = (convertedChunk, state, addChunk, newLength) => { + state.contents = addChunk(convertedChunk, state, newLength); + state.length = newLength; +}; + +const getChunkType = chunk => { + const typeOfChunk = typeof chunk; + + if (typeOfChunk === 'string') { + return 'string'; + } + + if (typeOfChunk !== 'object' || chunk === null) { + return 'others'; + } + + if (globalThis.Buffer?.isBuffer(chunk)) { + return 'buffer'; + } + + const prototypeName = objectToString.call(chunk); + + if (prototypeName === '[object ArrayBuffer]') { + return 'arrayBuffer'; + } + + if (prototypeName === '[object DataView]') { + return 'dataView'; + } + + if ( + Number.isInteger(chunk.byteLength) + && Number.isInteger(chunk.byteOffset) + && objectToString.call(chunk.buffer) === '[object ArrayBuffer]' + ) { + return 'typedArray'; + } + + return 'others'; +}; + +const {toString: objectToString} = Object.prototype; + +class MaxBufferError extends Error { + name = 'MaxBufferError'; + + constructor() { + super('maxBuffer exceeded'); + } } -function assertAsyncGeneratorFunction(value, message) { - if (!isAsyncGeneratorFunction(value)) { - throw new TypeError(message ?? typeErrorMessage('AsyncGeneratorFunction', value)); - } + +;// CONCATENATED MODULE: ./node_modules/.pnpm/get-stream@9.0.1/node_modules/get-stream/source/utils.js +const identity = value => value; + +const noop = () => undefined; + +const getContentsProperty = ({contents}) => contents; + +const throwObjectStream = chunk => { + throw new Error(`Streams in object mode are not supported: ${String(chunk)}`); +}; + +const getLengthProperty = convertedChunk => convertedChunk.length; + +;// CONCATENATED MODULE: ./node_modules/.pnpm/get-stream@9.0.1/node_modules/get-stream/source/array-buffer.js + + + +async function getStreamAsArrayBuffer(stream, options) { + return getStreamContents(stream, arrayBufferMethods, options); } -function assertAsyncIterable(value, message) { - if (!isAsyncIterable(value)) { - throw new TypeError(message ?? typeErrorMessage('AsyncIterable', value)); - } + +const initArrayBuffer = () => ({contents: new ArrayBuffer(0)}); + +const useTextEncoder = chunk => textEncoder.encode(chunk); +const textEncoder = new TextEncoder(); + +const useUint8Array = chunk => new Uint8Array(chunk); + +const useUint8ArrayWithOffset = chunk => new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength); + +const truncateArrayBufferChunk = (convertedChunk, chunkSize) => convertedChunk.slice(0, chunkSize); + +// `contents` is an increasingly growing `Uint8Array`. +const addArrayBufferChunk = (convertedChunk, {contents, length: previousLength}, length) => { + const newContents = hasArrayBufferResize() ? resizeArrayBuffer(contents, length) : resizeArrayBufferSlow(contents, length); + new Uint8Array(newContents).set(convertedChunk, previousLength); + return newContents; +}; + +// Without `ArrayBuffer.resize()`, `contents` size is always a power of 2. +// This means its last bytes are zeroes (not stream data), which need to be +// trimmed at the end with `ArrayBuffer.slice()`. +const resizeArrayBufferSlow = (contents, length) => { + if (length <= contents.byteLength) { + return contents; + } + + const arrayBuffer = new ArrayBuffer(getNewContentsLength(length)); + new Uint8Array(arrayBuffer).set(new Uint8Array(contents), 0); + return arrayBuffer; +}; + +// With `ArrayBuffer.resize()`, `contents` size matches exactly the size of +// the stream data. It does not include extraneous zeroes to trim at the end. +// The underlying `ArrayBuffer` does allocate a number of bytes that is a power +// of 2, but those bytes are only visible after calling `ArrayBuffer.resize()`. +const resizeArrayBuffer = (contents, length) => { + if (length <= contents.maxByteLength) { + contents.resize(length); + return contents; + } + + const arrayBuffer = new ArrayBuffer(length, {maxByteLength: getNewContentsLength(length)}); + new Uint8Array(arrayBuffer).set(new Uint8Array(contents), 0); + return arrayBuffer; +}; + +// Retrieve the closest `length` that is both >= and a power of 2 +const getNewContentsLength = length => SCALE_FACTOR ** Math.ceil(Math.log(length) / Math.log(SCALE_FACTOR)); + +const SCALE_FACTOR = 2; + +const finalizeArrayBuffer = ({contents, length}) => hasArrayBufferResize() ? contents : contents.slice(0, length); + +// `ArrayBuffer.slice()` is slow. When `ArrayBuffer.resize()` is available +// (Node >=20.0.0, Safari >=16.4 and Chrome), we can use it instead. +// eslint-disable-next-line no-warning-comments +// TODO: remove after dropping support for Node 20. +// eslint-disable-next-line no-warning-comments +// TODO: use `ArrayBuffer.transferToFixedLength()` instead once it is available +const hasArrayBufferResize = () => 'resize' in ArrayBuffer.prototype; + +const arrayBufferMethods = { + init: initArrayBuffer, + convertChunk: { + string: useTextEncoder, + buffer: useUint8Array, + arrayBuffer: useUint8Array, + dataView: useUint8ArrayWithOffset, + typedArray: useUint8ArrayWithOffset, + others: throwObjectStream, + }, + getSize: getLengthProperty, + truncateChunk: truncateArrayBufferChunk, + addChunk: addArrayBufferChunk, + getFinalChunk: noop, + finalize: finalizeArrayBuffer, +}; + +;// CONCATENATED MODULE: ./node_modules/.pnpm/get-stream@9.0.1/node_modules/get-stream/source/buffer.js + + +async function getStreamAsBuffer(stream, options) { + if (!('Buffer' in globalThis)) { + throw new Error('getStreamAsBuffer() is only supported in Node.js'); + } + + try { + return arrayBufferToNodeBuffer(await getStreamAsArrayBuffer(stream, options)); + } catch (error) { + if (error.bufferedData !== undefined) { + error.bufferedData = arrayBufferToNodeBuffer(error.bufferedData); + } + + throw error; + } } -function assertBigint(value, message) { - if (!isBigint(value)) { - throw new TypeError(message ?? typeErrorMessage('bigint', value)); - } + +const arrayBufferToNodeBuffer = arrayBuffer => globalThis.Buffer.from(arrayBuffer); + +// EXTERNAL MODULE: ./node_modules/.pnpm/http-cache-semantics@4.1.1/node_modules/http-cache-semantics/index.js +var http_cache_semantics = __nccwpck_require__(7893); +;// CONCATENATED MODULE: ./node_modules/.pnpm/lowercase-keys@3.0.0/node_modules/lowercase-keys/index.js +function lowercaseKeys(object) { + return Object.fromEntries(Object.entries(object).map(([key, value]) => [key.toLowerCase(), value])); } -function assertBigInt64Array(value, message) { - if (!isBigInt64Array(value)) { - throw new TypeError(message ?? typeErrorMessage('BigInt64Array', value)); - } + +;// CONCATENATED MODULE: ./node_modules/.pnpm/responselike@3.0.0/node_modules/responselike/index.js + + + +class Response extends external_node_stream_.Readable { + statusCode; + headers; + body; + url; + + constructor({statusCode, headers, body, url}) { + if (typeof statusCode !== 'number') { + throw new TypeError('Argument `statusCode` should be a number'); + } + + if (typeof headers !== 'object') { + throw new TypeError('Argument `headers` should be an object'); + } + + if (!(body instanceof Uint8Array)) { + throw new TypeError('Argument `body` should be a buffer'); + } + + if (typeof url !== 'string') { + throw new TypeError('Argument `url` should be a string'); + } + + super({ + read() { + this.push(body); + this.push(null); + }, + }); + + this.statusCode = statusCode; + this.headers = lowercaseKeys(headers); + this.body = body; + this.url = url; + } } -function assertBigUint64Array(value, message) { - if (!isBigUint64Array(value)) { - throw new TypeError(message ?? typeErrorMessage('BigUint64Array', value)); - } + +// EXTERNAL MODULE: ./node_modules/.pnpm/keyv@4.5.4/node_modules/keyv/src/index.js +var src = __nccwpck_require__(8534); +;// CONCATENATED MODULE: ./node_modules/.pnpm/mimic-response@4.0.0/node_modules/mimic-response/index.js +// We define these manually to ensure they're always copied +// even if they would move up the prototype chain +// https://nodejs.org/api/http.html#http_class_http_incomingmessage +const knownProperties = [ + 'aborted', + 'complete', + 'headers', + 'httpVersion', + 'httpVersionMinor', + 'httpVersionMajor', + 'method', + 'rawHeaders', + 'rawTrailers', + 'setTimeout', + 'socket', + 'statusCode', + 'statusMessage', + 'trailers', + 'url', +]; + +function mimicResponse(fromStream, toStream) { + if (toStream._readableState.autoDestroy) { + throw new Error('The second stream must have the `autoDestroy` option set to `false`'); + } + + const fromProperties = new Set([...Object.keys(fromStream), ...knownProperties]); + + const properties = {}; + + for (const property of fromProperties) { + // Don't overwrite existing properties. + if (property in toStream) { + continue; + } + + properties[property] = { + get() { + const value = fromStream[property]; + const isFunction = typeof value === 'function'; + + return isFunction ? value.bind(fromStream) : value; + }, + set(value) { + fromStream[property] = value; + }, + enumerable: true, + configurable: false, + }; + } + + Object.defineProperties(toStream, properties); + + fromStream.once('aborted', () => { + toStream.destroy(); + + toStream.emit('aborted'); + }); + + fromStream.once('close', () => { + if (fromStream.complete) { + if (toStream.readable) { + toStream.once('end', () => { + toStream.emit('close'); + }); + } else { + toStream.emit('close'); + } + } else { + toStream.emit('close'); + } + }); + + return toStream; } -function assertBlob(value, message) { - if (!isBlob(value)) { - throw new TypeError(message ?? typeErrorMessage('Blob', value)); + +;// CONCATENATED MODULE: ./node_modules/.pnpm/cacheable-request@12.0.1/node_modules/cacheable-request/dist/types.js +// Type definitions for cacheable-request 6.0 +// Project: https://github.com/lukechilds/cacheable-request#readme +// Definitions by: BendingBender +// Paul Melnikow +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 +class types_RequestError extends Error { + constructor(error) { + super(error.message); + Object.assign(this, error); } } -function assertBoolean(value, message) { - if (!isBoolean(value)) { - throw new TypeError(message ?? typeErrorMessage('boolean', value)); +class types_CacheError extends Error { + constructor(error) { + super(error.message); + Object.assign(this, error); } } -// eslint-disable-next-line @typescript-eslint/ban-types -function assertBoundFunction(value, message) { - if (!isBoundFunction(value)) { - throw new TypeError(message ?? typeErrorMessage('Function', value)); +//# sourceMappingURL=types.js.map +;// CONCATENATED MODULE: ./node_modules/.pnpm/cacheable-request@12.0.1/node_modules/cacheable-request/dist/index.js + + + + + + + + + + + +class CacheableRequest { + constructor(cacheRequest, cacheAdapter) { + this.hooks = new Map(); + this.request = () => (options, callback) => { + let url; + if (typeof options === 'string') { + url = normalizeUrlObject(external_node_url_namespaceObject.parse(options)); + options = {}; + } + else if (options instanceof external_node_url_namespaceObject.URL) { + url = normalizeUrlObject(external_node_url_namespaceObject.parse(options.toString())); + options = {}; + } + else { + const [pathname, ...searchParts] = (options.path ?? '').split('?'); + const search = searchParts.length > 0 + ? `?${searchParts.join('?')}` + : ''; + url = normalizeUrlObject({ ...options, pathname, search }); + } + options = { + headers: {}, + method: 'GET', + cache: true, + strictTtl: false, + automaticFailover: false, + ...options, + ...urlObjectToRequestOptions(url), + }; + options.headers = Object.fromEntries(entries(options.headers).map(([key, value]) => [key.toLowerCase(), value])); + const ee = new external_node_events_(); + const normalizedUrlString = normalizeUrl(external_node_url_namespaceObject.format(url), { + stripWWW: false, // eslint-disable-line @typescript-eslint/naming-convention + removeTrailingSlash: false, + stripAuthentication: false, + }); + let key = `${options.method}:${normalizedUrlString}`; + // POST, PATCH, and PUT requests may be cached, depending on the response + // cache-control headers. As a result, the body of the request should be + // added to the cache key in order to avoid collisions. + if (options.body && options.method !== undefined && ['POST', 'PATCH', 'PUT'].includes(options.method)) { + if (options.body instanceof external_node_stream_.Readable) { + // Streamed bodies should completely skip the cache because they may + // or may not be hashable and in either case the stream would need to + // close before the cache key could be generated. + options.cache = false; + } + else { + key += `:${external_node_crypto_namespaceObject.createHash('md5').update(options.body).digest('hex')}`; + } + } + let revalidate = false; + let madeRequest = false; + const makeRequest = (options_) => { + madeRequest = true; + let requestErrored = false; + let requestErrorCallback = () => { }; + const requestErrorPromise = new Promise(resolve => { + requestErrorCallback = () => { + if (!requestErrored) { + requestErrored = true; + resolve(); + } + }; + }); + const handler = async (response) => { + if (revalidate) { + response.status = response.statusCode; + const revalidatedPolicy = http_cache_semantics.fromObject(revalidate.cachePolicy).revalidatedPolicy(options_, response); + if (!revalidatedPolicy.modified) { + response.resume(); + await new Promise(resolve => { + // Skipping 'error' handler cause 'error' event should't be emitted for 304 response + response + .once('end', resolve); + }); + const headers = convertHeaders(revalidatedPolicy.policy.responseHeaders()); + response = new Response({ + statusCode: revalidate.statusCode, headers, body: revalidate.body, url: revalidate.url, + }); + response.cachePolicy = revalidatedPolicy.policy; + response.fromCache = true; + } + } + if (!response.fromCache) { + response.cachePolicy = new http_cache_semantics(options_, response, options_); + response.fromCache = false; + } + let clonedResponse; + if (options_.cache && response.cachePolicy.storable()) { + clonedResponse = cloneResponse(response); + (async () => { + try { + const bodyPromise = getStreamAsBuffer(response); + await Promise.race([ + requestErrorPromise, + new Promise(resolve => response.once('end', resolve)), // eslint-disable-line no-promise-executor-return + new Promise(resolve => response.once('close', resolve)), // eslint-disable-line no-promise-executor-return + ]); + const body = await bodyPromise; + let value = { + url: response.url, + statusCode: response.fromCache ? revalidate.statusCode : response.statusCode, + body, + cachePolicy: response.cachePolicy.toObject(), + }; + let ttl = options_.strictTtl ? response.cachePolicy.timeToLive() : undefined; + if (options_.maxTtl) { + ttl = ttl ? Math.min(ttl, options_.maxTtl) : options_.maxTtl; + } + if (this.hooks.size > 0) { + /* eslint-disable no-await-in-loop */ + for (const key_ of this.hooks.keys()) { + value = await this.runHook(key_, value, response); + } + /* eslint-enable no-await-in-loop */ + } + await this.cache.set(key, value, ttl); + } + catch (error) { + ee.emit('error', new types_CacheError(error)); + } + })(); + } + else if (options_.cache && revalidate) { + (async () => { + try { + await this.cache.delete(key); + } + catch (error) { + ee.emit('error', new types_CacheError(error)); + } + })(); + } + ee.emit('response', clonedResponse ?? response); + if (typeof callback === 'function') { + callback(clonedResponse ?? response); + } + }; + try { + const request_ = this.cacheRequest(options_, handler); + request_.once('error', requestErrorCallback); + request_.once('abort', requestErrorCallback); + request_.once('destroy', requestErrorCallback); + ee.emit('request', request_); + } + catch (error) { + ee.emit('error', new types_RequestError(error)); + } + }; + (async () => { + const get = async (options_) => { + await Promise.resolve(); + const cacheEntry = options_.cache ? await this.cache.get(key) : undefined; + if (cacheEntry === undefined && !options_.forceRefresh) { + makeRequest(options_); + return; + } + const policy = http_cache_semantics.fromObject(cacheEntry.cachePolicy); + if (policy.satisfiesWithoutRevalidation(options_) && !options_.forceRefresh) { + const headers = convertHeaders(policy.responseHeaders()); + const response = new Response({ + statusCode: cacheEntry.statusCode, headers, body: cacheEntry.body, url: cacheEntry.url, + }); + response.cachePolicy = policy; + response.fromCache = true; + ee.emit('response', response); + if (typeof callback === 'function') { + callback(response); + } + } + else if (policy.satisfiesWithoutRevalidation(options_) && Date.now() >= policy.timeToLive() && options_.forceRefresh) { + await this.cache.delete(key); + options_.headers = policy.revalidationHeaders(options_); + makeRequest(options_); + } + else { + revalidate = cacheEntry; + options_.headers = policy.revalidationHeaders(options_); + makeRequest(options_); + } + }; + const errorHandler = (error) => ee.emit('error', new types_CacheError(error)); + if (this.cache instanceof src) { + const cachek = this.cache; + cachek.once('error', errorHandler); + ee.on('error', () => cachek.removeListener('error', errorHandler)); + ee.on('response', () => cachek.removeListener('error', errorHandler)); + } + try { + await get(options); + } + catch (error) { + if (options.automaticFailover && !madeRequest) { + makeRequest(options); + } + ee.emit('error', new types_CacheError(error)); + } + })(); + return ee; + }; + this.addHook = (name, function_) => { + if (!this.hooks.has(name)) { + this.hooks.set(name, function_); + } + }; + this.removeHook = (name) => this.hooks.delete(name); + this.getHook = (name) => this.hooks.get(name); + this.runHook = async (name, ...arguments_) => this.hooks.get(name)?.(...arguments_); + if (cacheAdapter instanceof src) { + this.cache = cacheAdapter; + } + else if (typeof cacheAdapter === 'string') { + this.cache = new src({ + uri: cacheAdapter, + namespace: 'cacheable-request', + }); + } + else { + this.cache = new src({ + store: cacheAdapter, + namespace: 'cacheable-request', + }); + } + this.request = this.request.bind(this); + this.cacheRequest = cacheRequest; } } -/** -Note: [Prefer using `Uint8Array` instead of `Buffer`.](https://sindresorhus.com/blog/goodbye-nodejs-buffer) -*/ -function assertBuffer(value, message) { - if (!isBuffer(value)) { - throw new TypeError(message ?? typeErrorMessage('Buffer', value)); +const entries = Object.entries; +const cloneResponse = (response) => { + const clone = new external_node_stream_.PassThrough({ autoDestroy: false }); + mimicResponse(response, clone); + return response.pipe(clone); +}; +const urlObjectToRequestOptions = (url) => { + const options = { ...url }; + options.path = `${url.pathname || '/'}${url.search || ''}`; + delete options.pathname; + delete options.search; + return options; +}; +const normalizeUrlObject = (url) => +// If url was parsed by url.parse or new URL: +// - hostname will be set +// - host will be hostname[:port] +// - port will be set if it was explicit in the parsed string +// Otherwise, url was from request options: +// - hostname or host may be set +// - host shall not have port encoded +({ + protocol: url.protocol, + auth: url.auth, + hostname: url.hostname || url.host || 'localhost', + port: url.port, + pathname: url.pathname, + search: url.search, +}); +const convertHeaders = (headers) => { + const result = []; + for (const name of Object.keys(headers)) { + result[name.toLowerCase()] = headers[name]; } + return result; +}; +/* harmony default export */ const dist = (CacheableRequest); + +const onResponse = 'onResponse'; +//# sourceMappingURL=index.js.map +// EXTERNAL MODULE: ./node_modules/.pnpm/decompress-response@6.0.0/node_modules/decompress-response/index.js +var decompress_response = __nccwpck_require__(7748); +;// CONCATENATED MODULE: ./node_modules/.pnpm/form-data-encoder@4.0.2/node_modules/form-data-encoder/lib/index.js +var __accessCheck = (obj, member, msg) => { + if (!member.has(obj)) + throw TypeError("Cannot " + msg); +}; +var __privateGet = (obj, member, getter) => { + __accessCheck(obj, member, "read from private field"); + return getter ? getter.call(obj) : member.get(obj); +}; +var __privateAdd = (obj, member, value) => { + if (member.has(obj)) + throw TypeError("Cannot add the same private member more than once"); + member instanceof WeakSet ? member.add(obj) : member.set(obj, value); +}; +var __privateSet = (obj, member, value, setter) => { + __accessCheck(obj, member, "write to private field"); + setter ? setter.call(obj, value) : member.set(obj, value); + return value; +}; +var __privateMethod = (obj, member, method) => { + __accessCheck(obj, member, "access private method"); + return method; +}; + +// src/util/isFunction.ts +var lib_isFunction = (value) => typeof value === "function"; + +// src/util/isAsyncIterable.ts +var lib_isAsyncIterable = (value) => lib_isFunction(value[Symbol.asyncIterator]); + +// src/util/chunk.ts +var MAX_CHUNK_SIZE = 65536; +function* chunk(value) { + if (value.byteLength <= MAX_CHUNK_SIZE) { + yield value; + return; + } + let offset = 0; + while (offset < value.byteLength) { + const size = Math.min(value.byteLength - offset, MAX_CHUNK_SIZE); + const buffer = value.buffer.slice(offset, offset + size); + offset += buffer.byteLength; + yield new Uint8Array(buffer); + } } -function assertClass(value, message) { - if (!isClass(value)) { - throw new TypeError(message ?? typeErrorMessage('Class', value)); + +// src/util/getStreamIterator.ts +async function* readStream(readable) { + const reader = readable.getReader(); + while (true) { + const { done, value } = await reader.read(); + if (done) { + break; } + yield value; + } } -function assertDataView(value, message) { - if (!isDataView(value)) { - throw new TypeError(message ?? typeErrorMessage('DataView', value)); - } +async function* chunkStream(stream) { + for await (const value of stream) { + yield* chunk(value); + } } -function assertDate(value, message) { - if (!isDate(value)) { - throw new TypeError(message ?? typeErrorMessage('Date', value)); - } +var getStreamIterator = (source) => { + if (lib_isAsyncIterable(source)) { + return chunkStream(source); + } + if (lib_isFunction(source.getReader)) { + return chunkStream(readStream(source)); + } + throw new TypeError( + "Unsupported data source: Expected either ReadableStream or async iterable." + ); +}; + +// src/util/createBoundary.ts +var alphabet = "abcdefghijklmnopqrstuvwxyz0123456789"; +function createBoundary() { + let size = 16; + let res = ""; + while (size--) { + res += alphabet[Math.random() * alphabet.length << 0]; + } + return res; } -function assertDirectInstanceOf(instance, class_, message) { - if (!isDirectInstanceOf(instance, class_)) { - throw new TypeError(message ?? typeErrorMessage('T', instance)); - } + +// src/util/normalizeValue.ts +var normalizeValue = (value) => String(value).replace(/\r|\n/g, (match, i, str) => { + if (match === "\r" && str[i + 1] !== "\n" || match === "\n" && str[i - 1] !== "\r") { + return "\r\n"; + } + return match; +}); + +// src/util/isPlainObject.ts +var getType = (value) => Object.prototype.toString.call(value).slice(8, -1).toLowerCase(); +function lib_isPlainObject(value) { + if (getType(value) !== "object") { + return false; + } + const pp = Object.getPrototypeOf(value); + if (pp === null || pp === void 0) { + return true; + } + const Ctor = pp.constructor && pp.constructor.toString(); + return Ctor === Object.toString(); } -function assertEmptyArray(value, message) { - if (!isEmptyArray(value)) { - throw new TypeError(message ?? typeErrorMessage('empty array', value)); + +// src/util/proxyHeaders.ts +function getProperty(target, prop) { + if (typeof prop === "string") { + for (const [name, value] of Object.entries(target)) { + if (prop.toLowerCase() === name.toLowerCase()) { + return value; + } } + } + return void 0; } -function assertEmptyMap(value, message) { - if (!isEmptyMap(value)) { - throw new TypeError(message ?? typeErrorMessage('empty map', value)); +var proxyHeaders = (object) => new Proxy( + object, + { + get: (target, prop) => getProperty(target, prop), + has: (target, prop) => getProperty(target, prop) !== void 0 + } +); + +// src/util/isFormData.ts +var lib_isFormData = (value) => Boolean( + value && lib_isFunction(value.constructor) && value[Symbol.toStringTag] === "FormData" && lib_isFunction(value.append) && lib_isFunction(value.getAll) && lib_isFunction(value.entries) && lib_isFunction(value[Symbol.iterator]) +); + +// src/util/escapeName.ts +var escapeName = (name) => String(name).replace(/\r/g, "%0D").replace(/\n/g, "%0A").replace(/"/g, "%22"); + +// src/util/isFile.ts +var isFile = (value) => Boolean( + value && typeof value === "object" && lib_isFunction(value.constructor) && value[Symbol.toStringTag] === "File" && lib_isFunction(value.stream) && value.name != null +); + +// src/FormDataEncoder.ts +var defaultOptions = { + enableAdditionalHeaders: false +}; +var readonlyProp = { writable: false, configurable: false }; +var _CRLF, _CRLF_BYTES, _CRLF_BYTES_LENGTH, _DASHES, _encoder, _footer, _form, _options, _getFieldHeader, getFieldHeader_fn, _getContentLength, getContentLength_fn; +var FormDataEncoder = class { + constructor(form, boundaryOrOptions, options) { + __privateAdd(this, _getFieldHeader); + /** + * Returns form-data content length + */ + __privateAdd(this, _getContentLength); + __privateAdd(this, _CRLF, "\r\n"); + __privateAdd(this, _CRLF_BYTES, void 0); + __privateAdd(this, _CRLF_BYTES_LENGTH, void 0); + __privateAdd(this, _DASHES, "-".repeat(2)); + /** + * TextEncoder instance + */ + __privateAdd(this, _encoder, new TextEncoder()); + /** + * Returns form-data footer bytes + */ + __privateAdd(this, _footer, void 0); + /** + * FormData instance + */ + __privateAdd(this, _form, void 0); + /** + * Instance options + */ + __privateAdd(this, _options, void 0); + if (!lib_isFormData(form)) { + throw new TypeError("Expected first argument to be a FormData instance."); } -} -function assertEmptyObject(value, message) { - if (!isEmptyObject(value)) { - throw new TypeError(message ?? typeErrorMessage('empty object', value)); + let boundary; + if (lib_isPlainObject(boundaryOrOptions)) { + options = boundaryOrOptions; + } else { + boundary = boundaryOrOptions; } -} -function assertEmptySet(value, message) { - if (!isEmptySet(value)) { - throw new TypeError(message ?? typeErrorMessage('empty set', value)); + if (!boundary) { + boundary = createBoundary(); } -} -function assertEmptyString(value, message) { - if (!isEmptyString(value)) { - throw new TypeError(message ?? typeErrorMessage('empty string', value)); + if (typeof boundary !== "string") { + throw new TypeError("Expected boundary argument to be a string."); } -} -function assertEmptyStringOrWhitespace(value, message) { - if (!isEmptyStringOrWhitespace(value)) { - throw new TypeError(message ?? typeErrorMessage('empty string or whitespace', value)); + if (options && !lib_isPlainObject(options)) { + throw new TypeError("Expected options argument to be an object."); } -} -function assertEnumCase(value, targetEnum, message) { - if (!isEnumCase(value, targetEnum)) { - throw new TypeError(message ?? typeErrorMessage('EnumCase', value)); + __privateSet(this, _form, Array.from(form.entries())); + __privateSet(this, _options, { ...defaultOptions, ...options }); + __privateSet(this, _CRLF_BYTES, __privateGet(this, _encoder).encode(__privateGet(this, _CRLF))); + __privateSet(this, _CRLF_BYTES_LENGTH, __privateGet(this, _CRLF_BYTES).byteLength); + this.boundary = `form-data-boundary-${boundary}`; + this.contentType = `multipart/form-data; boundary=${this.boundary}`; + __privateSet(this, _footer, __privateGet(this, _encoder).encode( + `${__privateGet(this, _DASHES)}${this.boundary}${__privateGet(this, _DASHES)}${__privateGet(this, _CRLF).repeat(2)}` + )); + const headers = { + "Content-Type": this.contentType + }; + const contentLength = __privateMethod(this, _getContentLength, getContentLength_fn).call(this); + if (contentLength) { + this.contentLength = contentLength; + headers["Content-Length"] = contentLength; } -} -function assertError(value, message) { - if (!isError(value)) { - throw new TypeError(message ?? typeErrorMessage('Error', value)); + this.headers = proxyHeaders(Object.freeze(headers)); + Object.defineProperties(this, { + boundary: readonlyProp, + contentType: readonlyProp, + contentLength: readonlyProp, + headers: readonlyProp + }); + } + /** + * Creates an iterator allowing to go through form-data parts (with metadata). + * This method **will not** read the files and **will not** split values big into smaller chunks. + * + * Using this method, you can convert form-data content into Blob: + * + * @example + * + * ```ts + * import {Readable} from "stream" + * + * import {FormDataEncoder} from "form-data-encoder" + * + * import {FormData} from "formdata-polyfill/esm-min.js" + * import {fileFrom} from "fetch-blob/form.js" + * import {File} from "fetch-blob/file.js" + * import {Blob} from "fetch-blob" + * + * import fetch from "node-fetch" + * + * const form = new FormData() + * + * form.set("field", "Just a random string") + * form.set("file", new File(["Using files is class amazing"])) + * form.set("fileFromPath", await fileFrom("path/to/a/file.txt")) + * + * const encoder = new FormDataEncoder(form) + * + * const options = { + * method: "post", + * body: new Blob(encoder, {type: encoder.contentType}) + * } + * + * const response = await fetch("https://httpbin.org/post", options) + * + * console.log(await response.json()) + * ``` + */ + *values() { + for (const [name, raw] of __privateGet(this, _form)) { + const value = isFile(raw) ? raw : __privateGet(this, _encoder).encode( + normalizeValue(raw) + ); + yield __privateMethod(this, _getFieldHeader, getFieldHeader_fn).call(this, name, value); + yield value; + yield __privateGet(this, _CRLF_BYTES); } -} -function assertEvenInteger(value, message) { - if (!isEvenInteger(value)) { - throw new TypeError(message ?? typeErrorMessage('even integer', value)); + yield __privateGet(this, _footer); + } + /** + * Creates an async iterator allowing to perform the encoding by portions. + * This method reads through files and splits big values into smaller pieces (65536 bytes per each). + * + * @example + * + * ```ts + * import {Readable} from "stream" + * + * import {FormData, File, fileFromPath} from "formdata-node" + * import {FormDataEncoder} from "form-data-encoder" + * + * import fetch from "node-fetch" + * + * const form = new FormData() + * + * form.set("field", "Just a random string") + * form.set("file", new File(["Using files is class amazing"], "file.txt")) + * form.set("fileFromPath", await fileFromPath("path/to/a/file.txt")) + * + * const encoder = new FormDataEncoder(form) + * + * const options = { + * method: "post", + * headers: encoder.headers, + * body: Readable.from(encoder.encode()) // or Readable.from(encoder) + * } + * + * const response = await fetch("https://httpbin.org/post", options) + * + * console.log(await response.json()) + * ``` + */ + async *encode() { + for (const part of this.values()) { + if (isFile(part)) { + yield* getStreamIterator(part.stream()); + } else { + yield* chunk(part); + } } -} -function assertFalsy(value, message) { - if (!isFalsy(value)) { - throw new TypeError(message ?? typeErrorMessage('falsy', value)); + } + /** + * Creates an iterator allowing to read through the encoder data using for...of loops + */ + [Symbol.iterator]() { + return this.values(); + } + /** + * Creates an **async** iterator allowing to read through the encoder data using for-await...of loops + */ + [Symbol.asyncIterator]() { + return this.encode(); + } +}; +_CRLF = new WeakMap(); +_CRLF_BYTES = new WeakMap(); +_CRLF_BYTES_LENGTH = new WeakMap(); +_DASHES = new WeakMap(); +_encoder = new WeakMap(); +_footer = new WeakMap(); +_form = new WeakMap(); +_options = new WeakMap(); +_getFieldHeader = new WeakSet(); +getFieldHeader_fn = function(name, value) { + let header = ""; + header += `${__privateGet(this, _DASHES)}${this.boundary}${__privateGet(this, _CRLF)}`; + header += `Content-Disposition: form-data; name="${escapeName(name)}"`; + if (isFile(value)) { + header += `; filename="${escapeName(value.name)}"${__privateGet(this, _CRLF)}`; + header += `Content-Type: ${value.type || "application/octet-stream"}`; + } + if (__privateGet(this, _options).enableAdditionalHeaders === true) { + const size = isFile(value) ? value.size : value.byteLength; + if (size != null && !isNaN(size)) { + header += `${__privateGet(this, _CRLF)}Content-Length: ${size}`; } -} -function assertFloat32Array(value, message) { - if (!isFloat32Array(value)) { - throw new TypeError(message ?? typeErrorMessage('Float32Array', value)); + } + return __privateGet(this, _encoder).encode(`${header}${__privateGet(this, _CRLF).repeat(2)}`); +}; +_getContentLength = new WeakSet(); +getContentLength_fn = function() { + let length = 0; + for (const [name, raw] of __privateGet(this, _form)) { + const value = isFile(raw) ? raw : __privateGet(this, _encoder).encode( + normalizeValue(raw) + ); + const size = isFile(value) ? value.size : value.byteLength; + if (size == null || isNaN(size)) { + return void 0; } + length += __privateMethod(this, _getFieldHeader, getFieldHeader_fn).call(this, name, value).byteLength; + length += size; + length += __privateGet(this, _CRLF_BYTES_LENGTH); + } + return String(length + __privateGet(this, _footer).byteLength); +}; + + +;// CONCATENATED MODULE: ./node_modules/.pnpm/got@14.4.4/node_modules/got/dist/source/core/utils/is-form-data.js + +function is_form_data_isFormData(body) { + return distribution.nodeStream(body) && distribution["function"](body.getBoundary); } -function assertFloat64Array(value, message) { - if (!isFloat64Array(value)) { - throw new TypeError(message ?? typeErrorMessage('Float64Array', value)); + +;// CONCATENATED MODULE: ./node_modules/.pnpm/got@14.4.4/node_modules/got/dist/source/core/utils/get-body-size.js + + + + +async function getBodySize(body, headers) { + if (headers && 'content-length' in headers) { + return Number(headers['content-length']); } -} -function assertFormData(value, message) { - if (!isFormData(value)) { - throw new TypeError(message ?? typeErrorMessage('FormData', value)); + if (!body) { + return 0; } -} -// eslint-disable-next-line @typescript-eslint/ban-types -function assertFunction(value, message) { - if (!isFunction(value)) { - throw new TypeError(message ?? typeErrorMessage('Function', value)); + if (distribution.string(body)) { + return external_node_buffer_namespaceObject.Buffer.byteLength(body); } -} -function assertGenerator(value, message) { - if (!isGenerator(value)) { - throw new TypeError(message ?? typeErrorMessage('Generator', value)); + if (distribution.buffer(body)) { + return body.length; } -} -function assertGeneratorFunction(value, message) { - if (!isGeneratorFunction(value)) { - throw new TypeError(message ?? typeErrorMessage('GeneratorFunction', value)); + if (is_form_data_isFormData(body)) { + return (0,external_node_util_.promisify)(body.getLength.bind(body))(); } + return undefined; } -function assertHtmlElement(value, message) { - if (!isHtmlElement(value)) { - throw new TypeError(message ?? typeErrorMessage('HTMLElement', value)); + +;// CONCATENATED MODULE: ./node_modules/.pnpm/got@14.4.4/node_modules/got/dist/source/core/utils/proxy-events.js +function proxyEvents(from, to, events) { + const eventFunctions = {}; + for (const event of events) { + const eventFunction = (...arguments_) => { + to.emit(event, ...arguments_); + }; + eventFunctions[event] = eventFunction; + from.on(event, eventFunction); } + return () => { + for (const [event, eventFunction] of Object.entries(eventFunctions)) { + from.off(event, eventFunction); + } + }; } -function assertInfinite(value, message) { - if (!isInfinite(value)) { - throw new TypeError(message ?? typeErrorMessage('infinite number', value)); - } + +;// CONCATENATED MODULE: external "node:net" +const external_node_net_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:net"); +;// CONCATENATED MODULE: ./node_modules/.pnpm/got@14.4.4/node_modules/got/dist/source/core/utils/unhandle.js +// When attaching listeners, it's very easy to forget about them. +// Especially if you do error handling and set timeouts. +// So instead of checking if it's proper to throw an error on every timeout ever, +// use this simple tool which will remove all listeners you have attached. +function unhandle() { + const handlers = []; + return { + once(origin, event, function_) { + origin.once(event, function_); + handlers.push({ origin, event, fn: function_ }); + }, + unhandleAll() { + for (const handler of handlers) { + const { origin, event, fn } = handler; + origin.removeListener(event, fn); + } + handlers.length = 0; + }, + }; } -function assertInRange(value, range, message) { - if (!isInRange(value, range)) { - throw new TypeError(message ?? typeErrorMessage('in range', value)); + +;// CONCATENATED MODULE: ./node_modules/.pnpm/got@14.4.4/node_modules/got/dist/source/core/timed-out.js + + +const reentry = Symbol('reentry'); +const timed_out_noop = () => { }; +class timed_out_TimeoutError extends Error { + event; + code; + constructor(threshold, event) { + super(`Timeout awaiting '${event}' for ${threshold}ms`); + this.event = event; + this.name = 'TimeoutError'; + this.code = 'ETIMEDOUT'; } } -function assertInt16Array(value, message) { - if (!isInt16Array(value)) { - throw new TypeError(message ?? typeErrorMessage('Int16Array', value)); +function timedOut(request, delays, options) { + if (reentry in request) { + return timed_out_noop; } -} -function assertInt32Array(value, message) { - if (!isInt32Array(value)) { - throw new TypeError(message ?? typeErrorMessage('Int32Array', value)); + request[reentry] = true; + const cancelers = []; + const { once, unhandleAll } = unhandle(); + const addTimeout = (delay, callback, event) => { + const timeout = setTimeout(callback, delay, delay, event); + timeout.unref?.(); + const cancel = () => { + clearTimeout(timeout); + }; + cancelers.push(cancel); + return cancel; + }; + const { host, hostname } = options; + const timeoutHandler = (delay, event) => { + request.destroy(new timed_out_TimeoutError(delay, event)); + }; + const cancelTimeouts = () => { + for (const cancel of cancelers) { + cancel(); + } + unhandleAll(); + }; + request.once('error', error => { + cancelTimeouts(); + // Save original behavior + /* istanbul ignore next */ + if (request.listenerCount('error') === 0) { + throw error; + } + }); + if (delays.request !== undefined) { + const cancelTimeout = addTimeout(delays.request, timeoutHandler, 'request'); + once(request, 'response', (response) => { + once(response, 'end', cancelTimeout); + }); } -} -function assertInt8Array(value, message) { - if (!isInt8Array(value)) { - throw new TypeError(message ?? typeErrorMessage('Int8Array', value)); + if (delays.socket !== undefined) { + const { socket } = delays; + const socketTimeoutHandler = () => { + timeoutHandler(socket, 'socket'); + }; + request.setTimeout(socket, socketTimeoutHandler); + // `request.setTimeout(0)` causes a memory leak. + // We can just remove the listener and forget about the timer - it's unreffed. + // See https://github.com/sindresorhus/got/issues/690 + cancelers.push(() => { + request.removeListener('timeout', socketTimeoutHandler); + }); } -} -function assertInteger(value, message) { - if (!isInteger(value)) { - throw new TypeError(message ?? typeErrorMessage('integer', value)); + const hasLookup = delays.lookup !== undefined; + const hasConnect = delays.connect !== undefined; + const hasSecureConnect = delays.secureConnect !== undefined; + const hasSend = delays.send !== undefined; + if (hasLookup || hasConnect || hasSecureConnect || hasSend) { + once(request, 'socket', (socket) => { + const { socketPath } = request; + /* istanbul ignore next: hard to test */ + if (socket.connecting) { + const hasPath = Boolean(socketPath ?? external_node_net_namespaceObject.isIP(hostname ?? host ?? '') !== 0); + if (hasLookup && !hasPath && socket.address().address === undefined) { + const cancelTimeout = addTimeout(delays.lookup, timeoutHandler, 'lookup'); + once(socket, 'lookup', cancelTimeout); + } + if (hasConnect) { + const timeConnect = () => addTimeout(delays.connect, timeoutHandler, 'connect'); + if (hasPath) { + once(socket, 'connect', timeConnect()); + } + else { + once(socket, 'lookup', (error) => { + if (error === null) { + once(socket, 'connect', timeConnect()); + } + }); + } + } + if (hasSecureConnect && options.protocol === 'https:') { + once(socket, 'connect', () => { + const cancelTimeout = addTimeout(delays.secureConnect, timeoutHandler, 'secureConnect'); + once(socket, 'secureConnect', cancelTimeout); + }); + } + } + if (hasSend) { + const timeRequest = () => addTimeout(delays.send, timeoutHandler, 'send'); + /* istanbul ignore next: hard to test */ + if (socket.connecting) { + once(socket, 'connect', () => { + once(request, 'upload-complete', timeRequest()); + }); + } + else { + once(request, 'upload-complete', timeRequest()); + } + } + }); } -} -function assertIterable(value, message) { - if (!isIterable(value)) { - throw new TypeError(message ?? typeErrorMessage('Iterable', value)); + if (delays.response !== undefined) { + once(request, 'upload-complete', () => { + const cancelTimeout = addTimeout(delays.response, timeoutHandler, 'response'); + once(request, 'response', cancelTimeout); + }); } -} -function assertMap(value, message) { - if (!isMap(value)) { - throw new TypeError(message ?? typeErrorMessage('Map', value)); + if (delays.read !== undefined) { + once(request, 'response', (response) => { + const cancelTimeout = addTimeout(delays.read, timeoutHandler, 'read'); + once(response, 'end', cancelTimeout); + }); } + return cancelTimeouts; } -function assertNan(value, message) { - if (!isNan(value)) { - throw new TypeError(message ?? typeErrorMessage('NaN', value)); + +;// CONCATENATED MODULE: ./node_modules/.pnpm/got@14.4.4/node_modules/got/dist/source/core/utils/url-to-options.js + +function urlToOptions(url) { + // Cast to URL + url = url; + const options = { + protocol: url.protocol, + hostname: distribution.string(url.hostname) && url.hostname.startsWith('[') ? url.hostname.slice(1, -1) : url.hostname, + host: url.host, + hash: url.hash, + search: url.search, + pathname: url.pathname, + href: url.href, + path: `${url.pathname || ''}${url.search || ''}`, + }; + if (distribution.string(url.port) && url.port.length > 0) { + options.port = Number(url.port); } -} -function assertNativePromise(value, message) { - if (!isNativePromise(value)) { - throw new TypeError(message ?? typeErrorMessage('native Promise', value)); + if (url.username || url.password) { + options.auth = `${url.username || ''}:${url.password || ''}`; } + return options; } -function assertNegativeNumber(value, message) { - if (!isNegativeNumber(value)) { - throw new TypeError(message ?? typeErrorMessage('negative number', value)); + +;// CONCATENATED MODULE: ./node_modules/.pnpm/got@14.4.4/node_modules/got/dist/source/core/utils/weakable-map.js +class WeakableMap { + weakMap; + map; + constructor() { + this.weakMap = new WeakMap(); + this.map = new Map(); } -} -function assertNodeStream(value, message) { - if (!isNodeStream(value)) { - throw new TypeError(message ?? typeErrorMessage('Node.js Stream', value)); + set(key, value) { + if (typeof key === 'object') { + this.weakMap.set(key, value); + } + else { + this.map.set(key, value); + } } -} -function assertNonEmptyArray(value, message) { - if (!isNonEmptyArray(value)) { - throw new TypeError(message ?? typeErrorMessage('non-empty array', value)); + get(key) { + if (typeof key === 'object') { + return this.weakMap.get(key); + } + return this.map.get(key); } -} -function assertNonEmptyMap(value, message) { - if (!isNonEmptyMap(value)) { - throw new TypeError(message ?? typeErrorMessage('non-empty map', value)); + has(key) { + if (typeof key === 'object') { + return this.weakMap.has(key); + } + return this.map.has(key); } } -function assertNonEmptyObject(value, message) { - if (!isNonEmptyObject(value)) { - throw new TypeError(message ?? typeErrorMessage('non-empty object', value)); + +;// CONCATENATED MODULE: ./node_modules/.pnpm/got@14.4.4/node_modules/got/dist/source/core/calculate-retry-delay.js +const calculateRetryDelay = ({ attemptCount, retryOptions, error, retryAfter, computedValue, }) => { + if (error.name === 'RetryError') { + return 1; } -} -function assertNonEmptySet(value, message) { - if (!isNonEmptySet(value)) { - throw new TypeError(message ?? typeErrorMessage('non-empty set', value)); + if (attemptCount > retryOptions.limit) { + return 0; } -} -function assertNonEmptyString(value, message) { - if (!isNonEmptyString(value)) { - throw new TypeError(message ?? typeErrorMessage('non-empty string', value)); + const hasMethod = retryOptions.methods.includes(error.options.method); + const hasErrorCode = retryOptions.errorCodes.includes(error.code); + const hasStatusCode = error.response && retryOptions.statusCodes.includes(error.response.statusCode); + if (!hasMethod || (!hasErrorCode && !hasStatusCode)) { + return 0; + } + if (error.response) { + if (retryAfter) { + // In this case `computedValue` is `options.request.timeout` + if (retryAfter > computedValue) { + return 0; + } + return retryAfter; + } + if (error.response.statusCode === 413) { + return 0; + } } + const noise = Math.random() * retryOptions.noise; + return Math.min(((2 ** (attemptCount - 1)) * 1000), retryOptions.backoffLimit) + noise; +}; +/* harmony default export */ const calculate_retry_delay = (calculateRetryDelay); + +;// CONCATENATED MODULE: external "node:tls" +const external_node_tls_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:tls"); +// EXTERNAL MODULE: external "node:https" +var external_node_https_ = __nccwpck_require__(2286); +;// CONCATENATED MODULE: external "node:dns" +const external_node_dns_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:dns"); +;// CONCATENATED MODULE: ./node_modules/.pnpm/cacheable-lookup@7.0.0/node_modules/cacheable-lookup/source/index.js + + + + +const {Resolver: AsyncResolver} = external_node_dns_namespaceObject.promises; + +const kCacheableLookupCreateConnection = Symbol('cacheableLookupCreateConnection'); +const kCacheableLookupInstance = Symbol('cacheableLookupInstance'); +const kExpires = Symbol('expires'); + +const supportsALL = typeof external_node_dns_namespaceObject.ALL === 'number'; + +const verifyAgent = agent => { + if (!(agent && typeof agent.createConnection === 'function')) { + throw new Error('Expected an Agent instance as the first argument'); + } +}; + +const map4to6 = entries => { + for (const entry of entries) { + if (entry.family === 6) { + continue; + } + + entry.address = `::ffff:${entry.address}`; + entry.family = 6; + } +}; + +const getIfaceInfo = () => { + let has4 = false; + let has6 = false; + + for (const device of Object.values(external_node_os_.networkInterfaces())) { + for (const iface of device) { + if (iface.internal) { + continue; + } + + if (iface.family === 'IPv6') { + has6 = true; + } else { + has4 = true; + } + + if (has4 && has6) { + return {has4, has6}; + } + } + } + + return {has4, has6}; +}; + +const source_isIterable = map => { + return Symbol.iterator in map; +}; + +const ignoreNoResultErrors = dnsPromise => { + return dnsPromise.catch(error => { + if ( + error.code === 'ENODATA' || + error.code === 'ENOTFOUND' || + error.code === 'ENOENT' // Windows: name exists, but not this record type + ) { + return []; + } + + throw error; + }); +}; + +const ttl = {ttl: true}; +const source_all = {all: true}; +const all4 = {all: true, family: 4}; +const all6 = {all: true, family: 6}; + +class CacheableLookup { + constructor({ + cache = new Map(), + maxTtl = Infinity, + fallbackDuration = 3600, + errorTtl = 0.15, + resolver = new AsyncResolver(), + lookup = external_node_dns_namespaceObject.lookup + } = {}) { + this.maxTtl = maxTtl; + this.errorTtl = errorTtl; + + this._cache = cache; + this._resolver = resolver; + this._dnsLookup = lookup && (0,external_node_util_.promisify)(lookup); + this.stats = { + cache: 0, + query: 0 + }; + + if (this._resolver instanceof AsyncResolver) { + this._resolve4 = this._resolver.resolve4.bind(this._resolver); + this._resolve6 = this._resolver.resolve6.bind(this._resolver); + } else { + this._resolve4 = (0,external_node_util_.promisify)(this._resolver.resolve4.bind(this._resolver)); + this._resolve6 = (0,external_node_util_.promisify)(this._resolver.resolve6.bind(this._resolver)); + } + + this._iface = getIfaceInfo(); + + this._pending = {}; + this._nextRemovalTime = false; + this._hostnamesToFallback = new Set(); + + this.fallbackDuration = fallbackDuration; + + if (fallbackDuration > 0) { + const interval = setInterval(() => { + this._hostnamesToFallback.clear(); + }, fallbackDuration * 1000); + + /* istanbul ignore next: There is no `interval.unref()` when running inside an Electron renderer */ + if (interval.unref) { + interval.unref(); + } + + this._fallbackInterval = interval; + } + + this.lookup = this.lookup.bind(this); + this.lookupAsync = this.lookupAsync.bind(this); + } + + set servers(servers) { + this.clear(); + + this._resolver.setServers(servers); + } + + get servers() { + return this._resolver.getServers(); + } + + lookup(hostname, options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } else if (typeof options === 'number') { + options = { + family: options + }; + } + + if (!callback) { + throw new Error('Callback must be a function.'); + } + + // eslint-disable-next-line promise/prefer-await-to-then + this.lookupAsync(hostname, options).then(result => { + if (options.all) { + callback(null, result); + } else { + callback(null, result.address, result.family, result.expires, result.ttl, result.source); + } + }, callback); + } + + async lookupAsync(hostname, options = {}) { + if (typeof options === 'number') { + options = { + family: options + }; + } + + let cached = await this.query(hostname); + + if (options.family === 6) { + const filtered = cached.filter(entry => entry.family === 6); + + if (options.hints & external_node_dns_namespaceObject.V4MAPPED) { + if ((supportsALL && options.hints & external_node_dns_namespaceObject.ALL) || filtered.length === 0) { + map4to6(cached); + } else { + cached = filtered; + } + } else { + cached = filtered; + } + } else if (options.family === 4) { + cached = cached.filter(entry => entry.family === 4); + } + + if (options.hints & external_node_dns_namespaceObject.ADDRCONFIG) { + const {_iface} = this; + cached = cached.filter(entry => entry.family === 6 ? _iface.has6 : _iface.has4); + } + + if (cached.length === 0) { + const error = new Error(`cacheableLookup ENOTFOUND ${hostname}`); + error.code = 'ENOTFOUND'; + error.hostname = hostname; + + throw error; + } + + if (options.all) { + return cached; + } + + return cached[0]; + } + + async query(hostname) { + let source = 'cache'; + let cached = await this._cache.get(hostname); + + if (cached) { + this.stats.cache++; + } + + if (!cached) { + const pending = this._pending[hostname]; + if (pending) { + this.stats.cache++; + cached = await pending; + } else { + source = 'query'; + const newPromise = this.queryAndCache(hostname); + this._pending[hostname] = newPromise; + this.stats.query++; + try { + cached = await newPromise; + } finally { + delete this._pending[hostname]; + } + } + } + + cached = cached.map(entry => { + return {...entry, source}; + }); + + return cached; + } + + async _resolve(hostname) { + // ANY is unsafe as it doesn't trigger new queries in the underlying server. + const [A, AAAA] = await Promise.all([ + ignoreNoResultErrors(this._resolve4(hostname, ttl)), + ignoreNoResultErrors(this._resolve6(hostname, ttl)) + ]); + + let aTtl = 0; + let aaaaTtl = 0; + let cacheTtl = 0; + + const now = Date.now(); + + for (const entry of A) { + entry.family = 4; + entry.expires = now + (entry.ttl * 1000); + + aTtl = Math.max(aTtl, entry.ttl); + } + + for (const entry of AAAA) { + entry.family = 6; + entry.expires = now + (entry.ttl * 1000); + + aaaaTtl = Math.max(aaaaTtl, entry.ttl); + } + + if (A.length > 0) { + if (AAAA.length > 0) { + cacheTtl = Math.min(aTtl, aaaaTtl); + } else { + cacheTtl = aTtl; + } + } else { + cacheTtl = aaaaTtl; + } + + return { + entries: [ + ...A, + ...AAAA + ], + cacheTtl + }; + } + + async _lookup(hostname) { + try { + const [A, AAAA] = await Promise.all([ + // Passing {all: true} doesn't return all IPv4 and IPv6 entries. + // See https://github.com/szmarczak/cacheable-lookup/issues/42 + ignoreNoResultErrors(this._dnsLookup(hostname, all4)), + ignoreNoResultErrors(this._dnsLookup(hostname, all6)) + ]); + + return { + entries: [ + ...A, + ...AAAA + ], + cacheTtl: 0 + }; + } catch { + return { + entries: [], + cacheTtl: 0 + }; + } + } + + async _set(hostname, data, cacheTtl) { + if (this.maxTtl > 0 && cacheTtl > 0) { + cacheTtl = Math.min(cacheTtl, this.maxTtl) * 1000; + data[kExpires] = Date.now() + cacheTtl; + + try { + await this._cache.set(hostname, data, cacheTtl); + } catch (error) { + this.lookupAsync = async () => { + const cacheError = new Error('Cache Error. Please recreate the CacheableLookup instance.'); + cacheError.cause = error; + + throw cacheError; + }; + } + + if (source_isIterable(this._cache)) { + this._tick(cacheTtl); + } + } + } + + async queryAndCache(hostname) { + if (this._hostnamesToFallback.has(hostname)) { + return this._dnsLookup(hostname, source_all); + } + + let query = await this._resolve(hostname); + + if (query.entries.length === 0 && this._dnsLookup) { + query = await this._lookup(hostname); + + if (query.entries.length !== 0 && this.fallbackDuration > 0) { + // Use `dns.lookup(...)` for that particular hostname + this._hostnamesToFallback.add(hostname); + } + } + + const cacheTtl = query.entries.length === 0 ? this.errorTtl : query.cacheTtl; + await this._set(hostname, query.entries, cacheTtl); + + return query.entries; + } + + _tick(ms) { + const nextRemovalTime = this._nextRemovalTime; + + if (!nextRemovalTime || ms < nextRemovalTime) { + clearTimeout(this._removalTimeout); + + this._nextRemovalTime = ms; + + this._removalTimeout = setTimeout(() => { + this._nextRemovalTime = false; + + let nextExpiry = Infinity; + + const now = Date.now(); + + for (const [hostname, entries] of this._cache) { + const expires = entries[kExpires]; + + if (now >= expires) { + this._cache.delete(hostname); + } else if (expires < nextExpiry) { + nextExpiry = expires; + } + } + + if (nextExpiry !== Infinity) { + this._tick(nextExpiry - now); + } + }, ms); + + /* istanbul ignore next: There is no `timeout.unref()` when running inside an Electron renderer */ + if (this._removalTimeout.unref) { + this._removalTimeout.unref(); + } + } + } + + install(agent) { + verifyAgent(agent); + + if (kCacheableLookupCreateConnection in agent) { + throw new Error('CacheableLookup has been already installed'); + } + + agent[kCacheableLookupCreateConnection] = agent.createConnection; + agent[kCacheableLookupInstance] = this; + + agent.createConnection = (options, callback) => { + if (!('lookup' in options)) { + options.lookup = this.lookup; + } + + return agent[kCacheableLookupCreateConnection](options, callback); + }; + } + + uninstall(agent) { + verifyAgent(agent); + + if (agent[kCacheableLookupCreateConnection]) { + if (agent[kCacheableLookupInstance] !== this) { + throw new Error('The agent is not owned by this CacheableLookup instance'); + } + + agent.createConnection = agent[kCacheableLookupCreateConnection]; + + delete agent[kCacheableLookupCreateConnection]; + delete agent[kCacheableLookupInstance]; + } + } + + updateInterfaceInfo() { + const {_iface} = this; + + this._iface = getIfaceInfo(); + + if ((_iface.has4 && !this._iface.has4) || (_iface.has6 && !this._iface.has6)) { + this._cache.clear(); + } + } + + clear(hostname) { + if (hostname) { + this._cache.delete(hostname); + return; + } + + this._cache.clear(); + } } -function assertNonEmptyStringAndNotWhitespace(value, message) { - if (!isNonEmptyStringAndNotWhitespace(value)) { - throw new TypeError(message ?? typeErrorMessage('non-empty string and not whitespace', value)); + +// EXTERNAL MODULE: ./node_modules/.pnpm/http2-wrapper@2.2.1/node_modules/http2-wrapper/source/index.js +var http2_wrapper_source = __nccwpck_require__(9695); +;// CONCATENATED MODULE: ./node_modules/.pnpm/got@14.4.4/node_modules/got/dist/source/core/parse-link-header.js +function parseLinkHeader(link) { + const parsed = []; + const items = link.split(','); + for (const item of items) { + // https://tools.ietf.org/html/rfc5988#section-5 + const [rawUriReference, ...rawLinkParameters] = item.split(';'); + const trimmedUriReference = rawUriReference.trim(); + // eslint-disable-next-line @typescript-eslint/prefer-string-starts-ends-with + if (trimmedUriReference[0] !== '<' || trimmedUriReference.at(-1) !== '>') { + throw new Error(`Invalid format of the Link header reference: ${trimmedUriReference}`); + } + const reference = trimmedUriReference.slice(1, -1); + const parameters = {}; + if (rawLinkParameters.length === 0) { + throw new Error(`Unexpected end of Link header parameters: ${rawLinkParameters.join(';')}`); + } + for (const rawParameter of rawLinkParameters) { + const trimmedRawParameter = rawParameter.trim(); + const center = trimmedRawParameter.indexOf('='); + if (center === -1) { + throw new Error(`Failed to parse Link header: ${link}`); + } + const name = trimmedRawParameter.slice(0, center).trim(); + const value = trimmedRawParameter.slice(center + 1).trim(); + parameters[name] = value; + } + parsed.push({ + reference, + parameters, + }); } + return parsed; } -// eslint-disable-next-line @typescript-eslint/ban-types -function assertNull(value, message) { - if (!isNull(value)) { - throw new TypeError(message ?? typeErrorMessage('null', value)); + +;// CONCATENATED MODULE: ./node_modules/.pnpm/got@14.4.4/node_modules/got/dist/source/core/options.js + + + +// DO NOT use destructuring for `https.request` and `http.request` as it's not compatible with `nock`. + + + + + + + + +const [major, minor] = external_node_process_.versions.node.split('.').map(Number); +function validateSearchParameters(searchParameters) { + // eslint-disable-next-line guard-for-in + for (const key in searchParameters) { + const value = searchParameters[key]; + assert.any([distribution.string, distribution.number, distribution.boolean, distribution["null"], distribution.undefined], value); } } -// eslint-disable-next-line @typescript-eslint/ban-types -function assertNullOrUndefined(value, message) { - if (!isNullOrUndefined(value)) { - throw new TypeError(message ?? typeErrorMessage('null or undefined', value)); +const globalCache = new Map(); +let globalDnsCache; +const getGlobalDnsCache = () => { + if (globalDnsCache) { + return globalDnsCache; } -} -function assertNumber(value, message) { - if (!isNumber(value)) { - throw new TypeError(message ?? typeErrorMessage('number', value)); + globalDnsCache = new CacheableLookup(); + return globalDnsCache; +}; +const defaultInternals = { + request: undefined, + agent: { + http: undefined, + https: undefined, + http2: undefined, + }, + h2session: undefined, + decompress: true, + timeout: { + connect: undefined, + lookup: undefined, + read: undefined, + request: undefined, + response: undefined, + secureConnect: undefined, + send: undefined, + socket: undefined, + }, + prefixUrl: '', + body: undefined, + form: undefined, + json: undefined, + cookieJar: undefined, + ignoreInvalidCookies: false, + searchParams: undefined, + dnsLookup: undefined, + dnsCache: undefined, + context: {}, + hooks: { + init: [], + beforeRequest: [], + beforeError: [], + beforeRedirect: [], + beforeRetry: [], + afterResponse: [], + }, + followRedirect: true, + maxRedirects: 10, + cache: undefined, + throwHttpErrors: true, + username: '', + password: '', + http2: false, + allowGetBody: false, + headers: { + 'user-agent': 'got (https://github.com/sindresorhus/got)', + }, + methodRewriting: false, + dnsLookupIpVersion: undefined, + parseJson: JSON.parse, + stringifyJson: JSON.stringify, + retry: { + limit: 2, + methods: [ + 'GET', + 'PUT', + 'HEAD', + 'DELETE', + 'OPTIONS', + 'TRACE', + ], + statusCodes: [ + 408, + 413, + 429, + 500, + 502, + 503, + 504, + 521, + 522, + 524, + ], + errorCodes: [ + 'ETIMEDOUT', + 'ECONNRESET', + 'EADDRINUSE', + 'ECONNREFUSED', + 'EPIPE', + 'ENOTFOUND', + 'ENETUNREACH', + 'EAI_AGAIN', + ], + maxRetryAfter: undefined, + calculateDelay: ({ computedValue }) => computedValue, + backoffLimit: Number.POSITIVE_INFINITY, + noise: 100, + }, + localAddress: undefined, + method: 'GET', + createConnection: undefined, + cacheOptions: { + shared: undefined, + cacheHeuristic: undefined, + immutableMinTimeToLive: undefined, + ignoreCargoCult: undefined, + }, + https: { + alpnProtocols: undefined, + rejectUnauthorized: undefined, + checkServerIdentity: undefined, + certificateAuthority: undefined, + key: undefined, + certificate: undefined, + passphrase: undefined, + pfx: undefined, + ciphers: undefined, + honorCipherOrder: undefined, + minVersion: undefined, + maxVersion: undefined, + signatureAlgorithms: undefined, + tlsSessionLifetime: undefined, + dhparam: undefined, + ecdhCurve: undefined, + certificateRevocationLists: undefined, + }, + encoding: undefined, + resolveBodyOnly: false, + isStream: false, + responseType: 'text', + url: undefined, + pagination: { + transform(response) { + if (response.request.options.responseType === 'json') { + return response.body; + } + return JSON.parse(response.body); + }, + paginate({ response }) { + const rawLinkHeader = response.headers.link; + if (typeof rawLinkHeader !== 'string' || rawLinkHeader.trim() === '') { + return false; + } + const parsed = parseLinkHeader(rawLinkHeader); + const next = parsed.find(entry => entry.parameters.rel === 'next' || entry.parameters.rel === '"next"'); + if (next) { + return { + url: new URL(next.reference, response.url), + }; + } + return false; + }, + filter: () => true, + shouldContinue: () => true, + countLimit: Number.POSITIVE_INFINITY, + backoff: 0, + requestLimit: 10_000, + stackAllItems: false, + }, + setHost: true, + maxHeaderSize: undefined, + signal: undefined, + enableUnixSockets: false, +}; +const cloneInternals = (internals) => { + const { hooks, retry } = internals; + const result = { + ...internals, + context: { ...internals.context }, + cacheOptions: { ...internals.cacheOptions }, + https: { ...internals.https }, + agent: { ...internals.agent }, + headers: { ...internals.headers }, + retry: { + ...retry, + errorCodes: [...retry.errorCodes], + methods: [...retry.methods], + statusCodes: [...retry.statusCodes], + }, + timeout: { ...internals.timeout }, + hooks: { + init: [...hooks.init], + beforeRequest: [...hooks.beforeRequest], + beforeError: [...hooks.beforeError], + beforeRedirect: [...hooks.beforeRedirect], + beforeRetry: [...hooks.beforeRetry], + afterResponse: [...hooks.afterResponse], + }, + searchParams: internals.searchParams ? new URLSearchParams(internals.searchParams) : undefined, + pagination: { ...internals.pagination }, + }; + if (result.url !== undefined) { + result.prefixUrl = ''; } -} -function assertNumericString(value, message) { - if (!isNumericString(value)) { - throw new TypeError(message ?? typeErrorMessage('string with a number', value)); + return result; +}; +const cloneRaw = (raw) => { + const { hooks, retry } = raw; + const result = { ...raw }; + if (distribution.object(raw.context)) { + result.context = { ...raw.context }; } -} -// eslint-disable-next-line @typescript-eslint/ban-types -function assertObject(value, message) { - if (!isObject(value)) { - throw new TypeError(message ?? typeErrorMessage('Object', value)); + if (distribution.object(raw.cacheOptions)) { + result.cacheOptions = { ...raw.cacheOptions }; } -} -function assertObservable(value, message) { - if (!isObservable(value)) { - throw new TypeError(message ?? typeErrorMessage('Observable', value)); + if (distribution.object(raw.https)) { + result.https = { ...raw.https }; } -} -function assertOddInteger(value, message) { - if (!isOddInteger(value)) { - throw new TypeError(message ?? typeErrorMessage('odd integer', value)); + if (distribution.object(raw.cacheOptions)) { + result.cacheOptions = { ...result.cacheOptions }; } -} -function assertPlainObject(value, message) { - if (!isPlainObject(value)) { - throw new TypeError(message ?? typeErrorMessage('plain object', value)); + if (distribution.object(raw.agent)) { + result.agent = { ...raw.agent }; } -} -function assertPositiveNumber(value, message) { - if (!isPositiveNumber(value)) { - throw new TypeError(message ?? typeErrorMessage('positive number', value)); + if (distribution.object(raw.headers)) { + result.headers = { ...raw.headers }; } -} -function assertPrimitive(value, message) { - if (!isPrimitive(value)) { - throw new TypeError(message ?? typeErrorMessage('primitive', value)); + if (distribution.object(retry)) { + result.retry = { ...retry }; + if (distribution.array(retry.errorCodes)) { + result.retry.errorCodes = [...retry.errorCodes]; + } + if (distribution.array(retry.methods)) { + result.retry.methods = [...retry.methods]; + } + if (distribution.array(retry.statusCodes)) { + result.retry.statusCodes = [...retry.statusCodes]; + } } -} -function assertPromise(value, message) { - if (!isPromise(value)) { - throw new TypeError(message ?? typeErrorMessage('Promise', value)); + if (distribution.object(raw.timeout)) { + result.timeout = { ...raw.timeout }; } -} -function assertPropertyKey(value, message) { - if (!isPropertyKey(value)) { - throw new TypeError(message ?? typeErrorMessage('PropertyKey', value)); + if (distribution.object(hooks)) { + result.hooks = { + ...hooks, + }; + if (distribution.array(hooks.init)) { + result.hooks.init = [...hooks.init]; + } + if (distribution.array(hooks.beforeRequest)) { + result.hooks.beforeRequest = [...hooks.beforeRequest]; + } + if (distribution.array(hooks.beforeError)) { + result.hooks.beforeError = [...hooks.beforeError]; + } + if (distribution.array(hooks.beforeRedirect)) { + result.hooks.beforeRedirect = [...hooks.beforeRedirect]; + } + if (distribution.array(hooks.beforeRetry)) { + result.hooks.beforeRetry = [...hooks.beforeRetry]; + } + if (distribution.array(hooks.afterResponse)) { + result.hooks.afterResponse = [...hooks.afterResponse]; + } } -} -function assertRegExp(value, message) { - if (!isRegExp(value)) { - throw new TypeError(message ?? typeErrorMessage('RegExp', value)); + // TODO: raw.searchParams + if (distribution.object(raw.pagination)) { + result.pagination = { ...raw.pagination }; } -} -function assertSafeInteger(value, message) { - if (!isSafeInteger(value)) { - throw new TypeError(message ?? typeErrorMessage('integer', value)); + return result; +}; +const getHttp2TimeoutOption = (internals) => { + const delays = [internals.timeout.socket, internals.timeout.connect, internals.timeout.lookup, internals.timeout.request, internals.timeout.secureConnect].filter(delay => typeof delay === 'number'); + if (delays.length > 0) { + return Math.min(...delays); } -} -function assertSet(value, message) { - if (!isSet(value)) { - throw new TypeError(message ?? typeErrorMessage('Set', value)); + return undefined; +}; +const init = (options, withOptions, self) => { + const initHooks = options.hooks?.init; + if (initHooks) { + for (const hook of initHooks) { + hook(withOptions, self); + } } -} -function assertSharedArrayBuffer(value, message) { - if (!isSharedArrayBuffer(value)) { - throw new TypeError(message ?? typeErrorMessage('SharedArrayBuffer', value)); +}; +class Options { + _unixOptions; + _internals; + _merging; + _init; + constructor(input, options, defaults) { + assert.any([distribution.string, distribution.urlInstance, distribution.object, distribution.undefined], input); + assert.any([distribution.object, distribution.undefined], options); + assert.any([distribution.object, distribution.undefined], defaults); + if (input instanceof Options || options instanceof Options) { + throw new TypeError('The defaults must be passed as the third argument'); + } + this._internals = cloneInternals(defaults?._internals ?? defaults ?? defaultInternals); + this._init = [...(defaults?._init ?? [])]; + this._merging = false; + this._unixOptions = undefined; + // This rule allows `finally` to be considered more important. + // Meaning no matter the error thrown in the `try` block, + // if `finally` throws then the `finally` error will be thrown. + // + // Yes, we want this. If we set `url` first, then the `url.searchParams` + // would get merged. Instead we set the `searchParams` first, then + // `url.searchParams` is overwritten as expected. + // + /* eslint-disable no-unsafe-finally */ + try { + if (distribution.plainObject(input)) { + try { + this.merge(input); + this.merge(options); + } + finally { + this.url = input.url; + } + } + else { + try { + this.merge(options); + } + finally { + if (options?.url !== undefined) { + if (input === undefined) { + this.url = options.url; + } + else { + throw new TypeError('The `url` option is mutually exclusive with the `input` argument'); + } + } + else if (input !== undefined) { + this.url = input; + } + } + } + } + catch (error) { + error.options = this; + throw error; + } + /* eslint-enable no-unsafe-finally */ } -} -function assertString(value, message) { - if (!isString(value)) { - throw new TypeError(message ?? typeErrorMessage('string', value)); + merge(options) { + if (!options) { + return; + } + if (options instanceof Options) { + for (const init of options._init) { + this.merge(init); + } + return; + } + options = cloneRaw(options); + init(this, options, this); + init(options, options, this); + this._merging = true; + // Always merge `isStream` first + if ('isStream' in options) { + this.isStream = options.isStream; + } + try { + let push = false; + for (const key in options) { + // `got.extend()` options + if (key === 'mutableDefaults' || key === 'handlers') { + continue; + } + // Never merge `url` + if (key === 'url') { + continue; + } + if (!(key in this)) { + throw new Error(`Unexpected option: ${key}`); + } + // @ts-expect-error Type 'unknown' is not assignable to type 'never'. + const value = options[key]; + if (value === undefined) { + continue; + } + // @ts-expect-error Type 'unknown' is not assignable to type 'never'. + this[key] = value; + push = true; + } + if (push) { + this._init.push(options); + } + } + finally { + this._merging = false; + } } -} -function assertSymbol(value, message) { - if (!isSymbol(value)) { - throw new TypeError(message ?? typeErrorMessage('symbol', value)); + /** + Custom request function. + The main purpose of this is to [support HTTP2 using a wrapper](https://github.com/szmarczak/http2-wrapper). + + @default http.request | https.request + */ + get request() { + return this._internals.request; } -} -function assertTruthy(value, message) { - if (!isTruthy(value)) { - throw new TypeError(message ?? typeErrorMessage('truthy', value)); + set request(value) { + assert.any([distribution["function"], distribution.undefined], value); + this._internals.request = value; } -} -function assertTupleLike(value, guards, message) { - if (!isTupleLike(value, guards)) { - throw new TypeError(message ?? typeErrorMessage('tuple-like', value)); + /** + An object representing `http`, `https` and `http2` keys for [`http.Agent`](https://nodejs.org/api/http.html#http_class_http_agent), [`https.Agent`](https://nodejs.org/api/https.html#https_class_https_agent) and [`http2wrapper.Agent`](https://github.com/szmarczak/http2-wrapper#new-http2agentoptions) instance. + This is necessary because a request to one protocol might redirect to another. + In such a scenario, Got will switch over to the right protocol agent for you. + + If a key is not present, it will default to a global agent. + + @example + ``` + import got from 'got'; + import HttpAgent from 'agentkeepalive'; + + const {HttpsAgent} = HttpAgent; + + await got('https://sindresorhus.com', { + agent: { + http: new HttpAgent(), + https: new HttpsAgent() + } + }); + ``` + */ + get agent() { + return this._internals.agent; } -} -function assertTypedArray(value, message) { - if (!isTypedArray(value)) { - throw new TypeError(message ?? typeErrorMessage('TypedArray', value)); + set agent(value) { + assert.plainObject(value); + // eslint-disable-next-line guard-for-in + for (const key in value) { + if (!(key in this._internals.agent)) { + throw new TypeError(`Unexpected agent option: ${key}`); + } + // @ts-expect-error - No idea why `value[key]` doesn't work here. + assert.any([distribution.object, distribution.undefined], value[key]); + } + if (this._merging) { + Object.assign(this._internals.agent, value); + } + else { + this._internals.agent = { ...value }; + } } -} -function assertUint16Array(value, message) { - if (!isUint16Array(value)) { - throw new TypeError(message ?? typeErrorMessage('Uint16Array', value)); + get h2session() { + return this._internals.h2session; } -} -function assertUint32Array(value, message) { - if (!isUint32Array(value)) { - throw new TypeError(message ?? typeErrorMessage('Uint32Array', value)); + set h2session(value) { + this._internals.h2session = value; } -} -function assertUint8Array(value, message) { - if (!isUint8Array(value)) { - throw new TypeError(message ?? typeErrorMessage('Uint8Array', value)); + /** + Decompress the response automatically. + + This will set the `accept-encoding` header to `gzip, deflate, br` unless you set it yourself. + + If this is disabled, a compressed response is returned as a `Buffer`. + This may be useful if you want to handle decompression yourself or stream the raw compressed data. + + @default true + */ + get decompress() { + return this._internals.decompress; } -} -function assertUint8ClampedArray(value, message) { - if (!isUint8ClampedArray(value)) { - throw new TypeError(message ?? typeErrorMessage('Uint8ClampedArray', value)); + set decompress(value) { + assert.boolean(value); + this._internals.decompress = value; } -} -function assertUndefined(value, message) { - if (!isUndefined(value)) { - throw new TypeError(message ?? typeErrorMessage('undefined', value)); + /** + Milliseconds to wait for the server to end the response before aborting the request with `got.TimeoutError` error (a.k.a. `request` property). + By default, there's no timeout. + + This also accepts an `object` with the following fields to constrain the duration of each phase of the request lifecycle: + + - `lookup` starts when a socket is assigned and ends when the hostname has been resolved. + Does not apply when using a Unix domain socket. + - `connect` starts when `lookup` completes (or when the socket is assigned if lookup does not apply to the request) and ends when the socket is connected. + - `secureConnect` starts when `connect` completes and ends when the handshaking process completes (HTTPS only). + - `socket` starts when the socket is connected. See [request.setTimeout](https://nodejs.org/api/http.html#http_request_settimeout_timeout_callback). + - `response` starts when the request has been written to the socket and ends when the response headers are received. + - `send` starts when the socket is connected and ends with the request has been written to the socket. + - `request` starts when the request is initiated and ends when the response's end event fires. + */ + get timeout() { + // We always return `Delays` here. + // It has to be `Delays | number`, otherwise TypeScript will error because the getter and the setter have incompatible types. + return this._internals.timeout; } -} -function assertUrlInstance(value, message) { - if (!isUrlInstance(value)) { - throw new TypeError(message ?? typeErrorMessage('URL', value)); + set timeout(value) { + assert.plainObject(value); + // eslint-disable-next-line guard-for-in + for (const key in value) { + if (!(key in this._internals.timeout)) { + throw new Error(`Unexpected timeout option: ${key}`); + } + // @ts-expect-error - No idea why `value[key]` doesn't work here. + assert.any([distribution.number, distribution.undefined], value[key]); + } + if (this._merging) { + Object.assign(this._internals.timeout, value); + } + else { + this._internals.timeout = { ...value }; + } } -} -// eslint-disable-next-line unicorn/prevent-abbreviations -function assertUrlSearchParams(value, message) { - if (!isUrlSearchParams(value)) { - throw new TypeError(message ?? typeErrorMessage('URLSearchParams', value)); + /** + When specified, `prefixUrl` will be prepended to `url`. + The prefix can be any valid URL, either relative or absolute. + A trailing slash `/` is optional - one will be added automatically. + + __Note__: `prefixUrl` will be ignored if the `url` argument is a URL instance. + + __Note__: Leading slashes in `input` are disallowed when using this option to enforce consistency and avoid confusion. + For example, when the prefix URL is `https://example.com/foo` and the input is `/bar`, there's ambiguity whether the resulting URL would become `https://example.com/foo/bar` or `https://example.com/bar`. + The latter is used by browsers. + + __Tip__: Useful when used with `got.extend()` to create niche-specific Got instances. + + __Tip__: You can change `prefixUrl` using hooks as long as the URL still includes the `prefixUrl`. + If the URL doesn't include it anymore, it will throw. + + @example + ``` + import got from 'got'; + + await got('unicorn', {prefixUrl: 'https://cats.com'}); + //=> 'https://cats.com/unicorn' + + const instance = got.extend({ + prefixUrl: 'https://google.com' + }); + + await instance('unicorn', { + hooks: { + beforeRequest: [ + options => { + options.prefixUrl = 'https://cats.com'; + } + ] + } + }); + //=> 'https://cats.com/unicorn' + ``` + */ + get prefixUrl() { + // We always return `string` here. + // It has to be `string | URL`, otherwise TypeScript will error because the getter and the setter have incompatible types. + return this._internals.prefixUrl; } -} -function assertUrlString(value, message) { - if (!isUrlString(value)) { - throw new TypeError(message ?? typeErrorMessage('string with a URL', value)); + set prefixUrl(value) { + assert.any([distribution.string, distribution.urlInstance], value); + if (value === '') { + this._internals.prefixUrl = ''; + return; + } + value = value.toString(); + if (!value.endsWith('/')) { + value += '/'; + } + if (this._internals.prefixUrl && this._internals.url) { + const { href } = this._internals.url; + this._internals.url.href = value + href.slice(this._internals.prefixUrl.length); + } + this._internals.prefixUrl = value; } -} -function assertValidDate(value, message) { - if (!isValidDate(value)) { - throw new TypeError(message ?? typeErrorMessage('valid Date', value)); + /** + __Note #1__: The `body` option cannot be used with the `json` or `form` option. + + __Note #2__: If you provide this option, `got.stream()` will be read-only. + + __Note #3__: If you provide a payload with the `GET` or `HEAD` method, it will throw a `TypeError` unless the method is `GET` and the `allowGetBody` option is set to `true`. + + __Note #4__: This option is not enumerable and will not be merged with the instance defaults. + + The `content-length` header will be automatically set if `body` is a `string` / `Buffer` / [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData) / [`form-data` instance](https://github.com/form-data/form-data), and `content-length` and `transfer-encoding` are not manually set in `options.headers`. + + Since Got 12, the `content-length` is not automatically set when `body` is a `fs.createReadStream`. + */ + get body() { + return this._internals.body; } -} -function assertValidLength(value, message) { - if (!isValidLength(value)) { - throw new TypeError(message ?? typeErrorMessage('valid length', value)); + set body(value) { + assert.any([distribution.string, distribution.buffer, distribution.nodeStream, distribution.generator, distribution.asyncGenerator, lib_isFormData, distribution.undefined], value); + if (distribution.nodeStream(value)) { + assert.truthy(value.readable); + } + if (value !== undefined) { + assert.undefined(this._internals.form); + assert.undefined(this._internals.json); + } + this._internals.body = value; } -} -// eslint-disable-next-line @typescript-eslint/ban-types -function assertWeakMap(value, message) { - if (!isWeakMap(value)) { - throw new TypeError(message ?? typeErrorMessage('WeakMap', value)); + /** + The form body is converted to a query string using [`(new URLSearchParams(object)).toString()`](https://nodejs.org/api/url.html#url_constructor_new_urlsearchparams_obj). + + If the `Content-Type` header is not present, it will be set to `application/x-www-form-urlencoded`. + + __Note #1__: If you provide this option, `got.stream()` will be read-only. + + __Note #2__: This option is not enumerable and will not be merged with the instance defaults. + */ + get form() { + return this._internals.form; } -} -// eslint-disable-next-line @typescript-eslint/ban-types, unicorn/prevent-abbreviations -function assertWeakRef(value, message) { - if (!isWeakRef(value)) { - throw new TypeError(message ?? typeErrorMessage('WeakRef', value)); + set form(value) { + assert.any([distribution.plainObject, distribution.undefined], value); + if (value !== undefined) { + assert.undefined(this._internals.body); + assert.undefined(this._internals.json); + } + this._internals.form = value; } -} -// eslint-disable-next-line @typescript-eslint/ban-types -function assertWeakSet(value, message) { - if (!isWeakSet(value)) { - throw new TypeError(message ?? typeErrorMessage('WeakSet', value)); + /** + JSON body. If the `Content-Type` header is not set, it will be set to `application/json`. + + __Note #1__: If you provide this option, `got.stream()` will be read-only. + + __Note #2__: This option is not enumerable and will not be merged with the instance defaults. + */ + get json() { + return this._internals.json; } -} -function assertWhitespaceString(value, message) { - if (!isWhitespaceString(value)) { - throw new TypeError(message ?? typeErrorMessage('whitespace string', value)); + set json(value) { + if (value !== undefined) { + assert.undefined(this._internals.body); + assert.undefined(this._internals.form); + } + this._internals.json = value; } -} -/* harmony default export */ const distribution = (is); + /** + The URL to request, as a string, a [`https.request` options object](https://nodejs.org/api/https.html#https_https_request_options_callback), or a [WHATWG `URL`](https://nodejs.org/api/url.html#url_class_url). -// EXTERNAL MODULE: external "node:events" -var external_node_events_ = __nccwpck_require__(5673); -;// CONCATENATED MODULE: ./node_modules/.pnpm/p-cancelable@4.0.1/node_modules/p-cancelable/index.js -class CancelError extends Error { - constructor(reason) { - super(reason || 'Promise was canceled'); - this.name = 'CancelError'; - } + Properties from `options` will override properties in the parsed `url`. - get isCanceled() { - return true; - } -} + If no protocol is specified, it will throw a `TypeError`. -const promiseState = Object.freeze({ - pending: Symbol('pending'), - canceled: Symbol('canceled'), - resolved: Symbol('resolved'), - rejected: Symbol('rejected'), -}); + __Note__: The query string is **not** parsed as search params. -class PCancelable { - static fn(userFunction) { - return (...arguments_) => new PCancelable((resolve, reject, onCancel) => { - arguments_.push(onCancel); - userFunction(...arguments_).then(resolve, reject); - }); - } + @example + ``` + await got('https://example.com/?query=a b'); //=> https://example.com/?query=a%20b + await got('https://example.com/', {searchParams: {query: 'a b'}}); //=> https://example.com/?query=a+b - #cancelHandlers = []; - #rejectOnCancel = true; - #state = promiseState.pending; - #promise; - #reject; + // The query string is overridden by `searchParams` + await got('https://example.com/?query=a b', {searchParams: {query: 'a b'}}); //=> https://example.com/?query=a+b + ``` + */ + get url() { + return this._internals.url; + } + set url(value) { + assert.any([distribution.string, distribution.urlInstance, distribution.undefined], value); + if (value === undefined) { + this._internals.url = undefined; + return; + } + if (distribution.string(value) && value.startsWith('/')) { + throw new Error('`url` must not start with a slash'); + } + const urlString = `${this.prefixUrl}${value.toString()}`; + const url = new URL(urlString); + this._internals.url = url; + if (url.protocol === 'unix:') { + url.href = `http://unix${url.pathname}${url.search}`; + } + if (url.protocol !== 'http:' && url.protocol !== 'https:') { + const error = new Error(`Unsupported protocol: ${url.protocol}`); + error.code = 'ERR_UNSUPPORTED_PROTOCOL'; + throw error; + } + if (this._internals.username) { + url.username = this._internals.username; + this._internals.username = ''; + } + if (this._internals.password) { + url.password = this._internals.password; + this._internals.password = ''; + } + if (this._internals.searchParams) { + url.search = this._internals.searchParams.toString(); + this._internals.searchParams = undefined; + } + if (url.hostname === 'unix') { + if (!this._internals.enableUnixSockets) { + throw new Error('Using UNIX domain sockets but option `enableUnixSockets` is not enabled'); + } + const matches = /(?.+?):(?.+)/.exec(`${url.pathname}${url.search}`); + if (matches?.groups) { + const { socketPath, path } = matches.groups; + this._unixOptions = { + socketPath, + path, + host: '', + }; + } + else { + this._unixOptions = undefined; + } + return; + } + this._unixOptions = undefined; + } + /** + Cookie support. You don't have to care about parsing or how to store them. - constructor(executor) { - this.#promise = new Promise((resolve, reject) => { - this.#reject = reject; + __Note__: If you provide this option, `options.headers.cookie` will be overridden. + */ + get cookieJar() { + return this._internals.cookieJar; + } + set cookieJar(value) { + assert.any([distribution.object, distribution.undefined], value); + if (value === undefined) { + this._internals.cookieJar = undefined; + return; + } + let { setCookie, getCookieString } = value; + assert["function"](setCookie); + assert["function"](getCookieString); + /* istanbul ignore next: Horrible `tough-cookie` v3 check */ + if (setCookie.length === 4 && getCookieString.length === 0) { + setCookie = (0,external_node_util_.promisify)(setCookie.bind(value)); + getCookieString = (0,external_node_util_.promisify)(getCookieString.bind(value)); + this._internals.cookieJar = { + setCookie, + getCookieString: getCookieString, + }; + } + else { + this._internals.cookieJar = value; + } + } + /** + You can abort the `request` using [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController). - const onResolve = value => { - if (this.#state !== promiseState.canceled || !onCancel.shouldReject) { - resolve(value); - this.#setState(promiseState.resolved); - } - }; + @example + ``` + import got from 'got'; - const onReject = error => { - if (this.#state !== promiseState.canceled || !onCancel.shouldReject) { - reject(error); - this.#setState(promiseState.rejected); - } - }; + const abortController = new AbortController(); - const onCancel = handler => { - if (this.#state !== promiseState.pending) { - throw new Error(`The \`onCancel\` handler was attached after the promise ${this.#state.description}.`); - } + const request = got('https://httpbin.org/anything', { + signal: abortController.signal + }); - this.#cancelHandlers.push(handler); - }; + setTimeout(() => { + abortController.abort(); + }, 100); + ``` + */ + get signal() { + return this._internals.signal; + } + set signal(value) { + assert.object(value); + this._internals.signal = value; + } + /** + Ignore invalid cookies instead of throwing an error. + Only useful when the `cookieJar` option has been set. Not recommended. - Object.defineProperties(onCancel, { - shouldReject: { - get: () => this.#rejectOnCancel, - set: boolean => { - this.#rejectOnCancel = boolean; - }, - }, - }); + @default false + */ + get ignoreInvalidCookies() { + return this._internals.ignoreInvalidCookies; + } + set ignoreInvalidCookies(value) { + assert.boolean(value); + this._internals.ignoreInvalidCookies = value; + } + /** + Query string that will be added to the request URL. + This will override the query string in `url`. - executor(onResolve, onReject, onCancel); - }); - } + If you need to pass in an array, you can do it using a `URLSearchParams` instance. - // eslint-disable-next-line unicorn/no-thenable - then(onFulfilled, onRejected) { - return this.#promise.then(onFulfilled, onRejected); - } + @example + ``` + import got from 'got'; - catch(onRejected) { - return this.#promise.catch(onRejected); - } + const searchParams = new URLSearchParams([['key', 'a'], ['key', 'b']]); - finally(onFinally) { - return this.#promise.finally(onFinally); - } + await got('https://example.com', {searchParams}); - cancel(reason) { - if (this.#state !== promiseState.pending) { - return; - } + console.log(searchParams.toString()); + //=> 'key=a&key=b' + ``` + */ + get searchParams() { + if (this._internals.url) { + return this._internals.url.searchParams; + } + if (this._internals.searchParams === undefined) { + this._internals.searchParams = new URLSearchParams(); + } + return this._internals.searchParams; + } + set searchParams(value) { + assert.any([distribution.string, distribution.object, distribution.undefined], value); + const url = this._internals.url; + if (value === undefined) { + this._internals.searchParams = undefined; + if (url) { + url.search = ''; + } + return; + } + const searchParameters = this.searchParams; + let updated; + if (distribution.string(value)) { + updated = new URLSearchParams(value); + } + else if (value instanceof URLSearchParams) { + updated = value; + } + else { + validateSearchParameters(value); + updated = new URLSearchParams(); + // eslint-disable-next-line guard-for-in + for (const key in value) { + const entry = value[key]; + if (entry === null) { + updated.append(key, ''); + } + else if (entry === undefined) { + searchParameters.delete(key); + } + else { + updated.append(key, entry); + } + } + } + if (this._merging) { + // These keys will be replaced + for (const key of updated.keys()) { + searchParameters.delete(key); + } + for (const [key, value] of updated) { + searchParameters.append(key, value); + } + } + else if (url) { + url.search = searchParameters.toString(); + } + else { + this._internals.searchParams = searchParameters; + } + } + get searchParameters() { + throw new Error('The `searchParameters` option does not exist. Use `searchParams` instead.'); + } + set searchParameters(_value) { + throw new Error('The `searchParameters` option does not exist. Use `searchParams` instead.'); + } + get dnsLookup() { + return this._internals.dnsLookup; + } + set dnsLookup(value) { + assert.any([distribution["function"], distribution.undefined], value); + this._internals.dnsLookup = value; + } + /** + An instance of [`CacheableLookup`](https://github.com/szmarczak/cacheable-lookup) used for making DNS lookups. + Useful when making lots of requests to different *public* hostnames. - this.#setState(promiseState.canceled); + `CacheableLookup` uses `dns.resolver4(..)` and `dns.resolver6(...)` under the hood and fall backs to `dns.lookup(...)` when the first two fail, which may lead to additional delay. - if (this.#cancelHandlers.length > 0) { - try { - for (const handler of this.#cancelHandlers) { - handler(); - } - } catch (error) { - this.#reject(error); - return; - } - } + __Note__: This should stay disabled when making requests to internal hostnames such as `localhost`, `database.local` etc. - if (this.#rejectOnCancel) { - this.#reject(new CancelError(reason)); - } - } + @default false + */ + get dnsCache() { + return this._internals.dnsCache; + } + set dnsCache(value) { + assert.any([distribution.object, distribution.boolean, distribution.undefined], value); + if (value === true) { + this._internals.dnsCache = getGlobalDnsCache(); + } + else if (value === false) { + this._internals.dnsCache = undefined; + } + else { + this._internals.dnsCache = value; + } + } + /** + User data. `context` is shallow merged and enumerable. If it contains non-enumerable properties they will NOT be merged. - get isCanceled() { - return this.#state === promiseState.canceled; - } + @example + ``` + import got from 'got'; - #setState(state) { - if (this.#state === promiseState.pending) { - this.#state = state; - } - } -} + const instance = got.extend({ + hooks: { + beforeRequest: [ + options => { + if (!options.context || !options.context.token) { + throw new Error('Token required'); + } -Object.setPrototypeOf(PCancelable.prototype, Promise.prototype); + options.headers.token = options.context.token; + } + ] + } + }); -;// CONCATENATED MODULE: ./node_modules/.pnpm/got@14.4.2/node_modules/got/dist/source/core/errors.js + const context = { + token: 'secret' + }; -// A hacky check to prevent circular references. -function isRequest(x) { - return distribution.object(x) && '_onResponse' in x; -} -/** -An error to be thrown when a request fails. -Contains a `code` property with error class code, like `ECONNREFUSED`. -*/ -class RequestError extends Error { - input; - code; - stack; - response; - request; - timings; - constructor(message, error, self) { - super(message, { cause: error }); - Error.captureStackTrace(this, this.constructor); - this.name = 'RequestError'; - this.code = error.code ?? 'ERR_GOT_REQUEST_ERROR'; - this.input = error.input; - if (isRequest(self)) { - Object.defineProperty(this, 'request', { - enumerable: false, - value: self, - }); - Object.defineProperty(this, 'response', { - enumerable: false, - value: self.response, - }); - this.options = self.options; + const response = await instance('https://httpbin.org/headers', {context}); + + // Let's see the headers + console.log(response.body); + ``` + */ + get context() { + return this._internals.context; + } + set context(value) { + assert.object(value); + if (this._merging) { + Object.assign(this._internals.context, value); } else { - this.options = self; + this._internals.context = { ...value }; } - this.timings = this.request?.timings; - // Recover the original stacktrace - if (distribution.string(error.stack) && distribution.string(this.stack)) { - const indexOfMessage = this.stack.indexOf(this.message) + this.message.length; - const thisStackTrace = this.stack.slice(indexOfMessage).split('\n').reverse(); - const errorStackTrace = error.stack.slice(error.stack.indexOf(error.message) + error.message.length).split('\n').reverse(); - // Remove duplicated traces - while (errorStackTrace.length > 0 && errorStackTrace[0] === thisStackTrace[0]) { - thisStackTrace.shift(); + } + /** + Hooks allow modifications during the request lifecycle. + Hook functions may be async and are run serially. + */ + get hooks() { + return this._internals.hooks; + } + set hooks(value) { + assert.object(value); + // eslint-disable-next-line guard-for-in + for (const knownHookEvent in value) { + if (!(knownHookEvent in this._internals.hooks)) { + throw new Error(`Unexpected hook event: ${knownHookEvent}`); + } + const typedKnownHookEvent = knownHookEvent; + const hooks = value[typedKnownHookEvent]; + assert.any([distribution.array, distribution.undefined], hooks); + if (hooks) { + for (const hook of hooks) { + assert["function"](hook); + } + } + if (this._merging) { + if (hooks) { + // @ts-expect-error FIXME + this._internals.hooks[typedKnownHookEvent].push(...hooks); + } + } + else { + if (!hooks) { + throw new Error(`Missing hook event: ${knownHookEvent}`); + } + // @ts-expect-error FIXME + this._internals.hooks[knownHookEvent] = [...hooks]; } - this.stack = `${this.stack.slice(0, indexOfMessage)}${thisStackTrace.reverse().join('\n')}${errorStackTrace.reverse().join('\n')}`; } } -} -/** -An error to be thrown when the server redirects you more than ten times. -Includes a `response` property. -*/ -class MaxRedirectsError extends RequestError { - constructor(request) { - super(`Redirected ${request.options.maxRedirects} times. Aborting.`, {}, request); - this.name = 'MaxRedirectsError'; - this.code = 'ERR_TOO_MANY_REDIRECTS'; + /** + Whether redirect responses should be followed automatically. + + Optionally, pass a function to dynamically decide based on the response object. + + Note that if a `303` is sent by the server in response to any request type (`POST`, `DELETE`, etc.), Got will automatically request the resource pointed to in the location header via `GET`. + This is in accordance with [the spec](https://tools.ietf.org/html/rfc7231#section-6.4.4). You can optionally turn on this behavior also for other redirect codes - see `methodRewriting`. + + @default true + */ + get followRedirect() { + return this._internals.followRedirect; + } + set followRedirect(value) { + assert.any([distribution.boolean, distribution["function"]], value); + this._internals.followRedirect = value; + } + get followRedirects() { + throw new TypeError('The `followRedirects` option does not exist. Use `followRedirect` instead.'); + } + set followRedirects(_value) { + throw new TypeError('The `followRedirects` option does not exist. Use `followRedirect` instead.'); + } + /** + If exceeded, the request will be aborted and a `MaxRedirectsError` will be thrown. + + @default 10 + */ + get maxRedirects() { + return this._internals.maxRedirects; + } + set maxRedirects(value) { + assert.number(value); + this._internals.maxRedirects = value; + } + /** + A cache adapter instance for storing cached response data. + + @default false + */ + get cache() { + return this._internals.cache; } -} -/** -An error to be thrown when the server response code is not 2xx nor 3xx if `options.followRedirect` is `true`, but always except for 304. -Includes a `response` property. -*/ -// TODO: Change `HTTPError` to `HTTPError` in the next major version to enforce type usage. -// eslint-disable-next-line @typescript-eslint/naming-convention -class HTTPError extends RequestError { - constructor(response) { - super(`Response code ${response.statusCode} (${response.statusMessage})`, {}, response.request); - this.name = 'HTTPError'; - this.code = 'ERR_NON_2XX_3XX_RESPONSE'; + set cache(value) { + assert.any([distribution.object, distribution.string, distribution.boolean, distribution.undefined], value); + if (value === true) { + this._internals.cache = globalCache; + } + else if (value === false) { + this._internals.cache = undefined; + } + else { + this._internals.cache = value; + } } -} -/** -An error to be thrown when a cache method fails. -For example, if the database goes down or there's a filesystem error. -*/ -class CacheError extends RequestError { - constructor(error, request) { - super(error.message, error, request); - this.name = 'CacheError'; - this.code = this.code === 'ERR_GOT_REQUEST_ERROR' ? 'ERR_CACHE_ACCESS' : this.code; + /** + Determines if a `got.HTTPError` is thrown for unsuccessful responses. + + If this is disabled, requests that encounter an error status code will be resolved with the `response` instead of throwing. + This may be useful if you are checking for resource availability and are expecting error responses. + + @default true + */ + get throwHttpErrors() { + return this._internals.throwHttpErrors; } -} -/** -An error to be thrown when the request body is a stream and an error occurs while reading from that stream. -*/ -class UploadError extends RequestError { - constructor(error, request) { - super(error.message, error, request); - this.name = 'UploadError'; - this.code = this.code === 'ERR_GOT_REQUEST_ERROR' ? 'ERR_UPLOAD' : this.code; + set throwHttpErrors(value) { + assert.boolean(value); + this._internals.throwHttpErrors = value; } -} -/** -An error to be thrown when the request is aborted due to a timeout. -Includes an `event` and `timings` property. -*/ -class TimeoutError extends RequestError { - timings; - event; - constructor(error, timings, request) { - super(error.message, error, request); - this.name = 'TimeoutError'; - this.event = error.event; - this.timings = timings; + get username() { + const url = this._internals.url; + const value = url ? url.username : this._internals.username; + return decodeURIComponent(value); } -} -/** -An error to be thrown when reading from response stream fails. -*/ -class ReadError extends RequestError { - constructor(error, request) { - super(error.message, error, request); - this.name = 'ReadError'; - this.code = this.code === 'ERR_GOT_REQUEST_ERROR' ? 'ERR_READING_RESPONSE_STREAM' : this.code; + set username(value) { + assert.string(value); + const url = this._internals.url; + const fixedValue = encodeURIComponent(value); + if (url) { + url.username = fixedValue; + } + else { + this._internals.username = fixedValue; + } } -} -/** -An error which always triggers a new retry when thrown. -*/ -class RetryError extends RequestError { - constructor(request) { - super('Retrying', {}, request); - this.name = 'RetryError'; - this.code = 'ERR_RETRYING'; + get password() { + const url = this._internals.url; + const value = url ? url.password : this._internals.password; + return decodeURIComponent(value); } -} -/** -An error to be thrown when the request is aborted by AbortController. -*/ -class AbortError extends RequestError { - constructor(request) { - super('This operation was aborted.', {}, request); - this.code = 'ERR_ABORTED'; - this.name = 'AbortError'; + set password(value) { + assert.string(value); + const url = this._internals.url; + const fixedValue = encodeURIComponent(value); + if (url) { + url.password = fixedValue; + } + else { + this._internals.password = fixedValue; + } } -} + /** + If set to `true`, Got will additionally accept HTTP2 requests. -// EXTERNAL MODULE: external "node:process" -var external_node_process_ = __nccwpck_require__(7742); -;// CONCATENATED MODULE: external "node:buffer" -const external_node_buffer_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:buffer"); -// EXTERNAL MODULE: external "node:stream" -var external_node_stream_ = __nccwpck_require__(4492); -// EXTERNAL MODULE: external "node:http" -var external_node_http_ = __nccwpck_require__(8849); -// EXTERNAL MODULE: external "events" -var external_events_ = __nccwpck_require__(2361); -// EXTERNAL MODULE: external "util" -var external_util_ = __nccwpck_require__(3837); -// EXTERNAL MODULE: ./node_modules/.pnpm/defer-to-connect@2.0.1/node_modules/defer-to-connect/dist/source/index.js -var source = __nccwpck_require__(6906); -;// CONCATENATED MODULE: ./node_modules/.pnpm/@szmarczak+http-timer@5.0.1/node_modules/@szmarczak/http-timer/dist/source/index.js + It will choose either HTTP/1.1 or HTTP/2 depending on the ALPN protocol. + __Note__: This option requires Node.js 15.10.0 or newer as HTTP/2 support on older Node.js versions is very buggy. + __Note__: Overriding `options.request` will disable HTTP2 support. -const timer = (request) => { - if (request.timings) { - return request.timings; - } - const timings = { - start: Date.now(), - socket: undefined, - lookup: undefined, - connect: undefined, - secureConnect: undefined, - upload: undefined, - response: undefined, - end: undefined, - error: undefined, - abort: undefined, - phases: { - wait: undefined, - dns: undefined, - tcp: undefined, - tls: undefined, - request: undefined, - firstByte: undefined, - download: undefined, - total: undefined, - }, - }; - request.timings = timings; - const handleError = (origin) => { - origin.once(external_events_.errorMonitor, () => { - timings.error = Date.now(); - timings.phases.total = timings.error - timings.start; - }); - }; - handleError(request); - const onAbort = () => { - timings.abort = Date.now(); - timings.phases.total = timings.abort - timings.start; - }; - request.prependOnceListener('abort', onAbort); - const onSocket = (socket) => { - timings.socket = Date.now(); - timings.phases.wait = timings.socket - timings.start; - if (external_util_.types.isProxy(socket)) { - return; - } - const lookupListener = () => { - timings.lookup = Date.now(); - timings.phases.dns = timings.lookup - timings.socket; - }; - socket.prependOnceListener('lookup', lookupListener); - source(socket, { - connect: () => { - timings.connect = Date.now(); - if (timings.lookup === undefined) { - socket.removeListener('lookup', lookupListener); - timings.lookup = timings.connect; - timings.phases.dns = timings.lookup - timings.socket; - } - timings.phases.tcp = timings.connect - timings.lookup; - }, - secureConnect: () => { - timings.secureConnect = Date.now(); - timings.phases.tls = timings.secureConnect - timings.connect; - }, - }); - }; - if (request.socket) { - onSocket(request.socket); + @default false + + @example + ``` + import got from 'got'; + + const {headers} = await got('https://nghttp2.org/httpbin/anything', {http2: true}); + + console.log(headers.via); + //=> '2 nghttpx' + ``` + */ + get http2() { + return this._internals.http2; } - else { - request.prependOnceListener('socket', onSocket); + set http2(value) { + assert.boolean(value); + this._internals.http2 = value; } - const onUpload = () => { - timings.upload = Date.now(); - timings.phases.request = timings.upload - (timings.secureConnect ?? timings.connect); - }; - if (request.writableFinished) { - onUpload(); + /** + Set this to `true` to allow sending body for the `GET` method. + However, the [HTTP/2 specification](https://tools.ietf.org/html/rfc7540#section-8.1.3) says that `An HTTP GET request includes request header fields and no payload body`, therefore when using the HTTP/2 protocol this option will have no effect. + This option is only meant to interact with non-compliant servers when you have no other choice. + + __Note__: The [RFC 7231](https://tools.ietf.org/html/rfc7231#section-4.3.1) doesn't specify any particular behavior for the GET method having a payload, therefore __it's considered an [anti-pattern](https://en.wikipedia.org/wiki/Anti-pattern)__. + + @default false + */ + get allowGetBody() { + return this._internals.allowGetBody; } - else { - request.prependOnceListener('finish', onUpload); + set allowGetBody(value) { + assert.boolean(value); + this._internals.allowGetBody = value; } - request.prependOnceListener('response', (response) => { - timings.response = Date.now(); - timings.phases.firstByte = timings.response - timings.upload; - response.timings = timings; - handleError(response); - response.prependOnceListener('end', () => { - request.off('abort', onAbort); - response.off('aborted', onAbort); - if (timings.phases.total) { - // Aborted or errored - return; - } - timings.end = Date.now(); - timings.phases.download = timings.end - timings.response; - timings.phases.total = timings.end - timings.start; - }); - response.prependOnceListener('aborted', onAbort); - }); - return timings; -}; -/* harmony default export */ const dist_source = (timer); - -;// CONCATENATED MODULE: external "node:url" -const external_node_url_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:url"); -;// CONCATENATED MODULE: ./node_modules/.pnpm/normalize-url@8.0.1/node_modules/normalize-url/index.js -// https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs -const DATA_URL_DEFAULT_MIME_TYPE = 'text/plain'; -const DATA_URL_DEFAULT_CHARSET = 'us-ascii'; + /** + Request headers. -const testParameter = (name, filters) => filters.some(filter => filter instanceof RegExp ? filter.test(name) : filter === name); + Existing headers will be overwritten. Headers set to `undefined` will be omitted. -const supportedProtocols = new Set([ - 'https:', - 'http:', - 'file:', -]); + @default {} + */ + get headers() { + return this._internals.headers; + } + set headers(value) { + assert.plainObject(value); + if (this._merging) { + Object.assign(this._internals.headers, lowercaseKeys(value)); + } + else { + this._internals.headers = lowercaseKeys(value); + } + } + /** + Specifies if the HTTP request method should be [rewritten as `GET`](https://tools.ietf.org/html/rfc7231#section-6.4) on redirects. -const hasCustomProtocol = urlString => { - try { - const {protocol} = new URL(urlString); + As the [specification](https://tools.ietf.org/html/rfc7231#section-6.4) prefers to rewrite the HTTP method only on `303` responses, this is Got's default behavior. + Setting `methodRewriting` to `true` will also rewrite `301` and `302` responses, as allowed by the spec. This is the behavior followed by `curl` and browsers. - return protocol.endsWith(':') - && !protocol.includes('.') - && !supportedProtocols.has(protocol); - } catch { - return false; - } -}; + __Note__: Got never performs method rewriting on `307` and `308` responses, as this is [explicitly prohibited by the specification](https://www.rfc-editor.org/rfc/rfc7231#section-6.4.7). -const normalizeDataURL = (urlString, {stripHash}) => { - const match = /^data:(?[^,]*?),(?[^#]*?)(?:#(?.*))?$/.exec(urlString); + @default false + */ + get methodRewriting() { + return this._internals.methodRewriting; + } + set methodRewriting(value) { + assert.boolean(value); + this._internals.methodRewriting = value; + } + /** + Indicates which DNS record family to use. - if (!match) { - throw new Error(`Invalid URL: ${urlString}`); - } + Values: + - `undefined`: IPv4 (if present) or IPv6 + - `4`: Only IPv4 + - `6`: Only IPv6 - let {type, data, hash} = match.groups; - const mediaType = type.split(';'); - hash = stripHash ? '' : hash; + @default undefined + */ + get dnsLookupIpVersion() { + return this._internals.dnsLookupIpVersion; + } + set dnsLookupIpVersion(value) { + if (value !== undefined && value !== 4 && value !== 6) { + throw new TypeError(`Invalid DNS lookup IP version: ${value}`); + } + this._internals.dnsLookupIpVersion = value; + } + /** + A function used to parse JSON responses. - let isBase64 = false; - if (mediaType[mediaType.length - 1] === 'base64') { - mediaType.pop(); - isBase64 = true; - } + @example + ``` + import got from 'got'; + import Bourne from '@hapi/bourne'; - // Lowercase MIME type - const mimeType = mediaType.shift()?.toLowerCase() ?? ''; - const attributes = mediaType - .map(attribute => { - let [key, value = ''] = attribute.split('=').map(string => string.trim()); + const parsed = await got('https://example.com', { + parseJson: text => Bourne.parse(text) + }).json(); - // Lowercase `charset` - if (key === 'charset') { - value = value.toLowerCase(); + console.log(parsed); + ``` + */ + get parseJson() { + return this._internals.parseJson; + } + set parseJson(value) { + assert["function"](value); + this._internals.parseJson = value; + } + /** + A function used to stringify the body of JSON requests. - if (value === DATA_URL_DEFAULT_CHARSET) { - return ''; - } - } + @example + ``` + import got from 'got'; - return `${key}${value ? `=${value}` : ''}`; - }) - .filter(Boolean); + await got.post('https://example.com', { + stringifyJson: object => JSON.stringify(object, (key, value) => { + if (key.startsWith('_')) { + return; + } - const normalizedMediaType = [ - ...attributes, - ]; + return value; + }), + json: { + some: 'payload', + _ignoreMe: 1234 + } + }); + ``` - if (isBase64) { - normalizedMediaType.push('base64'); - } + @example + ``` + import got from 'got'; - if (normalizedMediaType.length > 0 || (mimeType && mimeType !== DATA_URL_DEFAULT_MIME_TYPE)) { - normalizedMediaType.unshift(mimeType); - } + await got.post('https://example.com', { + stringifyJson: object => JSON.stringify(object, (key, value) => { + if (typeof value === 'number') { + return value.toString(); + } - return `data:${normalizedMediaType.join(';')},${isBase64 ? data.trim() : data}${hash ? `#${hash}` : ''}`; -}; + return value; + }), + json: { + some: 'payload', + number: 1 + } + }); + ``` + */ + get stringifyJson() { + return this._internals.stringifyJson; + } + set stringifyJson(value) { + assert["function"](value); + this._internals.stringifyJson = value; + } + /** + An object representing `limit`, `calculateDelay`, `methods`, `statusCodes`, `maxRetryAfter` and `errorCodes` fields for maximum retry count, retry handler, allowed methods, allowed status codes, maximum [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) time and allowed error codes. -function normalizeUrl(urlString, options) { - options = { - defaultProtocol: 'http', - normalizeProtocol: true, - forceHttp: false, - forceHttps: false, - stripAuthentication: true, - stripHash: false, - stripTextFragment: true, - stripWWW: true, - removeQueryParameters: [/^utm_\w+/i], - removeTrailingSlash: true, - removeSingleSlash: true, - removeDirectoryIndex: false, - removeExplicitPort: false, - sortQueryParameters: true, - ...options, - }; + Delays between retries counts with function `1000 * Math.pow(2, retry) + Math.random() * 100`, where `retry` is attempt number (starts from 1). - // Legacy: Append `:` to the protocol if missing. - if (typeof options.defaultProtocol === 'string' && !options.defaultProtocol.endsWith(':')) { - options.defaultProtocol = `${options.defaultProtocol}:`; - } + The `calculateDelay` property is a `function` that receives an object with `attemptCount`, `retryOptions`, `error` and `computedValue` properties for current retry count, the retry options, error and default computed value. + The function must return a delay in milliseconds (or a Promise resolving with it) (`0` return value cancels retry). - urlString = urlString.trim(); + By default, it retries *only* on the specified methods, status codes, and on these network errors: - // Data URL - if (/^data:/i.test(urlString)) { - return normalizeDataURL(urlString, options); - } + - `ETIMEDOUT`: One of the [timeout](#timeout) limits were reached. + - `ECONNRESET`: Connection was forcibly closed by a peer. + - `EADDRINUSE`: Could not bind to any free port. + - `ECONNREFUSED`: Connection was refused by the server. + - `EPIPE`: The remote side of the stream being written has been closed. + - `ENOTFOUND`: Couldn't resolve the hostname to an IP address. + - `ENETUNREACH`: No internet connection. + - `EAI_AGAIN`: DNS lookup timed out. - if (hasCustomProtocol(urlString)) { - return urlString; - } + __Note__: If `maxRetryAfter` is set to `undefined`, it will use `options.timeout`. + __Note__: If [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) header is greater than `maxRetryAfter`, it will cancel the request. + */ + get retry() { + return this._internals.retry; + } + set retry(value) { + assert.plainObject(value); + assert.any([distribution["function"], distribution.undefined], value.calculateDelay); + assert.any([distribution.number, distribution.undefined], value.maxRetryAfter); + assert.any([distribution.number, distribution.undefined], value.limit); + assert.any([distribution.array, distribution.undefined], value.methods); + assert.any([distribution.array, distribution.undefined], value.statusCodes); + assert.any([distribution.array, distribution.undefined], value.errorCodes); + assert.any([distribution.number, distribution.undefined], value.noise); + if (value.noise && Math.abs(value.noise) > 100) { + throw new Error(`The maximum acceptable retry noise is +/- 100ms, got ${value.noise}`); + } + for (const key in value) { + if (!(key in this._internals.retry)) { + throw new Error(`Unexpected retry option: ${key}`); + } + } + if (this._merging) { + Object.assign(this._internals.retry, value); + } + else { + this._internals.retry = { ...value }; + } + const { retry } = this._internals; + retry.methods = [...new Set(retry.methods.map(method => method.toUpperCase()))]; + retry.statusCodes = [...new Set(retry.statusCodes)]; + retry.errorCodes = [...new Set(retry.errorCodes)]; + } + /** + From `http.RequestOptions`. - const hasRelativeProtocol = urlString.startsWith('//'); - const isRelativeUrl = !hasRelativeProtocol && /^\.*\//.test(urlString); + The IP address used to send the request from. + */ + get localAddress() { + return this._internals.localAddress; + } + set localAddress(value) { + assert.any([distribution.string, distribution.undefined], value); + this._internals.localAddress = value; + } + /** + The HTTP method used to make the request. - // Prepend protocol - if (!isRelativeUrl) { - urlString = urlString.replace(/^(?!(?:\w+:)?\/\/)|^\/\//, options.defaultProtocol); - } + @default 'GET' + */ + get method() { + return this._internals.method; + } + set method(value) { + assert.string(value); + this._internals.method = value.toUpperCase(); + } + get createConnection() { + return this._internals.createConnection; + } + set createConnection(value) { + assert.any([distribution["function"], distribution.undefined], value); + this._internals.createConnection = value; + } + /** + From `http-cache-semantics` - const urlObject = new URL(urlString); + @default {} + */ + get cacheOptions() { + return this._internals.cacheOptions; + } + set cacheOptions(value) { + assert.plainObject(value); + assert.any([distribution.boolean, distribution.undefined], value.shared); + assert.any([distribution.number, distribution.undefined], value.cacheHeuristic); + assert.any([distribution.number, distribution.undefined], value.immutableMinTimeToLive); + assert.any([distribution.boolean, distribution.undefined], value.ignoreCargoCult); + for (const key in value) { + if (!(key in this._internals.cacheOptions)) { + throw new Error(`Cache option \`${key}\` does not exist`); + } + } + if (this._merging) { + Object.assign(this._internals.cacheOptions, value); + } + else { + this._internals.cacheOptions = { ...value }; + } + } + /** + Options for the advanced HTTPS API. + */ + get https() { + return this._internals.https; + } + set https(value) { + assert.plainObject(value); + assert.any([distribution.boolean, distribution.undefined], value.rejectUnauthorized); + assert.any([distribution["function"], distribution.undefined], value.checkServerIdentity); + assert.any([distribution.string, distribution.object, distribution.array, distribution.undefined], value.certificateAuthority); + assert.any([distribution.string, distribution.object, distribution.array, distribution.undefined], value.key); + assert.any([distribution.string, distribution.object, distribution.array, distribution.undefined], value.certificate); + assert.any([distribution.string, distribution.undefined], value.passphrase); + assert.any([distribution.string, distribution.buffer, distribution.array, distribution.undefined], value.pfx); + assert.any([distribution.array, distribution.undefined], value.alpnProtocols); + assert.any([distribution.string, distribution.undefined], value.ciphers); + assert.any([distribution.string, distribution.buffer, distribution.undefined], value.dhparam); + assert.any([distribution.string, distribution.undefined], value.signatureAlgorithms); + assert.any([distribution.string, distribution.undefined], value.minVersion); + assert.any([distribution.string, distribution.undefined], value.maxVersion); + assert.any([distribution.boolean, distribution.undefined], value.honorCipherOrder); + assert.any([distribution.number, distribution.undefined], value.tlsSessionLifetime); + assert.any([distribution.string, distribution.undefined], value.ecdhCurve); + assert.any([distribution.string, distribution.buffer, distribution.array, distribution.undefined], value.certificateRevocationLists); + for (const key in value) { + if (!(key in this._internals.https)) { + throw new Error(`HTTPS option \`${key}\` does not exist`); + } + } + if (this._merging) { + Object.assign(this._internals.https, value); + } + else { + this._internals.https = { ...value }; + } + } + /** + [Encoding](https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings) to be used on `setEncoding` of the response data. - if (options.forceHttp && options.forceHttps) { - throw new Error('The `forceHttp` and `forceHttps` options cannot be used together'); - } + To get a [`Buffer`](https://nodejs.org/api/buffer.html), you need to set `responseType` to `buffer` instead. + Don't set this option to `null`. - if (options.forceHttp && urlObject.protocol === 'https:') { - urlObject.protocol = 'http:'; - } + __Note__: This doesn't affect streams! Instead, you need to do `got.stream(...).setEncoding(encoding)`. - if (options.forceHttps && urlObject.protocol === 'http:') { - urlObject.protocol = 'https:'; - } + @default 'utf-8' + */ + get encoding() { + return this._internals.encoding; + } + set encoding(value) { + if (value === null) { + throw new TypeError('To get a Buffer, set `options.responseType` to `buffer` instead'); + } + assert.any([distribution.string, distribution.undefined], value); + this._internals.encoding = value; + } + /** + When set to `true` the promise will return the Response body instead of the Response object. - // Remove auth - if (options.stripAuthentication) { - urlObject.username = ''; - urlObject.password = ''; - } + @default false + */ + get resolveBodyOnly() { + return this._internals.resolveBodyOnly; + } + set resolveBodyOnly(value) { + assert.boolean(value); + this._internals.resolveBodyOnly = value; + } + /** + Returns a `Stream` instead of a `Promise`. + This is equivalent to calling `got.stream(url, options?)`. - // Remove hash - if (options.stripHash) { - urlObject.hash = ''; - } else if (options.stripTextFragment) { - urlObject.hash = urlObject.hash.replace(/#?:~:text.*?$/i, ''); - } + @default false + */ + get isStream() { + return this._internals.isStream; + } + set isStream(value) { + assert.boolean(value); + this._internals.isStream = value; + } + /** + The parsing method. - // Remove duplicate slashes if not preceded by a protocol - // NOTE: This could be implemented using a single negative lookbehind - // regex, but we avoid that to maintain compatibility with older js engines - // which do not have support for that feature. - if (urlObject.pathname) { - // TODO: Replace everything below with `urlObject.pathname = urlObject.pathname.replace(/(? ({ + buf: object.buffer, + passphrase: object.passphrase, + })); + } + return { + ...internals.cacheOptions, + ...this._unixOptions, + // HTTPS options + // eslint-disable-next-line @typescript-eslint/naming-convention + ALPNProtocols: https.alpnProtocols, + ca: https.certificateAuthority, + cert: https.certificate, + key: https.key, + passphrase: https.passphrase, + pfx: https.pfx, + rejectUnauthorized: https.rejectUnauthorized, + checkServerIdentity: https.checkServerIdentity ?? external_node_tls_namespaceObject.checkServerIdentity, + ciphers: https.ciphers, + honorCipherOrder: https.honorCipherOrder, + minVersion: https.minVersion, + maxVersion: https.maxVersion, + sigalgs: https.signatureAlgorithms, + sessionTimeout: https.tlsSessionLifetime, + dhparam: https.dhparam, + ecdhCurve: https.ecdhCurve, + crl: https.certificateRevocationLists, + // HTTP options + lookup: internals.dnsLookup ?? internals.dnsCache?.lookup, + family: internals.dnsLookupIpVersion, + agent, + setHost: internals.setHost, + method: internals.method, + maxHeaderSize: internals.maxHeaderSize, + localAddress: internals.localAddress, + headers: internals.headers, + createConnection: internals.createConnection, + timeout: internals.http2 ? getHttp2TimeoutOption(internals) : undefined, + // HTTP/2 options + h2session: internals.h2session, + }; + } + getRequestFunction() { + const url = this._internals.url; + const { request } = this._internals; + if (!request && url) { + return this.getFallbackRequestFunction(); + } + return request; + } + getFallbackRequestFunction() { + const url = this._internals.url; + if (!url) { + return; + } + if (url.protocol === 'https:') { + if (this._internals.http2) { + if (major < 15 || (major === 15 && minor < 10)) { + const error = new Error('To use the `http2` option, install Node.js 15.10.0 or above'); + error.code = 'EUNSUPPORTED'; + throw error; + } + return http2_wrapper_source.auto; + } + return external_node_https_.request; + } + return external_node_http_.request; + } + freeze() { + const options = this._internals; + Object.freeze(options); + Object.freeze(options.hooks); + Object.freeze(options.hooks.afterResponse); + Object.freeze(options.hooks.beforeError); + Object.freeze(options.hooks.beforeRedirect); + Object.freeze(options.hooks.beforeRequest); + Object.freeze(options.hooks.beforeRetry); + Object.freeze(options.hooks.init); + Object.freeze(options.https); + Object.freeze(options.cacheOptions); + Object.freeze(options.agent); + Object.freeze(options.headers); + Object.freeze(options.timeout); + Object.freeze(options.retry); + Object.freeze(options.retry.errorCodes); + Object.freeze(options.retry.methods); + Object.freeze(options.retry.statusCodes); + } +} - // Decode URI octets - if (urlObject.pathname) { - try { - urlObject.pathname = decodeURI(urlObject.pathname); - } catch {} - } +;// CONCATENATED MODULE: ./node_modules/.pnpm/got@14.4.4/node_modules/got/dist/source/core/response.js - // Remove directory index - if (options.removeDirectoryIndex === true) { - options.removeDirectoryIndex = [/^index\.[a-z]+$/]; - } +const isResponseOk = (response) => { + const { statusCode } = response; + const { followRedirect } = response.request.options; + const shouldFollow = typeof followRedirect === 'function' ? followRedirect(response) : followRedirect; + const limitStatusCode = shouldFollow ? 299 : 399; + return (statusCode >= 200 && statusCode <= limitStatusCode) || statusCode === 304; +}; +/** +An error to be thrown when server response code is 2xx, and parsing body fails. +Includes a `response` property. +*/ +class ParseError extends RequestError { + constructor(error, response) { + const { options } = response.request; + super(`${error.message} in "${options.url.toString()}"`, error, response.request); + this.name = 'ParseError'; + this.code = 'ERR_BODY_PARSE_FAILURE'; + } +} +const parseBody = (response, responseType, parseJson, encoding) => { + const { rawBody } = response; + try { + if (responseType === 'text') { + return rawBody.toString(encoding); + } + if (responseType === 'json') { + return rawBody.length === 0 ? '' : parseJson(rawBody.toString(encoding)); + } + if (responseType === 'buffer') { + return rawBody; + } + } + catch (error) { + throw new ParseError(error, response); + } + throw new ParseError({ + message: `Unknown body type '${responseType}'`, + name: 'Error', + }, response); +}; - if (Array.isArray(options.removeDirectoryIndex) && options.removeDirectoryIndex.length > 0) { - let pathComponents = urlObject.pathname.split('/'); - const lastComponent = pathComponents[pathComponents.length - 1]; +;// CONCATENATED MODULE: ./node_modules/.pnpm/got@14.4.4/node_modules/got/dist/source/core/utils/is-client-request.js +function isClientRequest(clientRequest) { + return clientRequest.writable && !clientRequest.writableEnded; +} +/* harmony default export */ const is_client_request = (isClientRequest); - if (testParameter(lastComponent, options.removeDirectoryIndex)) { - pathComponents = pathComponents.slice(0, -1); - urlObject.pathname = pathComponents.slice(1).join('/') + '/'; - } - } +;// CONCATENATED MODULE: ./node_modules/.pnpm/got@14.4.4/node_modules/got/dist/source/core/utils/is-unix-socket-url.js +// eslint-disable-next-line @typescript-eslint/naming-convention +function isUnixSocketURL(url) { + return url.protocol === 'unix:' || url.hostname === 'unix'; +} - if (urlObject.hostname) { - // Remove trailing dot - urlObject.hostname = urlObject.hostname.replace(/\.$/, ''); +;// CONCATENATED MODULE: ./node_modules/.pnpm/got@14.4.4/node_modules/got/dist/source/core/index.js - // Remove `www.` - if (options.stripWWW && /^www\.(?!www\.)[a-z\-\d]{1,63}\.[a-z.\-\d]{2,63}$/.test(urlObject.hostname)) { - // Each label should be max 63 at length (min: 1). - // Source: https://en.wikipedia.org/wiki/Hostname#Restrictions_on_valid_host_names - // Each TLD should be up to 63 characters long (min: 2). - // It is technically possible to have a single character TLD, but none currently exist. - urlObject.hostname = urlObject.hostname.replace(/^www\./, ''); - } - } - // Remove query unwanted parameters - if (Array.isArray(options.removeQueryParameters)) { - // eslint-disable-next-line unicorn/no-useless-spread -- We are intentionally spreading to get a copy. - for (const key of [...urlObject.searchParams.keys()]) { - if (testParameter(key, options.removeQueryParameters)) { - urlObject.searchParams.delete(key); - } - } - } - if (!Array.isArray(options.keepQueryParameters) && options.removeQueryParameters === true) { - urlObject.search = ''; - } - // Keep wanted query parameters - if (Array.isArray(options.keepQueryParameters) && options.keepQueryParameters.length > 0) { - // eslint-disable-next-line unicorn/no-useless-spread -- We are intentionally spreading to get a copy. - for (const key of [...urlObject.searchParams.keys()]) { - if (!testParameter(key, options.keepQueryParameters)) { - urlObject.searchParams.delete(key); - } - } - } - // Sort query parameters - if (options.sortQueryParameters) { - urlObject.searchParams.sort(); - // Calling `.sort()` encodes the search parameters, so we need to decode them again. - try { - urlObject.search = decodeURIComponent(urlObject.search); - } catch {} - } - if (options.removeTrailingSlash) { - urlObject.pathname = urlObject.pathname.replace(/\/$/, ''); - } - // Remove an explicit port number, excluding a default port number, if applicable - if (options.removeExplicitPort && urlObject.port) { - urlObject.port = ''; - } - const oldUrlString = urlString; - // Take advantage of many of the Node `url` normalizations - urlString = urlObject.toString(); - if (!options.removeSingleSlash && urlObject.pathname === '/' && !oldUrlString.endsWith('/') && urlObject.hash === '') { - urlString = urlString.replace(/\/$/, ''); - } - // Remove ending `/` unless removeSingleSlash is false - if ((options.removeTrailingSlash || urlObject.pathname === '/') && urlObject.hash === '' && options.removeSingleSlash) { - urlString = urlString.replace(/\/$/, ''); - } - // Restore relative protocol, if applicable - if (hasRelativeProtocol && !options.normalizeProtocol) { - urlString = urlString.replace(/^http:\/\//, '//'); - } - // Remove http/https - if (options.stripProtocol) { - urlString = urlString.replace(/^(?:https?:)?\/\//, ''); - } - return urlString; -} -;// CONCATENATED MODULE: ./node_modules/.pnpm/is-stream@4.0.1/node_modules/is-stream/index.js -function isStream(stream, {checkOpen = true} = {}) { - return stream !== null - && typeof stream === 'object' - && (stream.writable || stream.readable || !checkOpen || (stream.writable === undefined && stream.readable === undefined)) - && typeof stream.pipe === 'function'; -} -function isWritableStream(stream, {checkOpen = true} = {}) { - return isStream(stream, {checkOpen}) - && (stream.writable || !checkOpen) - && typeof stream.write === 'function' - && typeof stream.end === 'function' - && typeof stream.writable === 'boolean' - && typeof stream.writableObjectMode === 'boolean' - && typeof stream.destroy === 'function' - && typeof stream.destroyed === 'boolean'; -} -function isReadableStream(stream, {checkOpen = true} = {}) { - return isStream(stream, {checkOpen}) - && (stream.readable || !checkOpen) - && typeof stream.read === 'function' - && typeof stream.readable === 'boolean' - && typeof stream.readableObjectMode === 'boolean' - && typeof stream.destroy === 'function' - && typeof stream.destroyed === 'boolean'; -} -function isDuplexStream(stream, options) { - return isWritableStream(stream, options) - && isReadableStream(stream, options); -} -function isTransformStream(stream, options) { - return isDuplexStream(stream, options) - && typeof stream._transform === 'function'; -} -;// CONCATENATED MODULE: ./node_modules/.pnpm/@sec-ant+readable-stream@0.4.1/node_modules/@sec-ant/readable-stream/dist/ponyfill/asyncIterator.js -const a = Object.getPrototypeOf( - Object.getPrototypeOf( - /* istanbul ignore next */ - async function* () { +const supportsBrotli = distribution.string(external_node_process_.versions.brotli); +const methodsWithoutBody = new Set(['GET', 'HEAD']); +const cacheableStore = new WeakableMap(); +const redirectCodes = new Set([300, 301, 302, 303, 304, 307, 308]); +const proxiedRequestEvents = [ + 'socket', + 'connect', + 'continue', + 'information', + 'upgrade', +]; +const core_noop = () => { }; +class Request extends external_node_stream_.Duplex { + // @ts-expect-error - Ignoring for now. + ['constructor']; + _noPipe; + // @ts-expect-error https://github.com/microsoft/TypeScript/issues/9568 + options; + response; + requestUrl; + redirectUrls; + retryCount; + _stopRetry; + _downloadedSize; + _uploadedSize; + _stopReading; + _pipedServerResponses; + _request; + _responseSize; + _bodySize; + _unproxyEvents; + _isFromCache; + _cannotHaveBody; + _triggerRead; + _cancelTimeouts; + _removeListeners; + _nativeResponse; + _flushed; + _aborted; + // We need this because `this._request` if `undefined` when using cache + _requestInitialized; + constructor(url, options, defaults) { + super({ + // Don't destroy immediately, as the error may be emitted on unsuccessful retry + autoDestroy: false, + // It needs to be zero because we're just proxying the data to another stream + highWaterMark: 0, + }); + this._downloadedSize = 0; + this._uploadedSize = 0; + this._stopReading = false; + this._pipedServerResponses = new Set(); + this._cannotHaveBody = false; + this._unproxyEvents = core_noop; + this._triggerRead = false; + this._cancelTimeouts = core_noop; + this._removeListeners = core_noop; + this._jobs = []; + this._flushed = false; + this._requestInitialized = false; + this._aborted = false; + this.redirectUrls = []; + this.retryCount = 0; + this._stopRetry = core_noop; + this.on('pipe', (source) => { + if (source?.headers) { + Object.assign(this.options.headers, source.headers); + } + }); + this.on('newListener', event => { + if (event === 'retry' && this.listenerCount('retry') > 0) { + throw new Error('A retry listener has been attached already.'); + } + }); + try { + this.options = new Options(url, options, defaults); + if (!this.options.url) { + if (this.options.prefixUrl === '') { + throw new TypeError('Missing `url` property'); + } + this.options.url = ''; + } + this.requestUrl = this.options.url; + } + catch (error) { + const { options } = error; + if (options) { + this.options = options; + } + this.flush = async () => { + this.flush = async () => { }; + this.destroy(error); + }; + return; + } + // Important! If you replace `body` in a handler with another stream, make sure it's readable first. + // The below is run only once. + const { body } = this.options; + if (distribution.nodeStream(body)) { + body.once('error', error => { + if (this._flushed) { + this._beforeError(new UploadError(error, this)); + } + else { + this.flush = async () => { + this.flush = async () => { }; + this._beforeError(new UploadError(error, this)); + }; + } + }); + } + if (this.options.signal) { + const abort = () => { + // See https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/timeout_static#return_value + if (this.options.signal?.reason?.name === 'TimeoutError') { + this.destroy(new TimeoutError(this.options.signal.reason, this.timings, this)); + } + else { + this.destroy(new AbortError(this)); + } + }; + if (this.options.signal.aborted) { + abort(); + } + else { + this.options.signal.addEventListener('abort', abort); + this._removeListeners = () => { + this.options.signal?.removeEventListener('abort', abort); + }; + } + } + } + async flush() { + if (this._flushed) { + return; + } + this._flushed = true; + try { + await this._finalizeBody(); + if (this.destroyed) { + return; + } + await this._makeRequest(); + if (this.destroyed) { + this._request?.destroy(); + return; + } + // Queued writes etc. + for (const job of this._jobs) { + job(); + } + // Prevent memory leak + this._jobs.length = 0; + this._requestInitialized = true; + } + catch (error) { + this._beforeError(error); + } + } + _beforeError(error) { + if (this._stopReading) { + return; + } + const { response, options } = this; + const attemptCount = this.retryCount + (error.name === 'RetryError' ? 0 : 1); + this._stopReading = true; + if (!(error instanceof RequestError)) { + error = new RequestError(error.message, error, this); + } + const typedError = error; + void (async () => { + // Node.js parser is really weird. + // It emits post-request Parse Errors on the same instance as previous request. WTF. + // Therefore, we need to check if it has been destroyed as well. + // + // Furthermore, Node.js 16 `response.destroy()` doesn't immediately destroy the socket, + // but makes the response unreadable. So we additionally need to check `response.readable`. + if (response?.readable && !response.rawBody && !this._request?.socket?.destroyed) { + // @types/node has incorrect typings. `setEncoding` accepts `null` as well. + response.setEncoding(this.readableEncoding); + const success = await this._setRawBody(response); + if (success) { + response.body = response.rawBody.toString(); + } + } + if (this.listenerCount('retry') !== 0) { + let backoff; + try { + let retryAfter; + if (response && 'retry-after' in response.headers) { + retryAfter = Number(response.headers['retry-after']); + if (Number.isNaN(retryAfter)) { + retryAfter = Date.parse(response.headers['retry-after']) - Date.now(); + if (retryAfter <= 0) { + retryAfter = 1; + } + } + else { + retryAfter *= 1000; + } + } + const retryOptions = options.retry; + backoff = await retryOptions.calculateDelay({ + attemptCount, + retryOptions, + error: typedError, + retryAfter, + computedValue: calculate_retry_delay({ + attemptCount, + retryOptions, + error: typedError, + retryAfter, + computedValue: retryOptions.maxRetryAfter ?? options.timeout.request ?? Number.POSITIVE_INFINITY, + }), + }); + } + catch (error_) { + void this._error(new RequestError(error_.message, error_, this)); + return; + } + if (backoff) { + await new Promise(resolve => { + const timeout = setTimeout(resolve, backoff); + this._stopRetry = () => { + clearTimeout(timeout); + resolve(); + }; + }); + // Something forced us to abort the retry + if (this.destroyed) { + return; + } + try { + for (const hook of this.options.hooks.beforeRetry) { + // eslint-disable-next-line no-await-in-loop + await hook(typedError, this.retryCount + 1); + } + } + catch (error_) { + void this._error(new RequestError(error_.message, error, this)); + return; + } + // Something forced us to abort the retry + if (this.destroyed) { + return; + } + this.destroy(); + this.emit('retry', this.retryCount + 1, error, (updatedOptions) => { + const request = new Request(options.url, updatedOptions, options); + request.retryCount = this.retryCount + 1; + external_node_process_.nextTick(() => { + void request.flush(); + }); + return request; + }); + return; + } + } + void this._error(typedError); + })(); + } + _read() { + this._triggerRead = true; + const { response } = this; + if (response && !this._stopReading) { + // We cannot put this in the `if` above + // because `.read()` also triggers the `end` event + if (response.readableLength) { + this._triggerRead = false; + } + let data; + while ((data = response.read()) !== null) { + this._downloadedSize += data.length; // eslint-disable-line @typescript-eslint/restrict-plus-operands + const progress = this.downloadProgress; + if (progress.percent < 1) { + this.emit('downloadProgress', progress); + } + this.push(data); + } + } + } + _write(chunk, encoding, callback) { + const write = () => { + this._writeRequest(chunk, encoding, callback); + }; + if (this._requestInitialized) { + write(); + } + else { + this._jobs.push(write); + } + } + _final(callback) { + const endRequest = () => { + // We need to check if `this._request` is present, + // because it isn't when we use cache. + if (!this._request || this._request.destroyed) { + callback(); + return; + } + this._request.end((error) => { + // The request has been destroyed before `_final` finished. + // See https://github.com/nodejs/node/issues/39356 + if (this._request._writableState?.errored) { + return; + } + if (!error) { + this._bodySize = this._uploadedSize; + this.emit('uploadProgress', this.uploadProgress); + this._request.emit('upload-complete'); + } + callback(error); + }); + }; + if (this._requestInitialized) { + endRequest(); + } + else { + this._jobs.push(endRequest); + } + } + _destroy(error, callback) { + this._stopReading = true; + this.flush = async () => { }; + // Prevent further retries + this._stopRetry(); + this._cancelTimeouts(); + this._removeListeners(); + if (this.options) { + const { body } = this.options; + if (distribution.nodeStream(body)) { + body.destroy(); + } + } + if (this._request) { + this._request.destroy(); + } + if (error !== null && !distribution.undefined(error) && !(error instanceof RequestError)) { + error = new RequestError(error.message, error, this); + } + callback(error); + } + pipe(destination, options) { + if (destination instanceof external_node_http_.ServerResponse) { + this._pipedServerResponses.add(destination); + } + return super.pipe(destination, options); + } + unpipe(destination) { + if (destination instanceof external_node_http_.ServerResponse) { + this._pipedServerResponses.delete(destination); + } + super.unpipe(destination); + return this; + } + async _finalizeBody() { + const { options } = this; + const { headers } = options; + const isForm = !distribution.undefined(options.form); + // eslint-disable-next-line @typescript-eslint/naming-convention + const isJSON = !distribution.undefined(options.json); + const isBody = !distribution.undefined(options.body); + const cannotHaveBody = methodsWithoutBody.has(options.method) && !(options.method === 'GET' && options.allowGetBody); + this._cannotHaveBody = cannotHaveBody; + if (isForm || isJSON || isBody) { + if (cannotHaveBody) { + throw new TypeError(`The \`${options.method}\` method cannot be used with a body`); + } + // Serialize body + const noContentType = !distribution.string(headers['content-type']); + if (isBody) { + // Body is spec-compliant FormData + if (lib_isFormData(options.body)) { + const encoder = new FormDataEncoder(options.body); + if (noContentType) { + headers['content-type'] = encoder.headers['Content-Type']; + } + if ('Content-Length' in encoder.headers) { + headers['content-length'] = encoder.headers['Content-Length']; + } + options.body = encoder.encode(); + } + // Special case for https://github.com/form-data/form-data + if (is_form_data_isFormData(options.body) && noContentType) { + headers['content-type'] = `multipart/form-data; boundary=${options.body.getBoundary()}`; + } + } + else if (isForm) { + if (noContentType) { + headers['content-type'] = 'application/x-www-form-urlencoded'; + } + const { form } = options; + options.form = undefined; + options.body = (new URLSearchParams(form)).toString(); + } + else { + if (noContentType) { + headers['content-type'] = 'application/json'; + } + const { json } = options; + options.json = undefined; + options.body = options.stringifyJson(json); + } + const uploadBodySize = await getBodySize(options.body, options.headers); + // See https://tools.ietf.org/html/rfc7230#section-3.3.2 + // A user agent SHOULD send a Content-Length in a request message when + // no Transfer-Encoding is sent and the request method defines a meaning + // for an enclosed payload body. For example, a Content-Length header + // field is normally sent in a POST request even when the value is 0 + // (indicating an empty payload body). A user agent SHOULD NOT send a + // Content-Length header field when the request message does not contain + // a payload body and the method semantics do not anticipate such a + // body. + if (distribution.undefined(headers['content-length']) && distribution.undefined(headers['transfer-encoding']) && !cannotHaveBody && !distribution.undefined(uploadBodySize)) { + headers['content-length'] = String(uploadBodySize); + } + } + if (options.responseType === 'json' && !('accept' in options.headers)) { + options.headers.accept = 'application/json'; + } + this._bodySize = Number(headers['content-length']) || undefined; + } + async _onResponseBase(response) { + // This will be called e.g. when using cache so we need to check if this request has been aborted. + if (this.isAborted) { + return; + } + const { options } = this; + const { url } = options; + this._nativeResponse = response; + if (options.decompress) { + response = decompress_response(response); + } + const statusCode = response.statusCode; + const typedResponse = response; + typedResponse.statusMessage = typedResponse.statusMessage ?? external_node_http_.STATUS_CODES[statusCode]; + typedResponse.url = options.url.toString(); + typedResponse.requestUrl = this.requestUrl; + typedResponse.redirectUrls = this.redirectUrls; + typedResponse.request = this; + typedResponse.isFromCache = this._nativeResponse.fromCache ?? false; + typedResponse.ip = this.ip; + typedResponse.retryCount = this.retryCount; + typedResponse.ok = isResponseOk(typedResponse); + this._isFromCache = typedResponse.isFromCache; + this._responseSize = Number(response.headers['content-length']) || undefined; + this.response = typedResponse; + response.once('end', () => { + this._responseSize = this._downloadedSize; + this.emit('downloadProgress', this.downloadProgress); + }); + response.once('error', (error) => { + this._aborted = true; + // Force clean-up, because some packages don't do this. + // TODO: Fix decompress-response + response.destroy(); + this._beforeError(new ReadError(error, this)); + }); + response.once('aborted', () => { + this._aborted = true; + this._beforeError(new ReadError({ + name: 'Error', + message: 'The server aborted pending request', + code: 'ECONNRESET', + }, this)); + }); + this.emit('downloadProgress', this.downloadProgress); + const rawCookies = response.headers['set-cookie']; + if (distribution.object(options.cookieJar) && rawCookies) { + let promises = rawCookies.map(async (rawCookie) => options.cookieJar.setCookie(rawCookie, url.toString())); + if (options.ignoreInvalidCookies) { + // eslint-disable-next-line @typescript-eslint/no-floating-promises + promises = promises.map(async (promise) => { + try { + await promise; + } + catch { } + }); + } + try { + await Promise.all(promises); + } + catch (error) { + this._beforeError(error); + return; + } + } + // The above is running a promise, therefore we need to check if this request has been aborted yet again. + if (this.isAborted) { + return; + } + if (response.headers.location && redirectCodes.has(statusCode)) { + // We're being redirected, we don't care about the response. + // It'd be best to abort the request, but we can't because + // we would have to sacrifice the TCP connection. We don't want that. + const shouldFollow = typeof options.followRedirect === 'function' ? options.followRedirect(typedResponse) : options.followRedirect; + if (shouldFollow) { + response.resume(); + this._cancelTimeouts(); + this._unproxyEvents(); + if (this.redirectUrls.length >= options.maxRedirects) { + this._beforeError(new MaxRedirectsError(this)); + return; + } + this._request = undefined; + const updatedOptions = new Options(undefined, undefined, this.options); + const serverRequestedGet = statusCode === 303 && updatedOptions.method !== 'GET' && updatedOptions.method !== 'HEAD'; + const canRewrite = statusCode !== 307 && statusCode !== 308; + const userRequestedGet = updatedOptions.methodRewriting && canRewrite; + if (serverRequestedGet || userRequestedGet) { + updatedOptions.method = 'GET'; + updatedOptions.body = undefined; + updatedOptions.json = undefined; + updatedOptions.form = undefined; + delete updatedOptions.headers['content-length']; + } + try { + // We need this in order to support UTF-8 + const redirectBuffer = external_node_buffer_namespaceObject.Buffer.from(response.headers.location, 'binary').toString(); + const redirectUrl = new URL(redirectBuffer, url); + if (!isUnixSocketURL(url) && isUnixSocketURL(redirectUrl)) { + this._beforeError(new RequestError('Cannot redirect to UNIX socket', {}, this)); + return; + } + // Redirecting to a different site, clear sensitive data. + if (redirectUrl.hostname !== url.hostname || redirectUrl.port !== url.port) { + if ('host' in updatedOptions.headers) { + delete updatedOptions.headers.host; + } + if ('cookie' in updatedOptions.headers) { + delete updatedOptions.headers.cookie; + } + if ('authorization' in updatedOptions.headers) { + delete updatedOptions.headers.authorization; + } + if (updatedOptions.username || updatedOptions.password) { + updatedOptions.username = ''; + updatedOptions.password = ''; + } + } + else { + redirectUrl.username = updatedOptions.username; + redirectUrl.password = updatedOptions.password; + } + this.redirectUrls.push(redirectUrl); + updatedOptions.prefixUrl = ''; + updatedOptions.url = redirectUrl; + for (const hook of updatedOptions.hooks.beforeRedirect) { + // eslint-disable-next-line no-await-in-loop + await hook(updatedOptions, typedResponse); + } + this.emit('redirect', updatedOptions, typedResponse); + this.options = updatedOptions; + await this._makeRequest(); + } + catch (error) { + this._beforeError(error); + return; + } + return; + } + } + // `HTTPError`s always have `error.response.body` defined. + // Therefore, we cannot retry if `options.throwHttpErrors` is false. + // On the last retry, if `options.throwHttpErrors` is false, we would need to return the body, + // but that wouldn't be possible since the body would be already read in `error.response.body`. + if (options.isStream && options.throwHttpErrors && !isResponseOk(typedResponse)) { + this._beforeError(new HTTPError(typedResponse)); + return; + } + response.on('readable', () => { + if (this._triggerRead) { + this._read(); + } + }); + this.on('resume', () => { + response.resume(); + }); + this.on('pause', () => { + response.pause(); + }); + response.once('end', () => { + this.push(null); + }); + if (this._noPipe) { + const success = await this._setRawBody(); + if (success) { + this.emit('response', response); + } + return; + } + this.emit('response', response); + for (const destination of this._pipedServerResponses) { + if (destination.headersSent) { + continue; + } + // eslint-disable-next-line guard-for-in + for (const key in response.headers) { + const isAllowed = options.decompress ? key !== 'content-encoding' : true; + const value = response.headers[key]; + if (isAllowed) { + destination.setHeader(key, value); + } + } + destination.statusCode = statusCode; + } } - ).prototype -); -class c { - #t; - #n; - #r = !1; - #e = void 0; - constructor(e, t) { - this.#t = e, this.#n = t; - } - next() { - const e = () => this.#s(); - return this.#e = this.#e ? this.#e.then(e, e) : e(), this.#e; - } - return(e) { - const t = () => this.#i(e); - return this.#e ? this.#e.then(t, t) : t(); - } - async #s() { - if (this.#r) - return { - done: !0, - value: void 0 - }; - let e; - try { - e = await this.#t.read(); - } catch (t) { - throw this.#e = void 0, this.#r = !0, this.#t.releaseLock(), t; + async _setRawBody(from = this) { + if (from.readableEnded) { + return false; + } + try { + // Errors are emitted via the `error` event + const fromArray = await from.toArray(); + const rawBody = isBuffer(fromArray.at(0)) ? external_node_buffer_namespaceObject.Buffer.concat(fromArray) : external_node_buffer_namespaceObject.Buffer.from(fromArray.join('')); + // On retry Request is destroyed with no error, therefore the above will successfully resolve. + // So in order to check if this was really successfull, we need to check if it has been properly ended. + if (!this.isAborted) { + this.response.rawBody = rawBody; + return true; + } + } + catch { } + return false; } - return e.done && (this.#e = void 0, this.#r = !0, this.#t.releaseLock()), e; - } - async #i(e) { - if (this.#r) - return { - done: !0, - value: e - }; - if (this.#r = !0, !this.#n) { - const t = this.#t.cancel(e); - return this.#t.releaseLock(), await t, { - done: !0, - value: e - }; + async _onResponse(response) { + try { + await this._onResponseBase(response); + } + catch (error) { + /* istanbul ignore next: better safe than sorry */ + this._beforeError(error); + } } - return this.#t.releaseLock(), { - done: !0, - value: e - }; - } -} -const n = Symbol(); -function i() { - return this[n].next(); -} -Object.defineProperty(i, "name", { value: "next" }); -function o(r) { - return this[n].return(r); -} -Object.defineProperty(o, "name", { value: "return" }); -const u = Object.create(a, { - next: { - enumerable: !0, - configurable: !0, - writable: !0, - value: i - }, - return: { - enumerable: !0, - configurable: !0, - writable: !0, - value: o - } -}); -function h({ preventCancel: r = !1 } = {}) { - const e = this.getReader(), t = new c( - e, - r - ), s = Object.create(u); - return s[n] = t, s; -} - - -;// CONCATENATED MODULE: ./node_modules/.pnpm/@sec-ant+readable-stream@0.4.1/node_modules/@sec-ant/readable-stream/dist/ponyfill/index.js - - - - -;// CONCATENATED MODULE: ./node_modules/.pnpm/get-stream@9.0.1/node_modules/get-stream/source/stream.js - - - -const getAsyncIterable = stream => { - if (isReadableStream(stream, {checkOpen: false}) && nodeImports.on !== undefined) { - return getStreamIterable(stream); - } - - if (typeof stream?.[Symbol.asyncIterator] === 'function') { - return stream; - } - - // `ReadableStream[Symbol.asyncIterator]` support is missing in multiple browsers, so we ponyfill it - if (stream_toString.call(stream) === '[object ReadableStream]') { - return h.call(stream); - } - - throw new TypeError('The first argument must be a Readable, a ReadableStream, or an async iterable.'); -}; - -const {toString: stream_toString} = Object.prototype; - -// The default iterable for Node.js streams does not allow for multiple readers at once, so we re-implement it -const getStreamIterable = async function * (stream) { - const controller = new AbortController(); - const state = {}; - handleStreamEnd(stream, controller, state); - - try { - for await (const [chunk] of nodeImports.on(stream, 'data', {signal: controller.signal})) { - yield chunk; - } - } catch (error) { - // Stream failure, for example due to `stream.destroy(error)` - if (state.error !== undefined) { - throw state.error; - // `error` event directly emitted on stream - } else if (!controller.signal.aborted) { - throw error; - // Otherwise, stream completed successfully - } - // The `finally` block also runs when the caller throws, for example due to the `maxBuffer` option - } finally { - stream.destroy(); - } -}; - -const handleStreamEnd = async (stream, controller, state) => { - try { - await nodeImports.finished(stream, { - cleanup: true, - readable: true, - writable: false, - error: false, - }); - } catch (error) { - state.error = error; - } finally { - controller.abort(); - } -}; - -// Loaded by the Node entrypoint, but not by the browser one. -// This prevents using dynamic imports. -const nodeImports = {}; - -;// CONCATENATED MODULE: ./node_modules/.pnpm/get-stream@9.0.1/node_modules/get-stream/source/contents.js - + _onRequest(request) { + const { options } = this; + const { timeout, url } = options; + dist_source(request); + if (this.options.http2) { + // Unset stream timeout, as the `timeout` option was used only for connection timeout. + request.setTimeout(0); + } + this._cancelTimeouts = timedOut(request, timeout, url); + const responseEventName = options.cache ? 'cacheableResponse' : 'response'; + request.once(responseEventName, (response) => { + void this._onResponse(response); + }); + request.once('error', (error) => { + this._aborted = true; + // Force clean-up, because some packages (e.g. nock) don't do this. + request.destroy(); + error = error instanceof timed_out_TimeoutError ? new TimeoutError(error, this.timings, this) : new RequestError(error.message, error, this); + this._beforeError(error); + }); + this._unproxyEvents = proxyEvents(request, this, proxiedRequestEvents); + this._request = request; + this.emit('uploadProgress', this.uploadProgress); + this._sendBody(); + this.emit('request', request); + } + async _asyncWrite(chunk) { + return new Promise((resolve, reject) => { + super.write(chunk, error => { + if (error) { + reject(error); + return; + } + resolve(); + }); + }); + } + _sendBody() { + // Send body + const { body } = this.options; + const currentRequest = this.redirectUrls.length === 0 ? this : this._request ?? this; + if (distribution.nodeStream(body)) { + body.pipe(currentRequest); + } + else if (distribution.generator(body) || distribution.asyncGenerator(body)) { + (async () => { + try { + for await (const chunk of body) { + await this._asyncWrite(chunk); + } + super.end(); + } + catch (error) { + this._beforeError(error); + } + })(); + } + else if (!distribution.undefined(body)) { + this._writeRequest(body, undefined, () => { }); + currentRequest.end(); + } + else if (this._cannotHaveBody || this._noPipe) { + currentRequest.end(); + } + } + _prepareCache(cache) { + if (!cacheableStore.has(cache)) { + const cacheableRequest = new dist(((requestOptions, handler) => { + const result = requestOptions._request(requestOptions, handler); + // TODO: remove this when `cacheable-request` supports async request functions. + if (distribution.promise(result)) { + // We only need to implement the error handler in order to support HTTP2 caching. + // The result will be a promise anyway. + // @ts-expect-error ignore + result.once = (event, handler) => { + if (event === 'error') { + (async () => { + try { + await result; + } + catch (error) { + handler(error); + } + })(); + } + else if (event === 'abort' || event === 'destroy') { + // The empty catch is needed here in case when + // it rejects before it's `await`ed in `_makeRequest`. + (async () => { + try { + const request = (await result); + request.once(event, handler); + } + catch { } + })(); + } + else { + /* istanbul ignore next: safety check */ + throw new Error(`Unknown HTTP2 promise event: ${event}`); + } + return result; + }; + } + return result; + }), cache); + cacheableStore.set(cache, cacheableRequest.request()); + } + } + async _createCacheableRequest(url, options) { + return new Promise((resolve, reject) => { + // TODO: Remove `utils/url-to-options.ts` when `cacheable-request` is fixed + Object.assign(options, urlToOptions(url)); + let request; + // TODO: Fix `cacheable-response`. This is ugly. + const cacheRequest = cacheableStore.get(options.cache)(options, async (response) => { + response._readableState.autoDestroy = false; + if (request) { + const fix = () => { + if (response.req) { + response.complete = response.req.res.complete; + } + }; + response.prependOnceListener('end', fix); + fix(); + (await request).emit('cacheableResponse', response); + } + resolve(response); + }); + cacheRequest.once('error', reject); + cacheRequest.once('request', async (requestOrPromise) => { + request = requestOrPromise; + resolve(request); + }); + }); + } + async _makeRequest() { + const { options } = this; + const { headers, username, password } = options; + const cookieJar = options.cookieJar; + for (const key in headers) { + if (distribution.undefined(headers[key])) { + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete + delete headers[key]; + } + else if (distribution["null"](headers[key])) { + throw new TypeError(`Use \`undefined\` instead of \`null\` to delete the \`${key}\` header`); + } + } + if (options.decompress && distribution.undefined(headers['accept-encoding'])) { + headers['accept-encoding'] = supportsBrotli ? 'gzip, deflate, br' : 'gzip, deflate'; + } + if (username || password) { + const credentials = external_node_buffer_namespaceObject.Buffer.from(`${username}:${password}`).toString('base64'); + headers.authorization = `Basic ${credentials}`; + } + // Set cookies + if (cookieJar) { + const cookieString = await cookieJar.getCookieString(options.url.toString()); + if (distribution.nonEmptyString(cookieString)) { + headers.cookie = cookieString; + } + } + // Reset `prefixUrl` + options.prefixUrl = ''; + let request; + for (const hook of options.hooks.beforeRequest) { + // eslint-disable-next-line no-await-in-loop + const result = await hook(options); + if (!distribution.undefined(result)) { + // @ts-expect-error Skip the type mismatch to support abstract responses + request = () => result; + break; + } + } + request ||= options.getRequestFunction(); + const url = options.url; + this._requestOptions = options.createNativeRequestOptions(); + if (options.cache) { + this._requestOptions._request = request; + this._requestOptions.cache = options.cache; + this._requestOptions.body = options.body; + this._prepareCache(options.cache); + } + // Cache support + const function_ = options.cache ? this._createCacheableRequest : request; + try { + // We can't do `await fn(...)`, + // because stream `error` event can be emitted before `Promise.resolve()`. + let requestOrResponse = function_(url, this._requestOptions); + if (distribution.promise(requestOrResponse)) { + requestOrResponse = await requestOrResponse; + } + // Fallback + if (distribution.undefined(requestOrResponse)) { + requestOrResponse = options.getFallbackRequestFunction()(url, this._requestOptions); + if (distribution.promise(requestOrResponse)) { + requestOrResponse = await requestOrResponse; + } + } + if (is_client_request(requestOrResponse)) { + this._onRequest(requestOrResponse); + } + else if (this.writable) { + this.once('finish', () => { + void this._onResponse(requestOrResponse); + }); + this._sendBody(); + } + else { + void this._onResponse(requestOrResponse); + } + } + catch (error) { + if (error instanceof types_CacheError) { + throw new CacheError(error, this); + } + throw error; + } + } + async _error(error) { + try { + if (error instanceof HTTPError && !this.options.throwHttpErrors) { + // This branch can be reached only when using the Promise API + // Skip calling the hooks on purpose. + // See https://github.com/sindresorhus/got/issues/2103 + } + else { + for (const hook of this.options.hooks.beforeError) { + // eslint-disable-next-line no-await-in-loop + error = await hook(error); + } + } + } + catch (error_) { + error = new RequestError(error_.message, error_, this); + } + this.destroy(error); + } + _writeRequest(chunk, encoding, callback) { + if (!this._request || this._request.destroyed) { + // Probably the `ClientRequest` instance will throw + return; + } + this._request.write(chunk, encoding, (error) => { + // The `!destroyed` check is required to prevent `uploadProgress` being emitted after the stream was destroyed + if (!error && !this._request.destroyed) { + this._uploadedSize += external_node_buffer_namespaceObject.Buffer.byteLength(chunk, encoding); + const progress = this.uploadProgress; + if (progress.percent < 1) { + this.emit('uploadProgress', progress); + } + } + callback(error); + }); + } + /** + The remote IP address. + */ + get ip() { + return this.socket?.remoteAddress; + } + /** + Indicates whether the request has been aborted or not. + */ + get isAborted() { + return this._aborted; + } + get socket() { + return this._request?.socket ?? undefined; + } + /** + Progress event for downloading (receiving a response). + */ + get downloadProgress() { + let percent; + if (this._responseSize) { + percent = this._downloadedSize / this._responseSize; + } + else if (this._responseSize === this._downloadedSize) { + percent = 1; + } + else { + percent = 0; + } + return { + percent, + transferred: this._downloadedSize, + total: this._responseSize, + }; + } + /** + Progress event for uploading (sending a request). + */ + get uploadProgress() { + let percent; + if (this._bodySize) { + percent = this._uploadedSize / this._bodySize; + } + else if (this._bodySize === this._uploadedSize) { + percent = 1; + } + else { + percent = 0; + } + return { + percent, + transferred: this._uploadedSize, + total: this._bodySize, + }; + } + /** + The object contains the following properties: -const getStreamContents = async (stream, {init, convertChunk, getSize, truncateChunk, addChunk, getFinalChunk, finalize}, {maxBuffer = Number.POSITIVE_INFINITY} = {}) => { - const asyncIterable = getAsyncIterable(stream); + - `start` - Time when the request started. + - `socket` - Time when a socket was assigned to the request. + - `lookup` - Time when the DNS lookup finished. + - `connect` - Time when the socket successfully connected. + - `secureConnect` - Time when the socket securely connected. + - `upload` - Time when the request finished uploading. + - `response` - Time when the request fired `response` event. + - `end` - Time when the response fired `end` event. + - `error` - Time when the request fired `error` event. + - `abort` - Time when the request fired `abort` event. + - `phases` + - `wait` - `timings.socket - timings.start` + - `dns` - `timings.lookup - timings.socket` + - `tcp` - `timings.connect - timings.lookup` + - `tls` - `timings.secureConnect - timings.connect` + - `request` - `timings.upload - (timings.secureConnect || timings.connect)` + - `firstByte` - `timings.response - timings.upload` + - `download` - `timings.end - timings.response` + - `total` - `(timings.end || timings.error || timings.abort) - timings.start` - const state = init(); - state.length = 0; + If something has not been measured yet, it will be `undefined`. - try { - for await (const chunk of asyncIterable) { - const chunkType = getChunkType(chunk); - const convertedChunk = convertChunk[chunkType](chunk, state); - appendChunk({ - convertedChunk, - state, - getSize, - truncateChunk, - addChunk, - maxBuffer, - }); - } + __Note__: The time is a `number` representing the milliseconds elapsed since the UNIX epoch. + */ + get timings() { + return this._request?.timings; + } + /** + Whether the response was retrieved from the cache. + */ + get isFromCache() { + return this._isFromCache; + } + get reusedSocket() { + return this._request?.reusedSocket; + } +} - appendFinalChunk({ - state, - convertChunk, - getSize, - truncateChunk, - addChunk, - getFinalChunk, - maxBuffer, - }); - return finalize(state); - } catch (error) { - const normalizedError = typeof error === 'object' && error !== null ? error : new Error(error); - normalizedError.bufferedData = finalize(state); - throw normalizedError; - } -}; +;// CONCATENATED MODULE: ./node_modules/.pnpm/got@14.4.4/node_modules/got/dist/source/as-promise/types.js -const appendFinalChunk = ({state, getSize, truncateChunk, addChunk, getFinalChunk, maxBuffer}) => { - const convertedChunk = getFinalChunk(state); - if (convertedChunk !== undefined) { - appendChunk({ - convertedChunk, - state, - getSize, - truncateChunk, - addChunk, - maxBuffer, - }); - } -}; +/** +An error to be thrown when the request is aborted with `.cancel()`. +*/ +class types_CancelError extends RequestError { + constructor(request) { + super('Promise was canceled', {}, request); + this.name = 'CancelError'; + this.code = 'ERR_CANCELED'; + } + /** + Whether the promise is canceled. + */ + get isCanceled() { + return true; + } +} -const appendChunk = ({convertedChunk, state, getSize, truncateChunk, addChunk, maxBuffer}) => { - const chunkSize = getSize(convertedChunk); - const newLength = state.length + chunkSize; +;// CONCATENATED MODULE: ./node_modules/.pnpm/got@14.4.4/node_modules/got/dist/source/as-promise/index.js - if (newLength <= maxBuffer) { - addNewChunk(convertedChunk, state, addChunk, newLength); - return; - } - const truncatedChunk = truncateChunk(convertedChunk, maxBuffer - state.length); - if (truncatedChunk !== undefined) { - addNewChunk(truncatedChunk, state, addChunk, maxBuffer); - } - throw new MaxBufferError(); -}; -const addNewChunk = (convertedChunk, state, addChunk, newLength) => { - state.contents = addChunk(convertedChunk, state, newLength); - state.length = newLength; -}; -const getChunkType = chunk => { - const typeOfChunk = typeof chunk; - if (typeOfChunk === 'string') { - return 'string'; - } - if (typeOfChunk !== 'object' || chunk === null) { - return 'others'; - } +const as_promise_proxiedRequestEvents = [ + 'request', + 'response', + 'redirect', + 'uploadProgress', + 'downloadProgress', +]; +function asPromise(firstRequest) { + let globalRequest; + let globalResponse; + let normalizedOptions; + const emitter = new external_node_events_.EventEmitter(); + const promise = new PCancelable((resolve, reject, onCancel) => { + onCancel(() => { + globalRequest.destroy(); + }); + onCancel.shouldReject = false; + onCancel(() => { + reject(new types_CancelError(globalRequest)); + }); + const makeRequest = (retryCount) => { + // Errors when a new request is made after the promise settles. + // Used to detect a race condition. + // See https://github.com/sindresorhus/got/issues/1489 + onCancel(() => { }); + const request = firstRequest ?? new Request(undefined, undefined, normalizedOptions); + request.retryCount = retryCount; + request._noPipe = true; + globalRequest = request; + request.once('response', async (response) => { + // Parse body + const contentEncoding = (response.headers['content-encoding'] ?? '').toLowerCase(); + const isCompressed = contentEncoding === 'gzip' || contentEncoding === 'deflate' || contentEncoding === 'br'; + const { options } = request; + if (isCompressed && !options.decompress) { + response.body = response.rawBody; + } + else { + try { + response.body = parseBody(response, options.responseType, options.parseJson, options.encoding); + } + catch (error) { + // Fall back to `utf8` + try { + response.body = response.rawBody.toString(); + } + catch (error) { + request._beforeError(new ParseError(error, response)); + return; + } + if (isResponseOk(response)) { + request._beforeError(error); + return; + } + } + } + try { + const hooks = options.hooks.afterResponse; + for (const [index, hook] of hooks.entries()) { + // @ts-expect-error TS doesn't notice that CancelableRequest is a Promise + // eslint-disable-next-line no-await-in-loop + response = await hook(response, async (updatedOptions) => { + options.merge(updatedOptions); + options.prefixUrl = ''; + if (updatedOptions.url) { + options.url = updatedOptions.url; + } + // Remove any further hooks for that request, because we'll call them anyway. + // The loop continues. We don't want duplicates (asPromise recursion). + options.hooks.afterResponse = options.hooks.afterResponse.slice(0, index); + throw new RetryError(request); + }); + if (!(distribution.object(response) && distribution.number(response.statusCode) && !distribution.nullOrUndefined(response.body))) { + throw new TypeError('The `afterResponse` hook returned an invalid value'); + } + } + } + catch (error) { + request._beforeError(error); + return; + } + globalResponse = response; + if (!isResponseOk(response)) { + request._beforeError(new HTTPError(response)); + return; + } + request.destroy(); + resolve(request.options.resolveBodyOnly ? response.body : response); + }); + const onError = (error) => { + if (promise.isCanceled) { + return; + } + const { options } = request; + if (error instanceof HTTPError && !options.throwHttpErrors) { + const { response } = error; + request.destroy(); + resolve(request.options.resolveBodyOnly ? response.body : response); + return; + } + reject(error); + }; + request.once('error', onError); + const previousBody = request.options?.body; + request.once('retry', (newRetryCount, error) => { + firstRequest = undefined; + const newBody = request.options.body; + if (previousBody === newBody && distribution.nodeStream(newBody)) { + error.message = 'Cannot retry with consumed body stream'; + onError(error); + return; + } + // This is needed! We need to reuse `request.options` because they can get modified! + // For example, by calling `promise.json()`. + normalizedOptions = request.options; + makeRequest(newRetryCount); + }); + proxyEvents(request, emitter, as_promise_proxiedRequestEvents); + if (distribution.undefined(firstRequest)) { + void request.flush(); + } + }; + makeRequest(0); + }); + promise.on = (event, function_) => { + emitter.on(event, function_); + return promise; + }; + promise.off = (event, function_) => { + emitter.off(event, function_); + return promise; + }; + const shortcut = (responseType) => { + const newPromise = (async () => { + // Wait until downloading has ended + await promise; + const { options } = globalResponse.request; + return parseBody(globalResponse, responseType, options.parseJson, options.encoding); + })(); + // eslint-disable-next-line @typescript-eslint/no-floating-promises + Object.defineProperties(newPromise, Object.getOwnPropertyDescriptors(promise)); + return newPromise; + }; + promise.json = () => { + if (globalRequest.options) { + const { headers } = globalRequest.options; + if (!globalRequest.writableFinished && !('accept' in headers)) { + headers.accept = 'application/json'; + } + } + return shortcut('json'); + }; + promise.buffer = () => shortcut('buffer'); + promise.text = () => shortcut('text'); + return promise; +} - if (globalThis.Buffer?.isBuffer(chunk)) { - return 'buffer'; - } +;// CONCATENATED MODULE: ./node_modules/.pnpm/got@14.4.4/node_modules/got/dist/source/create.js - const prototypeName = objectToString.call(chunk); - if (prototypeName === '[object ArrayBuffer]') { - return 'arrayBuffer'; - } - if (prototypeName === '[object DataView]') { - return 'dataView'; - } - if ( - Number.isInteger(chunk.byteLength) - && Number.isInteger(chunk.byteOffset) - && objectToString.call(chunk.buffer) === '[object ArrayBuffer]' - ) { - return 'typedArray'; - } - return 'others'; +const isGotInstance = (value) => distribution["function"](value); +const aliases = [ + 'get', + 'post', + 'put', + 'patch', + 'head', + 'delete', +]; +const create = (defaults) => { + defaults = { + options: new Options(undefined, undefined, defaults.options), + handlers: [...defaults.handlers], + mutableDefaults: defaults.mutableDefaults, + }; + Object.defineProperty(defaults, 'mutableDefaults', { + enumerable: true, + configurable: false, + writable: false, + }); + // Got interface + const got = ((url, options, defaultOptions = defaults.options) => { + const request = new Request(url, options, defaultOptions); + let promise; + const lastHandler = (normalized) => { + // Note: `options` is `undefined` when `new Options(...)` fails + request.options = normalized; + request._noPipe = !normalized?.isStream; + void request.flush(); + if (normalized?.isStream) { + return request; + } + promise ||= asPromise(request); + return promise; + }; + let iteration = 0; + const iterateHandlers = (newOptions) => { + const handler = defaults.handlers[iteration++] ?? lastHandler; + const result = handler(newOptions, iterateHandlers); + if (distribution.promise(result) && !request.options?.isStream) { + promise ||= asPromise(request); + if (result !== promise) { + const descriptors = Object.getOwnPropertyDescriptors(promise); + for (const key in descriptors) { + if (key in result) { + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete + delete descriptors[key]; + } + } + // eslint-disable-next-line @typescript-eslint/no-floating-promises + Object.defineProperties(result, descriptors); + result.cancel = promise.cancel; + } + } + return result; + }; + return iterateHandlers(request.options); + }); + got.extend = (...instancesOrOptions) => { + const options = new Options(undefined, undefined, defaults.options); + const handlers = [...defaults.handlers]; + let mutableDefaults; + for (const value of instancesOrOptions) { + if (isGotInstance(value)) { + options.merge(value.defaults.options); + handlers.push(...value.defaults.handlers); + mutableDefaults = value.defaults.mutableDefaults; + } + else { + options.merge(value); + if (value.handlers) { + handlers.push(...value.handlers); + } + mutableDefaults = value.mutableDefaults; + } + } + return create({ + options, + handlers, + mutableDefaults: Boolean(mutableDefaults), + }); + }; + // Pagination + const paginateEach = (async function* (url, options) { + let normalizedOptions = new Options(url, options, defaults.options); + normalizedOptions.resolveBodyOnly = false; + const { pagination } = normalizedOptions; + assert["function"](pagination.transform); + assert["function"](pagination.shouldContinue); + assert["function"](pagination.filter); + assert["function"](pagination.paginate); + assert.number(pagination.countLimit); + assert.number(pagination.requestLimit); + assert.number(pagination.backoff); + const allItems = []; + let { countLimit } = pagination; + let numberOfRequests = 0; + while (numberOfRequests < pagination.requestLimit) { + if (numberOfRequests !== 0) { + // eslint-disable-next-line no-await-in-loop + await (0,external_node_timers_promises_namespaceObject.setTimeout)(pagination.backoff); + } + // eslint-disable-next-line no-await-in-loop + const response = (await got(undefined, undefined, normalizedOptions)); + // eslint-disable-next-line no-await-in-loop + const parsed = await pagination.transform(response); + const currentItems = []; + assert.array(parsed); + for (const item of parsed) { + if (pagination.filter({ item, currentItems, allItems })) { + if (!pagination.shouldContinue({ item, currentItems, allItems })) { + return; + } + yield item; + if (pagination.stackAllItems) { + allItems.push(item); + } + currentItems.push(item); + if (--countLimit <= 0) { + return; + } + } + } + const optionsToMerge = pagination.paginate({ + response, + currentItems, + allItems, + }); + if (optionsToMerge === false) { + return; + } + if (optionsToMerge === response.request.options) { + normalizedOptions = response.request.options; + } + else { + normalizedOptions.merge(optionsToMerge); + assert.any([distribution.urlInstance, distribution.undefined], optionsToMerge.url); + if (optionsToMerge.url !== undefined) { + normalizedOptions.prefixUrl = ''; + normalizedOptions.url = optionsToMerge.url; + } + } + numberOfRequests++; + } + }); + got.paginate = paginateEach; + got.paginate.all = (async (url, options) => { + const results = []; + for await (const item of paginateEach(url, options)) { + results.push(item); + } + return results; + }); + // For those who like very descriptive names + got.paginate.each = paginateEach; + // Stream API + got.stream = ((url, options) => got(url, { ...options, isStream: true })); + // Shortcuts + for (const method of aliases) { + got[method] = ((url, options) => got(url, { ...options, method })); + got.stream[method] = ((url, options) => got(url, { ...options, method, isStream: true })); + } + if (!defaults.mutableDefaults) { + Object.freeze(defaults.handlers); + defaults.options.freeze(); + } + Object.defineProperty(got, 'defaults', { + value: defaults, + writable: false, + configurable: false, + enumerable: true, + }); + return got; }; +/* harmony default export */ const source_create = (create); -const {toString: objectToString} = Object.prototype; - -class MaxBufferError extends Error { - name = 'MaxBufferError'; - - constructor() { - super('maxBuffer exceeded'); - } -} - -;// CONCATENATED MODULE: ./node_modules/.pnpm/get-stream@9.0.1/node_modules/get-stream/source/utils.js -const identity = value => value; - -const noop = () => undefined; +;// CONCATENATED MODULE: ./node_modules/.pnpm/got@14.4.4/node_modules/got/dist/source/index.js -const getContentsProperty = ({contents}) => contents; -const throwObjectStream = chunk => { - throw new Error(`Streams in object mode are not supported: ${String(chunk)}`); +const defaults = { + options: new Options(), + handlers: [], + mutableDefaults: false, }; - -const getLengthProperty = convertedChunk => convertedChunk.length; - -;// CONCATENATED MODULE: ./node_modules/.pnpm/get-stream@9.0.1/node_modules/get-stream/source/array-buffer.js - +const got = source_create(defaults); +/* harmony default export */ const got_dist_source = (got); +// TODO: Remove this in the next major version. -async function getStreamAsArrayBuffer(stream, options) { - return getStreamContents(stream, arrayBufferMethods, options); -} -const initArrayBuffer = () => ({contents: new ArrayBuffer(0)}); -const useTextEncoder = chunk => textEncoder.encode(chunk); -const textEncoder = new TextEncoder(); -const useUint8Array = chunk => new Uint8Array(chunk); -const useUint8ArrayWithOffset = chunk => new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength); -const truncateArrayBufferChunk = (convertedChunk, chunkSize) => convertedChunk.slice(0, chunkSize); -// `contents` is an increasingly growing `Uint8Array`. -const addArrayBufferChunk = (convertedChunk, {contents, length: previousLength}, length) => { - const newContents = hasArrayBufferResize() ? resizeArrayBuffer(contents, length) : resizeArrayBufferSlow(contents, length); - new Uint8Array(newContents).set(convertedChunk, previousLength); - return newContents; -}; -// Without `ArrayBuffer.resize()`, `contents` size is always a power of 2. -// This means its last bytes are zeroes (not stream data), which need to be -// trimmed at the end with `ArrayBuffer.slice()`. -const resizeArrayBufferSlow = (contents, length) => { - if (length <= contents.byteLength) { - return contents; - } - const arrayBuffer = new ArrayBuffer(getNewContentsLength(length)); - new Uint8Array(arrayBuffer).set(new Uint8Array(contents), 0); - return arrayBuffer; -}; -// With `ArrayBuffer.resize()`, `contents` size matches exactly the size of -// the stream data. It does not include extraneous zeroes to trim at the end. -// The underlying `ArrayBuffer` does allocate a number of bytes that is a power -// of 2, but those bytes are only visible after calling `ArrayBuffer.resize()`. -const resizeArrayBuffer = (contents, length) => { - if (length <= contents.maxByteLength) { - contents.resize(length); - return contents; - } - const arrayBuffer = new ArrayBuffer(length, {maxByteLength: getNewContentsLength(length)}); - new Uint8Array(arrayBuffer).set(new Uint8Array(contents), 0); - return arrayBuffer; +;// CONCATENATED MODULE: external "node:dns/promises" +const external_node_dns_promises_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:dns/promises"); +// EXTERNAL MODULE: ./node_modules/.pnpm/@actions+cache@3.3.0/node_modules/@actions/cache/lib/cache.js +var cache = __nccwpck_require__(5591); +;// CONCATENATED MODULE: external "node:child_process" +const external_node_child_process_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:child_process"); +;// CONCATENATED MODULE: ./node_modules/.pnpm/github.com+DeterminateSystems+detsys-ts@4280bc94c9545f31ccf08001cc16f20ccb91b770_4q7gpbzpftzcqas42ud7gqm62a/node_modules/detsys-ts/dist/index.js +var __defProp = Object.defineProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); }; -// Retrieve the closest `length` that is both >= and a power of 2 -const getNewContentsLength = length => SCALE_FACTOR ** Math.ceil(Math.log(length) / Math.log(SCALE_FACTOR)); +// package.json +var version = "1.0.0"; -const SCALE_FACTOR = 2; +// src/linux-release-info.ts -const finalizeArrayBuffer = ({contents, length}) => hasArrayBufferResize() ? contents : contents.slice(0, length); -// `ArrayBuffer.slice()` is slow. When `ArrayBuffer.resize()` is available -// (Node >=20.0.0, Safari >=16.4 and Chrome), we can use it instead. -// eslint-disable-next-line no-warning-comments -// TODO: remove after dropping support for Node 20. -// eslint-disable-next-line no-warning-comments -// TODO: use `ArrayBuffer.transferToFixedLength()` instead once it is available -const hasArrayBufferResize = () => 'resize' in ArrayBuffer.prototype; -const arrayBufferMethods = { - init: initArrayBuffer, - convertChunk: { - string: useTextEncoder, - buffer: useUint8Array, - arrayBuffer: useUint8Array, - dataView: useUint8ArrayWithOffset, - typedArray: useUint8ArrayWithOffset, - others: throwObjectStream, - }, - getSize: getLengthProperty, - truncateChunk: truncateArrayBufferChunk, - addChunk: addArrayBufferChunk, - getFinalChunk: noop, - finalize: finalizeArrayBuffer, +var readFileAsync = (0,external_node_util_.promisify)(external_node_fs_namespaceObject.readFile); +var linuxReleaseInfoOptionsDefaults = { + mode: "async", + customFile: null, + debug: false }; - -;// CONCATENATED MODULE: ./node_modules/.pnpm/get-stream@9.0.1/node_modules/get-stream/source/buffer.js - - -async function getStreamAsBuffer(stream, options) { - if (!('Buffer' in globalThis)) { - throw new Error('getStreamAsBuffer() is only supported in Node.js'); - } - - try { - return arrayBufferToNodeBuffer(await getStreamAsArrayBuffer(stream, options)); - } catch (error) { - if (error.bufferedData !== undefined) { - error.bufferedData = arrayBufferToNodeBuffer(error.bufferedData); - } - - throw error; - } +function releaseInfo(infoOptions) { + const options = { ...linuxReleaseInfoOptionsDefaults, ...infoOptions }; + const searchOsReleaseFileList = osReleaseFileList( + options.customFile + ); + if (external_node_os_.type() !== "Linux") { + if (options.mode === "sync") { + return getOsInfo(); + } else { + return Promise.resolve(getOsInfo()); + } + } + if (options.mode === "sync") { + return readSyncOsreleaseFile(searchOsReleaseFileList, options); + } else { + return Promise.resolve( + readAsyncOsReleaseFile(searchOsReleaseFileList, options) + ); + } } - -const arrayBufferToNodeBuffer = arrayBuffer => globalThis.Buffer.from(arrayBuffer); - -// EXTERNAL MODULE: ./node_modules/.pnpm/http-cache-semantics@4.1.1/node_modules/http-cache-semantics/index.js -var http_cache_semantics = __nccwpck_require__(7893); -;// CONCATENATED MODULE: ./node_modules/.pnpm/lowercase-keys@3.0.0/node_modules/lowercase-keys/index.js -function lowercaseKeys(object) { - return Object.fromEntries(Object.entries(object).map(([key, value]) => [key.toLowerCase(), value])); +function formatFileData(sourceData, srcParseData) { + const lines = srcParseData.split("\n"); + for (const line of lines) { + const lineData = line.split("="); + if (lineData.length === 2) { + lineData[1] = lineData[1].replace(/["'\r]/gi, ""); + Object.defineProperty(sourceData, lineData[0].toLowerCase(), { + value: lineData[1], + writable: true, + enumerable: true, + configurable: true + }); + } + } + return sourceData; } - -;// CONCATENATED MODULE: ./node_modules/.pnpm/responselike@3.0.0/node_modules/responselike/index.js - - - -class Response extends external_node_stream_.Readable { - statusCode; - headers; - body; - url; - - constructor({statusCode, headers, body, url}) { - if (typeof statusCode !== 'number') { - throw new TypeError('Argument `statusCode` should be a number'); - } - - if (typeof headers !== 'object') { - throw new TypeError('Argument `headers` should be an object'); - } - - if (!(body instanceof Uint8Array)) { - throw new TypeError('Argument `body` should be a buffer'); - } - - if (typeof url !== 'string') { - throw new TypeError('Argument `url` should be a string'); - } - - super({ - read() { - this.push(body); - this.push(null); - }, - }); - - this.statusCode = statusCode; - this.headers = lowercaseKeys(headers); - this.body = body; - this.url = url; - } +function osReleaseFileList(customFile) { + const DEFAULT_OS_RELEASE_FILES = ["/etc/os-release", "/usr/lib/os-release"]; + if (!customFile) { + return DEFAULT_OS_RELEASE_FILES; + } else { + return Array(customFile); + } +} +function getOsInfo() { + return { + type: external_node_os_.type(), + platform: external_node_os_.platform(), + hostname: external_node_os_.hostname(), + arch: external_node_os_.arch(), + release: external_node_os_.release() + }; +} +async function readAsyncOsReleaseFile(fileList, options) { + let fileData = null; + for (const osReleaseFile of fileList) { + try { + if (options.debug) { + console.log(`Trying to read '${osReleaseFile}'...`); + } + fileData = await readFileAsync(osReleaseFile, "binary"); + if (options.debug) { + console.log(`Read data: +${fileData}`); + } + break; + } catch (error3) { + if (options.debug) { + console.error(error3); + } + } + } + if (fileData === null) { + throw new Error("Cannot read os-release file!"); + } + return formatFileData(getOsInfo(), fileData); +} +function readSyncOsreleaseFile(releaseFileList, options) { + let fileData = null; + for (const osReleaseFile of releaseFileList) { + try { + if (options.debug) { + console.log(`Trying to read '${osReleaseFile}'...`); + } + fileData = external_node_fs_namespaceObject.readFileSync(osReleaseFile, "binary"); + if (options.debug) { + console.log(`Read data: +${fileData}`); + } + break; + } catch (error3) { + if (options.debug) { + console.error(error3); + } + } + } + if (fileData === null) { + throw new Error("Cannot read os-release file!"); + } + return formatFileData(getOsInfo(), fileData); } -// EXTERNAL MODULE: ./node_modules/.pnpm/keyv@4.5.4/node_modules/keyv/src/index.js -var src = __nccwpck_require__(8534); -;// CONCATENATED MODULE: ./node_modules/.pnpm/mimic-response@4.0.0/node_modules/mimic-response/index.js -// We define these manually to ensure they're always copied -// even if they would move up the prototype chain -// https://nodejs.org/api/http.html#http_class_http_incomingmessage -const knownProperties = [ - 'aborted', - 'complete', - 'headers', - 'httpVersion', - 'httpVersionMinor', - 'httpVersionMajor', - 'method', - 'rawHeaders', - 'rawTrailers', - 'setTimeout', - 'socket', - 'statusCode', - 'statusMessage', - 'trailers', - 'url', -]; - -function mimicResponse(fromStream, toStream) { - if (toStream._readableState.autoDestroy) { - throw new Error('The second stream must have the `autoDestroy` option set to `false`'); - } - - const fromProperties = new Set([...Object.keys(fromStream), ...knownProperties]); - - const properties = {}; - - for (const property of fromProperties) { - // Don't overwrite existing properties. - if (property in toStream) { - continue; - } - - properties[property] = { - get() { - const value = fromStream[property]; - const isFunction = typeof value === 'function'; - - return isFunction ? value.bind(fromStream) : value; - }, - set(value) { - fromStream[property] = value; - }, - enumerable: true, - configurable: false, - }; - } - - Object.defineProperties(toStream, properties); - - fromStream.once('aborted', () => { - toStream.destroy(); - - toStream.emit('aborted'); - }); +// src/actions-core-platform.ts - fromStream.once('close', () => { - if (fromStream.complete) { - if (toStream.readable) { - toStream.once('end', () => { - toStream.emit('close'); - }); - } else { - toStream.emit('close'); - } - } else { - toStream.emit('close'); - } - }); - return toStream; -} -;// CONCATENATED MODULE: ./node_modules/.pnpm/cacheable-request@12.0.1/node_modules/cacheable-request/dist/types.js -// Type definitions for cacheable-request 6.0 -// Project: https://github.com/lukechilds/cacheable-request#readme -// Definitions by: BendingBender -// Paul Melnikow -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 -class types_RequestError extends Error { - constructor(error) { - super(error.message); - Object.assign(this, error); +var getWindowsInfo = async () => { + const { stdout: version2 } = await exec.getExecOutput( + 'powershell -command "(Get-CimInstance -ClassName Win32_OperatingSystem).Version"', + void 0, + { + silent: true } -} -class types_CacheError extends Error { - constructor(error) { - super(error.message); - Object.assign(this, error); + ); + const { stdout: name } = await exec.getExecOutput( + 'powershell -command "(Get-CimInstance -ClassName Win32_OperatingSystem).Caption"', + void 0, + { + silent: true } + ); + return { + name: name.trim(), + version: version2.trim() + }; +}; +var getMacOsInfo = async () => { + const { stdout } = await exec.getExecOutput("sw_vers", void 0, { + silent: true + }); + const version2 = stdout.match(/ProductVersion:\s*(.+)/)?.[1] ?? ""; + const name = stdout.match(/ProductName:\s*(.+)/)?.[1] ?? ""; + return { + name, + version: version2 + }; +}; +var getLinuxInfo = async () => { + let data = {}; + try { + data = releaseInfo({ mode: "sync" }); + lib_core.debug(`Identified release info: ${JSON.stringify(data)}`); + } catch (e) { + lib_core.debug(`Error collecting release info: ${e}`); + } + return { + name: getPropertyViaWithDefault( + data, + ["id", "name", "pretty_name", "id_like"], + "unknown" + ), + version: getPropertyViaWithDefault( + data, + ["version_id", "version", "version_codename"], + "unknown" + ) + }; +}; +function getPropertyViaWithDefault(data, names, defaultValue) { + for (const name of names) { + const ret = getPropertyWithDefault(data, name, defaultValue); + if (ret !== defaultValue) { + return ret; + } + } + return defaultValue; +} +function getPropertyWithDefault(data, name, defaultValue) { + if (!data.hasOwnProperty(name)) { + return defaultValue; + } + const value = data[name]; + if (typeof value !== typeof defaultValue) { + return defaultValue; + } + return value; +} +var platform2 = external_os_.platform(); +var arch2 = external_os_.arch(); +var isWindows = platform2 === "win32"; +var isMacOS = platform2 === "darwin"; +var isLinux = platform2 === "linux"; +async function getDetails() { + return { + ...await (isWindows ? getWindowsInfo() : isMacOS ? getMacOsInfo() : getLinuxInfo()), + platform: platform2, + arch: arch2, + isWindows, + isMacOS, + isLinux + }; } -//# sourceMappingURL=types.js.map -;// CONCATENATED MODULE: ./node_modules/.pnpm/cacheable-request@12.0.1/node_modules/cacheable-request/dist/index.js - - - - +// src/errors.ts +function stringifyError(e) { + if (e instanceof Error) { + return e.message; + } else if (typeof e === "string") { + return e; + } else { + return JSON.stringify(e); + } +} +// src/backtrace.ts -class CacheableRequest { - constructor(cacheRequest, cacheAdapter) { - this.hooks = new Map(); - this.request = () => (options, callback) => { - let url; - if (typeof options === 'string') { - url = normalizeUrlObject(external_node_url_namespaceObject.parse(options)); - options = {}; - } - else if (options instanceof external_node_url_namespaceObject.URL) { - url = normalizeUrlObject(external_node_url_namespaceObject.parse(options.toString())); - options = {}; - } - else { - const [pathname, ...searchParts] = (options.path ?? '').split('?'); - const search = searchParts.length > 0 - ? `?${searchParts.join('?')}` - : ''; - url = normalizeUrlObject({ ...options, pathname, search }); - } - options = { - headers: {}, - method: 'GET', - cache: true, - strictTtl: false, - automaticFailover: false, - ...options, - ...urlObjectToRequestOptions(url), - }; - options.headers = Object.fromEntries(entries(options.headers).map(([key, value]) => [key.toLowerCase(), value])); - const ee = new external_node_events_(); - const normalizedUrlString = normalizeUrl(external_node_url_namespaceObject.format(url), { - stripWWW: false, // eslint-disable-line @typescript-eslint/naming-convention - removeTrailingSlash: false, - stripAuthentication: false, - }); - let key = `${options.method}:${normalizedUrlString}`; - // POST, PATCH, and PUT requests may be cached, depending on the response - // cache-control headers. As a result, the body of the request should be - // added to the cache key in order to avoid collisions. - if (options.body && options.method !== undefined && ['POST', 'PATCH', 'PUT'].includes(options.method)) { - if (options.body instanceof external_node_stream_.Readable) { - // Streamed bodies should completely skip the cache because they may - // or may not be hashable and in either case the stream would need to - // close before the cache key could be generated. - options.cache = false; - } - else { - key += `:${external_node_crypto_namespaceObject.createHash('md5').update(options.body).digest('hex')}`; - } - } - let revalidate = false; - let madeRequest = false; - const makeRequest = (options_) => { - madeRequest = true; - let requestErrored = false; - let requestErrorCallback = () => { }; - const requestErrorPromise = new Promise(resolve => { - requestErrorCallback = () => { - if (!requestErrored) { - requestErrored = true; - resolve(); - } - }; - }); - const handler = async (response) => { - if (revalidate) { - response.status = response.statusCode; - const revalidatedPolicy = http_cache_semantics.fromObject(revalidate.cachePolicy).revalidatedPolicy(options_, response); - if (!revalidatedPolicy.modified) { - response.resume(); - await new Promise(resolve => { - // Skipping 'error' handler cause 'error' event should't be emitted for 304 response - response - .once('end', resolve); - }); - const headers = convertHeaders(revalidatedPolicy.policy.responseHeaders()); - response = new Response({ - statusCode: revalidate.statusCode, headers, body: revalidate.body, url: revalidate.url, - }); - response.cachePolicy = revalidatedPolicy.policy; - response.fromCache = true; - } - } - if (!response.fromCache) { - response.cachePolicy = new http_cache_semantics(options_, response, options_); - response.fromCache = false; - } - let clonedResponse; - if (options_.cache && response.cachePolicy.storable()) { - clonedResponse = cloneResponse(response); - (async () => { - try { - const bodyPromise = getStreamAsBuffer(response); - await Promise.race([ - requestErrorPromise, - new Promise(resolve => response.once('end', resolve)), // eslint-disable-line no-promise-executor-return - new Promise(resolve => response.once('close', resolve)), // eslint-disable-line no-promise-executor-return - ]); - const body = await bodyPromise; - let value = { - url: response.url, - statusCode: response.fromCache ? revalidate.statusCode : response.statusCode, - body, - cachePolicy: response.cachePolicy.toObject(), - }; - let ttl = options_.strictTtl ? response.cachePolicy.timeToLive() : undefined; - if (options_.maxTtl) { - ttl = ttl ? Math.min(ttl, options_.maxTtl) : options_.maxTtl; - } - if (this.hooks.size > 0) { - /* eslint-disable no-await-in-loop */ - for (const key_ of this.hooks.keys()) { - value = await this.runHook(key_, value, response); - } - /* eslint-enable no-await-in-loop */ - } - await this.cache.set(key, value, ttl); - } - catch (error) { - ee.emit('error', new types_CacheError(error)); - } - })(); - } - else if (options_.cache && revalidate) { - (async () => { - try { - await this.cache.delete(key); - } - catch (error) { - ee.emit('error', new types_CacheError(error)); - } - })(); - } - ee.emit('response', clonedResponse ?? response); - if (typeof callback === 'function') { - callback(clonedResponse ?? response); - } - }; - try { - const request_ = this.cacheRequest(options_, handler); - request_.once('error', requestErrorCallback); - request_.once('abort', requestErrorCallback); - request_.once('destroy', requestErrorCallback); - ee.emit('request', request_); - } - catch (error) { - ee.emit('error', new types_RequestError(error)); - } - }; - (async () => { - const get = async (options_) => { - await Promise.resolve(); - const cacheEntry = options_.cache ? await this.cache.get(key) : undefined; - if (cacheEntry === undefined && !options_.forceRefresh) { - makeRequest(options_); - return; - } - const policy = http_cache_semantics.fromObject(cacheEntry.cachePolicy); - if (policy.satisfiesWithoutRevalidation(options_) && !options_.forceRefresh) { - const headers = convertHeaders(policy.responseHeaders()); - const response = new Response({ - statusCode: cacheEntry.statusCode, headers, body: cacheEntry.body, url: cacheEntry.url, - }); - response.cachePolicy = policy; - response.fromCache = true; - ee.emit('response', response); - if (typeof callback === 'function') { - callback(response); - } - } - else if (policy.satisfiesWithoutRevalidation(options_) && Date.now() >= policy.timeToLive() && options_.forceRefresh) { - await this.cache.delete(key); - options_.headers = policy.revalidationHeaders(options_); - makeRequest(options_); - } - else { - revalidate = cacheEntry; - options_.headers = policy.revalidationHeaders(options_); - makeRequest(options_); - } - }; - const errorHandler = (error) => ee.emit('error', new types_CacheError(error)); - if (this.cache instanceof src) { - const cachek = this.cache; - cachek.once('error', errorHandler); - ee.on('error', () => cachek.removeListener('error', errorHandler)); - ee.on('response', () => cachek.removeListener('error', errorHandler)); - } - try { - await get(options); - } - catch (error) { - if (options.automaticFailover && !madeRequest) { - makeRequest(options); - } - ee.emit('error', new types_CacheError(error)); - } - })(); - return ee; - }; - this.addHook = (name, function_) => { - if (!this.hooks.has(name)) { - this.hooks.set(name, function_); - } - }; - this.removeHook = (name) => this.hooks.delete(name); - this.getHook = (name) => this.hooks.get(name); - this.runHook = async (name, ...arguments_) => this.hooks.get(name)?.(...arguments_); - if (cacheAdapter instanceof src) { - this.cache = cacheAdapter; +async function collectBacktraces(prefixes, startTimestampMs) { + if (isMacOS) { + return await collectBacktracesMacOS(prefixes, startTimestampMs); + } + if (isLinux) { + return await collectBacktracesSystemd(prefixes, startTimestampMs); + } + return /* @__PURE__ */ new Map(); +} +async function collectBacktracesMacOS(prefixes, startTimestampMs) { + const backtraces = /* @__PURE__ */ new Map(); + try { + const { stdout: logJson } = await exec.getExecOutput( + "log", + [ + "show", + "--style", + "json", + "--last", + // Note we collect the last 1m only, because it should only take a few seconds to write the crash log. + // Therefore, any crashes before this 1m should be long done by now. + "1m", + "--no-info", + "--predicate", + "sender = 'ReportCrash'" + ], + { + silent: true + } + ); + const sussyArray = JSON.parse(logJson); + if (!Array.isArray(sussyArray)) { + throw new Error(`Log json isn't an array: ${logJson}`); + } + if (sussyArray.length > 0) { + lib_core.info(`Collecting crash data...`); + const delay = async (ms) => new Promise((resolve) => setTimeout(resolve, ms)); + await delay(5e3); + } + } catch (e) { + lib_core.debug( + "Failed to check logs for in-progress crash dumps; now proceeding with the assumption that all crash dumps completed." + ); + } + const dirs = [ + ["system", "/Library/Logs/DiagnosticReports/"], + ["user", `${process.env["HOME"]}/Library/Logs/DiagnosticReports/`] + ]; + for (const [source, dir] of dirs) { + const fileNames = (await (0,promises_namespaceObject.readdir)(dir)).filter((fileName) => { + return prefixes.some((prefix) => fileName.startsWith(prefix)); + }).filter((fileName) => { + return !fileName.endsWith(".diag"); + }); + const doGzip = (0,external_node_util_.promisify)(external_node_zlib_.gzip); + for (const fileName of fileNames) { + try { + if ((await (0,promises_namespaceObject.stat)(`${dir}/${fileName}`)).ctimeMs >= startTimestampMs) { + const logText = await (0,promises_namespaceObject.readFile)(`${dir}/${fileName}`); + const buf = await doGzip(logText); + backtraces.set( + `backtrace_value_${source}_${fileName}`, + buf.toString("base64") + ); } - else if (typeof cacheAdapter === 'string') { - this.cache = new src({ - uri: cacheAdapter, - namespace: 'cacheable-request', + } catch (innerError) { + backtraces.set( + `backtrace_failure_${source}_${fileName}`, + stringifyError(innerError) + ); + } + } + } + return backtraces; +} +async function collectBacktracesSystemd(prefixes, startTimestampMs) { + const sinceSeconds = Math.ceil((Date.now() - startTimestampMs) / 1e3); + const backtraces = /* @__PURE__ */ new Map(); + const coredumps = []; + try { + const { stdout: coredumpjson } = await exec.getExecOutput( + "coredumpctl", + ["--json=pretty", "list", "--since", `${sinceSeconds} seconds ago`], + { + silent: true + } + ); + const sussyArray = JSON.parse(coredumpjson); + if (!Array.isArray(sussyArray)) { + throw new Error(`Coredump isn't an array: ${coredumpjson}`); + } + for (const sussyObject of sussyArray) { + const keys = Object.keys(sussyObject); + if (keys.includes("exe") && keys.includes("pid")) { + if (typeof sussyObject.exe == "string" && typeof sussyObject.pid == "number") { + const execParts = sussyObject.exe.split("/"); + const binaryName = execParts[execParts.length - 1]; + if (prefixes.some((prefix) => binaryName.startsWith(prefix))) { + coredumps.push({ + exe: sussyObject.exe, + pid: sussyObject.pid }); + } + } else { + lib_core.debug( + `Mysterious coredump entry missing exe string and/or pid number: ${JSON.stringify(sussyObject)}` + ); } - else { - this.cache = new src({ - store: cacheAdapter, - namespace: 'cacheable-request', - }); + } else { + lib_core.debug( + `Mysterious coredump entry missing exe value and/or pid value: ${JSON.stringify(sussyObject)}` + ); + } + } + } catch (innerError) { + lib_core.debug( + `Cannot collect backtraces: ${stringifyError(innerError)}` + ); + return backtraces; + } + const doGzip = (0,external_node_util_.promisify)(external_node_zlib_.gzip); + for (const coredump of coredumps) { + try { + const { stdout: logText } = await exec.getExecOutput( + "coredumpctl", + ["info", `${coredump.pid}`], + { + silent: true } - this.request = this.request.bind(this); - this.cacheRequest = cacheRequest; + ); + const buf = await doGzip(logText); + backtraces.set(`backtrace_value_${coredump.pid}`, buf.toString("base64")); + } catch (innerError) { + backtraces.set( + `backtrace_failure_${coredump.pid}`, + stringifyError(innerError) + ); } + } + return backtraces; } -const entries = Object.entries; -const cloneResponse = (response) => { - const clone = new external_node_stream_.PassThrough({ autoDestroy: false }); - mimicResponse(response, clone); - return response.pipe(clone); -}; -const urlObjectToRequestOptions = (url) => { - const options = { ...url }; - options.path = `${url.pathname || '/'}${url.search || ''}`; - delete options.pathname; - delete options.search; - return options; -}; -const normalizeUrlObject = (url) => -// If url was parsed by url.parse or new URL: -// - hostname will be set -// - host will be hostname[:port] -// - port will be set if it was explicit in the parsed string -// Otherwise, url was from request options: -// - hostname or host may be set -// - host shall not have port encoded -({ - protocol: url.protocol, - auth: url.auth, - hostname: url.hostname || url.host || 'localhost', - port: url.port, - pathname: url.pathname, - search: url.search, -}); -const convertHeaders = (headers) => { - const result = []; - for (const name of Object.keys(headers)) { - result[name.toLowerCase()] = headers[name]; - } - return result; -}; -/* harmony default export */ const dist = (CacheableRequest); -const onResponse = 'onResponse'; -//# sourceMappingURL=index.js.map -// EXTERNAL MODULE: ./node_modules/.pnpm/decompress-response@6.0.0/node_modules/decompress-response/index.js -var decompress_response = __nccwpck_require__(7748); -;// CONCATENATED MODULE: ./node_modules/.pnpm/form-data-encoder@4.0.2/node_modules/form-data-encoder/lib/index.js -var __accessCheck = (obj, member, msg) => { - if (!member.has(obj)) - throw TypeError("Cannot " + msg); -}; -var __privateGet = (obj, member, getter) => { - __accessCheck(obj, member, "read from private field"); - return getter ? getter.call(obj) : member.get(obj); -}; -var __privateAdd = (obj, member, value) => { - if (member.has(obj)) - throw TypeError("Cannot add the same private member more than once"); - member instanceof WeakSet ? member.add(obj) : member.set(obj, value); -}; -var __privateSet = (obj, member, value, setter) => { - __accessCheck(obj, member, "write to private field"); - setter ? setter.call(obj, value) : member.set(obj, value); - return value; -}; -var __privateMethod = (obj, member, method) => { - __accessCheck(obj, member, "access private method"); - return method; -}; +// src/correlation.ts + + +var OPTIONAL_VARIABLES = ["INVOCATION_ID"]; +function identify(projectName) { + const ident = { + correlation_source: "github-actions", + repository: hashEnvironmentVariables("GHR", [ + "GITHUB_SERVER_URL", + "GITHUB_REPOSITORY_OWNER", + "GITHUB_REPOSITORY_OWNER_ID", + "GITHUB_REPOSITORY", + "GITHUB_REPOSITORY_ID" + ]), + workflow: hashEnvironmentVariables("GHW", [ + "GITHUB_SERVER_URL", + "GITHUB_REPOSITORY_OWNER", + "GITHUB_REPOSITORY_OWNER_ID", + "GITHUB_REPOSITORY", + "GITHUB_REPOSITORY_ID", + "GITHUB_WORKFLOW" + ]), + job: hashEnvironmentVariables("GHWJ", [ + "GITHUB_SERVER_URL", + "GITHUB_REPOSITORY_OWNER", + "GITHUB_REPOSITORY_OWNER_ID", + "GITHUB_REPOSITORY", + "GITHUB_REPOSITORY_ID", + "GITHUB_WORKFLOW", + "GITHUB_JOB" + ]), + run: hashEnvironmentVariables("GHWJR", [ + "GITHUB_SERVER_URL", + "GITHUB_REPOSITORY_OWNER", + "GITHUB_REPOSITORY_OWNER_ID", + "GITHUB_REPOSITORY", + "GITHUB_REPOSITORY_ID", + "GITHUB_WORKFLOW", + "GITHUB_JOB", + "GITHUB_RUN_ID" + ]), + run_differentiator: hashEnvironmentVariables("GHWJA", [ + "GITHUB_SERVER_URL", + "GITHUB_REPOSITORY_OWNER", + "GITHUB_REPOSITORY_OWNER_ID", + "GITHUB_REPOSITORY", + "GITHUB_REPOSITORY_ID", + "GITHUB_WORKFLOW", + "GITHUB_JOB", + "GITHUB_RUN_ID", + "GITHUB_RUN_NUMBER", + "GITHUB_RUN_ATTEMPT", + "INVOCATION_ID" + ]), + groups: { + ci: "github-actions", + project: projectName, + github_organization: hashEnvironmentVariables("GHO", [ + "GITHUB_SERVER_URL", + "GITHUB_REPOSITORY_OWNER", + "GITHUB_REPOSITORY_OWNER_ID" + ]) + } + }; + lib_core.debug("Correlation data:"); + lib_core.debug(JSON.stringify(ident, null, 2)); + return ident; +} +function hashEnvironmentVariables(prefix, variables) { + const hash = (0,external_node_crypto_namespaceObject.createHash)("sha256"); + for (const varName of variables) { + let value = process.env[varName]; + if (value === void 0) { + if (OPTIONAL_VARIABLES.includes(varName)) { + lib_core.debug( + `Optional environment variable not set: ${varName} -- substituting with the variable name` + ); + value = varName; + } else { + lib_core.debug( + `Environment variable not set: ${varName} -- can't generate the requested identity` + ); + return void 0; + } + } + hash.update(value); + hash.update("\0"); + } + return `${prefix}-${hash.digest("hex")}`; +} -// src/util/isFunction.ts -var lib_isFunction = (value) => typeof value === "function"; +// src/ids-host.ts -// src/util/isAsyncIterable.ts -var lib_isAsyncIterable = (value) => lib_isFunction(value[Symbol.asyncIterator]); -// src/util/chunk.ts -var MAX_CHUNK_SIZE = 65536; -function* chunk(value) { - if (value.byteLength <= MAX_CHUNK_SIZE) { - yield value; - return; + +var DEFAULT_LOOKUP = "_detsys_ids._tcp.install.determinate.systems."; +var ALLOWED_SUFFIXES = [ + ".install.determinate.systems", + ".install.detsys.dev" +]; +var DEFAULT_IDS_HOST = "https://install.determinate.systems"; +var LOOKUP = process.env["IDS_LOOKUP"] ?? DEFAULT_LOOKUP; +var DEFAULT_TIMEOUT = 1e4; +var IdsHost = class { + constructor(idsProjectName, diagnosticsSuffix, runtimeDiagnosticsUrl) { + this.idsProjectName = idsProjectName; + this.diagnosticsSuffix = diagnosticsSuffix; + this.runtimeDiagnosticsUrl = runtimeDiagnosticsUrl; + this.client = void 0; } - let offset = 0; - while (offset < value.byteLength) { - const size = Math.min(value.byteLength - offset, MAX_CHUNK_SIZE); - const buffer = value.buffer.slice(offset, offset + size); - offset += buffer.byteLength; - yield new Uint8Array(buffer); + async getGot(recordFailoverCallback) { + if (this.client === void 0) { + this.client = got_dist_source.extend({ + timeout: { + request: DEFAULT_TIMEOUT + }, + retry: { + limit: Math.max((await this.getUrlsByPreference()).length, 3), + methods: ["GET", "HEAD"] + }, + hooks: { + beforeRetry: [ + async (error3, retryCount) => { + const prevUrl = await this.getRootUrl(); + this.markCurrentHostBroken(); + const nextUrl = await this.getRootUrl(); + if (recordFailoverCallback !== void 0) { + recordFailoverCallback(error3, prevUrl, nextUrl); + } + lib_core.info( + `Retrying after error ${error3.code}, retry #: ${retryCount}` + ); + } + ], + beforeRequest: [ + async (options) => { + const currentUrl = options.url; + if (this.isUrlSubjectToDynamicUrls(currentUrl)) { + const newUrl = new URL(currentUrl); + const url = await this.getRootUrl(); + newUrl.host = url.host; + options.url = newUrl; + lib_core.debug(`Transmuted ${currentUrl} into ${newUrl}`); + } else { + lib_core.debug(`No transmutations on ${currentUrl}`); + } + } + ] + } + }); + } + return this.client; } -} - -// src/util/getStreamIterator.ts -async function* readStream(readable) { - const reader = readable.getReader(); - while (true) { - const { done, value } = await reader.read(); - if (done) { - break; + markCurrentHostBroken() { + this.prioritizedURLs?.shift(); + } + setPrioritizedUrls(urls) { + this.prioritizedURLs = urls; + } + isUrlSubjectToDynamicUrls(url) { + if (url.origin === DEFAULT_IDS_HOST) { + return true; } - yield value; + for (const suffix of ALLOWED_SUFFIXES) { + if (url.host.endsWith(suffix)) { + return true; + } + } + return false; } -} -async function* chunkStream(stream) { - for await (const value of stream) { - yield* chunk(value); + async getDynamicRootUrl() { + const idsHost = process.env["IDS_HOST"]; + if (idsHost !== void 0) { + try { + return new URL(idsHost); + } catch (err) { + lib_core.error( + `IDS_HOST environment variable is not a valid URL. Ignoring. ${stringifyError(err)}` + ); + } + } + let url = void 0; + try { + const urls = await this.getUrlsByPreference(); + url = urls[0]; + } catch (err) { + lib_core.error( + `Error collecting IDS URLs by preference: ${stringifyError(err)}` + ); + } + if (url === void 0) { + return void 0; + } else { + return new URL(url); + } + } + async getRootUrl() { + const url = await this.getDynamicRootUrl(); + if (url === void 0) { + return new URL(DEFAULT_IDS_HOST); + } + return url; + } + async getDiagnosticsUrl() { + if (this.runtimeDiagnosticsUrl === "") { + return void 0; + } + if (this.runtimeDiagnosticsUrl !== "-" && this.runtimeDiagnosticsUrl !== void 0) { + try { + return new URL(this.runtimeDiagnosticsUrl); + } catch (err) { + lib_core.info( + `User-provided diagnostic endpoint ignored: not a valid URL: ${stringifyError(err)}` + ); + } + } + try { + const diagnosticUrl = await this.getRootUrl(); + diagnosticUrl.pathname += this.idsProjectName; + diagnosticUrl.pathname += "/"; + diagnosticUrl.pathname += this.diagnosticsSuffix || "diagnostics"; + return diagnosticUrl; + } catch (err) { + lib_core.info( + `Generated diagnostic endpoint ignored, and diagnostics are disabled: not a valid URL: ${stringifyError(err)}` + ); + return void 0; + } + } + async getUrlsByPreference() { + if (this.prioritizedURLs === void 0) { + this.prioritizedURLs = orderRecordsByPriorityWeight( + await discoverServiceRecords() + ).flatMap((record) => recordToUrl(record) || []); + } + return this.prioritizedURLs; + } +}; +function recordToUrl(record) { + const urlStr = `https://${record.name}:${record.port}`; + try { + return new URL(urlStr); + } catch (err) { + lib_core.debug( + `Record ${JSON.stringify(record)} produced an invalid URL: ${urlStr} (${err})` + ); + return void 0; } } -var getStreamIterator = (source) => { - if (lib_isAsyncIterable(source)) { - return chunkStream(source); +async function discoverServiceRecords() { + return await discoverServicesStub((0,external_node_dns_promises_namespaceObject.resolveSrv)(LOOKUP), 1e3); +} +async function discoverServicesStub(lookup, timeout) { + const defaultFallback = new Promise( + (resolve, _reject) => { + setTimeout(resolve, timeout, []); + } + ); + let records; + try { + records = await Promise.race([lookup, defaultFallback]); + } catch (reason) { + lib_core.debug(`Error resolving SRV records: ${stringifyError(reason)}`); + records = []; } - if (lib_isFunction(source.getReader)) { - return chunkStream(readStream(source)); + const acceptableRecords = records.filter((record) => { + for (const suffix of ALLOWED_SUFFIXES) { + if (record.name.endsWith(suffix)) { + return true; + } + } + lib_core.debug( + `Unacceptable domain due to an invalid suffix: ${record.name}` + ); + return false; + }); + if (acceptableRecords.length === 0) { + lib_core.debug(`No records found for ${LOOKUP}`); + } else { + lib_core.debug( + `Resolved ${LOOKUP} to ${JSON.stringify(acceptableRecords)}` + ); } - throw new TypeError( - "Unsupported data source: Expected either ReadableStream or async iterable." + return acceptableRecords; +} +function orderRecordsByPriorityWeight(records) { + const byPriorityWeight = /* @__PURE__ */ new Map(); + for (const record of records) { + const existing = byPriorityWeight.get(record.priority); + if (existing) { + existing.push(record); + } else { + byPriorityWeight.set(record.priority, [record]); + } + } + const prioritizedRecords = []; + const keys = Array.from(byPriorityWeight.keys()).sort( + (a, b) => a - b ); -}; - -// src/util/createBoundary.ts -var alphabet = "abcdefghijklmnopqrstuvwxyz0123456789"; -function createBoundary() { - let size = 16; - let res = ""; - while (size--) { - res += alphabet[Math.random() * alphabet.length << 0]; + for (const priority of keys) { + const recordsByPrio = byPriorityWeight.get(priority); + if (recordsByPrio === void 0) { + continue; + } + prioritizedRecords.push(...weightedRandom(recordsByPrio)); } - return res; + return prioritizedRecords; +} +function weightedRandom(records) { + const scratchRecords = records.slice(); + const result = []; + while (scratchRecords.length > 0) { + const weights = []; + { + for (let i = 0; i < scratchRecords.length; i++) { + weights.push( + scratchRecords[i].weight + (i > 0 ? scratchRecords[i - 1].weight : 0) + ); + } + } + const point = Math.random() * weights[weights.length - 1]; + for (let selectedIndex = 0; selectedIndex < weights.length; selectedIndex++) { + if (weights[selectedIndex] > point) { + result.push(scratchRecords.splice(selectedIndex, 1)[0]); + break; + } + } + } + return result; } -// src/util/normalizeValue.ts -var normalizeValue = (value) => String(value).replace(/\r|\n/g, (match, i, str) => { - if (match === "\r" && str[i + 1] !== "\n" || match === "\n" && str[i - 1] !== "\r") { - return "\r\n"; +// src/inputs.ts +var inputs_exports = {}; +__export(inputs_exports, { + getArrayOfStrings: () => getArrayOfStrings, + getArrayOfStringsOrNull: () => getArrayOfStringsOrNull, + getBool: () => getBool, + getBoolOrUndefined: () => getBoolOrUndefined, + getMultilineStringOrNull: () => getMultilineStringOrNull, + getNumberOrNull: () => getNumberOrNull, + getString: () => getString, + getStringOrNull: () => getStringOrNull, + getStringOrUndefined: () => getStringOrUndefined, + handleString: () => handleString +}); + +var getBool = (name) => { + return lib_core.getBooleanInput(name); +}; +var getBoolOrUndefined = (name) => { + if (getStringOrUndefined(name) === void 0) { + return void 0; } - return match; + return lib_core.getBooleanInput(name); +}; +var getArrayOfStrings = (name, separator) => { + const original = getString(name); + return handleString(original, separator); +}; +var getArrayOfStringsOrNull = (name, separator) => { + const original = getStringOrNull(name); + if (original === null) { + return null; + } else { + return handleString(original, separator); + } +}; +var handleString = (input, separator) => { + const sepChar = separator === "comma" ? "," : /\s+/; + const trimmed = input.trim(); + if (trimmed === "") { + return []; + } + return trimmed.split(sepChar).map((s) => s.trim()); +}; +var getMultilineStringOrNull = (name) => { + const value = lib_core.getMultilineInput(name); + if (value.length === 0) { + return null; + } else { + return value; + } +}; +var getNumberOrNull = (name) => { + const value = lib_core.getInput(name); + if (value === "") { + return null; + } else { + return Number(value); + } +}; +var getString = (name) => { + return lib_core.getInput(name); +}; +var getStringOrNull = (name) => { + const value = lib_core.getInput(name); + if (value === "") { + return null; + } else { + return value; + } +}; +var getStringOrUndefined = (name) => { + const value = lib_core.getInput(name); + if (value === "") { + return void 0; + } else { + return value; + } +}; + +// src/platform.ts +var platform_exports = {}; +__export(platform_exports, { + getArchOs: () => getArchOs, + getNixPlatform: () => getNixPlatform }); -// src/util/isPlainObject.ts -var getType = (value) => Object.prototype.toString.call(value).slice(8, -1).toLowerCase(); -function lib_isPlainObject(value) { - if (getType(value) !== "object") { - return false; +function getArchOs() { + const envArch = process.env.RUNNER_ARCH; + const envOs = process.env.RUNNER_OS; + if (envArch && envOs) { + return `${envArch}-${envOs}`; + } else { + lib_core.error( + `Can't identify the platform: RUNNER_ARCH or RUNNER_OS undefined (${envArch}-${envOs})` + ); + throw new Error("RUNNER_ARCH and/or RUNNER_OS is not defined"); } - const pp = Object.getPrototypeOf(value); - if (pp === null || pp === void 0) { - return true; +} +function getNixPlatform(archOs) { + const archOsMap = /* @__PURE__ */ new Map([ + ["X64-macOS", "x86_64-darwin"], + ["ARM64-macOS", "aarch64-darwin"], + ["X64-Linux", "x86_64-linux"], + ["ARM64-Linux", "aarch64-linux"] + ]); + const mappedTo = archOsMap.get(archOs); + if (mappedTo) { + return mappedTo; + } else { + lib_core.error( + `ArchOs (${archOs}) doesn't map to a supported Nix platform.` + ); + throw new Error( + `Cannot convert ArchOs (${archOs}) to a supported Nix platform.` + ); } - const Ctor = pp.constructor && pp.constructor.toString(); - return Ctor === Object.toString(); } -// src/util/proxyHeaders.ts -function getProperty(target, prop) { - if (typeof prop === "string") { - for (const [name, value] of Object.entries(target)) { - if (prop.toLowerCase() === name.toLowerCase()) { - return value; - } - } - } - return void 0; +// src/sourcedef.ts + +function constructSourceParameters(legacyPrefix) { + return { + path: noisilyGetInput("path", legacyPrefix), + url: noisilyGetInput("url", legacyPrefix), + tag: noisilyGetInput("tag", legacyPrefix), + pr: noisilyGetInput("pr", legacyPrefix), + branch: noisilyGetInput("branch", legacyPrefix), + revision: noisilyGetInput("revision", legacyPrefix) + }; } -var proxyHeaders = (object) => new Proxy( - object, - { - get: (target, prop) => getProperty(target, prop), - has: (target, prop) => getProperty(target, prop) !== void 0 +function noisilyGetInput(suffix, legacyPrefix) { + const preferredInput = getStringOrUndefined(`source-${suffix}`); + if (!legacyPrefix) { + return preferredInput; } -); + const legacyInput = getStringOrUndefined(`${legacyPrefix}-${suffix}`); + if (preferredInput && legacyInput) { + lib_core.warning( + `The supported option source-${suffix} and the legacy option ${legacyPrefix}-${suffix} are both set. Preferring source-${suffix}. Please stop setting ${legacyPrefix}-${suffix}.` + ); + return preferredInput; + } else if (legacyInput) { + lib_core.warning( + `The legacy option ${legacyPrefix}-${suffix} is set. Please migrate to source-${suffix}.` + ); + return legacyInput; + } else { + return preferredInput; + } +} -// src/util/isFormData.ts -var lib_isFormData = (value) => Boolean( - value && lib_isFunction(value.constructor) && value[Symbol.toStringTag] === "FormData" && lib_isFunction(value.append) && lib_isFunction(value.getAll) && lib_isFunction(value.entries) && lib_isFunction(value[Symbol.iterator]) -); +// src/index.ts -// src/util/escapeName.ts -var escapeName = (name) => String(name).replace(/\r/g, "%0D").replace(/\n/g, "%0A").replace(/"/g, "%22"); -// src/util/isFile.ts -var isFile = (value) => Boolean( - value && typeof value === "object" && lib_isFunction(value.constructor) && value[Symbol.toStringTag] === "File" && lib_isFunction(value.stream) && value.name != null -); -// src/FormDataEncoder.ts -var defaultOptions = { - enableAdditionalHeaders: false -}; -var readonlyProp = { writable: false, configurable: false }; -var _CRLF, _CRLF_BYTES, _CRLF_BYTES_LENGTH, _DASHES, _encoder, _footer, _form, _options, _getFieldHeader, getFieldHeader_fn, _getContentLength, getContentLength_fn; -var FormDataEncoder = class { - constructor(form, boundaryOrOptions, options) { - __privateAdd(this, _getFieldHeader); - /** - * Returns form-data content length - */ - __privateAdd(this, _getContentLength); - __privateAdd(this, _CRLF, "\r\n"); - __privateAdd(this, _CRLF_BYTES, void 0); - __privateAdd(this, _CRLF_BYTES_LENGTH, void 0); - __privateAdd(this, _DASHES, "-".repeat(2)); - /** - * TextEncoder instance - */ - __privateAdd(this, _encoder, new TextEncoder()); - /** - * Returns form-data footer bytes - */ - __privateAdd(this, _footer, void 0); - /** - * FormData instance - */ - __privateAdd(this, _form, void 0); - /** - * Instance options - */ - __privateAdd(this, _options, void 0); - if (!lib_isFormData(form)) { - throw new TypeError("Expected first argument to be a FormData instance."); - } - let boundary; - if (lib_isPlainObject(boundaryOrOptions)) { - options = boundaryOrOptions; + + + + + + + + + + +var EVENT_BACKTRACES = "backtrace"; +var EVENT_EXCEPTION = "exception"; +var EVENT_ARTIFACT_CACHE_HIT = "artifact_cache_hit"; +var EVENT_ARTIFACT_CACHE_MISS = "artifact_cache_miss"; +var EVENT_ARTIFACT_CACHE_PERSIST = "artifact_cache_persist"; +var EVENT_PREFLIGHT_REQUIRE_NIX_DENIED = "preflight-require-nix-denied"; +var FACT_ARTIFACT_FETCHED_FROM_CACHE = "artifact_fetched_from_cache"; +var FACT_ENDED_WITH_EXCEPTION = "ended_with_exception"; +var FACT_FINAL_EXCEPTION = "final_exception"; +var FACT_OS = "$os"; +var FACT_OS_VERSION = "$os_version"; +var FACT_SOURCE_URL = "source_url"; +var FACT_SOURCE_URL_ETAG = "source_url_etag"; +var FACT_NIX_LOCATION = "nix_location"; +var FACT_NIX_STORE_TRUST = "nix_store_trusted"; +var FACT_NIX_STORE_VERSION = "nix_store_version"; +var FACT_NIX_STORE_CHECK_METHOD = "nix_store_check_method"; +var FACT_NIX_STORE_CHECK_ERROR = "nix_store_check_error"; +var STATE_KEY_EXECUTION_PHASE = "detsys_action_execution_phase"; +var STATE_KEY_NIX_NOT_FOUND = "detsys_action_nix_not_found"; +var STATE_NOT_FOUND = "not-found"; +var STATE_KEY_CROSS_PHASE_ID = "detsys_cross_phase_id"; +var STATE_BACKTRACE_START_TIMESTAMP = "detsys_backtrace_start_timestamp"; +var DIAGNOSTIC_ENDPOINT_TIMEOUT_MS = 1e4; +var CHECK_IN_ENDPOINT_TIMEOUT_MS = 1e3; +var DetSysAction = class { + determineExecutionPhase() { + const currentPhase = lib_core.getState(STATE_KEY_EXECUTION_PHASE); + if (currentPhase === "") { + lib_core.saveState(STATE_KEY_EXECUTION_PHASE, "post"); + return "main"; } else { - boundary = boundaryOrOptions; + return "post"; } - if (!boundary) { - boundary = createBoundary(); + } + constructor(actionOptions) { + this.actionOptions = makeOptionsConfident(actionOptions); + this.idsHost = new IdsHost( + this.actionOptions.idsProjectName, + actionOptions.diagnosticsSuffix, + // Note: we don't use actionsCore.getInput('diagnostic-endpoint') on purpose: + // getInput silently converts absent data to an empty string. + process.env["INPUT_DIAGNOSTIC-ENDPOINT"] + ); + this.exceptionAttachments = /* @__PURE__ */ new Map(); + this.nixStoreTrust = "unknown"; + this.strictMode = getBool("_internal-strict-mode"); + if (getBoolOrUndefined( + "_internal-obliterate-actions-id-token-request-variables" + ) === true) { + process.env["ACTIONS_ID_TOKEN_REQUEST_URL"] = void 0; + process.env["ACTIONS_ID_TOKEN_REQUEST_TOKEN"] = void 0; } - if (typeof boundary !== "string") { - throw new TypeError("Expected boundary argument to be a string."); + this.features = {}; + this.featureEventMetadata = {}; + this.events = []; + this.getCrossPhaseId(); + this.collectBacktraceSetup(); + this.facts = { + $lib: "idslib", + $lib_version: version, + project: this.actionOptions.name, + ids_project: this.actionOptions.idsProjectName + }; + const params = [ + ["github_action_ref", "GITHUB_ACTION_REF"], + ["github_action_repository", "GITHUB_ACTION_REPOSITORY"], + ["github_event_name", "GITHUB_EVENT_NAME"], + ["$os", "RUNNER_OS"], + ["arch", "RUNNER_ARCH"] + ]; + for (const [target, env] of params) { + const value = process.env[env]; + if (value) { + this.facts[target] = value; + } } - if (options && !lib_isPlainObject(options)) { - throw new TypeError("Expected options argument to be an object."); + this.identity = identify(this.actionOptions.name); + this.archOs = getArchOs(); + this.nixSystem = getNixPlatform(this.archOs); + this.facts.arch_os = this.archOs; + this.facts.nix_system = this.nixSystem; + { + getDetails().then((details) => { + if (details.name !== "unknown") { + this.addFact(FACT_OS, details.name); + } + if (details.version !== "unknown") { + this.addFact(FACT_OS_VERSION, details.version); + } + }).catch((e) => { + lib_core.debug( + `Failure getting platform details: ${stringifyError2(e)}` + ); + }); } - __privateSet(this, _form, Array.from(form.entries())); - __privateSet(this, _options, { ...defaultOptions, ...options }); - __privateSet(this, _CRLF_BYTES, __privateGet(this, _encoder).encode(__privateGet(this, _CRLF))); - __privateSet(this, _CRLF_BYTES_LENGTH, __privateGet(this, _CRLF_BYTES).byteLength); - this.boundary = `form-data-boundary-${boundary}`; - this.contentType = `multipart/form-data; boundary=${this.boundary}`; - __privateSet(this, _footer, __privateGet(this, _encoder).encode( - `${__privateGet(this, _DASHES)}${this.boundary}${__privateGet(this, _DASHES)}${__privateGet(this, _CRLF).repeat(2)}` - )); - const headers = { - "Content-Type": this.contentType - }; - const contentLength = __privateMethod(this, _getContentLength, getContentLength_fn).call(this); - if (contentLength) { - this.contentLength = contentLength; - headers["Content-Length"] = contentLength; + this.executionPhase = this.determineExecutionPhase(); + this.facts.execution_phase = this.executionPhase; + if (this.actionOptions.fetchStyle === "gh-env-style") { + this.architectureFetchSuffix = this.archOs; + } else if (this.actionOptions.fetchStyle === "nix-style") { + this.architectureFetchSuffix = this.nixSystem; + } else if (this.actionOptions.fetchStyle === "universal") { + this.architectureFetchSuffix = "universal"; + } else { + throw new Error( + `fetchStyle ${this.actionOptions.fetchStyle} is not a valid style` + ); } - this.headers = proxyHeaders(Object.freeze(headers)); - Object.defineProperties(this, { - boundary: readonlyProp, - contentType: readonlyProp, - contentLength: readonlyProp, - headers: readonlyProp - }); + this.sourceParameters = constructSourceParameters( + this.actionOptions.legacySourcePrefix + ); + this.recordEvent(`begin_${this.executionPhase}`); } /** - * Creates an iterator allowing to go through form-data parts (with metadata). - * This method **will not** read the files and **will not** split values big into smaller chunks. - * - * Using this method, you can convert form-data content into Blob: - * - * @example - * - * ```ts - * import {Readable} from "stream" - * - * import {FormDataEncoder} from "form-data-encoder" - * - * import {FormData} from "formdata-polyfill/esm-min.js" - * import {fileFrom} from "fetch-blob/form.js" - * import {File} from "fetch-blob/file.js" - * import {Blob} from "fetch-blob" - * - * import fetch from "node-fetch" - * - * const form = new FormData() - * - * form.set("field", "Just a random string") - * form.set("file", new File(["Using files is class amazing"])) - * form.set("fileFromPath", await fileFrom("path/to/a/file.txt")) - * - * const encoder = new FormDataEncoder(form) - * - * const options = { - * method: "post", - * body: new Blob(encoder, {type: encoder.contentType}) - * } + * Attach a file to the diagnostics data in error conditions. * - * const response = await fetch("https://httpbin.org/post", options) + * The file at `location` doesn't need to exist when stapleFile is called. * - * console.log(await response.json()) - * ``` + * If the file doesn't exist or is unreadable when trying to staple the attachments, the JS error will be stored in a context value at `staple_failure_{name}`. + * If the file is readable, the file's contents will be stored in a context value at `staple_value_{name}`. */ - *values() { - for (const [name, raw] of __privateGet(this, _form)) { - const value = isFile(raw) ? raw : __privateGet(this, _encoder).encode( - normalizeValue(raw) - ); - yield __privateMethod(this, _getFieldHeader, getFieldHeader_fn).call(this, name, value); - yield value; - yield __privateGet(this, _CRLF_BYTES); - } - yield __privateGet(this, _footer); + stapleFile(name, location) { + this.exceptionAttachments.set(name, location); } /** - * Creates an async iterator allowing to perform the encoding by portions. - * This method reads through files and splits big values into smaller pieces (65536 bytes per each). - * - * @example - * - * ```ts - * import {Readable} from "stream" - * - * import {FormData, File, fileFromPath} from "formdata-node" - * import {FormDataEncoder} from "form-data-encoder" - * - * import fetch from "node-fetch" - * - * const form = new FormData() - * - * form.set("field", "Just a random string") - * form.set("file", new File(["Using files is class amazing"], "file.txt")) - * form.set("fileFromPath", await fileFromPath("path/to/a/file.txt")) - * - * const encoder = new FormDataEncoder(form) - * - * const options = { - * method: "post", - * headers: encoder.headers, - * body: Readable.from(encoder.encode()) // or Readable.from(encoder) - * } - * - * const response = await fetch("https://httpbin.org/post", options) - * - * console.log(await response.json()) - * ``` + * Execute the Action as defined. */ - async *encode() { - for (const part of this.values()) { - if (isFile(part)) { - yield* getStreamIterator(part.stream()); - } else { - yield* chunk(part); - } + execute() { + this.executeAsync().catch((error3) => { + console.log(error3); + process.exitCode = 1; + }); + } + getTemporaryName() { + const tmpDir = process.env["RUNNER_TEMP"] || (0,external_node_os_.tmpdir)(); + return external_node_path_namespaceObject.join(tmpDir, `${this.actionOptions.name}-${(0,external_node_crypto_namespaceObject.randomUUID)()}`); + } + addFact(key, value) { + this.facts[key] = value; + } + async getDiagnosticsUrl() { + return await this.idsHost.getDiagnosticsUrl(); + } + getUniqueId() { + return this.identity.run_differentiator || process.env.RUNNER_TRACKING_ID || (0,external_node_crypto_namespaceObject.randomUUID)(); + } + // This ID will be saved in the action's state, to be persisted across phase steps + getCrossPhaseId() { + let crossPhaseId = lib_core.getState(STATE_KEY_CROSS_PHASE_ID); + if (crossPhaseId === "") { + crossPhaseId = (0,external_node_crypto_namespaceObject.randomUUID)(); + lib_core.saveState(STATE_KEY_CROSS_PHASE_ID, crossPhaseId); } + return crossPhaseId; + } + getCorrelationHashes() { + return this.identity; + } + recordEvent(eventName, context = {}) { + const prefixedName = eventName === "$feature_flag_called" ? eventName : `${this.actionOptions.eventPrefix}${eventName}`; + this.events.push({ + event_name: prefixedName, + context, + correlation: this.identity, + facts: this.facts, + features: this.featureEventMetadata, + timestamp: /* @__PURE__ */ new Date(), + uuid: (0,external_node_crypto_namespaceObject.randomUUID)() + }); } /** - * Creates an iterator allowing to read through the encoder data using for...of loops + * Unpacks the closure returned by `fetchArtifact()`, imports the + * contents into the Nix store, and returns the path of the executable at + * `/nix/store/STORE_PATH/bin/${bin}`. */ - [Symbol.iterator]() { - return this.values(); + async unpackClosure(bin) { + const artifact = await this.fetchArtifact(); + const { stdout } = await (0,external_node_util_.promisify)(external_node_child_process_namespaceObject.exec)( + `cat "${artifact}" | xz -d | nix-store --import` + ); + const paths = stdout.split(external_node_os_.EOL); + const lastPath = paths.at(-2); + return `${lastPath}/bin/${bin}`; } /** - * Creates an **async** iterator allowing to read through the encoder data using for-await...of loops + * Fetches the executable at the URL determined by the `source-*` inputs and + * other facts, `chmod`s it, and returns the path to the executable on disk. */ - [Symbol.asyncIterator]() { - return this.encode(); + async fetchExecutable() { + const binaryPath = await this.fetchArtifact(); + await (0,promises_namespaceObject.chmod)(binaryPath, promises_namespaceObject.constants.S_IXUSR | promises_namespaceObject.constants.S_IXGRP); + return binaryPath; } -}; -_CRLF = new WeakMap(); -_CRLF_BYTES = new WeakMap(); -_CRLF_BYTES_LENGTH = new WeakMap(); -_DASHES = new WeakMap(); -_encoder = new WeakMap(); -_footer = new WeakMap(); -_form = new WeakMap(); -_options = new WeakMap(); -_getFieldHeader = new WeakSet(); -getFieldHeader_fn = function(name, value) { - let header = ""; - header += `${__privateGet(this, _DASHES)}${this.boundary}${__privateGet(this, _CRLF)}`; - header += `Content-Disposition: form-data; name="${escapeName(name)}"`; - if (isFile(value)) { - header += `; filename="${escapeName(value.name)}"${__privateGet(this, _CRLF)}`; - header += `Content-Type: ${value.type || "application/octet-stream"}`; + get isMain() { + return this.executionPhase === "main"; } - if (__privateGet(this, _options).enableAdditionalHeaders === true) { - const size = isFile(value) ? value.size : value.byteLength; - if (size != null && !isNaN(size)) { - header += `${__privateGet(this, _CRLF)}Content-Length: ${size}`; + get isPost() { + return this.executionPhase === "post"; + } + async executeAsync() { + try { + await this.checkIn(); + process.env.DETSYS_CORRELATION = JSON.stringify( + this.getCorrelationHashes() + ); + if (!await this.preflightRequireNix()) { + this.recordEvent(EVENT_PREFLIGHT_REQUIRE_NIX_DENIED); + return; + } else { + await this.preflightNixStoreInfo(); + this.addFact(FACT_NIX_STORE_TRUST, this.nixStoreTrust); + } + if (this.isMain) { + await this.main(); + } else if (this.isPost) { + await this.post(); + } + this.addFact(FACT_ENDED_WITH_EXCEPTION, false); + } catch (e) { + this.addFact(FACT_ENDED_WITH_EXCEPTION, true); + const reportable = stringifyError2(e); + this.addFact(FACT_FINAL_EXCEPTION, reportable); + if (this.isPost) { + lib_core.warning(reportable); + } else { + lib_core.setFailed(reportable); + } + const doGzip = (0,external_node_util_.promisify)(external_node_zlib_.gzip); + const exceptionContext = /* @__PURE__ */ new Map(); + for (const [attachmentLabel, filePath] of this.exceptionAttachments) { + try { + const logText = (0,external_node_fs_namespaceObject.readFileSync)(filePath); + const buf = await doGzip(logText); + exceptionContext.set( + `staple_value_${attachmentLabel}`, + buf.toString("base64") + ); + } catch (innerError) { + exceptionContext.set( + `staple_failure_${attachmentLabel}`, + stringifyError2(innerError) + ); + } + } + this.recordEvent(EVENT_EXCEPTION, Object.fromEntries(exceptionContext)); + } finally { + if (this.isPost) { + await this.collectBacktraces(); + } + await this.complete(); } } - return __privateGet(this, _encoder).encode(`${header}${__privateGet(this, _CRLF).repeat(2)}`); -}; -_getContentLength = new WeakSet(); -getContentLength_fn = function() { - let length = 0; - for (const [name, raw] of __privateGet(this, _form)) { - const value = isFile(raw) ? raw : __privateGet(this, _encoder).encode( - normalizeValue(raw) + async getClient() { + return await this.idsHost.getGot( + (incitingError, prevUrl, nextUrl) => { + this.recordPlausibleTimeout(incitingError); + this.recordEvent("ids-failover", { + previousUrl: prevUrl.toString(), + nextUrl: nextUrl.toString() + }); + } ); - const size = isFile(value) ? value.size : value.byteLength; - if (size == null || isNaN(size)) { - return void 0; - } - length += __privateMethod(this, _getFieldHeader, getFieldHeader_fn).call(this, name, value).byteLength; - length += size; - length += __privateGet(this, _CRLF_BYTES_LENGTH); } - return String(length + __privateGet(this, _footer).byteLength); -}; - - -;// CONCATENATED MODULE: ./node_modules/.pnpm/got@14.4.2/node_modules/got/dist/source/core/utils/is-form-data.js - -function is_form_data_isFormData(body) { - return distribution.nodeStream(body) && distribution["function"](body.getBoundary); -} - -;// CONCATENATED MODULE: ./node_modules/.pnpm/got@14.4.2/node_modules/got/dist/source/core/utils/get-body-size.js - - - - -async function getBodySize(body, headers) { - if (headers && 'content-length' in headers) { - return Number(headers['content-length']); - } - if (!body) { - return 0; + async checkIn() { + const checkin = await this.requestCheckIn(); + if (checkin === void 0) { + return; } - if (distribution.string(body)) { - return external_node_buffer_namespaceObject.Buffer.byteLength(body); + this.features = checkin.options; + for (const [key, feature] of Object.entries(this.features)) { + this.featureEventMetadata[key] = feature.variant; } - if (distribution.buffer(body)) { - return body.length; + const impactSymbol = /* @__PURE__ */ new Map([ + ["none", "\u26AA"], + ["maintenance", "\u{1F6E0}\uFE0F"], + ["minor", "\u{1F7E1}"], + ["major", "\u{1F7E0}"], + ["critical", "\u{1F534}"] + ]); + const defaultImpactSymbol = "\u{1F535}"; + if (checkin.status !== null) { + const summaries = []; + for (const incident of checkin.status.incidents) { + summaries.push( + `${impactSymbol.get(incident.impact) || defaultImpactSymbol} ${incident.status.replace("_", " ")}: ${incident.name} (${incident.shortlink})` + ); + } + for (const maintenance of checkin.status.scheduled_maintenances) { + summaries.push( + `${impactSymbol.get(maintenance.impact) || defaultImpactSymbol} ${maintenance.status.replace("_", " ")}: ${maintenance.name} (${maintenance.shortlink})` + ); + } + if (summaries.length > 0) { + lib_core.info( + // Bright red, Bold, Underline + `${"\x1B[0;31m"}${"\x1B[1m"}${"\x1B[4m"}${checkin.status.page.name} Status` + ); + for (const notice of summaries) { + lib_core.info(notice); + } + lib_core.info(`See: ${checkin.status.page.url}`); + lib_core.info(``); + } } - if (is_form_data_isFormData(body)) { - return (0,external_node_util_.promisify)(body.getLength.bind(body))(); + } + getFeature(name) { + if (!this.features.hasOwnProperty(name)) { + return void 0; } - return undefined; -} - -;// CONCATENATED MODULE: ./node_modules/.pnpm/got@14.4.2/node_modules/got/dist/source/core/utils/proxy-events.js -function proxyEvents(from, to, events) { - const eventFunctions = {}; - for (const event of events) { - const eventFunction = (...arguments_) => { - to.emit(event, ...arguments_); - }; - eventFunctions[event] = eventFunction; - from.on(event, eventFunction); + const result = this.features[name]; + if (result === void 0) { + return void 0; } - return () => { - for (const [event, eventFunction] of Object.entries(eventFunctions)) { - from.off(event, eventFunction); - } - }; -} - -;// CONCATENATED MODULE: external "node:net" -const external_node_net_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:net"); -;// CONCATENATED MODULE: ./node_modules/.pnpm/got@14.4.2/node_modules/got/dist/source/core/utils/unhandle.js -// When attaching listeners, it's very easy to forget about them. -// Especially if you do error handling and set timeouts. -// So instead of checking if it's proper to throw an error on every timeout ever, -// use this simple tool which will remove all listeners you have attached. -function unhandle() { - const handlers = []; - return { - once(origin, event, function_) { - origin.once(event, function_); - handlers.push({ origin, event, fn: function_ }); - }, - unhandleAll() { - for (const handler of handlers) { - const { origin, event, fn } = handler; - origin.removeListener(event, fn); - } - handlers.length = 0; - }, - }; -} - -;// CONCATENATED MODULE: ./node_modules/.pnpm/got@14.4.2/node_modules/got/dist/source/core/timed-out.js - - -const reentry = Symbol('reentry'); -const timed_out_noop = () => { }; -class timed_out_TimeoutError extends Error { - event; - code; - constructor(threshold, event) { - super(`Timeout awaiting '${event}' for ${threshold}ms`); - this.event = event; - this.name = 'TimeoutError'; - this.code = 'ETIMEDOUT'; + this.recordEvent("$feature_flag_called", { + $feature_flag: name, + $feature_flag_response: result.variant + }); + return result; + } + /** + * Check in to install.determinate.systems, to accomplish three things: + * + * 1. Preflight the server selected from IdsHost, to increase the chances of success. + * 2. Fetch any incidents and maintenance events to let users know in case things are weird. + * 3. Get feature flag data so we can gently roll out new features. + */ + async requestCheckIn() { + for (let attemptsRemaining = 5; attemptsRemaining > 0; attemptsRemaining--) { + const checkInUrl = await this.getCheckInUrl(); + if (checkInUrl === void 0) { + return void 0; + } + try { + lib_core.debug(`Preflighting via ${checkInUrl}`); + checkInUrl.searchParams.set("ci", "github"); + checkInUrl.searchParams.set( + "correlation", + JSON.stringify(this.identity) + ); + return (await this.getClient()).get(checkInUrl, { + timeout: { + request: CHECK_IN_ENDPOINT_TIMEOUT_MS + } + }).json(); + } catch (e) { + this.recordPlausibleTimeout(e); + lib_core.debug(`Error checking in: ${stringifyError2(e)}`); + this.idsHost.markCurrentHostBroken(); + } } -} -function timedOut(request, delays, options) { - if (reentry in request) { - return timed_out_noop; + return void 0; + } + recordPlausibleTimeout(e) { + if (e instanceof TimeoutError && "timings" in e && "request" in e) { + const reportContext = { + url: e.request.requestUrl?.toString(), + retry_count: e.request.retryCount + }; + for (const [key, value] of Object.entries(e.timings.phases)) { + if (Number.isFinite(value)) { + reportContext[`timing_phase_${key}`] = value; + } + } + this.recordEvent("timeout", reportContext); } - request[reentry] = true; - const cancelers = []; - const { once, unhandleAll } = unhandle(); - const addTimeout = (delay, callback, event) => { - const timeout = setTimeout(callback, delay, delay, event); - timeout.unref?.(); - const cancel = () => { - clearTimeout(timeout); - }; - cancelers.push(cancel); - return cancel; - }; - const { host, hostname } = options; - const timeoutHandler = (delay, event) => { - request.destroy(new timed_out_TimeoutError(delay, event)); - }; - const cancelTimeouts = () => { - for (const cancel of cancelers) { - cancel(); + } + /** + * Fetch an artifact, such as a tarball, from the location determined by the + * `source-*` inputs. If `source-binary` is specified, this will return a path + * to a binary on disk; otherwise, the artifact will be downloaded from the + * URL determined by the other `source-*` inputs (`source-url`, `source-pr`, + * etc.). + */ + async fetchArtifact() { + const sourceBinary = getStringOrNull("source-binary"); + if (sourceBinary !== null && sourceBinary !== "") { + lib_core.debug(`Using the provided source binary at ${sourceBinary}`); + return sourceBinary; + } + lib_core.startGroup( + `Downloading ${this.actionOptions.name} for ${this.architectureFetchSuffix}` + ); + try { + lib_core.info(`Fetching from ${await this.getSourceUrl()}`); + const correlatedUrl = await this.getSourceUrl(); + correlatedUrl.searchParams.set("ci", "github"); + correlatedUrl.searchParams.set( + "correlation", + JSON.stringify(this.identity) + ); + const versionCheckup = await (await this.getClient()).head(correlatedUrl); + if (versionCheckup.headers.etag) { + const v = versionCheckup.headers.etag; + this.addFact(FACT_SOURCE_URL_ETAG, v); + lib_core.debug( + `Checking the tool cache for ${await this.getSourceUrl()} at ${v}` + ); + const cached = await this.getCachedVersion(v); + if (cached) { + this.facts[FACT_ARTIFACT_FETCHED_FROM_CACHE] = true; + lib_core.debug(`Tool cache hit.`); + return cached; } - unhandleAll(); - }; - request.once('error', error => { - cancelTimeouts(); - // Save original behavior - /* istanbul ignore next */ - if (request.listenerCount('error') === 0) { - throw error; + } + this.facts[FACT_ARTIFACT_FETCHED_FROM_CACHE] = false; + lib_core.debug( + `No match from the cache, re-fetching from the redirect: ${versionCheckup.url}` + ); + const destFile = this.getTemporaryName(); + const fetchStream = await this.downloadFile( + new URL(versionCheckup.url), + destFile + ); + if (fetchStream.response?.headers.etag) { + const v = fetchStream.response.headers.etag; + try { + await this.saveCachedVersion(v, destFile); + } catch (e) { + lib_core.debug(`Error caching the artifact: ${stringifyError2(e)}`); } - }); - if (delays.request !== undefined) { - const cancelTimeout = addTimeout(delays.request, timeoutHandler, 'request'); - once(request, 'response', (response) => { - once(response, 'end', cancelTimeout); - }); + } + return destFile; + } catch (e) { + this.recordPlausibleTimeout(e); + throw e; + } finally { + lib_core.endGroup(); } - if (delays.socket !== undefined) { - const { socket } = delays; - const socketTimeoutHandler = () => { - timeoutHandler(socket, 'socket'); - }; - request.setTimeout(socket, socketTimeoutHandler); - // `request.setTimeout(0)` causes a memory leak. - // We can just remove the listener and forget about the timer - it's unreffed. - // See https://github.com/sindresorhus/got/issues/690 - cancelers.push(() => { - request.removeListener('timeout', socketTimeoutHandler); - }); + } + /** + * A helper function for failing on error only if strict mode is enabled. + * This is intended only for CI environments testing Actions themselves. + */ + failOnError(msg) { + if (this.strictMode) { + lib_core.setFailed(`strict mode failure: ${msg}`); } - const hasLookup = delays.lookup !== undefined; - const hasConnect = delays.connect !== undefined; - const hasSecureConnect = delays.secureConnect !== undefined; - const hasSend = delays.send !== undefined; - if (hasLookup || hasConnect || hasSecureConnect || hasSend) { - once(request, 'socket', (socket) => { - const { socketPath } = request; - /* istanbul ignore next: hard to test */ - if (socket.connecting) { - const hasPath = Boolean(socketPath ?? external_node_net_namespaceObject.isIP(hostname ?? host ?? '') !== 0); - if (hasLookup && !hasPath && socket.address().address === undefined) { - const cancelTimeout = addTimeout(delays.lookup, timeoutHandler, 'lookup'); - once(socket, 'lookup', cancelTimeout); - } - if (hasConnect) { - const timeConnect = () => addTimeout(delays.connect, timeoutHandler, 'connect'); - if (hasPath) { - once(socket, 'connect', timeConnect()); - } - else { - once(socket, 'lookup', (error) => { - if (error === null) { - once(socket, 'connect', timeConnect()); - } - }); - } - } - if (hasSecureConnect && options.protocol === 'https:') { - once(socket, 'connect', () => { - const cancelTimeout = addTimeout(delays.secureConnect, timeoutHandler, 'secureConnect'); - once(socket, 'secureConnect', cancelTimeout); - }); - } - } - if (hasSend) { - const timeRequest = () => addTimeout(delays.send, timeoutHandler, 'send'); - /* istanbul ignore next: hard to test */ - if (socket.connecting) { - once(socket, 'connect', () => { - once(request, 'upload-complete', timeRequest()); - }); - } - else { - once(request, 'upload-complete', timeRequest()); - } - } + } + async downloadFile(url, destination) { + const client = await this.getClient(); + return new Promise((resolve, reject) => { + let writeStream; + let failed = false; + const retry = (stream) => { + if (writeStream) { + writeStream.destroy(); + } + writeStream = (0,external_node_fs_namespaceObject.createWriteStream)(destination, { + encoding: "binary", + mode: 493 }); - } - if (delays.response !== undefined) { - once(request, 'upload-complete', () => { - const cancelTimeout = addTimeout(delays.response, timeoutHandler, 'response'); - once(request, 'response', cancelTimeout); + writeStream.once("error", (error3) => { + failed = true; + reject(error3); }); - } - if (delays.read !== undefined) { - once(request, 'response', (response) => { - const cancelTimeout = addTimeout(delays.read, timeoutHandler, 'read'); - once(response, 'end', cancelTimeout); + writeStream.on("finish", () => { + if (!failed) { + resolve(stream); + } + }); + stream.once("retry", (_count, _error, createRetryStream) => { + retry(createRetryStream()); }); + stream.pipe(writeStream); + }; + retry(client.stream(url)); + }); + } + async complete() { + this.recordEvent(`complete_${this.executionPhase}`); + await this.submitEvents(); + } + async getCheckInUrl() { + const checkInUrl = await this.idsHost.getDynamicRootUrl(); + if (checkInUrl === void 0) { + return void 0; } - return cancelTimeouts; -} - -;// CONCATENATED MODULE: ./node_modules/.pnpm/got@14.4.2/node_modules/got/dist/source/core/utils/url-to-options.js - -function urlToOptions(url) { - // Cast to URL - url = url; - const options = { - protocol: url.protocol, - hostname: distribution.string(url.hostname) && url.hostname.startsWith('[') ? url.hostname.slice(1, -1) : url.hostname, - host: url.host, - hash: url.hash, - search: url.search, - pathname: url.pathname, - href: url.href, - path: `${url.pathname || ''}${url.search || ''}`, - }; - if (distribution.string(url.port) && url.port.length > 0) { - options.port = Number(url.port); + checkInUrl.pathname += "check-in"; + return checkInUrl; + } + async getSourceUrl() { + const p = this.sourceParameters; + if (p.url) { + this.addFact(FACT_SOURCE_URL, p.url); + return new URL(p.url); } - if (url.username || url.password) { - options.auth = `${url.username || ''}:${url.password || ''}`; + const fetchUrl = await this.idsHost.getRootUrl(); + fetchUrl.pathname += this.actionOptions.idsProjectName; + if (p.tag) { + fetchUrl.pathname += `/tag/${p.tag}`; + } else if (p.pr) { + fetchUrl.pathname += `/pr/${p.pr}`; + } else if (p.branch) { + fetchUrl.pathname += `/branch/${p.branch}`; + } else if (p.revision) { + fetchUrl.pathname += `/rev/${p.revision}`; + } else { + fetchUrl.pathname += `/stable`; } - return options; -} - -;// CONCATENATED MODULE: ./node_modules/.pnpm/got@14.4.2/node_modules/got/dist/source/core/utils/weakable-map.js -class WeakableMap { - weakMap; - map; - constructor() { - this.weakMap = new WeakMap(); - this.map = new Map(); + fetchUrl.pathname += `/${this.architectureFetchSuffix}`; + this.addFact(FACT_SOURCE_URL, fetchUrl.toString()); + return fetchUrl; + } + cacheKey(version2) { + const cleanedVersion = version2.replace(/[^a-zA-Z0-9-+.]/g, ""); + return `determinatesystem-${this.actionOptions.name}-${this.architectureFetchSuffix}-${cleanedVersion}`; + } + async getCachedVersion(version2) { + const startCwd = process.cwd(); + try { + const tempDir = this.getTemporaryName(); + await (0,promises_namespaceObject.mkdir)(tempDir); + process.chdir(tempDir); + process.env.GITHUB_WORKSPACE_BACKUP = process.env.GITHUB_WORKSPACE; + delete process.env.GITHUB_WORKSPACE; + if (await cache.restoreCache( + [this.actionOptions.name], + this.cacheKey(version2), + [], + void 0, + true + )) { + this.recordEvent(EVENT_ARTIFACT_CACHE_HIT); + return `${tempDir}/${this.actionOptions.name}`; + } + this.recordEvent(EVENT_ARTIFACT_CACHE_MISS); + return void 0; + } finally { + process.env.GITHUB_WORKSPACE = process.env.GITHUB_WORKSPACE_BACKUP; + delete process.env.GITHUB_WORKSPACE_BACKUP; + process.chdir(startCwd); } - set(key, value) { - if (typeof key === 'object') { - this.weakMap.set(key, value); - } - else { - this.map.set(key, value); - } + } + async saveCachedVersion(version2, toolPath) { + const startCwd = process.cwd(); + try { + const tempDir = this.getTemporaryName(); + await (0,promises_namespaceObject.mkdir)(tempDir); + process.chdir(tempDir); + await (0,promises_namespaceObject.copyFile)(toolPath, `${tempDir}/${this.actionOptions.name}`); + process.env.GITHUB_WORKSPACE_BACKUP = process.env.GITHUB_WORKSPACE; + delete process.env.GITHUB_WORKSPACE; + await cache.saveCache( + [this.actionOptions.name], + this.cacheKey(version2), + void 0, + true + ); + this.recordEvent(EVENT_ARTIFACT_CACHE_PERSIST); + } finally { + process.env.GITHUB_WORKSPACE = process.env.GITHUB_WORKSPACE_BACKUP; + delete process.env.GITHUB_WORKSPACE_BACKUP; + process.chdir(startCwd); } - get(key) { - if (typeof key === 'object') { - return this.weakMap.get(key); - } - return this.map.get(key); + } + collectBacktraceSetup() { + if (process.env.DETSYS_BACKTRACE_COLLECTOR === "") { + lib_core.exportVariable( + "DETSYS_BACKTRACE_COLLECTOR", + this.getCrossPhaseId() + ); + lib_core.saveState(STATE_BACKTRACE_START_TIMESTAMP, Date.now()); } - has(key) { - if (typeof key === 'object') { - return this.weakMap.has(key); - } - return this.map.has(key); + } + async collectBacktraces() { + try { + if (process.env.DETSYS_BACKTRACE_COLLECTOR !== this.getCrossPhaseId()) { + return; + } + const backtraces = await collectBacktraces( + this.actionOptions.binaryNamePrefixes, + parseInt(lib_core.getState(STATE_BACKTRACE_START_TIMESTAMP)) + ); + lib_core.debug(`Backtraces identified: ${backtraces.size}`); + if (backtraces.size > 0) { + this.recordEvent(EVENT_BACKTRACES, Object.fromEntries(backtraces)); + } + } catch (innerError) { + lib_core.debug( + `Error collecting backtraces: ${stringifyError2(innerError)}` + ); } -} - -;// CONCATENATED MODULE: ./node_modules/.pnpm/got@14.4.2/node_modules/got/dist/source/core/calculate-retry-delay.js -const calculateRetryDelay = ({ attemptCount, retryOptions, error, retryAfter, computedValue, }) => { - if (error.name === 'RetryError') { - return 1; + } + async preflightRequireNix() { + let nixLocation; + const pathParts = (process.env["PATH"] || "").split(":"); + for (const location of pathParts) { + const candidateNix = external_node_path_namespaceObject.join(location, "nix"); + try { + await promises_namespaceObject.access(candidateNix, promises_namespaceObject.constants.X_OK); + lib_core.debug(`Found Nix at ${candidateNix}`); + nixLocation = candidateNix; + break; + } catch { + lib_core.debug(`Nix not at ${candidateNix}`); + } } - if (attemptCount > retryOptions.limit) { - return 0; + this.addFact(FACT_NIX_LOCATION, nixLocation || ""); + if (this.actionOptions.requireNix === "ignore") { + return true; } - const hasMethod = retryOptions.methods.includes(error.options.method); - const hasErrorCode = retryOptions.errorCodes.includes(error.code); - const hasStatusCode = error.response && retryOptions.statusCodes.includes(error.response.statusCode); - if (!hasMethod || (!hasErrorCode && !hasStatusCode)) { - return 0; + const currentNotFoundState = lib_core.getState(STATE_KEY_NIX_NOT_FOUND); + if (currentNotFoundState === STATE_NOT_FOUND) { + return false; } - if (error.response) { - if (retryAfter) { - // In this case `computedValue` is `options.request.timeout` - if (retryAfter > computedValue) { - return 0; - } - return retryAfter; - } - if (error.response.statusCode === 413) { - return 0; - } + if (nixLocation !== void 0) { + return true; } - const noise = Math.random() * retryOptions.noise; - return Math.min(((2 ** (attemptCount - 1)) * 1000), retryOptions.backoffLimit) + noise; -}; -/* harmony default export */ const calculate_retry_delay = (calculateRetryDelay); - -;// CONCATENATED MODULE: external "node:tls" -const external_node_tls_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:tls"); -// EXTERNAL MODULE: external "node:https" -var external_node_https_ = __nccwpck_require__(2286); -;// CONCATENATED MODULE: external "node:dns" -const external_node_dns_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:dns"); -;// CONCATENATED MODULE: ./node_modules/.pnpm/cacheable-lookup@7.0.0/node_modules/cacheable-lookup/source/index.js - - - - -const {Resolver: AsyncResolver} = external_node_dns_namespaceObject.promises; - -const kCacheableLookupCreateConnection = Symbol('cacheableLookupCreateConnection'); -const kCacheableLookupInstance = Symbol('cacheableLookupInstance'); -const kExpires = Symbol('expires'); - -const supportsALL = typeof external_node_dns_namespaceObject.ALL === 'number'; - -const verifyAgent = agent => { - if (!(agent && typeof agent.createConnection === 'function')) { - throw new Error('Expected an Agent instance as the first argument'); - } -}; - -const map4to6 = entries => { - for (const entry of entries) { - if (entry.family === 6) { - continue; - } - - entry.address = `::ffff:${entry.address}`; - entry.family = 6; - } -}; - -const getIfaceInfo = () => { - let has4 = false; - let has6 = false; - - for (const device of Object.values(external_node_os_.networkInterfaces())) { - for (const iface of device) { - if (iface.internal) { - continue; - } - - if (iface.family === 'IPv6') { - has6 = true; - } else { - has4 = true; - } - - if (has4 && has6) { - return {has4, has6}; - } - } - } - - return {has4, has6}; -}; - -const source_isIterable = map => { - return Symbol.iterator in map; -}; - -const ignoreNoResultErrors = dnsPromise => { - return dnsPromise.catch(error => { - if ( - error.code === 'ENODATA' || - error.code === 'ENOTFOUND' || - error.code === 'ENOENT' // Windows: name exists, but not this record type - ) { - return []; - } - - throw error; - }); + lib_core.saveState(STATE_KEY_NIX_NOT_FOUND, STATE_NOT_FOUND); + switch (this.actionOptions.requireNix) { + case "fail": + lib_core.setFailed( + [ + "This action can only be used when Nix is installed.", + "Add `- uses: DeterminateSystems/nix-installer-action@main` earlier in your workflow." + ].join(" ") + ); + break; + case "warn": + lib_core.warning( + [ + "This action is in no-op mode because Nix is not installed.", + "Add `- uses: DeterminateSystems/nix-installer-action@main` earlier in your workflow." + ].join(" ") + ); + break; + } + return false; + } + async preflightNixStoreInfo() { + let output = ""; + const options = {}; + options.silent = true; + options.listeners = { + stdout: (data) => { + output += data.toString(); + } + }; + try { + output = ""; + await exec.exec("nix", ["store", "info", "--json"], options); + this.addFact(FACT_NIX_STORE_CHECK_METHOD, "info"); + } catch { + try { + output = ""; + await exec.exec("nix", ["store", "ping", "--json"], options); + this.addFact(FACT_NIX_STORE_CHECK_METHOD, "ping"); + } catch { + this.addFact(FACT_NIX_STORE_CHECK_METHOD, "none"); + return; + } + } + try { + const parsed = JSON.parse(output); + if (parsed.trusted === 1) { + this.nixStoreTrust = "trusted"; + } else if (parsed.trusted === 0) { + this.nixStoreTrust = "untrusted"; + } else if (parsed.trusted !== void 0) { + this.addFact( + FACT_NIX_STORE_CHECK_ERROR, + `Mysterious trusted value: ${JSON.stringify(parsed.trusted)}` + ); + } + this.addFact(FACT_NIX_STORE_VERSION, JSON.stringify(parsed.version)); + } catch (e) { + this.addFact(FACT_NIX_STORE_CHECK_ERROR, stringifyError2(e)); + } + } + async submitEvents() { + const diagnosticsUrl = await this.idsHost.getDiagnosticsUrl(); + if (diagnosticsUrl === void 0) { + lib_core.debug( + "Diagnostics are disabled. Not sending the following events:" + ); + lib_core.debug(JSON.stringify(this.events, void 0, 2)); + return; + } + const batch = { + type: "eventlog", + sent_at: /* @__PURE__ */ new Date(), + events: this.events + }; + try { + await (await this.getClient()).post(diagnosticsUrl, { + json: batch, + timeout: { + request: DIAGNOSTIC_ENDPOINT_TIMEOUT_MS + } + }); + } catch (err) { + this.recordPlausibleTimeout(err); + lib_core.debug( + `Error submitting diagnostics event to ${diagnosticsUrl}: ${stringifyError2(err)}` + ); + } + this.events = []; + } }; +function stringifyError2(error3) { + return error3 instanceof Error || typeof error3 == "string" ? error3.toString() : JSON.stringify(error3); +} +function makeOptionsConfident(actionOptions) { + const idsProjectName = actionOptions.idsProjectName ?? actionOptions.name; + const finalOpts = { + name: actionOptions.name, + idsProjectName, + eventPrefix: actionOptions.eventPrefix || "action:", + fetchStyle: actionOptions.fetchStyle, + legacySourcePrefix: actionOptions.legacySourcePrefix, + requireNix: actionOptions.requireNix, + binaryNamePrefixes: actionOptions.binaryNamePrefixes ?? [ + "nix", + "determinate-nixd", + actionOptions.name + ] + }; + lib_core.debug("idslib options:"); + lib_core.debug(JSON.stringify(finalOpts, void 0, 2)); + return finalOpts; +} -const ttl = {ttl: true}; -const source_all = {all: true}; -const all4 = {all: true, family: 4}; -const all6 = {all: true, family: 6}; - -class CacheableLookup { - constructor({ - cache = new Map(), - maxTtl = Infinity, - fallbackDuration = 3600, - errorTtl = 0.15, - resolver = new AsyncResolver(), - lookup = external_node_dns_namespaceObject.lookup - } = {}) { - this.maxTtl = maxTtl; - this.errorTtl = errorTtl; - - this._cache = cache; - this._resolver = resolver; - this._dnsLookup = lookup && (0,external_node_util_.promisify)(lookup); - this.stats = { - cache: 0, - query: 0 - }; - - if (this._resolver instanceof AsyncResolver) { - this._resolve4 = this._resolver.resolve4.bind(this._resolver); - this._resolve6 = this._resolver.resolve6.bind(this._resolver); - } else { - this._resolve4 = (0,external_node_util_.promisify)(this._resolver.resolve4.bind(this._resolver)); - this._resolve6 = (0,external_node_util_.promisify)(this._resolver.resolve6.bind(this._resolver)); - } - - this._iface = getIfaceInfo(); - - this._pending = {}; - this._nextRemovalTime = false; - this._hostnamesToFallback = new Set(); - - this.fallbackDuration = fallbackDuration; - - if (fallbackDuration > 0) { - const interval = setInterval(() => { - this._hostnamesToFallback.clear(); - }, fallbackDuration * 1000); - - /* istanbul ignore next: There is no `interval.unref()` when running inside an Electron renderer */ - if (interval.unref) { - interval.unref(); - } - - this._fallbackInterval = interval; - } - - this.lookup = this.lookup.bind(this); - this.lookupAsync = this.lookupAsync.bind(this); - } - - set servers(servers) { - this.clear(); - - this._resolver.setServers(servers); - } - - get servers() { - return this._resolver.getServers(); - } - - lookup(hostname, options, callback) { - if (typeof options === 'function') { - callback = options; - options = {}; - } else if (typeof options === 'number') { - options = { - family: options - }; - } - - if (!callback) { - throw new Error('Callback must be a function.'); - } - - // eslint-disable-next-line promise/prefer-await-to-then - this.lookupAsync(hostname, options).then(result => { - if (options.all) { - callback(null, result); - } else { - callback(null, result.address, result.family, result.expires, result.ttl, result.source); - } - }, callback); - } - - async lookupAsync(hostname, options = {}) { - if (typeof options === 'number') { - options = { - family: options - }; - } - - let cached = await this.query(hostname); - - if (options.family === 6) { - const filtered = cached.filter(entry => entry.family === 6); - - if (options.hints & external_node_dns_namespaceObject.V4MAPPED) { - if ((supportsALL && options.hints & external_node_dns_namespaceObject.ALL) || filtered.length === 0) { - map4to6(cached); - } else { - cached = filtered; - } - } else { - cached = filtered; - } - } else if (options.family === 4) { - cached = cached.filter(entry => entry.family === 4); - } - - if (options.hints & external_node_dns_namespaceObject.ADDRCONFIG) { - const {_iface} = this; - cached = cached.filter(entry => entry.family === 6 ? _iface.has6 : _iface.has4); - } - - if (cached.length === 0) { - const error = new Error(`cacheableLookup ENOTFOUND ${hostname}`); - error.code = 'ENOTFOUND'; - error.hostname = hostname; - - throw error; - } - - if (options.all) { - return cached; - } - - return cached[0]; - } - - async query(hostname) { - let source = 'cache'; - let cached = await this._cache.get(hostname); - - if (cached) { - this.stats.cache++; - } - - if (!cached) { - const pending = this._pending[hostname]; - if (pending) { - this.stats.cache++; - cached = await pending; - } else { - source = 'query'; - const newPromise = this.queryAndCache(hostname); - this._pending[hostname] = newPromise; - this.stats.query++; - try { - cached = await newPromise; - } finally { - delete this._pending[hostname]; - } - } - } - - cached = cached.map(entry => { - return {...entry, source}; - }); - - return cached; - } - - async _resolve(hostname) { - // ANY is unsafe as it doesn't trigger new queries in the underlying server. - const [A, AAAA] = await Promise.all([ - ignoreNoResultErrors(this._resolve4(hostname, ttl)), - ignoreNoResultErrors(this._resolve6(hostname, ttl)) - ]); - - let aTtl = 0; - let aaaaTtl = 0; - let cacheTtl = 0; - - const now = Date.now(); - - for (const entry of A) { - entry.family = 4; - entry.expires = now + (entry.ttl * 1000); - - aTtl = Math.max(aTtl, entry.ttl); - } - - for (const entry of AAAA) { - entry.family = 6; - entry.expires = now + (entry.ttl * 1000); - - aaaaTtl = Math.max(aaaaTtl, entry.ttl); - } - - if (A.length > 0) { - if (AAAA.length > 0) { - cacheTtl = Math.min(aTtl, aaaaTtl); - } else { - cacheTtl = aTtl; - } - } else { - cacheTtl = aaaaTtl; - } - - return { - entries: [ - ...A, - ...AAAA - ], - cacheTtl - }; - } - - async _lookup(hostname) { - try { - const [A, AAAA] = await Promise.all([ - // Passing {all: true} doesn't return all IPv4 and IPv6 entries. - // See https://github.com/szmarczak/cacheable-lookup/issues/42 - ignoreNoResultErrors(this._dnsLookup(hostname, all4)), - ignoreNoResultErrors(this._dnsLookup(hostname, all6)) - ]); - - return { - entries: [ - ...A, - ...AAAA - ], - cacheTtl: 0 - }; - } catch { - return { - entries: [], - cacheTtl: 0 - }; - } - } - - async _set(hostname, data, cacheTtl) { - if (this.maxTtl > 0 && cacheTtl > 0) { - cacheTtl = Math.min(cacheTtl, this.maxTtl) * 1000; - data[kExpires] = Date.now() + cacheTtl; - - try { - await this._cache.set(hostname, data, cacheTtl); - } catch (error) { - this.lookupAsync = async () => { - const cacheError = new Error('Cache Error. Please recreate the CacheableLookup instance.'); - cacheError.cause = error; - - throw cacheError; - }; - } - - if (source_isIterable(this._cache)) { - this._tick(cacheTtl); - } - } - } - - async queryAndCache(hostname) { - if (this._hostnamesToFallback.has(hostname)) { - return this._dnsLookup(hostname, source_all); - } - - let query = await this._resolve(hostname); - - if (query.entries.length === 0 && this._dnsLookup) { - query = await this._lookup(hostname); - - if (query.entries.length !== 0 && this.fallbackDuration > 0) { - // Use `dns.lookup(...)` for that particular hostname - this._hostnamesToFallback.add(hostname); - } - } - - const cacheTtl = query.entries.length === 0 ? this.errorTtl : query.cacheTtl; - await this._set(hostname, query.entries, cacheTtl); - - return query.entries; - } - - _tick(ms) { - const nextRemovalTime = this._nextRemovalTime; - - if (!nextRemovalTime || ms < nextRemovalTime) { - clearTimeout(this._removalTimeout); - - this._nextRemovalTime = ms; - - this._removalTimeout = setTimeout(() => { - this._nextRemovalTime = false; - - let nextExpiry = Infinity; - - const now = Date.now(); - - for (const [hostname, entries] of this._cache) { - const expires = entries[kExpires]; - - if (now >= expires) { - this._cache.delete(hostname); - } else if (expires < nextExpiry) { - nextExpiry = expires; - } - } - - if (nextExpiry !== Infinity) { - this._tick(nextExpiry - now); - } - }, ms); - - /* istanbul ignore next: There is no `timeout.unref()` when running inside an Electron renderer */ - if (this._removalTimeout.unref) { - this._removalTimeout.unref(); - } - } - } - - install(agent) { - verifyAgent(agent); - - if (kCacheableLookupCreateConnection in agent) { - throw new Error('CacheableLookup has been already installed'); - } - - agent[kCacheableLookupCreateConnection] = agent.createConnection; - agent[kCacheableLookupInstance] = this; - - agent.createConnection = (options, callback) => { - if (!('lookup' in options)) { - options.lookup = this.lookup; - } - - return agent[kCacheableLookupCreateConnection](options, callback); - }; - } - - uninstall(agent) { - verifyAgent(agent); - - if (agent[kCacheableLookupCreateConnection]) { - if (agent[kCacheableLookupInstance] !== this) { - throw new Error('The agent is not owned by this CacheableLookup instance'); - } - - agent.createConnection = agent[kCacheableLookupCreateConnection]; - - delete agent[kCacheableLookupCreateConnection]; - delete agent[kCacheableLookupInstance]; - } - } - - updateInterfaceInfo() { - const {_iface} = this; - - this._iface = getIfaceInfo(); - - if ((_iface.has4 && !this._iface.has4) || (_iface.has6 && !this._iface.has6)) { - this._cache.clear(); - } - } - - clear(hostname) { - if (hostname) { - this._cache.delete(hostname); - return; - } - - this._cache.clear(); - } +/*! + * linux-release-info + * Get Linux release info (distribution name, version, arch, release, etc.) + * from '/etc/os-release' or '/usr/lib/os-release' files and from native os + * module. On Windows and Darwin platforms it only returns common node os module + * info (platform, hostname, release, and arch) + * + * Licensed under MIT + * Copyright (c) 2018-2020 [Samuel Carreira] + */ +//# sourceMappingURL=index.js.map +;// CONCATENATED MODULE: ./node_modules/.pnpm/@sindresorhus+is@7.0.0/node_modules/@sindresorhus/is/distribution/index.js +const distribution_typedArrayTypeNames = [ + 'Int8Array', + 'Uint8Array', + 'Uint8ClampedArray', + 'Int16Array', + 'Uint16Array', + 'Int32Array', + 'Uint32Array', + 'Float32Array', + 'Float64Array', + 'BigInt64Array', + 'BigUint64Array', +]; +function distribution_isTypedArrayName(name) { + return distribution_typedArrayTypeNames.includes(name); +} +const distribution_objectTypeNames = [ + 'Function', + 'Generator', + 'AsyncGenerator', + 'GeneratorFunction', + 'AsyncGeneratorFunction', + 'AsyncFunction', + 'Observable', + 'Array', + 'Buffer', + 'Blob', + 'Object', + 'RegExp', + 'Date', + 'Error', + 'Map', + 'Set', + 'WeakMap', + 'WeakSet', + 'WeakRef', + 'ArrayBuffer', + 'SharedArrayBuffer', + 'DataView', + 'Promise', + 'URL', + 'FormData', + 'URLSearchParams', + 'HTMLElement', + 'NaN', + ...distribution_typedArrayTypeNames, +]; +function distribution_isObjectTypeName(name) { + return distribution_objectTypeNames.includes(name); +} +const distribution_primitiveTypeNames = [ + 'null', + 'undefined', + 'string', + 'number', + 'bigint', + 'boolean', + 'symbol', +]; +function distribution_isPrimitiveTypeName(name) { + return distribution_primitiveTypeNames.includes(name); } - -// EXTERNAL MODULE: ./node_modules/.pnpm/http2-wrapper@2.2.1/node_modules/http2-wrapper/source/index.js -var http2_wrapper_source = __nccwpck_require__(9695); -;// CONCATENATED MODULE: ./node_modules/.pnpm/got@14.4.2/node_modules/got/dist/source/core/parse-link-header.js -function parseLinkHeader(link) { - const parsed = []; - const items = link.split(','); - for (const item of items) { - // https://tools.ietf.org/html/rfc5988#section-5 - const [rawUriReference, ...rawLinkParameters] = item.split(';'); - const trimmedUriReference = rawUriReference.trim(); - // eslint-disable-next-line @typescript-eslint/prefer-string-starts-ends-with - if (trimmedUriReference[0] !== '<' || trimmedUriReference.at(-1) !== '>') { - throw new Error(`Invalid format of the Link header reference: ${trimmedUriReference}`); +const distribution_assertionTypeDescriptions = [ + 'positive number', + 'negative number', + 'Class', + 'string with a number', + 'null or undefined', + 'Iterable', + 'AsyncIterable', + 'native Promise', + 'EnumCase', + 'string with a URL', + 'truthy', + 'falsy', + 'primitive', + 'integer', + 'plain object', + 'TypedArray', + 'array-like', + 'tuple-like', + 'Node.js Stream', + 'infinite number', + 'empty array', + 'non-empty array', + 'empty string', + 'empty string or whitespace', + 'non-empty string', + 'non-empty string and not whitespace', + 'empty object', + 'non-empty object', + 'empty set', + 'non-empty set', + 'empty map', + 'non-empty map', + 'PropertyKey', + 'even integer', + 'odd integer', + 'T', + 'in range', + 'predicate returns truthy for any value', + 'predicate returns truthy for all values', + 'valid Date', + 'valid length', + 'whitespace string', + ...distribution_objectTypeNames, + ...distribution_primitiveTypeNames, +]; +const distribution_getObjectType = (value) => { + const objectTypeName = Object.prototype.toString.call(value).slice(8, -1); + if (/HTML\w+Element/.test(objectTypeName) && distribution_isHtmlElement(value)) { + return 'HTMLElement'; + } + if (distribution_isObjectTypeName(objectTypeName)) { + return objectTypeName; + } + return undefined; +}; +function distribution_detect(value) { + if (value === null) { + return 'null'; + } + switch (typeof value) { + case 'undefined': { + return 'undefined'; } - const reference = trimmedUriReference.slice(1, -1); - const parameters = {}; - if (rawLinkParameters.length === 0) { - throw new Error(`Unexpected end of Link header parameters: ${rawLinkParameters.join(';')}`); + case 'string': { + return 'string'; } - for (const rawParameter of rawLinkParameters) { - const trimmedRawParameter = rawParameter.trim(); - const center = trimmedRawParameter.indexOf('='); - if (center === -1) { - throw new Error(`Failed to parse Link header: ${link}`); - } - const name = trimmedRawParameter.slice(0, center).trim(); - const value = trimmedRawParameter.slice(center + 1).trim(); - parameters[name] = value; + case 'number': { + return Number.isNaN(value) ? 'NaN' : 'number'; } - parsed.push({ - reference, - parameters, - }); + case 'boolean': { + return 'boolean'; + } + case 'function': { + return 'Function'; + } + case 'bigint': { + return 'bigint'; + } + case 'symbol': { + return 'symbol'; + } + default: } - return parsed; + if (distribution_isObservable(value)) { + return 'Observable'; + } + if (distribution_isArray(value)) { + return 'Array'; + } + if (distribution_isBuffer(value)) { + return 'Buffer'; + } + const tagType = distribution_getObjectType(value); + if (tagType) { + return tagType; + } + if (value instanceof String || value instanceof Boolean || value instanceof Number) { + throw new TypeError('Please don\'t use object wrappers for primitive types'); + } + return 'Object'; } - -;// CONCATENATED MODULE: ./node_modules/.pnpm/got@14.4.2/node_modules/got/dist/source/core/options.js - - - -// DO NOT use destructuring for `https.request` and `http.request` as it's not compatible with `nock`. - - - - - - - - -const [major, minor] = external_node_process_.versions.node.split('.').map(Number); -function validateSearchParameters(searchParameters) { - // eslint-disable-next-line guard-for-in - for (const key in searchParameters) { - const value = searchParameters[key]; - assert.any([distribution.string, distribution.number, distribution.boolean, distribution["null"], distribution.undefined], value); +function distribution_hasPromiseApi(value) { + return distribution_isFunction(value?.then) && distribution_isFunction(value?.catch); +} +const distribution_is = Object.assign(distribution_detect, { + all: distribution_isAll, + any: distribution_isAny, + array: distribution_isArray, + arrayBuffer: distribution_isArrayBuffer, + arrayLike: distribution_isArrayLike, + asyncFunction: distribution_isAsyncFunction, + asyncGenerator: distribution_isAsyncGenerator, + asyncGeneratorFunction: distribution_isAsyncGeneratorFunction, + asyncIterable: distribution_isAsyncIterable, + bigint: distribution_isBigint, + bigInt64Array: distribution_isBigInt64Array, + bigUint64Array: distribution_isBigUint64Array, + blob: distribution_isBlob, + boolean: distribution_isBoolean, + boundFunction: distribution_isBoundFunction, + buffer: distribution_isBuffer, + class: distribution_isClass, + dataView: distribution_isDataView, + date: distribution_isDate, + detect: distribution_detect, + directInstanceOf: distribution_isDirectInstanceOf, + emptyArray: distribution_isEmptyArray, + emptyMap: distribution_isEmptyMap, + emptyObject: distribution_isEmptyObject, + emptySet: distribution_isEmptySet, + emptyString: distribution_isEmptyString, + emptyStringOrWhitespace: distribution_isEmptyStringOrWhitespace, + enumCase: distribution_isEnumCase, + error: distribution_isError, + evenInteger: distribution_isEvenInteger, + falsy: distribution_isFalsy, + float32Array: distribution_isFloat32Array, + float64Array: distribution_isFloat64Array, + formData: distribution_isFormData, + function: distribution_isFunction, + generator: distribution_isGenerator, + generatorFunction: distribution_isGeneratorFunction, + htmlElement: distribution_isHtmlElement, + infinite: distribution_isInfinite, + inRange: distribution_isInRange, + int16Array: distribution_isInt16Array, + int32Array: distribution_isInt32Array, + int8Array: distribution_isInt8Array, + integer: distribution_isInteger, + iterable: distribution_isIterable, + map: distribution_isMap, + nan: distribution_isNan, + nativePromise: distribution_isNativePromise, + negativeNumber: distribution_isNegativeNumber, + nodeStream: distribution_isNodeStream, + nonEmptyArray: distribution_isNonEmptyArray, + nonEmptyMap: distribution_isNonEmptyMap, + nonEmptyObject: distribution_isNonEmptyObject, + nonEmptySet: distribution_isNonEmptySet, + nonEmptyString: distribution_isNonEmptyString, + nonEmptyStringAndNotWhitespace: distribution_isNonEmptyStringAndNotWhitespace, + null: distribution_isNull, + nullOrUndefined: distribution_isNullOrUndefined, + number: distribution_isNumber, + numericString: distribution_isNumericString, + object: distribution_isObject, + observable: distribution_isObservable, + oddInteger: distribution_isOddInteger, + plainObject: distribution_isPlainObject, + positiveNumber: distribution_isPositiveNumber, + primitive: distribution_isPrimitive, + promise: distribution_isPromise, + propertyKey: distribution_isPropertyKey, + regExp: distribution_isRegExp, + safeInteger: distribution_isSafeInteger, + set: distribution_isSet, + sharedArrayBuffer: distribution_isSharedArrayBuffer, + string: distribution_isString, + symbol: distribution_isSymbol, + truthy: distribution_isTruthy, + tupleLike: distribution_isTupleLike, + typedArray: distribution_isTypedArray, + uint16Array: distribution_isUint16Array, + uint32Array: distribution_isUint32Array, + uint8Array: distribution_isUint8Array, + uint8ClampedArray: distribution_isUint8ClampedArray, + undefined: distribution_isUndefined, + urlInstance: distribution_isUrlInstance, + urlSearchParams: distribution_isUrlSearchParams, + urlString: distribution_isUrlString, + validDate: distribution_isValidDate, + validLength: distribution_isValidLength, + weakMap: distribution_isWeakMap, + weakRef: distribution_isWeakRef, + weakSet: distribution_isWeakSet, + whitespaceString: distribution_isWhitespaceString, +}); +function distribution_isAbsoluteModule2(remainder) { + return (value) => distribution_isInteger(value) && Math.abs(value % 2) === remainder; +} +function distribution_isAll(predicate, ...values) { + return distribution_predicateOnArray(Array.prototype.every, predicate, values); +} +function distribution_isAny(predicate, ...values) { + const predicates = distribution_isArray(predicate) ? predicate : [predicate]; + return predicates.some(singlePredicate => distribution_predicateOnArray(Array.prototype.some, singlePredicate, values)); +} +function distribution_isArray(value, assertion) { + if (!Array.isArray(value)) { + return false; + } + if (!distribution_isFunction(assertion)) { + return true; } + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument + return value.every(element => assertion(element)); } -const globalCache = new Map(); -let globalDnsCache; -const getGlobalDnsCache = () => { - if (globalDnsCache) { - return globalDnsCache; +function distribution_isArrayBuffer(value) { + return distribution_getObjectType(value) === 'ArrayBuffer'; +} +function distribution_isArrayLike(value) { + return !distribution_isNullOrUndefined(value) && !distribution_isFunction(value) && distribution_isValidLength(value.length); +} +function distribution_isAsyncFunction(value) { + return distribution_getObjectType(value) === 'AsyncFunction'; +} +function distribution_isAsyncGenerator(value) { + return distribution_isAsyncIterable(value) && distribution_isFunction(value.next) && distribution_isFunction(value.throw); +} +function distribution_isAsyncGeneratorFunction(value) { + return distribution_getObjectType(value) === 'AsyncGeneratorFunction'; +} +function distribution_isAsyncIterable(value) { + return distribution_isFunction(value?.[Symbol.asyncIterator]); +} +function distribution_isBigint(value) { + return typeof value === 'bigint'; +} +function distribution_isBigInt64Array(value) { + return distribution_getObjectType(value) === 'BigInt64Array'; +} +function distribution_isBigUint64Array(value) { + return distribution_getObjectType(value) === 'BigUint64Array'; +} +function distribution_isBlob(value) { + return distribution_getObjectType(value) === 'Blob'; +} +function distribution_isBoolean(value) { + return value === true || value === false; +} +// eslint-disable-next-line @typescript-eslint/ban-types +function distribution_isBoundFunction(value) { + return distribution_isFunction(value) && !Object.hasOwn(value, 'prototype'); +} +/** +Note: [Prefer using `Uint8Array` instead of `Buffer`.](https://sindresorhus.com/blog/goodbye-nodejs-buffer) +*/ +function distribution_isBuffer(value) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-call + return value?.constructor?.isBuffer?.(value) ?? false; +} +function distribution_isClass(value) { + return distribution_isFunction(value) && value.toString().startsWith('class '); +} +function distribution_isDataView(value) { + return distribution_getObjectType(value) === 'DataView'; +} +function distribution_isDate(value) { + return distribution_getObjectType(value) === 'Date'; +} +function distribution_isDirectInstanceOf(instance, class_) { + if (instance === undefined || instance === null) { + return false; } - globalDnsCache = new CacheableLookup(); - return globalDnsCache; -}; -const defaultInternals = { - request: undefined, - agent: { - http: undefined, - https: undefined, - http2: undefined, - }, - h2session: undefined, - decompress: true, - timeout: { - connect: undefined, - lookup: undefined, - read: undefined, - request: undefined, - response: undefined, - secureConnect: undefined, - send: undefined, - socket: undefined, - }, - prefixUrl: '', - body: undefined, - form: undefined, - json: undefined, - cookieJar: undefined, - ignoreInvalidCookies: false, - searchParams: undefined, - dnsLookup: undefined, - dnsCache: undefined, - context: {}, - hooks: { - init: [], - beforeRequest: [], - beforeError: [], - beforeRedirect: [], - beforeRetry: [], - afterResponse: [], - }, - followRedirect: true, - maxRedirects: 10, - cache: undefined, - throwHttpErrors: true, - username: '', - password: '', - http2: false, - allowGetBody: false, - headers: { - 'user-agent': 'got (https://github.com/sindresorhus/got)', - }, - methodRewriting: false, - dnsLookupIpVersion: undefined, - parseJson: JSON.parse, - stringifyJson: JSON.stringify, - retry: { - limit: 2, - methods: [ - 'GET', - 'PUT', - 'HEAD', - 'DELETE', - 'OPTIONS', - 'TRACE', - ], - statusCodes: [ - 408, - 413, - 429, - 500, - 502, - 503, - 504, - 521, - 522, - 524, - ], - errorCodes: [ - 'ETIMEDOUT', - 'ECONNRESET', - 'EADDRINUSE', - 'ECONNREFUSED', - 'EPIPE', - 'ENOTFOUND', - 'ENETUNREACH', - 'EAI_AGAIN', - ], - maxRetryAfter: undefined, - calculateDelay: ({ computedValue }) => computedValue, - backoffLimit: Number.POSITIVE_INFINITY, - noise: 100, - }, - localAddress: undefined, - method: 'GET', - createConnection: undefined, - cacheOptions: { - shared: undefined, - cacheHeuristic: undefined, - immutableMinTimeToLive: undefined, - ignoreCargoCult: undefined, - }, - https: { - alpnProtocols: undefined, - rejectUnauthorized: undefined, - checkServerIdentity: undefined, - certificateAuthority: undefined, - key: undefined, - certificate: undefined, - passphrase: undefined, - pfx: undefined, - ciphers: undefined, - honorCipherOrder: undefined, - minVersion: undefined, - maxVersion: undefined, - signatureAlgorithms: undefined, - tlsSessionLifetime: undefined, - dhparam: undefined, - ecdhCurve: undefined, - certificateRevocationLists: undefined, - }, - encoding: undefined, - resolveBodyOnly: false, - isStream: false, - responseType: 'text', - url: undefined, - pagination: { - transform(response) { - if (response.request.options.responseType === 'json') { - return response.body; - } - return JSON.parse(response.body); - }, - paginate({ response }) { - const rawLinkHeader = response.headers.link; - if (typeof rawLinkHeader !== 'string' || rawLinkHeader.trim() === '') { - return false; - } - const parsed = parseLinkHeader(rawLinkHeader); - const next = parsed.find(entry => entry.parameters.rel === 'next' || entry.parameters.rel === '"next"'); - if (next) { - return { - url: new URL(next.reference, response.url), - }; - } - return false; - }, - filter: () => true, - shouldContinue: () => true, - countLimit: Number.POSITIVE_INFINITY, - backoff: 0, - requestLimit: 10_000, - stackAllItems: false, - }, - setHost: true, - maxHeaderSize: undefined, - signal: undefined, - enableUnixSockets: false, -}; -const cloneInternals = (internals) => { - const { hooks, retry } = internals; - const result = { - ...internals, - context: { ...internals.context }, - cacheOptions: { ...internals.cacheOptions }, - https: { ...internals.https }, - agent: { ...internals.agent }, - headers: { ...internals.headers }, - retry: { - ...retry, - errorCodes: [...retry.errorCodes], - methods: [...retry.methods], - statusCodes: [...retry.statusCodes], - }, - timeout: { ...internals.timeout }, - hooks: { - init: [...hooks.init], - beforeRequest: [...hooks.beforeRequest], - beforeError: [...hooks.beforeError], - beforeRedirect: [...hooks.beforeRedirect], - beforeRetry: [...hooks.beforeRetry], - afterResponse: [...hooks.afterResponse], - }, - searchParams: internals.searchParams ? new URLSearchParams(internals.searchParams) : undefined, - pagination: { ...internals.pagination }, - }; - if (result.url !== undefined) { - result.prefixUrl = ''; + return Object.getPrototypeOf(instance) === class_.prototype; +} +function distribution_isEmptyArray(value) { + return distribution_isArray(value) && value.length === 0; +} +function distribution_isEmptyMap(value) { + return distribution_isMap(value) && value.size === 0; +} +function distribution_isEmptyObject(value) { + return distribution_isObject(value) && !distribution_isMap(value) && !distribution_isSet(value) && Object.keys(value).length === 0; +} +function distribution_isEmptySet(value) { + return distribution_isSet(value) && value.size === 0; +} +function distribution_isEmptyString(value) { + return distribution_isString(value) && value.length === 0; +} +function distribution_isEmptyStringOrWhitespace(value) { + return distribution_isEmptyString(value) || distribution_isWhitespaceString(value); +} +function distribution_isEnumCase(value, targetEnum) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument + return Object.values(targetEnum).includes(value); +} +function distribution_isError(value) { + return distribution_getObjectType(value) === 'Error'; +} +function distribution_isEvenInteger(value) { + return distribution_isAbsoluteModule2(0)(value); +} +// Example: `is.falsy = (value: unknown): value is (not true | 0 | '' | undefined | null) => Boolean(value);` +function distribution_isFalsy(value) { + return !value; +} +function distribution_isFloat32Array(value) { + return distribution_getObjectType(value) === 'Float32Array'; +} +function distribution_isFloat64Array(value) { + return distribution_getObjectType(value) === 'Float64Array'; +} +function distribution_isFormData(value) { + return distribution_getObjectType(value) === 'FormData'; +} +// eslint-disable-next-line @typescript-eslint/ban-types +function distribution_isFunction(value) { + return typeof value === 'function'; +} +function distribution_isGenerator(value) { + return distribution_isIterable(value) && distribution_isFunction(value?.next) && distribution_isFunction(value?.throw); +} +function distribution_isGeneratorFunction(value) { + return distribution_getObjectType(value) === 'GeneratorFunction'; +} +// eslint-disable-next-line @typescript-eslint/naming-convention +const distribution_NODE_TYPE_ELEMENT = 1; +// eslint-disable-next-line @typescript-eslint/naming-convention +const distribution_DOM_PROPERTIES_TO_CHECK = [ + 'innerHTML', + 'ownerDocument', + 'style', + 'attributes', + 'nodeValue', +]; +function distribution_isHtmlElement(value) { + return distribution_isObject(value) + && value.nodeType === distribution_NODE_TYPE_ELEMENT + && distribution_isString(value.nodeName) + && !distribution_isPlainObject(value) + && distribution_DOM_PROPERTIES_TO_CHECK.every(property => property in value); +} +function distribution_isInfinite(value) { + return value === Number.POSITIVE_INFINITY || value === Number.NEGATIVE_INFINITY; +} +function distribution_isInRange(value, range) { + if (distribution_isNumber(range)) { + return value >= Math.min(0, range) && value <= Math.max(range, 0); + } + if (distribution_isArray(range) && range.length === 2) { + return value >= Math.min(...range) && value <= Math.max(...range); + } + throw new TypeError(`Invalid range: ${JSON.stringify(range)}`); +} +function distribution_isInt16Array(value) { + return distribution_getObjectType(value) === 'Int16Array'; +} +function distribution_isInt32Array(value) { + return distribution_getObjectType(value) === 'Int32Array'; +} +function distribution_isInt8Array(value) { + return distribution_getObjectType(value) === 'Int8Array'; +} +function distribution_isInteger(value) { + return Number.isInteger(value); +} +function distribution_isIterable(value) { + return distribution_isFunction(value?.[Symbol.iterator]); +} +function distribution_isMap(value) { + return distribution_getObjectType(value) === 'Map'; +} +function distribution_isNan(value) { + return Number.isNaN(value); +} +function distribution_isNativePromise(value) { + return distribution_getObjectType(value) === 'Promise'; +} +function distribution_isNegativeNumber(value) { + return distribution_isNumber(value) && value < 0; +} +function distribution_isNodeStream(value) { + return distribution_isObject(value) && distribution_isFunction(value.pipe) && !distribution_isObservable(value); +} +function distribution_isNonEmptyArray(value) { + return distribution_isArray(value) && value.length > 0; +} +function distribution_isNonEmptyMap(value) { + return distribution_isMap(value) && value.size > 0; +} +// TODO: Use `not` operator here to remove `Map` and `Set` from type guard: +// - https://github.com/Microsoft/TypeScript/pull/29317 +function distribution_isNonEmptyObject(value) { + return distribution_isObject(value) && !distribution_isMap(value) && !distribution_isSet(value) && Object.keys(value).length > 0; +} +function distribution_isNonEmptySet(value) { + return distribution_isSet(value) && value.size > 0; +} +// TODO: Use `not ''` when the `not` operator is available. +function distribution_isNonEmptyString(value) { + return distribution_isString(value) && value.length > 0; +} +// TODO: Use `not ''` when the `not` operator is available. +function distribution_isNonEmptyStringAndNotWhitespace(value) { + return distribution_isString(value) && !distribution_isEmptyStringOrWhitespace(value); +} +// eslint-disable-next-line @typescript-eslint/ban-types +function distribution_isNull(value) { + return value === null; +} +// eslint-disable-next-line @typescript-eslint/ban-types +function distribution_isNullOrUndefined(value) { + return distribution_isNull(value) || distribution_isUndefined(value); +} +function distribution_isNumber(value) { + return typeof value === 'number' && !Number.isNaN(value); +} +function distribution_isNumericString(value) { + return distribution_isString(value) && !distribution_isEmptyStringOrWhitespace(value) && !Number.isNaN(Number(value)); +} +// eslint-disable-next-line @typescript-eslint/ban-types +function distribution_isObject(value) { + return !distribution_isNull(value) && (typeof value === 'object' || distribution_isFunction(value)); +} +function distribution_isObservable(value) { + if (!value) { + return false; + } + // eslint-disable-next-line no-use-extend-native/no-use-extend-native, @typescript-eslint/no-unsafe-call + if (value === value[Symbol.observable]?.()) { + return true; + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-call + if (value === value['@@observable']?.()) { + return true; + } + return false; +} +function distribution_isOddInteger(value) { + return distribution_isAbsoluteModule2(1)(value); +} +function distribution_isPlainObject(value) { + // From: https://github.com/sindresorhus/is-plain-obj/blob/main/index.js + if (typeof value !== 'object' || value === null) { + return false; + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const prototype = Object.getPrototypeOf(value); + return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value) && !(Symbol.iterator in value); +} +function distribution_isPositiveNumber(value) { + return distribution_isNumber(value) && value > 0; +} +function distribution_isPrimitive(value) { + return distribution_isNull(value) || distribution_isPrimitiveTypeName(typeof value); +} +function distribution_isPromise(value) { + return distribution_isNativePromise(value) || distribution_hasPromiseApi(value); +} +// `PropertyKey` is any value that can be used as an object key (string, number, or symbol) +function distribution_isPropertyKey(value) { + return distribution_isAny([distribution_isString, distribution_isNumber, distribution_isSymbol], value); +} +function distribution_isRegExp(value) { + return distribution_getObjectType(value) === 'RegExp'; +} +function distribution_isSafeInteger(value) { + return Number.isSafeInteger(value); +} +function distribution_isSet(value) { + return distribution_getObjectType(value) === 'Set'; +} +function distribution_isSharedArrayBuffer(value) { + return distribution_getObjectType(value) === 'SharedArrayBuffer'; +} +function distribution_isString(value) { + return typeof value === 'string'; +} +function distribution_isSymbol(value) { + return typeof value === 'symbol'; +} +// Example: `is.truthy = (value: unknown): value is (not false | not 0 | not '' | not undefined | not null) => Boolean(value);` +// eslint-disable-next-line unicorn/prefer-native-coercion-functions +function distribution_isTruthy(value) { + return Boolean(value); +} +function distribution_isTupleLike(value, guards) { + if (distribution_isArray(guards) && distribution_isArray(value) && guards.length === value.length) { + return guards.every((guard, index) => guard(value[index])); + } + return false; +} +function distribution_isTypedArray(value) { + return distribution_isTypedArrayName(distribution_getObjectType(value)); +} +function distribution_isUint16Array(value) { + return distribution_getObjectType(value) === 'Uint16Array'; +} +function distribution_isUint32Array(value) { + return distribution_getObjectType(value) === 'Uint32Array'; +} +function distribution_isUint8Array(value) { + return distribution_getObjectType(value) === 'Uint8Array'; +} +function distribution_isUint8ClampedArray(value) { + return distribution_getObjectType(value) === 'Uint8ClampedArray'; +} +function distribution_isUndefined(value) { + return value === undefined; +} +function distribution_isUrlInstance(value) { + return distribution_getObjectType(value) === 'URL'; +} +// eslint-disable-next-line unicorn/prevent-abbreviations +function distribution_isUrlSearchParams(value) { + return distribution_getObjectType(value) === 'URLSearchParams'; +} +function distribution_isUrlString(value) { + if (!distribution_isString(value)) { + return false; + } + try { + new URL(value); // eslint-disable-line no-new + return true; + } + catch { + return false; + } +} +function distribution_isValidDate(value) { + return distribution_isDate(value) && !distribution_isNan(Number(value)); +} +function distribution_isValidLength(value) { + return distribution_isSafeInteger(value) && value >= 0; +} +// eslint-disable-next-line @typescript-eslint/ban-types +function distribution_isWeakMap(value) { + return distribution_getObjectType(value) === 'WeakMap'; +} +// eslint-disable-next-line @typescript-eslint/ban-types, unicorn/prevent-abbreviations +function distribution_isWeakRef(value) { + return distribution_getObjectType(value) === 'WeakRef'; +} +// eslint-disable-next-line @typescript-eslint/ban-types +function distribution_isWeakSet(value) { + return distribution_getObjectType(value) === 'WeakSet'; +} +function distribution_isWhitespaceString(value) { + return distribution_isString(value) && /^\s+$/.test(value); +} +function distribution_predicateOnArray(method, predicate, values) { + if (!distribution_isFunction(predicate)) { + throw new TypeError(`Invalid predicate: ${JSON.stringify(predicate)}`); } - return result; + if (values.length === 0) { + throw new TypeError('Invalid number of values'); + } + return method.call(values, predicate); +} +function distribution_typeErrorMessage(description, value) { + return `Expected value which is \`${description}\`, received value of type \`${distribution_is(value)}\`.`; +} +function distribution_unique(values) { + // eslint-disable-next-line unicorn/prefer-spread + return Array.from(new Set(values)); +} +const distribution_andFormatter = new Intl.ListFormat('en', { style: 'long', type: 'conjunction' }); +const distribution_orFormatter = new Intl.ListFormat('en', { style: 'long', type: 'disjunction' }); +function distribution_typeErrorMessageMultipleValues(expectedType, values) { + const uniqueExpectedTypes = distribution_unique((distribution_isArray(expectedType) ? expectedType : [expectedType]).map(value => `\`${value}\``)); + const uniqueValueTypes = distribution_unique(values.map(value => `\`${distribution_is(value)}\``)); + return `Expected values which are ${distribution_orFormatter.format(uniqueExpectedTypes)}. Received values of type${uniqueValueTypes.length > 1 ? 's' : ''} ${distribution_andFormatter.format(uniqueValueTypes)}.`; +} +const distribution_assert = { + all: distribution_assertAll, + any: distribution_assertAny, + array: distribution_assertArray, + arrayBuffer: distribution_assertArrayBuffer, + arrayLike: distribution_assertArrayLike, + asyncFunction: distribution_assertAsyncFunction, + asyncGenerator: distribution_assertAsyncGenerator, + asyncGeneratorFunction: distribution_assertAsyncGeneratorFunction, + asyncIterable: distribution_assertAsyncIterable, + bigint: distribution_assertBigint, + bigInt64Array: distribution_assertBigInt64Array, + bigUint64Array: distribution_assertBigUint64Array, + blob: distribution_assertBlob, + boolean: distribution_assertBoolean, + boundFunction: distribution_assertBoundFunction, + buffer: distribution_assertBuffer, + class: distribution_assertClass, + dataView: distribution_assertDataView, + date: distribution_assertDate, + directInstanceOf: distribution_assertDirectInstanceOf, + emptyArray: distribution_assertEmptyArray, + emptyMap: distribution_assertEmptyMap, + emptyObject: distribution_assertEmptyObject, + emptySet: distribution_assertEmptySet, + emptyString: distribution_assertEmptyString, + emptyStringOrWhitespace: distribution_assertEmptyStringOrWhitespace, + enumCase: distribution_assertEnumCase, + error: distribution_assertError, + evenInteger: distribution_assertEvenInteger, + falsy: distribution_assertFalsy, + float32Array: distribution_assertFloat32Array, + float64Array: distribution_assertFloat64Array, + formData: distribution_assertFormData, + function: distribution_assertFunction, + generator: distribution_assertGenerator, + generatorFunction: distribution_assertGeneratorFunction, + htmlElement: distribution_assertHtmlElement, + infinite: distribution_assertInfinite, + inRange: distribution_assertInRange, + int16Array: distribution_assertInt16Array, + int32Array: distribution_assertInt32Array, + int8Array: distribution_assertInt8Array, + integer: distribution_assertInteger, + iterable: distribution_assertIterable, + map: distribution_assertMap, + nan: distribution_assertNan, + nativePromise: distribution_assertNativePromise, + negativeNumber: distribution_assertNegativeNumber, + nodeStream: distribution_assertNodeStream, + nonEmptyArray: distribution_assertNonEmptyArray, + nonEmptyMap: distribution_assertNonEmptyMap, + nonEmptyObject: distribution_assertNonEmptyObject, + nonEmptySet: distribution_assertNonEmptySet, + nonEmptyString: distribution_assertNonEmptyString, + nonEmptyStringAndNotWhitespace: distribution_assertNonEmptyStringAndNotWhitespace, + null: distribution_assertNull, + nullOrUndefined: distribution_assertNullOrUndefined, + number: distribution_assertNumber, + numericString: distribution_assertNumericString, + object: distribution_assertObject, + observable: distribution_assertObservable, + oddInteger: distribution_assertOddInteger, + plainObject: distribution_assertPlainObject, + positiveNumber: distribution_assertPositiveNumber, + primitive: distribution_assertPrimitive, + promise: distribution_assertPromise, + propertyKey: distribution_assertPropertyKey, + regExp: distribution_assertRegExp, + safeInteger: distribution_assertSafeInteger, + set: distribution_assertSet, + sharedArrayBuffer: distribution_assertSharedArrayBuffer, + string: distribution_assertString, + symbol: distribution_assertSymbol, + truthy: distribution_assertTruthy, + tupleLike: distribution_assertTupleLike, + typedArray: distribution_assertTypedArray, + uint16Array: distribution_assertUint16Array, + uint32Array: distribution_assertUint32Array, + uint8Array: distribution_assertUint8Array, + uint8ClampedArray: distribution_assertUint8ClampedArray, + undefined: distribution_assertUndefined, + urlInstance: distribution_assertUrlInstance, + urlSearchParams: distribution_assertUrlSearchParams, + urlString: distribution_assertUrlString, + validDate: distribution_assertValidDate, + validLength: distribution_assertValidLength, + weakMap: distribution_assertWeakMap, + weakRef: distribution_assertWeakRef, + weakSet: distribution_assertWeakSet, + whitespaceString: distribution_assertWhitespaceString, +}; +const distribution_methodTypeMap = { + isArray: 'Array', + isArrayBuffer: 'ArrayBuffer', + isArrayLike: 'array-like', + isAsyncFunction: 'AsyncFunction', + isAsyncGenerator: 'AsyncGenerator', + isAsyncGeneratorFunction: 'AsyncGeneratorFunction', + isAsyncIterable: 'AsyncIterable', + isBigint: 'bigint', + isBigInt64Array: 'BigInt64Array', + isBigUint64Array: 'BigUint64Array', + isBlob: 'Blob', + isBoolean: 'boolean', + isBoundFunction: 'Function', + isBuffer: 'Buffer', + isClass: 'Class', + isDataView: 'DataView', + isDate: 'Date', + isDirectInstanceOf: 'T', + isEmptyArray: 'empty array', + isEmptyMap: 'empty map', + isEmptyObject: 'empty object', + isEmptySet: 'empty set', + isEmptyString: 'empty string', + isEmptyStringOrWhitespace: 'empty string or whitespace', + isEnumCase: 'EnumCase', + isError: 'Error', + isEvenInteger: 'even integer', + isFalsy: 'falsy', + isFloat32Array: 'Float32Array', + isFloat64Array: 'Float64Array', + isFormData: 'FormData', + isFunction: 'Function', + isGenerator: 'Generator', + isGeneratorFunction: 'GeneratorFunction', + isHtmlElement: 'HTMLElement', + isInfinite: 'infinite number', + isInRange: 'in range', + isInt16Array: 'Int16Array', + isInt32Array: 'Int32Array', + isInt8Array: 'Int8Array', + isInteger: 'integer', + isIterable: 'Iterable', + isMap: 'Map', + isNan: 'NaN', + isNativePromise: 'native Promise', + isNegativeNumber: 'negative number', + isNodeStream: 'Node.js Stream', + isNonEmptyArray: 'non-empty array', + isNonEmptyMap: 'non-empty map', + isNonEmptyObject: 'non-empty object', + isNonEmptySet: 'non-empty set', + isNonEmptyString: 'non-empty string', + isNonEmptyStringAndNotWhitespace: 'non-empty string and not whitespace', + isNull: 'null', + isNullOrUndefined: 'null or undefined', + isNumber: 'number', + isNumericString: 'string with a number', + isObject: 'Object', + isObservable: 'Observable', + isOddInteger: 'odd integer', + isPlainObject: 'plain object', + isPositiveNumber: 'positive number', + isPrimitive: 'primitive', + isPromise: 'Promise', + isPropertyKey: 'PropertyKey', + isRegExp: 'RegExp', + isSafeInteger: 'integer', + isSet: 'Set', + isSharedArrayBuffer: 'SharedArrayBuffer', + isString: 'string', + isSymbol: 'symbol', + isTruthy: 'truthy', + isTupleLike: 'tuple-like', + isTypedArray: 'TypedArray', + isUint16Array: 'Uint16Array', + isUint32Array: 'Uint32Array', + isUint8Array: 'Uint8Array', + isUint8ClampedArray: 'Uint8ClampedArray', + isUndefined: 'undefined', + isUrlInstance: 'URL', + isUrlSearchParams: 'URLSearchParams', + isUrlString: 'string with a URL', + isValidDate: 'valid Date', + isValidLength: 'valid length', + isWeakMap: 'WeakMap', + isWeakRef: 'WeakRef', + isWeakSet: 'WeakSet', + isWhitespaceString: 'whitespace string', }; -const cloneRaw = (raw) => { - const { hooks, retry } = raw; - const result = { ...raw }; - if (distribution.object(raw.context)) { - result.context = { ...raw.context }; +function distribution_keysOf(value) { + return Object.keys(value); +} +const distribution_isMethodNames = distribution_keysOf(distribution_methodTypeMap); +function distribution_isIsMethodName(value) { + return distribution_isMethodNames.includes(value); +} +function distribution_assertAll(predicate, ...values) { + if (!distribution_isAll(predicate, ...values)) { + const expectedType = distribution_isIsMethodName(predicate.name) ? distribution_methodTypeMap[predicate.name] : 'predicate returns truthy for all values'; + throw new TypeError(distribution_typeErrorMessageMultipleValues(expectedType, values)); } - if (distribution.object(raw.cacheOptions)) { - result.cacheOptions = { ...raw.cacheOptions }; +} +function distribution_assertAny(predicate, ...values) { + if (!distribution_isAny(predicate, ...values)) { + const predicates = distribution_isArray(predicate) ? predicate : [predicate]; + const expectedTypes = predicates.map(predicate => distribution_isIsMethodName(predicate.name) ? distribution_methodTypeMap[predicate.name] : 'predicate returns truthy for any value'); + throw new TypeError(distribution_typeErrorMessageMultipleValues(expectedTypes, values)); } - if (distribution.object(raw.https)) { - result.https = { ...raw.https }; +} +function distribution_assertArray(value, assertion, message) { + if (!distribution_isArray(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('Array', value)); } - if (distribution.object(raw.cacheOptions)) { - result.cacheOptions = { ...result.cacheOptions }; + if (assertion) { + // eslint-disable-next-line unicorn/no-array-for-each, unicorn/no-array-callback-reference + value.forEach(assertion); } - if (distribution.object(raw.agent)) { - result.agent = { ...raw.agent }; +} +function distribution_assertArrayBuffer(value, message) { + if (!distribution_isArrayBuffer(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('ArrayBuffer', value)); } - if (distribution.object(raw.headers)) { - result.headers = { ...raw.headers }; +} +function distribution_assertArrayLike(value, message) { + if (!distribution_isArrayLike(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('array-like', value)); } - if (distribution.object(retry)) { - result.retry = { ...retry }; - if (distribution.array(retry.errorCodes)) { - result.retry.errorCodes = [...retry.errorCodes]; - } - if (distribution.array(retry.methods)) { - result.retry.methods = [...retry.methods]; - } - if (distribution.array(retry.statusCodes)) { - result.retry.statusCodes = [...retry.statusCodes]; - } +} +// eslint-disable-next-line @typescript-eslint/ban-types +function distribution_assertAsyncFunction(value, message) { + if (!distribution_isAsyncFunction(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('AsyncFunction', value)); } - if (distribution.object(raw.timeout)) { - result.timeout = { ...raw.timeout }; +} +function distribution_assertAsyncGenerator(value, message) { + if (!distribution_isAsyncGenerator(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('AsyncGenerator', value)); } - if (distribution.object(hooks)) { - result.hooks = { - ...hooks, - }; - if (distribution.array(hooks.init)) { - result.hooks.init = [...hooks.init]; - } - if (distribution.array(hooks.beforeRequest)) { - result.hooks.beforeRequest = [...hooks.beforeRequest]; - } - if (distribution.array(hooks.beforeError)) { - result.hooks.beforeError = [...hooks.beforeError]; - } - if (distribution.array(hooks.beforeRedirect)) { - result.hooks.beforeRedirect = [...hooks.beforeRedirect]; - } - if (distribution.array(hooks.beforeRetry)) { - result.hooks.beforeRetry = [...hooks.beforeRetry]; - } - if (distribution.array(hooks.afterResponse)) { - result.hooks.afterResponse = [...hooks.afterResponse]; - } +} +function distribution_assertAsyncGeneratorFunction(value, message) { + if (!distribution_isAsyncGeneratorFunction(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('AsyncGeneratorFunction', value)); } - // TODO: raw.searchParams - if (distribution.object(raw.pagination)) { - result.pagination = { ...raw.pagination }; +} +function distribution_assertAsyncIterable(value, message) { + if (!distribution_isAsyncIterable(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('AsyncIterable', value)); } - return result; -}; -const getHttp2TimeoutOption = (internals) => { - const delays = [internals.timeout.socket, internals.timeout.connect, internals.timeout.lookup, internals.timeout.request, internals.timeout.secureConnect].filter(delay => typeof delay === 'number'); - if (delays.length > 0) { - return Math.min(...delays); +} +function distribution_assertBigint(value, message) { + if (!distribution_isBigint(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('bigint', value)); } - return undefined; -}; -const init = (options, withOptions, self) => { - const initHooks = options.hooks?.init; - if (initHooks) { - for (const hook of initHooks) { - hook(withOptions, self); - } +} +function distribution_assertBigInt64Array(value, message) { + if (!distribution_isBigInt64Array(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('BigInt64Array', value)); } -}; -class Options { - _unixOptions; - _internals; - _merging; - _init; - constructor(input, options, defaults) { - assert.any([distribution.string, distribution.urlInstance, distribution.object, distribution.undefined], input); - assert.any([distribution.object, distribution.undefined], options); - assert.any([distribution.object, distribution.undefined], defaults); - if (input instanceof Options || options instanceof Options) { - throw new TypeError('The defaults must be passed as the third argument'); - } - this._internals = cloneInternals(defaults?._internals ?? defaults ?? defaultInternals); - this._init = [...(defaults?._init ?? [])]; - this._merging = false; - this._unixOptions = undefined; - // This rule allows `finally` to be considered more important. - // Meaning no matter the error thrown in the `try` block, - // if `finally` throws then the `finally` error will be thrown. - // - // Yes, we want this. If we set `url` first, then the `url.searchParams` - // would get merged. Instead we set the `searchParams` first, then - // `url.searchParams` is overwritten as expected. - // - /* eslint-disable no-unsafe-finally */ - try { - if (distribution.plainObject(input)) { - try { - this.merge(input); - this.merge(options); - } - finally { - this.url = input.url; - } - } - else { - try { - this.merge(options); - } - finally { - if (options?.url !== undefined) { - if (input === undefined) { - this.url = options.url; - } - else { - throw new TypeError('The `url` option is mutually exclusive with the `input` argument'); - } - } - else if (input !== undefined) { - this.url = input; - } - } - } - } - catch (error) { - error.options = this; - throw error; - } - /* eslint-enable no-unsafe-finally */ +} +function distribution_assertBigUint64Array(value, message) { + if (!distribution_isBigUint64Array(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('BigUint64Array', value)); } - merge(options) { - if (!options) { - return; - } - if (options instanceof Options) { - for (const init of options._init) { - this.merge(init); - } - return; - } - options = cloneRaw(options); - init(this, options, this); - init(options, options, this); - this._merging = true; - // Always merge `isStream` first - if ('isStream' in options) { - this.isStream = options.isStream; - } - try { - let push = false; - for (const key in options) { - // `got.extend()` options - if (key === 'mutableDefaults' || key === 'handlers') { - continue; - } - // Never merge `url` - if (key === 'url') { - continue; - } - if (!(key in this)) { - throw new Error(`Unexpected option: ${key}`); - } - // @ts-expect-error Type 'unknown' is not assignable to type 'never'. - const value = options[key]; - if (value === undefined) { - continue; - } - // @ts-expect-error Type 'unknown' is not assignable to type 'never'. - this[key] = value; - push = true; - } - if (push) { - this._init.push(options); - } - } - finally { - this._merging = false; - } +} +function distribution_assertBlob(value, message) { + if (!distribution_isBlob(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('Blob', value)); } - /** - Custom request function. - The main purpose of this is to [support HTTP2 using a wrapper](https://github.com/szmarczak/http2-wrapper). - - @default http.request | https.request - */ - get request() { - return this._internals.request; +} +function distribution_assertBoolean(value, message) { + if (!distribution_isBoolean(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('boolean', value)); } - set request(value) { - assert.any([distribution["function"], distribution.undefined], value); - this._internals.request = value; +} +// eslint-disable-next-line @typescript-eslint/ban-types +function distribution_assertBoundFunction(value, message) { + if (!distribution_isBoundFunction(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('Function', value)); } - /** - An object representing `http`, `https` and `http2` keys for [`http.Agent`](https://nodejs.org/api/http.html#http_class_http_agent), [`https.Agent`](https://nodejs.org/api/https.html#https_class_https_agent) and [`http2wrapper.Agent`](https://github.com/szmarczak/http2-wrapper#new-http2agentoptions) instance. - This is necessary because a request to one protocol might redirect to another. - In such a scenario, Got will switch over to the right protocol agent for you. - - If a key is not present, it will default to a global agent. - - @example - ``` - import got from 'got'; - import HttpAgent from 'agentkeepalive'; - - const {HttpsAgent} = HttpAgent; - - await got('https://sindresorhus.com', { - agent: { - http: new HttpAgent(), - https: new HttpsAgent() - } - }); - ``` - */ - get agent() { - return this._internals.agent; +} +/** +Note: [Prefer using `Uint8Array` instead of `Buffer`.](https://sindresorhus.com/blog/goodbye-nodejs-buffer) +*/ +function distribution_assertBuffer(value, message) { + if (!distribution_isBuffer(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('Buffer', value)); } - set agent(value) { - assert.plainObject(value); - // eslint-disable-next-line guard-for-in - for (const key in value) { - if (!(key in this._internals.agent)) { - throw new TypeError(`Unexpected agent option: ${key}`); - } - // @ts-expect-error - No idea why `value[key]` doesn't work here. - assert.any([distribution.object, distribution.undefined], value[key]); - } - if (this._merging) { - Object.assign(this._internals.agent, value); - } - else { - this._internals.agent = { ...value }; - } +} +function distribution_assertClass(value, message) { + if (!distribution_isClass(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('Class', value)); } - get h2session() { - return this._internals.h2session; +} +function distribution_assertDataView(value, message) { + if (!distribution_isDataView(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('DataView', value)); } - set h2session(value) { - this._internals.h2session = value; +} +function distribution_assertDate(value, message) { + if (!distribution_isDate(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('Date', value)); } - /** - Decompress the response automatically. - - This will set the `accept-encoding` header to `gzip, deflate, br` unless you set it yourself. - - If this is disabled, a compressed response is returned as a `Buffer`. - This may be useful if you want to handle decompression yourself or stream the raw compressed data. - - @default true - */ - get decompress() { - return this._internals.decompress; +} +function distribution_assertDirectInstanceOf(instance, class_, message) { + if (!distribution_isDirectInstanceOf(instance, class_)) { + throw new TypeError(message ?? distribution_typeErrorMessage('T', instance)); } - set decompress(value) { - assert.boolean(value); - this._internals.decompress = value; +} +function distribution_assertEmptyArray(value, message) { + if (!distribution_isEmptyArray(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('empty array', value)); } - /** - Milliseconds to wait for the server to end the response before aborting the request with `got.TimeoutError` error (a.k.a. `request` property). - By default, there's no timeout. - - This also accepts an `object` with the following fields to constrain the duration of each phase of the request lifecycle: - - - `lookup` starts when a socket is assigned and ends when the hostname has been resolved. - Does not apply when using a Unix domain socket. - - `connect` starts when `lookup` completes (or when the socket is assigned if lookup does not apply to the request) and ends when the socket is connected. - - `secureConnect` starts when `connect` completes and ends when the handshaking process completes (HTTPS only). - - `socket` starts when the socket is connected. See [request.setTimeout](https://nodejs.org/api/http.html#http_request_settimeout_timeout_callback). - - `response` starts when the request has been written to the socket and ends when the response headers are received. - - `send` starts when the socket is connected and ends with the request has been written to the socket. - - `request` starts when the request is initiated and ends when the response's end event fires. - */ - get timeout() { - // We always return `Delays` here. - // It has to be `Delays | number`, otherwise TypeScript will error because the getter and the setter have incompatible types. - return this._internals.timeout; +} +function distribution_assertEmptyMap(value, message) { + if (!distribution_isEmptyMap(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('empty map', value)); } - set timeout(value) { - assert.plainObject(value); - // eslint-disable-next-line guard-for-in - for (const key in value) { - if (!(key in this._internals.timeout)) { - throw new Error(`Unexpected timeout option: ${key}`); - } - // @ts-expect-error - No idea why `value[key]` doesn't work here. - assert.any([distribution.number, distribution.undefined], value[key]); - } - if (this._merging) { - Object.assign(this._internals.timeout, value); - } - else { - this._internals.timeout = { ...value }; - } +} +function distribution_assertEmptyObject(value, message) { + if (!distribution_isEmptyObject(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('empty object', value)); } - /** - When specified, `prefixUrl` will be prepended to `url`. - The prefix can be any valid URL, either relative or absolute. - A trailing slash `/` is optional - one will be added automatically. - - __Note__: `prefixUrl` will be ignored if the `url` argument is a URL instance. - - __Note__: Leading slashes in `input` are disallowed when using this option to enforce consistency and avoid confusion. - For example, when the prefix URL is `https://example.com/foo` and the input is `/bar`, there's ambiguity whether the resulting URL would become `https://example.com/foo/bar` or `https://example.com/bar`. - The latter is used by browsers. - - __Tip__: Useful when used with `got.extend()` to create niche-specific Got instances. - - __Tip__: You can change `prefixUrl` using hooks as long as the URL still includes the `prefixUrl`. - If the URL doesn't include it anymore, it will throw. - - @example - ``` - import got from 'got'; - - await got('unicorn', {prefixUrl: 'https://cats.com'}); - //=> 'https://cats.com/unicorn' - - const instance = got.extend({ - prefixUrl: 'https://google.com' - }); - - await instance('unicorn', { - hooks: { - beforeRequest: [ - options => { - options.prefixUrl = 'https://cats.com'; - } - ] - } - }); - //=> 'https://cats.com/unicorn' - ``` - */ - get prefixUrl() { - // We always return `string` here. - // It has to be `string | URL`, otherwise TypeScript will error because the getter and the setter have incompatible types. - return this._internals.prefixUrl; +} +function distribution_assertEmptySet(value, message) { + if (!distribution_isEmptySet(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('empty set', value)); } - set prefixUrl(value) { - assert.any([distribution.string, distribution.urlInstance], value); - if (value === '') { - this._internals.prefixUrl = ''; - return; - } - value = value.toString(); - if (!value.endsWith('/')) { - value += '/'; - } - if (this._internals.prefixUrl && this._internals.url) { - const { href } = this._internals.url; - this._internals.url.href = value + href.slice(this._internals.prefixUrl.length); - } - this._internals.prefixUrl = value; +} +function distribution_assertEmptyString(value, message) { + if (!distribution_isEmptyString(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('empty string', value)); } - /** - __Note #1__: The `body` option cannot be used with the `json` or `form` option. - - __Note #2__: If you provide this option, `got.stream()` will be read-only. - - __Note #3__: If you provide a payload with the `GET` or `HEAD` method, it will throw a `TypeError` unless the method is `GET` and the `allowGetBody` option is set to `true`. - - __Note #4__: This option is not enumerable and will not be merged with the instance defaults. - - The `content-length` header will be automatically set if `body` is a `string` / `Buffer` / [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData) / [`form-data` instance](https://github.com/form-data/form-data), and `content-length` and `transfer-encoding` are not manually set in `options.headers`. - - Since Got 12, the `content-length` is not automatically set when `body` is a `fs.createReadStream`. - */ - get body() { - return this._internals.body; +} +function distribution_assertEmptyStringOrWhitespace(value, message) { + if (!distribution_isEmptyStringOrWhitespace(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('empty string or whitespace', value)); } - set body(value) { - assert.any([distribution.string, distribution.buffer, distribution.nodeStream, distribution.generator, distribution.asyncGenerator, lib_isFormData, distribution.undefined], value); - if (distribution.nodeStream(value)) { - assert.truthy(value.readable); - } - if (value !== undefined) { - assert.undefined(this._internals.form); - assert.undefined(this._internals.json); - } - this._internals.body = value; +} +function distribution_assertEnumCase(value, targetEnum, message) { + if (!distribution_isEnumCase(value, targetEnum)) { + throw new TypeError(message ?? distribution_typeErrorMessage('EnumCase', value)); } - /** - The form body is converted to a query string using [`(new URLSearchParams(object)).toString()`](https://nodejs.org/api/url.html#url_constructor_new_urlsearchparams_obj). - - If the `Content-Type` header is not present, it will be set to `application/x-www-form-urlencoded`. - - __Note #1__: If you provide this option, `got.stream()` will be read-only. - - __Note #2__: This option is not enumerable and will not be merged with the instance defaults. - */ - get form() { - return this._internals.form; +} +function distribution_assertError(value, message) { + if (!distribution_isError(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('Error', value)); } - set form(value) { - assert.any([distribution.plainObject, distribution.undefined], value); - if (value !== undefined) { - assert.undefined(this._internals.body); - assert.undefined(this._internals.json); - } - this._internals.form = value; +} +function distribution_assertEvenInteger(value, message) { + if (!distribution_isEvenInteger(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('even integer', value)); } - /** - JSON body. If the `Content-Type` header is not set, it will be set to `application/json`. - - __Note #1__: If you provide this option, `got.stream()` will be read-only. - - __Note #2__: This option is not enumerable and will not be merged with the instance defaults. - */ - get json() { - return this._internals.json; +} +function distribution_assertFalsy(value, message) { + if (!distribution_isFalsy(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('falsy', value)); } - set json(value) { - if (value !== undefined) { - assert.undefined(this._internals.body); - assert.undefined(this._internals.form); - } - this._internals.json = value; +} +function distribution_assertFloat32Array(value, message) { + if (!distribution_isFloat32Array(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('Float32Array', value)); } - /** - The URL to request, as a string, a [`https.request` options object](https://nodejs.org/api/https.html#https_https_request_options_callback), or a [WHATWG `URL`](https://nodejs.org/api/url.html#url_class_url). - - Properties from `options` will override properties in the parsed `url`. - - If no protocol is specified, it will throw a `TypeError`. - - __Note__: The query string is **not** parsed as search params. - - @example - ``` - await got('https://example.com/?query=a b'); //=> https://example.com/?query=a%20b - await got('https://example.com/', {searchParams: {query: 'a b'}}); //=> https://example.com/?query=a+b - - // The query string is overridden by `searchParams` - await got('https://example.com/?query=a b', {searchParams: {query: 'a b'}}); //=> https://example.com/?query=a+b - ``` - */ - get url() { - return this._internals.url; +} +function distribution_assertFloat64Array(value, message) { + if (!distribution_isFloat64Array(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('Float64Array', value)); } - set url(value) { - assert.any([distribution.string, distribution.urlInstance, distribution.undefined], value); - if (value === undefined) { - this._internals.url = undefined; - return; - } - if (distribution.string(value) && value.startsWith('/')) { - throw new Error('`url` must not start with a slash'); - } - const urlString = `${this.prefixUrl}${value.toString()}`; - const url = new URL(urlString); - this._internals.url = url; - if (url.protocol === 'unix:') { - url.href = `http://unix${url.pathname}${url.search}`; - } - if (url.protocol !== 'http:' && url.protocol !== 'https:') { - const error = new Error(`Unsupported protocol: ${url.protocol}`); - error.code = 'ERR_UNSUPPORTED_PROTOCOL'; - throw error; - } - if (this._internals.username) { - url.username = this._internals.username; - this._internals.username = ''; - } - if (this._internals.password) { - url.password = this._internals.password; - this._internals.password = ''; - } - if (this._internals.searchParams) { - url.search = this._internals.searchParams.toString(); - this._internals.searchParams = undefined; - } - if (url.hostname === 'unix') { - if (!this._internals.enableUnixSockets) { - throw new Error('Using UNIX domain sockets but option `enableUnixSockets` is not enabled'); - } - const matches = /(?.+?):(?.+)/.exec(`${url.pathname}${url.search}`); - if (matches?.groups) { - const { socketPath, path } = matches.groups; - this._unixOptions = { - socketPath, - path, - host: '', - }; - } - else { - this._unixOptions = undefined; - } - return; - } - this._unixOptions = undefined; +} +function distribution_assertFormData(value, message) { + if (!distribution_isFormData(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('FormData', value)); } - /** - Cookie support. You don't have to care about parsing or how to store them. - - __Note__: If you provide this option, `options.headers.cookie` will be overridden. - */ - get cookieJar() { - return this._internals.cookieJar; +} +// eslint-disable-next-line @typescript-eslint/ban-types +function distribution_assertFunction(value, message) { + if (!distribution_isFunction(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('Function', value)); } - set cookieJar(value) { - assert.any([distribution.object, distribution.undefined], value); - if (value === undefined) { - this._internals.cookieJar = undefined; - return; - } - let { setCookie, getCookieString } = value; - assert["function"](setCookie); - assert["function"](getCookieString); - /* istanbul ignore next: Horrible `tough-cookie` v3 check */ - if (setCookie.length === 4 && getCookieString.length === 0) { - setCookie = (0,external_node_util_.promisify)(setCookie.bind(value)); - getCookieString = (0,external_node_util_.promisify)(getCookieString.bind(value)); - this._internals.cookieJar = { - setCookie, - getCookieString: getCookieString, - }; - } - else { - this._internals.cookieJar = value; - } +} +function distribution_assertGenerator(value, message) { + if (!distribution_isGenerator(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('Generator', value)); } - /** - You can abort the `request` using [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController). - - @example - ``` - import got from 'got'; - - const abortController = new AbortController(); - - const request = got('https://httpbin.org/anything', { - signal: abortController.signal - }); - - setTimeout(() => { - abortController.abort(); - }, 100); - ``` - */ - get signal() { - return this._internals.signal; +} +function distribution_assertGeneratorFunction(value, message) { + if (!distribution_isGeneratorFunction(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('GeneratorFunction', value)); } - set signal(value) { - assert.object(value); - this._internals.signal = value; +} +function distribution_assertHtmlElement(value, message) { + if (!distribution_isHtmlElement(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('HTMLElement', value)); } - /** - Ignore invalid cookies instead of throwing an error. - Only useful when the `cookieJar` option has been set. Not recommended. - - @default false - */ - get ignoreInvalidCookies() { - return this._internals.ignoreInvalidCookies; +} +function distribution_assertInfinite(value, message) { + if (!distribution_isInfinite(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('infinite number', value)); } - set ignoreInvalidCookies(value) { - assert.boolean(value); - this._internals.ignoreInvalidCookies = value; +} +function distribution_assertInRange(value, range, message) { + if (!distribution_isInRange(value, range)) { + throw new TypeError(message ?? distribution_typeErrorMessage('in range', value)); } - /** - Query string that will be added to the request URL. - This will override the query string in `url`. - - If you need to pass in an array, you can do it using a `URLSearchParams` instance. - - @example - ``` - import got from 'got'; - - const searchParams = new URLSearchParams([['key', 'a'], ['key', 'b']]); - - await got('https://example.com', {searchParams}); - - console.log(searchParams.toString()); - //=> 'key=a&key=b' - ``` - */ - get searchParams() { - if (this._internals.url) { - return this._internals.url.searchParams; - } - if (this._internals.searchParams === undefined) { - this._internals.searchParams = new URLSearchParams(); - } - return this._internals.searchParams; +} +function distribution_assertInt16Array(value, message) { + if (!distribution_isInt16Array(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('Int16Array', value)); } - set searchParams(value) { - assert.any([distribution.string, distribution.object, distribution.undefined], value); - const url = this._internals.url; - if (value === undefined) { - this._internals.searchParams = undefined; - if (url) { - url.search = ''; - } - return; - } - const searchParameters = this.searchParams; - let updated; - if (distribution.string(value)) { - updated = new URLSearchParams(value); - } - else if (value instanceof URLSearchParams) { - updated = value; - } - else { - validateSearchParameters(value); - updated = new URLSearchParams(); - // eslint-disable-next-line guard-for-in - for (const key in value) { - const entry = value[key]; - if (entry === null) { - updated.append(key, ''); - } - else if (entry === undefined) { - searchParameters.delete(key); - } - else { - updated.append(key, entry); - } - } - } - if (this._merging) { - // These keys will be replaced - for (const key of updated.keys()) { - searchParameters.delete(key); - } - for (const [key, value] of updated) { - searchParameters.append(key, value); - } - } - else if (url) { - url.search = searchParameters.toString(); - } - else { - this._internals.searchParams = searchParameters; - } +} +function distribution_assertInt32Array(value, message) { + if (!distribution_isInt32Array(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('Int32Array', value)); } - get searchParameters() { - throw new Error('The `searchParameters` option does not exist. Use `searchParams` instead.'); +} +function distribution_assertInt8Array(value, message) { + if (!distribution_isInt8Array(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('Int8Array', value)); } - set searchParameters(_value) { - throw new Error('The `searchParameters` option does not exist. Use `searchParams` instead.'); +} +function distribution_assertInteger(value, message) { + if (!distribution_isInteger(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('integer', value)); } - get dnsLookup() { - return this._internals.dnsLookup; +} +function distribution_assertIterable(value, message) { + if (!distribution_isIterable(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('Iterable', value)); } - set dnsLookup(value) { - assert.any([distribution["function"], distribution.undefined], value); - this._internals.dnsLookup = value; +} +function distribution_assertMap(value, message) { + if (!distribution_isMap(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('Map', value)); } - /** - An instance of [`CacheableLookup`](https://github.com/szmarczak/cacheable-lookup) used for making DNS lookups. - Useful when making lots of requests to different *public* hostnames. - - `CacheableLookup` uses `dns.resolver4(..)` and `dns.resolver6(...)` under the hood and fall backs to `dns.lookup(...)` when the first two fail, which may lead to additional delay. - - __Note__: This should stay disabled when making requests to internal hostnames such as `localhost`, `database.local` etc. - - @default false - */ - get dnsCache() { - return this._internals.dnsCache; +} +function distribution_assertNan(value, message) { + if (!distribution_isNan(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('NaN', value)); } - set dnsCache(value) { - assert.any([distribution.object, distribution.boolean, distribution.undefined], value); - if (value === true) { - this._internals.dnsCache = getGlobalDnsCache(); - } - else if (value === false) { - this._internals.dnsCache = undefined; - } - else { - this._internals.dnsCache = value; - } +} +function distribution_assertNativePromise(value, message) { + if (!distribution_isNativePromise(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('native Promise', value)); } - /** - User data. `context` is shallow merged and enumerable. If it contains non-enumerable properties they will NOT be merged. - - @example - ``` - import got from 'got'; - - const instance = got.extend({ - hooks: { - beforeRequest: [ - options => { - if (!options.context || !options.context.token) { - throw new Error('Token required'); - } - - options.headers.token = options.context.token; - } - ] - } - }); - - const context = { - token: 'secret' - }; - - const response = await instance('https://httpbin.org/headers', {context}); - - // Let's see the headers - console.log(response.body); - ``` - */ - get context() { - return this._internals.context; +} +function distribution_assertNegativeNumber(value, message) { + if (!distribution_isNegativeNumber(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('negative number', value)); } - set context(value) { - assert.object(value); - if (this._merging) { - Object.assign(this._internals.context, value); - } - else { - this._internals.context = { ...value }; - } +} +function distribution_assertNodeStream(value, message) { + if (!distribution_isNodeStream(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('Node.js Stream', value)); } - /** - Hooks allow modifications during the request lifecycle. - Hook functions may be async and are run serially. - */ - get hooks() { - return this._internals.hooks; +} +function distribution_assertNonEmptyArray(value, message) { + if (!distribution_isNonEmptyArray(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('non-empty array', value)); } - set hooks(value) { - assert.object(value); - // eslint-disable-next-line guard-for-in - for (const knownHookEvent in value) { - if (!(knownHookEvent in this._internals.hooks)) { - throw new Error(`Unexpected hook event: ${knownHookEvent}`); - } - const typedKnownHookEvent = knownHookEvent; - const hooks = value[typedKnownHookEvent]; - assert.any([distribution.array, distribution.undefined], hooks); - if (hooks) { - for (const hook of hooks) { - assert["function"](hook); - } - } - if (this._merging) { - if (hooks) { - // @ts-expect-error FIXME - this._internals.hooks[typedKnownHookEvent].push(...hooks); - } - } - else { - if (!hooks) { - throw new Error(`Missing hook event: ${knownHookEvent}`); - } - // @ts-expect-error FIXME - this._internals.hooks[knownHookEvent] = [...hooks]; - } - } +} +function distribution_assertNonEmptyMap(value, message) { + if (!distribution_isNonEmptyMap(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('non-empty map', value)); } - /** - Whether redirect responses should be followed automatically. - - Optionally, pass a function to dynamically decide based on the response object. - - Note that if a `303` is sent by the server in response to any request type (`POST`, `DELETE`, etc.), Got will automatically request the resource pointed to in the location header via `GET`. - This is in accordance with [the spec](https://tools.ietf.org/html/rfc7231#section-6.4.4). You can optionally turn on this behavior also for other redirect codes - see `methodRewriting`. - - @default true - */ - get followRedirect() { - return this._internals.followRedirect; +} +function distribution_assertNonEmptyObject(value, message) { + if (!distribution_isNonEmptyObject(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('non-empty object', value)); } - set followRedirect(value) { - assert.any([distribution.boolean, distribution["function"]], value); - this._internals.followRedirect = value; +} +function distribution_assertNonEmptySet(value, message) { + if (!distribution_isNonEmptySet(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('non-empty set', value)); } - get followRedirects() { - throw new TypeError('The `followRedirects` option does not exist. Use `followRedirect` instead.'); +} +function distribution_assertNonEmptyString(value, message) { + if (!distribution_isNonEmptyString(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('non-empty string', value)); } - set followRedirects(_value) { - throw new TypeError('The `followRedirects` option does not exist. Use `followRedirect` instead.'); +} +function distribution_assertNonEmptyStringAndNotWhitespace(value, message) { + if (!distribution_isNonEmptyStringAndNotWhitespace(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('non-empty string and not whitespace', value)); } - /** - If exceeded, the request will be aborted and a `MaxRedirectsError` will be thrown. - - @default 10 - */ - get maxRedirects() { - return this._internals.maxRedirects; +} +// eslint-disable-next-line @typescript-eslint/ban-types +function distribution_assertNull(value, message) { + if (!distribution_isNull(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('null', value)); } - set maxRedirects(value) { - assert.number(value); - this._internals.maxRedirects = value; +} +// eslint-disable-next-line @typescript-eslint/ban-types +function distribution_assertNullOrUndefined(value, message) { + if (!distribution_isNullOrUndefined(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('null or undefined', value)); } - /** - A cache adapter instance for storing cached response data. - - @default false - */ - get cache() { - return this._internals.cache; +} +function distribution_assertNumber(value, message) { + if (!distribution_isNumber(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('number', value)); } - set cache(value) { - assert.any([distribution.object, distribution.string, distribution.boolean, distribution.undefined], value); - if (value === true) { - this._internals.cache = globalCache; - } - else if (value === false) { - this._internals.cache = undefined; - } - else { - this._internals.cache = value; - } +} +function distribution_assertNumericString(value, message) { + if (!distribution_isNumericString(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('string with a number', value)); } - /** - Determines if a `got.HTTPError` is thrown for unsuccessful responses. - - If this is disabled, requests that encounter an error status code will be resolved with the `response` instead of throwing. - This may be useful if you are checking for resource availability and are expecting error responses. - - @default true - */ - get throwHttpErrors() { - return this._internals.throwHttpErrors; +} +// eslint-disable-next-line @typescript-eslint/ban-types +function distribution_assertObject(value, message) { + if (!distribution_isObject(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('Object', value)); } - set throwHttpErrors(value) { - assert.boolean(value); - this._internals.throwHttpErrors = value; +} +function distribution_assertObservable(value, message) { + if (!distribution_isObservable(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('Observable', value)); } - get username() { - const url = this._internals.url; - const value = url ? url.username : this._internals.username; - return decodeURIComponent(value); +} +function distribution_assertOddInteger(value, message) { + if (!distribution_isOddInteger(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('odd integer', value)); } - set username(value) { - assert.string(value); - const url = this._internals.url; - const fixedValue = encodeURIComponent(value); - if (url) { - url.username = fixedValue; - } - else { - this._internals.username = fixedValue; - } +} +function distribution_assertPlainObject(value, message) { + if (!distribution_isPlainObject(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('plain object', value)); } - get password() { - const url = this._internals.url; - const value = url ? url.password : this._internals.password; - return decodeURIComponent(value); +} +function distribution_assertPositiveNumber(value, message) { + if (!distribution_isPositiveNumber(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('positive number', value)); } - set password(value) { - assert.string(value); - const url = this._internals.url; - const fixedValue = encodeURIComponent(value); - if (url) { - url.password = fixedValue; - } - else { - this._internals.password = fixedValue; - } +} +function distribution_assertPrimitive(value, message) { + if (!distribution_isPrimitive(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('primitive', value)); } - /** - If set to `true`, Got will additionally accept HTTP2 requests. - - It will choose either HTTP/1.1 or HTTP/2 depending on the ALPN protocol. - - __Note__: This option requires Node.js 15.10.0 or newer as HTTP/2 support on older Node.js versions is very buggy. - - __Note__: Overriding `options.request` will disable HTTP2 support. - - @default false - - @example - ``` - import got from 'got'; - - const {headers} = await got('https://nghttp2.org/httpbin/anything', {http2: true}); - - console.log(headers.via); - //=> '2 nghttpx' - ``` - */ - get http2() { - return this._internals.http2; +} +function distribution_assertPromise(value, message) { + if (!distribution_isPromise(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('Promise', value)); } - set http2(value) { - assert.boolean(value); - this._internals.http2 = value; +} +function distribution_assertPropertyKey(value, message) { + if (!distribution_isPropertyKey(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('PropertyKey', value)); } - /** - Set this to `true` to allow sending body for the `GET` method. - However, the [HTTP/2 specification](https://tools.ietf.org/html/rfc7540#section-8.1.3) says that `An HTTP GET request includes request header fields and no payload body`, therefore when using the HTTP/2 protocol this option will have no effect. - This option is only meant to interact with non-compliant servers when you have no other choice. - - __Note__: The [RFC 7231](https://tools.ietf.org/html/rfc7231#section-4.3.1) doesn't specify any particular behavior for the GET method having a payload, therefore __it's considered an [anti-pattern](https://en.wikipedia.org/wiki/Anti-pattern)__. - - @default false - */ - get allowGetBody() { - return this._internals.allowGetBody; +} +function distribution_assertRegExp(value, message) { + if (!distribution_isRegExp(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('RegExp', value)); + } +} +function distribution_assertSafeInteger(value, message) { + if (!distribution_isSafeInteger(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('integer', value)); + } +} +function distribution_assertSet(value, message) { + if (!distribution_isSet(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('Set', value)); } - set allowGetBody(value) { - assert.boolean(value); - this._internals.allowGetBody = value; +} +function distribution_assertSharedArrayBuffer(value, message) { + if (!distribution_isSharedArrayBuffer(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('SharedArrayBuffer', value)); } - /** - Request headers. - - Existing headers will be overwritten. Headers set to `undefined` will be omitted. - - @default {} - */ - get headers() { - return this._internals.headers; +} +function distribution_assertString(value, message) { + if (!distribution_isString(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('string', value)); } - set headers(value) { - assert.plainObject(value); - if (this._merging) { - Object.assign(this._internals.headers, lowercaseKeys(value)); - } - else { - this._internals.headers = lowercaseKeys(value); - } +} +function distribution_assertSymbol(value, message) { + if (!distribution_isSymbol(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('symbol', value)); } - /** - Specifies if the HTTP request method should be [rewritten as `GET`](https://tools.ietf.org/html/rfc7231#section-6.4) on redirects. - - As the [specification](https://tools.ietf.org/html/rfc7231#section-6.4) prefers to rewrite the HTTP method only on `303` responses, this is Got's default behavior. - Setting `methodRewriting` to `true` will also rewrite `301` and `302` responses, as allowed by the spec. This is the behavior followed by `curl` and browsers. - - __Note__: Got never performs method rewriting on `307` and `308` responses, as this is [explicitly prohibited by the specification](https://www.rfc-editor.org/rfc/rfc7231#section-6.4.7). - - @default false - */ - get methodRewriting() { - return this._internals.methodRewriting; +} +function distribution_assertTruthy(value, message) { + if (!distribution_isTruthy(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('truthy', value)); } - set methodRewriting(value) { - assert.boolean(value); - this._internals.methodRewriting = value; +} +function distribution_assertTupleLike(value, guards, message) { + if (!distribution_isTupleLike(value, guards)) { + throw new TypeError(message ?? distribution_typeErrorMessage('tuple-like', value)); } - /** - Indicates which DNS record family to use. - - Values: - - `undefined`: IPv4 (if present) or IPv6 - - `4`: Only IPv4 - - `6`: Only IPv6 - - @default undefined - */ - get dnsLookupIpVersion() { - return this._internals.dnsLookupIpVersion; +} +function distribution_assertTypedArray(value, message) { + if (!distribution_isTypedArray(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('TypedArray', value)); } - set dnsLookupIpVersion(value) { - if (value !== undefined && value !== 4 && value !== 6) { - throw new TypeError(`Invalid DNS lookup IP version: ${value}`); - } - this._internals.dnsLookupIpVersion = value; +} +function distribution_assertUint16Array(value, message) { + if (!distribution_isUint16Array(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('Uint16Array', value)); } - /** - A function used to parse JSON responses. - - @example - ``` - import got from 'got'; - import Bourne from '@hapi/bourne'; - - const parsed = await got('https://example.com', { - parseJson: text => Bourne.parse(text) - }).json(); - - console.log(parsed); - ``` - */ - get parseJson() { - return this._internals.parseJson; +} +function distribution_assertUint32Array(value, message) { + if (!distribution_isUint32Array(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('Uint32Array', value)); } - set parseJson(value) { - assert["function"](value); - this._internals.parseJson = value; +} +function distribution_assertUint8Array(value, message) { + if (!distribution_isUint8Array(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('Uint8Array', value)); } - /** - A function used to stringify the body of JSON requests. - - @example - ``` - import got from 'got'; - - await got.post('https://example.com', { - stringifyJson: object => JSON.stringify(object, (key, value) => { - if (key.startsWith('_')) { - return; - } - - return value; - }), - json: { - some: 'payload', - _ignoreMe: 1234 - } - }); - ``` - - @example - ``` - import got from 'got'; - - await got.post('https://example.com', { - stringifyJson: object => JSON.stringify(object, (key, value) => { - if (typeof value === 'number') { - return value.toString(); - } - - return value; - }), - json: { - some: 'payload', - number: 1 - } - }); - ``` - */ - get stringifyJson() { - return this._internals.stringifyJson; +} +function distribution_assertUint8ClampedArray(value, message) { + if (!distribution_isUint8ClampedArray(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('Uint8ClampedArray', value)); } - set stringifyJson(value) { - assert["function"](value); - this._internals.stringifyJson = value; +} +function distribution_assertUndefined(value, message) { + if (!distribution_isUndefined(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('undefined', value)); } - /** - An object representing `limit`, `calculateDelay`, `methods`, `statusCodes`, `maxRetryAfter` and `errorCodes` fields for maximum retry count, retry handler, allowed methods, allowed status codes, maximum [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) time and allowed error codes. - - Delays between retries counts with function `1000 * Math.pow(2, retry) + Math.random() * 100`, where `retry` is attempt number (starts from 1). - - The `calculateDelay` property is a `function` that receives an object with `attemptCount`, `retryOptions`, `error` and `computedValue` properties for current retry count, the retry options, error and default computed value. - The function must return a delay in milliseconds (or a Promise resolving with it) (`0` return value cancels retry). - - By default, it retries *only* on the specified methods, status codes, and on these network errors: - - - `ETIMEDOUT`: One of the [timeout](#timeout) limits were reached. - - `ECONNRESET`: Connection was forcibly closed by a peer. - - `EADDRINUSE`: Could not bind to any free port. - - `ECONNREFUSED`: Connection was refused by the server. - - `EPIPE`: The remote side of the stream being written has been closed. - - `ENOTFOUND`: Couldn't resolve the hostname to an IP address. - - `ENETUNREACH`: No internet connection. - - `EAI_AGAIN`: DNS lookup timed out. - - __Note__: If `maxRetryAfter` is set to `undefined`, it will use `options.timeout`. - __Note__: If [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) header is greater than `maxRetryAfter`, it will cancel the request. - */ - get retry() { - return this._internals.retry; +} +function distribution_assertUrlInstance(value, message) { + if (!distribution_isUrlInstance(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('URL', value)); } - set retry(value) { - assert.plainObject(value); - assert.any([distribution["function"], distribution.undefined], value.calculateDelay); - assert.any([distribution.number, distribution.undefined], value.maxRetryAfter); - assert.any([distribution.number, distribution.undefined], value.limit); - assert.any([distribution.array, distribution.undefined], value.methods); - assert.any([distribution.array, distribution.undefined], value.statusCodes); - assert.any([distribution.array, distribution.undefined], value.errorCodes); - assert.any([distribution.number, distribution.undefined], value.noise); - if (value.noise && Math.abs(value.noise) > 100) { - throw new Error(`The maximum acceptable retry noise is +/- 100ms, got ${value.noise}`); - } - for (const key in value) { - if (!(key in this._internals.retry)) { - throw new Error(`Unexpected retry option: ${key}`); - } - } - if (this._merging) { - Object.assign(this._internals.retry, value); - } - else { - this._internals.retry = { ...value }; - } - const { retry } = this._internals; - retry.methods = [...new Set(retry.methods.map(method => method.toUpperCase()))]; - retry.statusCodes = [...new Set(retry.statusCodes)]; - retry.errorCodes = [...new Set(retry.errorCodes)]; +} +// eslint-disable-next-line unicorn/prevent-abbreviations +function distribution_assertUrlSearchParams(value, message) { + if (!distribution_isUrlSearchParams(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('URLSearchParams', value)); } - /** - From `http.RequestOptions`. - - The IP address used to send the request from. - */ - get localAddress() { - return this._internals.localAddress; +} +function distribution_assertUrlString(value, message) { + if (!distribution_isUrlString(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('string with a URL', value)); } - set localAddress(value) { - assert.any([distribution.string, distribution.undefined], value); - this._internals.localAddress = value; +} +function distribution_assertValidDate(value, message) { + if (!distribution_isValidDate(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('valid Date', value)); } - /** - The HTTP method used to make the request. - - @default 'GET' - */ - get method() { - return this._internals.method; +} +function distribution_assertValidLength(value, message) { + if (!distribution_isValidLength(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('valid length', value)); } - set method(value) { - assert.string(value); - this._internals.method = value.toUpperCase(); +} +// eslint-disable-next-line @typescript-eslint/ban-types +function distribution_assertWeakMap(value, message) { + if (!distribution_isWeakMap(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('WeakMap', value)); } - get createConnection() { - return this._internals.createConnection; +} +// eslint-disable-next-line @typescript-eslint/ban-types, unicorn/prevent-abbreviations +function distribution_assertWeakRef(value, message) { + if (!distribution_isWeakRef(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('WeakRef', value)); } - set createConnection(value) { - assert.any([distribution["function"], distribution.undefined], value); - this._internals.createConnection = value; +} +// eslint-disable-next-line @typescript-eslint/ban-types +function distribution_assertWeakSet(value, message) { + if (!distribution_isWeakSet(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('WeakSet', value)); } - /** - From `http-cache-semantics` - - @default {} - */ - get cacheOptions() { - return this._internals.cacheOptions; +} +function distribution_assertWhitespaceString(value, message) { + if (!distribution_isWhitespaceString(value)) { + throw new TypeError(message ?? distribution_typeErrorMessage('whitespace string', value)); } - set cacheOptions(value) { - assert.plainObject(value); - assert.any([distribution.boolean, distribution.undefined], value.shared); - assert.any([distribution.number, distribution.undefined], value.cacheHeuristic); - assert.any([distribution.number, distribution.undefined], value.immutableMinTimeToLive); - assert.any([distribution.boolean, distribution.undefined], value.ignoreCargoCult); - for (const key in value) { - if (!(key in this._internals.cacheOptions)) { - throw new Error(`Cache option \`${key}\` does not exist`); - } - } - if (this._merging) { - Object.assign(this._internals.cacheOptions, value); +} +/* harmony default export */ const is_distribution = (distribution_is); + +;// CONCATENATED MODULE: ./node_modules/.pnpm/got@14.4.2/node_modules/got/dist/source/core/errors.js + +// A hacky check to prevent circular references. +function errors_isRequest(x) { + return is_distribution.object(x) && '_onResponse' in x; +} +/** +An error to be thrown when a request fails. +Contains a `code` property with error class code, like `ECONNREFUSED`. +*/ +class errors_RequestError extends Error { + input; + code; + stack; + response; + request; + timings; + constructor(message, error, self) { + super(message, { cause: error }); + Error.captureStackTrace(this, this.constructor); + this.name = 'RequestError'; + this.code = error.code ?? 'ERR_GOT_REQUEST_ERROR'; + this.input = error.input; + if (errors_isRequest(self)) { + Object.defineProperty(this, 'request', { + enumerable: false, + value: self, + }); + Object.defineProperty(this, 'response', { + enumerable: false, + value: self.response, + }); + this.options = self.options; } else { - this._internals.cacheOptions = { ...value }; + this.options = self; } - } - /** - Options for the advanced HTTPS API. - */ - get https() { - return this._internals.https; - } - set https(value) { - assert.plainObject(value); - assert.any([distribution.boolean, distribution.undefined], value.rejectUnauthorized); - assert.any([distribution["function"], distribution.undefined], value.checkServerIdentity); - assert.any([distribution.string, distribution.object, distribution.array, distribution.undefined], value.certificateAuthority); - assert.any([distribution.string, distribution.object, distribution.array, distribution.undefined], value.key); - assert.any([distribution.string, distribution.object, distribution.array, distribution.undefined], value.certificate); - assert.any([distribution.string, distribution.undefined], value.passphrase); - assert.any([distribution.string, distribution.buffer, distribution.array, distribution.undefined], value.pfx); - assert.any([distribution.array, distribution.undefined], value.alpnProtocols); - assert.any([distribution.string, distribution.undefined], value.ciphers); - assert.any([distribution.string, distribution.buffer, distribution.undefined], value.dhparam); - assert.any([distribution.string, distribution.undefined], value.signatureAlgorithms); - assert.any([distribution.string, distribution.undefined], value.minVersion); - assert.any([distribution.string, distribution.undefined], value.maxVersion); - assert.any([distribution.boolean, distribution.undefined], value.honorCipherOrder); - assert.any([distribution.number, distribution.undefined], value.tlsSessionLifetime); - assert.any([distribution.string, distribution.undefined], value.ecdhCurve); - assert.any([distribution.string, distribution.buffer, distribution.array, distribution.undefined], value.certificateRevocationLists); - for (const key in value) { - if (!(key in this._internals.https)) { - throw new Error(`HTTPS option \`${key}\` does not exist`); + this.timings = this.request?.timings; + // Recover the original stacktrace + if (is_distribution.string(error.stack) && is_distribution.string(this.stack)) { + const indexOfMessage = this.stack.indexOf(this.message) + this.message.length; + const thisStackTrace = this.stack.slice(indexOfMessage).split('\n').reverse(); + const errorStackTrace = error.stack.slice(error.stack.indexOf(error.message) + error.message.length).split('\n').reverse(); + // Remove duplicated traces + while (errorStackTrace.length > 0 && errorStackTrace[0] === thisStackTrace[0]) { + thisStackTrace.shift(); } - } - if (this._merging) { - Object.assign(this._internals.https, value); - } - else { - this._internals.https = { ...value }; + this.stack = `${this.stack.slice(0, indexOfMessage)}${thisStackTrace.reverse().join('\n')}${errorStackTrace.reverse().join('\n')}`; } } - /** - [Encoding](https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings) to be used on `setEncoding` of the response data. - - To get a [`Buffer`](https://nodejs.org/api/buffer.html), you need to set `responseType` to `buffer` instead. - Don't set this option to `null`. - - __Note__: This doesn't affect streams! Instead, you need to do `got.stream(...).setEncoding(encoding)`. - - @default 'utf-8' - */ - get encoding() { - return this._internals.encoding; +} +/** +An error to be thrown when the server redirects you more than ten times. +Includes a `response` property. +*/ +class errors_MaxRedirectsError extends errors_RequestError { + constructor(request) { + super(`Redirected ${request.options.maxRedirects} times. Aborting.`, {}, request); + this.name = 'MaxRedirectsError'; + this.code = 'ERR_TOO_MANY_REDIRECTS'; } - set encoding(value) { - if (value === null) { - throw new TypeError('To get a Buffer, set `options.responseType` to `buffer` instead'); - } - assert.any([distribution.string, distribution.undefined], value); - this._internals.encoding = value; +} +/** +An error to be thrown when the server response code is not 2xx nor 3xx if `options.followRedirect` is `true`, but always except for 304. +Includes a `response` property. +*/ +// TODO: Change `HTTPError` to `HTTPError` in the next major version to enforce type usage. +// eslint-disable-next-line @typescript-eslint/naming-convention +class errors_HTTPError extends errors_RequestError { + constructor(response) { + super(`Response code ${response.statusCode} (${response.statusMessage})`, {}, response.request); + this.name = 'HTTPError'; + this.code = 'ERR_NON_2XX_3XX_RESPONSE'; } - /** - When set to `true` the promise will return the Response body instead of the Response object. - - @default false - */ - get resolveBodyOnly() { - return this._internals.resolveBodyOnly; +} +/** +An error to be thrown when a cache method fails. +For example, if the database goes down or there's a filesystem error. +*/ +class errors_CacheError extends errors_RequestError { + constructor(error, request) { + super(error.message, error, request); + this.name = 'CacheError'; + this.code = this.code === 'ERR_GOT_REQUEST_ERROR' ? 'ERR_CACHE_ACCESS' : this.code; } - set resolveBodyOnly(value) { - assert.boolean(value); - this._internals.resolveBodyOnly = value; +} +/** +An error to be thrown when the request body is a stream and an error occurs while reading from that stream. +*/ +class errors_UploadError extends errors_RequestError { + constructor(error, request) { + super(error.message, error, request); + this.name = 'UploadError'; + this.code = this.code === 'ERR_GOT_REQUEST_ERROR' ? 'ERR_UPLOAD' : this.code; } - /** - Returns a `Stream` instead of a `Promise`. - This is equivalent to calling `got.stream(url, options?)`. - - @default false - */ - get isStream() { - return this._internals.isStream; +} +/** +An error to be thrown when the request is aborted due to a timeout. +Includes an `event` and `timings` property. +*/ +class errors_TimeoutError extends errors_RequestError { + timings; + event; + constructor(error, timings, request) { + super(error.message, error, request); + this.name = 'TimeoutError'; + this.event = error.event; + this.timings = timings; } - set isStream(value) { - assert.boolean(value); - this._internals.isStream = value; +} +/** +An error to be thrown when reading from response stream fails. +*/ +class errors_ReadError extends errors_RequestError { + constructor(error, request) { + super(error.message, error, request); + this.name = 'ReadError'; + this.code = this.code === 'ERR_GOT_REQUEST_ERROR' ? 'ERR_READING_RESPONSE_STREAM' : this.code; } - /** - The parsing method. +} +/** +An error which always triggers a new retry when thrown. +*/ +class errors_RetryError extends errors_RequestError { + constructor(request) { + super('Retrying', {}, request); + this.name = 'RetryError'; + this.code = 'ERR_RETRYING'; + } +} +/** +An error to be thrown when the request is aborted by AbortController. +*/ +class errors_AbortError extends errors_RequestError { + constructor(request) { + super('This operation was aborted.', {}, request); + this.code = 'ERR_ABORTED'; + this.name = 'AbortError'; + } +} - The promise also has `.text()`, `.json()` and `.buffer()` methods which return another Got promise for the parsed body. +;// CONCATENATED MODULE: ./node_modules/.pnpm/got@14.4.2/node_modules/got/dist/source/core/utils/is-form-data.js - It's like setting the options to `{responseType: 'json', resolveBodyOnly: true}` but without affecting the main Got promise. +function utils_is_form_data_isFormData(body) { + return is_distribution.nodeStream(body) && is_distribution["function"](body.getBoundary); +} - __Note__: When using streams, this option is ignored. +;// CONCATENATED MODULE: ./node_modules/.pnpm/got@14.4.2/node_modules/got/dist/source/core/utils/get-body-size.js - @example - ``` - const responsePromise = got(url); - const bufferPromise = responsePromise.buffer(); - const jsonPromise = responsePromise.json(); - const [response, buffer, json] = Promise.all([responsePromise, bufferPromise, jsonPromise]); - // `response` is an instance of Got Response - // `buffer` is an instance of Buffer - // `json` is an object - ``` - @example - ``` - // This - const body = await got(url).json(); - // is semantically the same as this - const body = await got(url, {responseType: 'json', resolveBodyOnly: true}); - ``` - */ - get responseType() { - return this._internals.responseType; +async function get_body_size_getBodySize(body, headers) { + if (headers && 'content-length' in headers) { + return Number(headers['content-length']); } - set responseType(value) { - if (value === undefined) { - this._internals.responseType = 'text'; - return; - } - if (value !== 'text' && value !== 'buffer' && value !== 'json') { - throw new Error(`Invalid \`responseType\` option: ${value}`); + if (!body) { + return 0; + } + if (is_distribution.string(body)) { + return external_node_buffer_namespaceObject.Buffer.byteLength(body); + } + if (is_distribution.buffer(body)) { + return body.length; + } + if (utils_is_form_data_isFormData(body)) { + return (0,external_node_util_.promisify)(body.getLength.bind(body))(); + } + return undefined; +} + +;// CONCATENATED MODULE: ./node_modules/.pnpm/got@14.4.2/node_modules/got/dist/source/core/utils/proxy-events.js +function proxy_events_proxyEvents(from, to, events) { + const eventFunctions = {}; + for (const event of events) { + const eventFunction = (...arguments_) => { + to.emit(event, ...arguments_); + }; + eventFunctions[event] = eventFunction; + from.on(event, eventFunction); + } + return () => { + for (const [event, eventFunction] of Object.entries(eventFunctions)) { + from.off(event, eventFunction); } - this._internals.responseType = value; + }; +} + +;// CONCATENATED MODULE: ./node_modules/.pnpm/got@14.4.2/node_modules/got/dist/source/core/utils/unhandle.js +// When attaching listeners, it's very easy to forget about them. +// Especially if you do error handling and set timeouts. +// So instead of checking if it's proper to throw an error on every timeout ever, +// use this simple tool which will remove all listeners you have attached. +function unhandle_unhandle() { + const handlers = []; + return { + once(origin, event, function_) { + origin.once(event, function_); + handlers.push({ origin, event, fn: function_ }); + }, + unhandleAll() { + for (const handler of handlers) { + const { origin, event, fn } = handler; + origin.removeListener(event, fn); + } + handlers.length = 0; + }, + }; +} + +;// CONCATENATED MODULE: ./node_modules/.pnpm/got@14.4.2/node_modules/got/dist/source/core/timed-out.js + + +const timed_out_reentry = Symbol('reentry'); +const core_timed_out_noop = () => { }; +class core_timed_out_TimeoutError extends Error { + event; + code; + constructor(threshold, event) { + super(`Timeout awaiting '${event}' for ${threshold}ms`); + this.event = event; + this.name = 'TimeoutError'; + this.code = 'ETIMEDOUT'; } - get pagination() { - return this._internals.pagination; +} +function timed_out_timedOut(request, delays, options) { + if (timed_out_reentry in request) { + return core_timed_out_noop; } - set pagination(value) { - assert.object(value); - if (this._merging) { - Object.assign(this._internals.pagination, value); + request[timed_out_reentry] = true; + const cancelers = []; + const { once, unhandleAll } = unhandle_unhandle(); + const addTimeout = (delay, callback, event) => { + const timeout = setTimeout(callback, delay, delay, event); + timeout.unref?.(); + const cancel = () => { + clearTimeout(timeout); + }; + cancelers.push(cancel); + return cancel; + }; + const { host, hostname } = options; + const timeoutHandler = (delay, event) => { + request.destroy(new core_timed_out_TimeoutError(delay, event)); + }; + const cancelTimeouts = () => { + for (const cancel of cancelers) { + cancel(); } - else { - this._internals.pagination = value; + unhandleAll(); + }; + request.once('error', error => { + cancelTimeouts(); + // Save original behavior + /* istanbul ignore next */ + if (request.listenerCount('error') === 0) { + throw error; } + }); + if (delays.request !== undefined) { + const cancelTimeout = addTimeout(delays.request, timeoutHandler, 'request'); + once(request, 'response', (response) => { + once(response, 'end', cancelTimeout); + }); } - get auth() { - throw new Error('Parameter `auth` is deprecated. Use `username` / `password` instead.'); - } - set auth(_value) { - throw new Error('Parameter `auth` is deprecated. Use `username` / `password` instead.'); - } - get setHost() { - return this._internals.setHost; - } - set setHost(value) { - assert.boolean(value); - this._internals.setHost = value; + if (delays.socket !== undefined) { + const { socket } = delays; + const socketTimeoutHandler = () => { + timeoutHandler(socket, 'socket'); + }; + request.setTimeout(socket, socketTimeoutHandler); + // `request.setTimeout(0)` causes a memory leak. + // We can just remove the listener and forget about the timer - it's unreffed. + // See https://github.com/sindresorhus/got/issues/690 + cancelers.push(() => { + request.removeListener('timeout', socketTimeoutHandler); + }); } - get maxHeaderSize() { - return this._internals.maxHeaderSize; + const hasLookup = delays.lookup !== undefined; + const hasConnect = delays.connect !== undefined; + const hasSecureConnect = delays.secureConnect !== undefined; + const hasSend = delays.send !== undefined; + if (hasLookup || hasConnect || hasSecureConnect || hasSend) { + once(request, 'socket', (socket) => { + const { socketPath } = request; + /* istanbul ignore next: hard to test */ + if (socket.connecting) { + const hasPath = Boolean(socketPath ?? external_node_net_namespaceObject.isIP(hostname ?? host ?? '') !== 0); + if (hasLookup && !hasPath && socket.address().address === undefined) { + const cancelTimeout = addTimeout(delays.lookup, timeoutHandler, 'lookup'); + once(socket, 'lookup', cancelTimeout); + } + if (hasConnect) { + const timeConnect = () => addTimeout(delays.connect, timeoutHandler, 'connect'); + if (hasPath) { + once(socket, 'connect', timeConnect()); + } + else { + once(socket, 'lookup', (error) => { + if (error === null) { + once(socket, 'connect', timeConnect()); + } + }); + } + } + if (hasSecureConnect && options.protocol === 'https:') { + once(socket, 'connect', () => { + const cancelTimeout = addTimeout(delays.secureConnect, timeoutHandler, 'secureConnect'); + once(socket, 'secureConnect', cancelTimeout); + }); + } + } + if (hasSend) { + const timeRequest = () => addTimeout(delays.send, timeoutHandler, 'send'); + /* istanbul ignore next: hard to test */ + if (socket.connecting) { + once(socket, 'connect', () => { + once(request, 'upload-complete', timeRequest()); + }); + } + else { + once(request, 'upload-complete', timeRequest()); + } + } + }); } - set maxHeaderSize(value) { - assert.any([distribution.number, distribution.undefined], value); - this._internals.maxHeaderSize = value; + if (delays.response !== undefined) { + once(request, 'upload-complete', () => { + const cancelTimeout = addTimeout(delays.response, timeoutHandler, 'response'); + once(request, 'response', cancelTimeout); + }); } - get enableUnixSockets() { - return this._internals.enableUnixSockets; + if (delays.read !== undefined) { + once(request, 'response', (response) => { + const cancelTimeout = addTimeout(delays.read, timeoutHandler, 'read'); + once(response, 'end', cancelTimeout); + }); } - set enableUnixSockets(value) { - assert.boolean(value); - this._internals.enableUnixSockets = value; + return cancelTimeouts; +} + +;// CONCATENATED MODULE: ./node_modules/.pnpm/got@14.4.2/node_modules/got/dist/source/core/utils/url-to-options.js + +function url_to_options_urlToOptions(url) { + // Cast to URL + url = url; + const options = { + protocol: url.protocol, + hostname: is_distribution.string(url.hostname) && url.hostname.startsWith('[') ? url.hostname.slice(1, -1) : url.hostname, + host: url.host, + hash: url.hash, + search: url.search, + pathname: url.pathname, + href: url.href, + path: `${url.pathname || ''}${url.search || ''}`, + }; + if (is_distribution.string(url.port) && url.port.length > 0) { + options.port = Number(url.port); } - // eslint-disable-next-line @typescript-eslint/naming-convention - toJSON() { - return { ...this._internals }; + if (url.username || url.password) { + options.auth = `${url.username || ''}:${url.password || ''}`; } - [Symbol.for('nodejs.util.inspect.custom')](_depth, options) { - return (0,external_node_util_.inspect)(this._internals, options); + return options; +} + +;// CONCATENATED MODULE: ./node_modules/.pnpm/got@14.4.2/node_modules/got/dist/source/core/utils/weakable-map.js +class weakable_map_WeakableMap { + weakMap; + map; + constructor() { + this.weakMap = new WeakMap(); + this.map = new Map(); } - createNativeRequestOptions() { - const internals = this._internals; - const url = internals.url; - let agent; - if (url.protocol === 'https:') { - agent = internals.http2 ? internals.agent : internals.agent.https; + set(key, value) { + if (typeof key === 'object') { + this.weakMap.set(key, value); } else { - agent = internals.agent.http; - } - const { https } = internals; - let { pfx } = https; - if (distribution.array(pfx) && distribution.plainObject(pfx[0])) { - pfx = pfx.map(object => ({ - buf: object.buffer, - passphrase: object.passphrase, - })); + this.map.set(key, value); } - return { - ...internals.cacheOptions, - ...this._unixOptions, - // HTTPS options - // eslint-disable-next-line @typescript-eslint/naming-convention - ALPNProtocols: https.alpnProtocols, - ca: https.certificateAuthority, - cert: https.certificate, - key: https.key, - passphrase: https.passphrase, - pfx: https.pfx, - rejectUnauthorized: https.rejectUnauthorized, - checkServerIdentity: https.checkServerIdentity ?? external_node_tls_namespaceObject.checkServerIdentity, - ciphers: https.ciphers, - honorCipherOrder: https.honorCipherOrder, - minVersion: https.minVersion, - maxVersion: https.maxVersion, - sigalgs: https.signatureAlgorithms, - sessionTimeout: https.tlsSessionLifetime, - dhparam: https.dhparam, - ecdhCurve: https.ecdhCurve, - crl: https.certificateRevocationLists, - // HTTP options - lookup: internals.dnsLookup ?? internals.dnsCache?.lookup, - family: internals.dnsLookupIpVersion, - agent, - setHost: internals.setHost, - method: internals.method, - maxHeaderSize: internals.maxHeaderSize, - localAddress: internals.localAddress, - headers: internals.headers, - createConnection: internals.createConnection, - timeout: internals.http2 ? getHttp2TimeoutOption(internals) : undefined, - // HTTP/2 options - h2session: internals.h2session, - }; } - getRequestFunction() { - const url = this._internals.url; - const { request } = this._internals; - if (!request && url) { - return this.getFallbackRequestFunction(); + get(key) { + if (typeof key === 'object') { + return this.weakMap.get(key); } - return request; + return this.map.get(key); } - getFallbackRequestFunction() { - const url = this._internals.url; - if (!url) { - return; - } - if (url.protocol === 'https:') { - if (this._internals.http2) { - if (major < 15 || (major === 15 && minor < 10)) { - const error = new Error('To use the `http2` option, install Node.js 15.10.0 or above'); - error.code = 'EUNSUPPORTED'; - throw error; - } - return http2_wrapper_source.auto; - } - return external_node_https_.request; + has(key) { + if (typeof key === 'object') { + return this.weakMap.has(key); } - return external_node_http_.request; - } - freeze() { - const options = this._internals; - Object.freeze(options); - Object.freeze(options.hooks); - Object.freeze(options.hooks.afterResponse); - Object.freeze(options.hooks.beforeError); - Object.freeze(options.hooks.beforeRedirect); - Object.freeze(options.hooks.beforeRequest); - Object.freeze(options.hooks.beforeRetry); - Object.freeze(options.hooks.init); - Object.freeze(options.https); - Object.freeze(options.cacheOptions); - Object.freeze(options.agent); - Object.freeze(options.headers); - Object.freeze(options.timeout); - Object.freeze(options.retry); - Object.freeze(options.retry.errorCodes); - Object.freeze(options.retry.methods); - Object.freeze(options.retry.statusCodes); + return this.map.has(key); } } -;// CONCATENATED MODULE: ./node_modules/.pnpm/got@14.4.2/node_modules/got/dist/source/core/response.js - -const isResponseOk = (response) => { - const { statusCode } = response; - const { followRedirect } = response.request.options; - const shouldFollow = typeof followRedirect === 'function' ? followRedirect(response) : followRedirect; - const limitStatusCode = shouldFollow ? 299 : 399; - return (statusCode >= 200 && statusCode <= limitStatusCode) || statusCode === 304; -}; -/** -An error to be thrown when server response code is 2xx, and parsing body fails. -Includes a `response` property. -*/ -class ParseError extends RequestError { - constructor(error, response) { - const { options } = response.request; - super(`${error.message} in "${options.url.toString()}"`, error, response.request); - this.name = 'ParseError'; - this.code = 'ERR_BODY_PARSE_FAILURE'; +;// CONCATENATED MODULE: ./node_modules/.pnpm/got@14.4.2/node_modules/got/dist/source/core/calculate-retry-delay.js +const calculate_retry_delay_calculateRetryDelay = ({ attemptCount, retryOptions, error, retryAfter, computedValue, }) => { + if (error.name === 'RetryError') { + return 1; } -} -const parseBody = (response, responseType, parseJson, encoding) => { - const { rawBody } = response; - try { - if (responseType === 'text') { - return rawBody.toString(encoding); - } - if (responseType === 'json') { - return rawBody.length === 0 ? '' : parseJson(rawBody.toString(encoding)); + if (attemptCount > retryOptions.limit) { + return 0; + } + const hasMethod = retryOptions.methods.includes(error.options.method); + const hasErrorCode = retryOptions.errorCodes.includes(error.code); + const hasStatusCode = error.response && retryOptions.statusCodes.includes(error.response.statusCode); + if (!hasMethod || (!hasErrorCode && !hasStatusCode)) { + return 0; + } + if (error.response) { + if (retryAfter) { + // In this case `computedValue` is `options.request.timeout` + if (retryAfter > computedValue) { + return 0; + } + return retryAfter; } - if (responseType === 'buffer') { - return rawBody; + if (error.response.statusCode === 413) { + return 0; } } - catch (error) { - throw new ParseError(error, response); - } - throw new ParseError({ - message: `Unknown body type '${responseType}'`, - name: 'Error', - }, response); + const noise = Math.random() * retryOptions.noise; + return Math.min(((2 ** (attemptCount - 1)) * 1000), retryOptions.backoffLimit) + noise; }; +/* harmony default export */ const core_calculate_retry_delay = (calculate_retry_delay_calculateRetryDelay); -;// CONCATENATED MODULE: ./node_modules/.pnpm/got@14.4.2/node_modules/got/dist/source/core/utils/is-client-request.js -function isClientRequest(clientRequest) { - return clientRequest.writable && !clientRequest.writableEnded; -} -/* harmony default export */ const is_client_request = (isClientRequest); - -;// CONCATENATED MODULE: ./node_modules/.pnpm/got@14.4.2/node_modules/got/dist/source/core/utils/is-unix-socket-url.js -// eslint-disable-next-line @typescript-eslint/naming-convention -function isUnixSocketURL(url) { - return url.protocol === 'unix:' || url.hostname === 'unix'; +;// CONCATENATED MODULE: ./node_modules/.pnpm/got@14.4.2/node_modules/got/dist/source/core/parse-link-header.js +function parse_link_header_parseLinkHeader(link) { + const parsed = []; + const items = link.split(','); + for (const item of items) { + // https://tools.ietf.org/html/rfc5988#section-5 + const [rawUriReference, ...rawLinkParameters] = item.split(';'); + const trimmedUriReference = rawUriReference.trim(); + // eslint-disable-next-line @typescript-eslint/prefer-string-starts-ends-with + if (trimmedUriReference[0] !== '<' || trimmedUriReference.at(-1) !== '>') { + throw new Error(`Invalid format of the Link header reference: ${trimmedUriReference}`); + } + const reference = trimmedUriReference.slice(1, -1); + const parameters = {}; + if (rawLinkParameters.length === 0) { + throw new Error(`Unexpected end of Link header parameters: ${rawLinkParameters.join(';')}`); + } + for (const rawParameter of rawLinkParameters) { + const trimmedRawParameter = rawParameter.trim(); + const center = trimmedRawParameter.indexOf('='); + if (center === -1) { + throw new Error(`Failed to parse Link header: ${link}`); + } + const name = trimmedRawParameter.slice(0, center).trim(); + const value = trimmedRawParameter.slice(center + 1).trim(); + parameters[name] = value; + } + parsed.push({ + reference, + parameters, + }); + } + return parsed; } -;// CONCATENATED MODULE: ./node_modules/.pnpm/got@14.4.2/node_modules/got/dist/source/core/index.js - - - - - - - - - - +;// CONCATENATED MODULE: ./node_modules/.pnpm/got@14.4.2/node_modules/got/dist/source/core/options.js +// DO NOT use destructuring for `https.request` and `http.request` as it's not compatible with `nock`. @@ -82910,2233 +88728,1688 @@ function isUnixSocketURL(url) { -const supportsBrotli = distribution.string(external_node_process_.versions.brotli); -const methodsWithoutBody = new Set(['GET', 'HEAD']); -const cacheableStore = new WeakableMap(); -const redirectCodes = new Set([300, 301, 302, 303, 304, 307, 308]); -const proxiedRequestEvents = [ - 'socket', - 'connect', - 'continue', - 'information', - 'upgrade', -]; -const core_noop = () => { }; -class Request extends external_node_stream_.Duplex { - // @ts-expect-error - Ignoring for now. - ['constructor']; - _noPipe; - // @ts-expect-error https://github.com/microsoft/TypeScript/issues/9568 - options; - response; - requestUrl; - redirectUrls; - retryCount; - _stopRetry; - _downloadedSize; - _uploadedSize; - _stopReading; - _pipedServerResponses; - _request; - _responseSize; - _bodySize; - _unproxyEvents; - _isFromCache; - _cannotHaveBody; - _triggerRead; - _cancelTimeouts; - _removeListeners; - _nativeResponse; - _flushed; - _aborted; - // We need this because `this._request` if `undefined` when using cache - _requestInitialized; - constructor(url, options, defaults) { - super({ - // Don't destroy immediately, as the error may be emitted on unsuccessful retry - autoDestroy: false, - // It needs to be zero because we're just proxying the data to another stream - highWaterMark: 0, - }); - this._downloadedSize = 0; - this._uploadedSize = 0; - this._stopReading = false; - this._pipedServerResponses = new Set(); - this._cannotHaveBody = false; - this._unproxyEvents = core_noop; - this._triggerRead = false; - this._cancelTimeouts = core_noop; - this._removeListeners = core_noop; - this._jobs = []; - this._flushed = false; - this._requestInitialized = false; - this._aborted = false; - this.redirectUrls = []; - this.retryCount = 0; - this._stopRetry = core_noop; - this.on('pipe', (source) => { - if (source?.headers) { - Object.assign(this.options.headers, source.headers); - } - }); - this.on('newListener', event => { - if (event === 'retry' && this.listenerCount('retry') > 0) { - throw new Error('A retry listener has been attached already.'); - } - }); - try { - this.options = new Options(url, options, defaults); - if (!this.options.url) { - if (this.options.prefixUrl === '') { - throw new TypeError('Missing `url` property'); - } - this.options.url = ''; - } - this.requestUrl = this.options.url; - } - catch (error) { - const { options } = error; - if (options) { - this.options = options; +const [options_major, options_minor] = external_node_process_.versions.node.split('.').map(Number); +function options_validateSearchParameters(searchParameters) { + // eslint-disable-next-line guard-for-in + for (const key in searchParameters) { + const value = searchParameters[key]; + distribution_assert.any([is_distribution.string, is_distribution.number, is_distribution.boolean, is_distribution["null"], is_distribution.undefined], value); + } +} +const options_globalCache = new Map(); +let options_globalDnsCache; +const options_getGlobalDnsCache = () => { + if (options_globalDnsCache) { + return options_globalDnsCache; + } + options_globalDnsCache = new CacheableLookup(); + return options_globalDnsCache; +}; +const options_defaultInternals = { + request: undefined, + agent: { + http: undefined, + https: undefined, + http2: undefined, + }, + h2session: undefined, + decompress: true, + timeout: { + connect: undefined, + lookup: undefined, + read: undefined, + request: undefined, + response: undefined, + secureConnect: undefined, + send: undefined, + socket: undefined, + }, + prefixUrl: '', + body: undefined, + form: undefined, + json: undefined, + cookieJar: undefined, + ignoreInvalidCookies: false, + searchParams: undefined, + dnsLookup: undefined, + dnsCache: undefined, + context: {}, + hooks: { + init: [], + beforeRequest: [], + beforeError: [], + beforeRedirect: [], + beforeRetry: [], + afterResponse: [], + }, + followRedirect: true, + maxRedirects: 10, + cache: undefined, + throwHttpErrors: true, + username: '', + password: '', + http2: false, + allowGetBody: false, + headers: { + 'user-agent': 'got (https://github.com/sindresorhus/got)', + }, + methodRewriting: false, + dnsLookupIpVersion: undefined, + parseJson: JSON.parse, + stringifyJson: JSON.stringify, + retry: { + limit: 2, + methods: [ + 'GET', + 'PUT', + 'HEAD', + 'DELETE', + 'OPTIONS', + 'TRACE', + ], + statusCodes: [ + 408, + 413, + 429, + 500, + 502, + 503, + 504, + 521, + 522, + 524, + ], + errorCodes: [ + 'ETIMEDOUT', + 'ECONNRESET', + 'EADDRINUSE', + 'ECONNREFUSED', + 'EPIPE', + 'ENOTFOUND', + 'ENETUNREACH', + 'EAI_AGAIN', + ], + maxRetryAfter: undefined, + calculateDelay: ({ computedValue }) => computedValue, + backoffLimit: Number.POSITIVE_INFINITY, + noise: 100, + }, + localAddress: undefined, + method: 'GET', + createConnection: undefined, + cacheOptions: { + shared: undefined, + cacheHeuristic: undefined, + immutableMinTimeToLive: undefined, + ignoreCargoCult: undefined, + }, + https: { + alpnProtocols: undefined, + rejectUnauthorized: undefined, + checkServerIdentity: undefined, + certificateAuthority: undefined, + key: undefined, + certificate: undefined, + passphrase: undefined, + pfx: undefined, + ciphers: undefined, + honorCipherOrder: undefined, + minVersion: undefined, + maxVersion: undefined, + signatureAlgorithms: undefined, + tlsSessionLifetime: undefined, + dhparam: undefined, + ecdhCurve: undefined, + certificateRevocationLists: undefined, + }, + encoding: undefined, + resolveBodyOnly: false, + isStream: false, + responseType: 'text', + url: undefined, + pagination: { + transform(response) { + if (response.request.options.responseType === 'json') { + return response.body; } - this.flush = async () => { - this.flush = async () => { }; - this.destroy(error); - }; - return; - } - // Important! If you replace `body` in a handler with another stream, make sure it's readable first. - // The below is run only once. - const { body } = this.options; - if (distribution.nodeStream(body)) { - body.once('error', error => { - if (this._flushed) { - this._beforeError(new UploadError(error, this)); - } - else { - this.flush = async () => { - this.flush = async () => { }; - this._beforeError(new UploadError(error, this)); - }; - } - }); - } - if (this.options.signal) { - const abort = () => { - this.destroy(new AbortError(this)); - }; - if (this.options.signal.aborted) { - abort(); + return JSON.parse(response.body); + }, + paginate({ response }) { + const rawLinkHeader = response.headers.link; + if (typeof rawLinkHeader !== 'string' || rawLinkHeader.trim() === '') { + return false; } - else { - this.options.signal.addEventListener('abort', abort); - this._removeListeners = () => { - this.options.signal?.removeEventListener('abort', abort); + const parsed = parse_link_header_parseLinkHeader(rawLinkHeader); + const next = parsed.find(entry => entry.parameters.rel === 'next' || entry.parameters.rel === '"next"'); + if (next) { + return { + url: new URL(next.reference, response.url), }; } - } + return false; + }, + filter: () => true, + shouldContinue: () => true, + countLimit: Number.POSITIVE_INFINITY, + backoff: 0, + requestLimit: 10_000, + stackAllItems: false, + }, + setHost: true, + maxHeaderSize: undefined, + signal: undefined, + enableUnixSockets: false, +}; +const options_cloneInternals = (internals) => { + const { hooks, retry } = internals; + const result = { + ...internals, + context: { ...internals.context }, + cacheOptions: { ...internals.cacheOptions }, + https: { ...internals.https }, + agent: { ...internals.agent }, + headers: { ...internals.headers }, + retry: { + ...retry, + errorCodes: [...retry.errorCodes], + methods: [...retry.methods], + statusCodes: [...retry.statusCodes], + }, + timeout: { ...internals.timeout }, + hooks: { + init: [...hooks.init], + beforeRequest: [...hooks.beforeRequest], + beforeError: [...hooks.beforeError], + beforeRedirect: [...hooks.beforeRedirect], + beforeRetry: [...hooks.beforeRetry], + afterResponse: [...hooks.afterResponse], + }, + searchParams: internals.searchParams ? new URLSearchParams(internals.searchParams) : undefined, + pagination: { ...internals.pagination }, + }; + if (result.url !== undefined) { + result.prefixUrl = ''; } - async flush() { - if (this._flushed) { - return; - } - this._flushed = true; - try { - await this._finalizeBody(); - if (this.destroyed) { - return; - } - await this._makeRequest(); - if (this.destroyed) { - this._request?.destroy(); - return; - } - // Queued writes etc. - for (const job of this._jobs) { - job(); - } - // Prevent memory leak - this._jobs.length = 0; - this._requestInitialized = true; - } - catch (error) { - this._beforeError(error); - } + return result; +}; +const options_cloneRaw = (raw) => { + const { hooks, retry } = raw; + const result = { ...raw }; + if (is_distribution.object(raw.context)) { + result.context = { ...raw.context }; } - _beforeError(error) { - if (this._stopReading) { - return; - } - const { response, options } = this; - const attemptCount = this.retryCount + (error.name === 'RetryError' ? 0 : 1); - this._stopReading = true; - if (!(error instanceof RequestError)) { - error = new RequestError(error.message, error, this); - } - const typedError = error; - void (async () => { - // Node.js parser is really weird. - // It emits post-request Parse Errors on the same instance as previous request. WTF. - // Therefore, we need to check if it has been destroyed as well. - // - // Furthermore, Node.js 16 `response.destroy()` doesn't immediately destroy the socket, - // but makes the response unreadable. So we additionally need to check `response.readable`. - if (response?.readable && !response.rawBody && !this._request?.socket?.destroyed) { - // @types/node has incorrect typings. `setEncoding` accepts `null` as well. - response.setEncoding(this.readableEncoding); - const success = await this._setRawBody(response); - if (success) { - response.body = response.rawBody.toString(); - } - } - if (this.listenerCount('retry') !== 0) { - let backoff; - try { - let retryAfter; - if (response && 'retry-after' in response.headers) { - retryAfter = Number(response.headers['retry-after']); - if (Number.isNaN(retryAfter)) { - retryAfter = Date.parse(response.headers['retry-after']) - Date.now(); - if (retryAfter <= 0) { - retryAfter = 1; - } - } - else { - retryAfter *= 1000; - } - } - const retryOptions = options.retry; - backoff = await retryOptions.calculateDelay({ - attemptCount, - retryOptions, - error: typedError, - retryAfter, - computedValue: calculate_retry_delay({ - attemptCount, - retryOptions, - error: typedError, - retryAfter, - computedValue: retryOptions.maxRetryAfter ?? options.timeout.request ?? Number.POSITIVE_INFINITY, - }), - }); - } - catch (error_) { - void this._error(new RequestError(error_.message, error_, this)); - return; - } - if (backoff) { - await new Promise(resolve => { - const timeout = setTimeout(resolve, backoff); - this._stopRetry = () => { - clearTimeout(timeout); - resolve(); - }; - }); - // Something forced us to abort the retry - if (this.destroyed) { - return; - } - try { - for (const hook of this.options.hooks.beforeRetry) { - // eslint-disable-next-line no-await-in-loop - await hook(typedError, this.retryCount + 1); - } - } - catch (error_) { - void this._error(new RequestError(error_.message, error, this)); - return; - } - // Something forced us to abort the retry - if (this.destroyed) { - return; - } - this.destroy(); - this.emit('retry', this.retryCount + 1, error, (updatedOptions) => { - const request = new Request(options.url, updatedOptions, options); - request.retryCount = this.retryCount + 1; - external_node_process_.nextTick(() => { - void request.flush(); - }); - return request; - }); - return; - } - } - void this._error(typedError); - })(); + if (is_distribution.object(raw.cacheOptions)) { + result.cacheOptions = { ...raw.cacheOptions }; } - _read() { - this._triggerRead = true; - const { response } = this; - if (response && !this._stopReading) { - // We cannot put this in the `if` above - // because `.read()` also triggers the `end` event - if (response.readableLength) { - this._triggerRead = false; - } - let data; - while ((data = response.read()) !== null) { - this._downloadedSize += data.length; // eslint-disable-line @typescript-eslint/restrict-plus-operands - const progress = this.downloadProgress; - if (progress.percent < 1) { - this.emit('downloadProgress', progress); - } - this.push(data); - } - } + if (is_distribution.object(raw.https)) { + result.https = { ...raw.https }; } - _write(chunk, encoding, callback) { - const write = () => { - this._writeRequest(chunk, encoding, callback); - }; - if (this._requestInitialized) { - write(); + if (is_distribution.object(raw.cacheOptions)) { + result.cacheOptions = { ...result.cacheOptions }; + } + if (is_distribution.object(raw.agent)) { + result.agent = { ...raw.agent }; + } + if (is_distribution.object(raw.headers)) { + result.headers = { ...raw.headers }; + } + if (is_distribution.object(retry)) { + result.retry = { ...retry }; + if (is_distribution.array(retry.errorCodes)) { + result.retry.errorCodes = [...retry.errorCodes]; } - else { - this._jobs.push(write); + if (is_distribution.array(retry.methods)) { + result.retry.methods = [...retry.methods]; + } + if (is_distribution.array(retry.statusCodes)) { + result.retry.statusCodes = [...retry.statusCodes]; } } - _final(callback) { - const endRequest = () => { - // We need to check if `this._request` is present, - // because it isn't when we use cache. - if (!this._request || this._request.destroyed) { - callback(); - return; - } - this._request.end((error) => { - // The request has been destroyed before `_final` finished. - // See https://github.com/nodejs/node/issues/39356 - if (this._request._writableState?.errored) { - return; - } - if (!error) { - this._bodySize = this._uploadedSize; - this.emit('uploadProgress', this.uploadProgress); - this._request.emit('upload-complete'); - } - callback(error); - }); + if (is_distribution.object(raw.timeout)) { + result.timeout = { ...raw.timeout }; + } + if (is_distribution.object(hooks)) { + result.hooks = { + ...hooks, }; - if (this._requestInitialized) { - endRequest(); + if (is_distribution.array(hooks.init)) { + result.hooks.init = [...hooks.init]; } - else { - this._jobs.push(endRequest); + if (is_distribution.array(hooks.beforeRequest)) { + result.hooks.beforeRequest = [...hooks.beforeRequest]; } - } - _destroy(error, callback) { - this._stopReading = true; - this.flush = async () => { }; - // Prevent further retries - this._stopRetry(); - this._cancelTimeouts(); - this._removeListeners(); - if (this.options) { - const { body } = this.options; - if (distribution.nodeStream(body)) { - body.destroy(); - } + if (is_distribution.array(hooks.beforeError)) { + result.hooks.beforeError = [...hooks.beforeError]; } - if (this._request) { - this._request.destroy(); + if (is_distribution.array(hooks.beforeRedirect)) { + result.hooks.beforeRedirect = [...hooks.beforeRedirect]; } - if (error !== null && !distribution.undefined(error) && !(error instanceof RequestError)) { - error = new RequestError(error.message, error, this); + if (is_distribution.array(hooks.beforeRetry)) { + result.hooks.beforeRetry = [...hooks.beforeRetry]; } - callback(error); - } - pipe(destination, options) { - if (destination instanceof external_node_http_.ServerResponse) { - this._pipedServerResponses.add(destination); + if (is_distribution.array(hooks.afterResponse)) { + result.hooks.afterResponse = [...hooks.afterResponse]; } - return super.pipe(destination, options); } - unpipe(destination) { - if (destination instanceof external_node_http_.ServerResponse) { - this._pipedServerResponses.delete(destination); + // TODO: raw.searchParams + if (is_distribution.object(raw.pagination)) { + result.pagination = { ...raw.pagination }; + } + return result; +}; +const options_getHttp2TimeoutOption = (internals) => { + const delays = [internals.timeout.socket, internals.timeout.connect, internals.timeout.lookup, internals.timeout.request, internals.timeout.secureConnect].filter(delay => typeof delay === 'number'); + if (delays.length > 0) { + return Math.min(...delays); + } + return undefined; +}; +const options_init = (options, withOptions, self) => { + const initHooks = options.hooks?.init; + if (initHooks) { + for (const hook of initHooks) { + hook(withOptions, self); } - super.unpipe(destination); - return this; } - async _finalizeBody() { - const { options } = this; - const { headers } = options; - const isForm = !distribution.undefined(options.form); - // eslint-disable-next-line @typescript-eslint/naming-convention - const isJSON = !distribution.undefined(options.json); - const isBody = !distribution.undefined(options.body); - const cannotHaveBody = methodsWithoutBody.has(options.method) && !(options.method === 'GET' && options.allowGetBody); - this._cannotHaveBody = cannotHaveBody; - if (isForm || isJSON || isBody) { - if (cannotHaveBody) { - throw new TypeError(`The \`${options.method}\` method cannot be used with a body`); - } - // Serialize body - const noContentType = !distribution.string(headers['content-type']); - if (isBody) { - // Body is spec-compliant FormData - if (lib_isFormData(options.body)) { - const encoder = new FormDataEncoder(options.body); - if (noContentType) { - headers['content-type'] = encoder.headers['Content-Type']; - } - if ('Content-Length' in encoder.headers) { - headers['content-length'] = encoder.headers['Content-Length']; - } - options.body = encoder.encode(); - } - // Special case for https://github.com/form-data/form-data - if (is_form_data_isFormData(options.body) && noContentType) { - headers['content-type'] = `multipart/form-data; boundary=${options.body.getBoundary()}`; - } - } - else if (isForm) { - if (noContentType) { - headers['content-type'] = 'application/x-www-form-urlencoded'; - } - const { form } = options; - options.form = undefined; - options.body = (new URLSearchParams(form)).toString(); - } - else { - if (noContentType) { - headers['content-type'] = 'application/json'; +}; +class options_Options { + _unixOptions; + _internals; + _merging; + _init; + constructor(input, options, defaults) { + distribution_assert.any([is_distribution.string, is_distribution.urlInstance, is_distribution.object, is_distribution.undefined], input); + distribution_assert.any([is_distribution.object, is_distribution.undefined], options); + distribution_assert.any([is_distribution.object, is_distribution.undefined], defaults); + if (input instanceof options_Options || options instanceof options_Options) { + throw new TypeError('The defaults must be passed as the third argument'); + } + this._internals = options_cloneInternals(defaults?._internals ?? defaults ?? options_defaultInternals); + this._init = [...(defaults?._init ?? [])]; + this._merging = false; + this._unixOptions = undefined; + // This rule allows `finally` to be considered more important. + // Meaning no matter the error thrown in the `try` block, + // if `finally` throws then the `finally` error will be thrown. + // + // Yes, we want this. If we set `url` first, then the `url.searchParams` + // would get merged. Instead we set the `searchParams` first, then + // `url.searchParams` is overwritten as expected. + // + /* eslint-disable no-unsafe-finally */ + try { + if (is_distribution.plainObject(input)) { + try { + this.merge(input); + this.merge(options); + } + finally { + this.url = input.url; } - const { json } = options; - options.json = undefined; - options.body = options.stringifyJson(json); } - const uploadBodySize = await getBodySize(options.body, options.headers); - // See https://tools.ietf.org/html/rfc7230#section-3.3.2 - // A user agent SHOULD send a Content-Length in a request message when - // no Transfer-Encoding is sent and the request method defines a meaning - // for an enclosed payload body. For example, a Content-Length header - // field is normally sent in a POST request even when the value is 0 - // (indicating an empty payload body). A user agent SHOULD NOT send a - // Content-Length header field when the request message does not contain - // a payload body and the method semantics do not anticipate such a - // body. - if (distribution.undefined(headers['content-length']) && distribution.undefined(headers['transfer-encoding']) && !cannotHaveBody && !distribution.undefined(uploadBodySize)) { - headers['content-length'] = String(uploadBodySize); + else { + try { + this.merge(options); + } + finally { + if (options?.url !== undefined) { + if (input === undefined) { + this.url = options.url; + } + else { + throw new TypeError('The `url` option is mutually exclusive with the `input` argument'); + } + } + else if (input !== undefined) { + this.url = input; + } + } } } - if (options.responseType === 'json' && !('accept' in options.headers)) { - options.headers.accept = 'application/json'; + catch (error) { + error.options = this; + throw error; } - this._bodySize = Number(headers['content-length']) || undefined; + /* eslint-enable no-unsafe-finally */ } - async _onResponseBase(response) { - // This will be called e.g. when using cache so we need to check if this request has been aborted. - if (this.isAborted) { + merge(options) { + if (!options) { return; } - const { options } = this; - const { url } = options; - this._nativeResponse = response; - if (options.decompress) { - response = decompress_response(response); - } - const statusCode = response.statusCode; - const typedResponse = response; - typedResponse.statusMessage = typedResponse.statusMessage ?? external_node_http_.STATUS_CODES[statusCode]; - typedResponse.url = options.url.toString(); - typedResponse.requestUrl = this.requestUrl; - typedResponse.redirectUrls = this.redirectUrls; - typedResponse.request = this; - typedResponse.isFromCache = this._nativeResponse.fromCache ?? false; - typedResponse.ip = this.ip; - typedResponse.retryCount = this.retryCount; - typedResponse.ok = isResponseOk(typedResponse); - this._isFromCache = typedResponse.isFromCache; - this._responseSize = Number(response.headers['content-length']) || undefined; - this.response = typedResponse; - response.once('end', () => { - this._responseSize = this._downloadedSize; - this.emit('downloadProgress', this.downloadProgress); - }); - response.once('error', (error) => { - this._aborted = true; - // Force clean-up, because some packages don't do this. - // TODO: Fix decompress-response - response.destroy(); - this._beforeError(new ReadError(error, this)); - }); - response.once('aborted', () => { - this._aborted = true; - this._beforeError(new ReadError({ - name: 'Error', - message: 'The server aborted pending request', - code: 'ECONNRESET', - }, this)); - }); - this.emit('downloadProgress', this.downloadProgress); - const rawCookies = response.headers['set-cookie']; - if (distribution.object(options.cookieJar) && rawCookies) { - let promises = rawCookies.map(async (rawCookie) => options.cookieJar.setCookie(rawCookie, url.toString())); - if (options.ignoreInvalidCookies) { - // eslint-disable-next-line @typescript-eslint/no-floating-promises - promises = promises.map(async (promise) => { - try { - await promise; - } - catch { } - }); - } - try { - await Promise.all(promises); - } - catch (error) { - this._beforeError(error); - return; + if (options instanceof options_Options) { + for (const init of options._init) { + this.merge(init); } - } - // The above is running a promise, therefore we need to check if this request has been aborted yet again. - if (this.isAborted) { return; } - if (response.headers.location && redirectCodes.has(statusCode)) { - // We're being redirected, we don't care about the response. - // It'd be best to abort the request, but we can't because - // we would have to sacrifice the TCP connection. We don't want that. - const shouldFollow = typeof options.followRedirect === 'function' ? options.followRedirect(typedResponse) : options.followRedirect; - if (shouldFollow) { - response.resume(); - this._cancelTimeouts(); - this._unproxyEvents(); - if (this.redirectUrls.length >= options.maxRedirects) { - this._beforeError(new MaxRedirectsError(this)); - return; + options = options_cloneRaw(options); + options_init(this, options, this); + options_init(options, options, this); + this._merging = true; + // Always merge `isStream` first + if ('isStream' in options) { + this.isStream = options.isStream; + } + try { + let push = false; + for (const key in options) { + // `got.extend()` options + if (key === 'mutableDefaults' || key === 'handlers') { + continue; } - this._request = undefined; - const updatedOptions = new Options(undefined, undefined, this.options); - const serverRequestedGet = statusCode === 303 && updatedOptions.method !== 'GET' && updatedOptions.method !== 'HEAD'; - const canRewrite = statusCode !== 307 && statusCode !== 308; - const userRequestedGet = updatedOptions.methodRewriting && canRewrite; - if (serverRequestedGet || userRequestedGet) { - updatedOptions.method = 'GET'; - updatedOptions.body = undefined; - updatedOptions.json = undefined; - updatedOptions.form = undefined; - delete updatedOptions.headers['content-length']; + // Never merge `url` + if (key === 'url') { + continue; } - try { - // We need this in order to support UTF-8 - const redirectBuffer = external_node_buffer_namespaceObject.Buffer.from(response.headers.location, 'binary').toString(); - const redirectUrl = new URL(redirectBuffer, url); - if (!isUnixSocketURL(url) && isUnixSocketURL(redirectUrl)) { - this._beforeError(new RequestError('Cannot redirect to UNIX socket', {}, this)); - return; - } - // Redirecting to a different site, clear sensitive data. - if (redirectUrl.hostname !== url.hostname || redirectUrl.port !== url.port) { - if ('host' in updatedOptions.headers) { - delete updatedOptions.headers.host; - } - if ('cookie' in updatedOptions.headers) { - delete updatedOptions.headers.cookie; - } - if ('authorization' in updatedOptions.headers) { - delete updatedOptions.headers.authorization; - } - if (updatedOptions.username || updatedOptions.password) { - updatedOptions.username = ''; - updatedOptions.password = ''; - } - } - else { - redirectUrl.username = updatedOptions.username; - redirectUrl.password = updatedOptions.password; - } - this.redirectUrls.push(redirectUrl); - updatedOptions.prefixUrl = ''; - updatedOptions.url = redirectUrl; - for (const hook of updatedOptions.hooks.beforeRedirect) { - // eslint-disable-next-line no-await-in-loop - await hook(updatedOptions, typedResponse); - } - this.emit('redirect', updatedOptions, typedResponse); - this.options = updatedOptions; - await this._makeRequest(); + if (!(key in this)) { + throw new Error(`Unexpected option: ${key}`); } - catch (error) { - this._beforeError(error); - return; + // @ts-expect-error Type 'unknown' is not assignable to type 'never'. + const value = options[key]; + if (value === undefined) { + continue; } - return; + // @ts-expect-error Type 'unknown' is not assignable to type 'never'. + this[key] = value; + push = true; + } + if (push) { + this._init.push(options); } } - // `HTTPError`s always have `error.response.body` defined. - // Therefore, we cannot retry if `options.throwHttpErrors` is false. - // On the last retry, if `options.throwHttpErrors` is false, we would need to return the body, - // but that wouldn't be possible since the body would be already read in `error.response.body`. - if (options.isStream && options.throwHttpErrors && !isResponseOk(typedResponse)) { - this._beforeError(new HTTPError(typedResponse)); - return; + finally { + this._merging = false; } - response.on('readable', () => { - if (this._triggerRead) { - this._read(); - } - }); - this.on('resume', () => { - response.resume(); - }); - this.on('pause', () => { - response.pause(); - }); - response.once('end', () => { - this.push(null); - }); - if (this._noPipe) { - const success = await this._setRawBody(); - if (success) { - this.emit('response', response); + } + /** + Custom request function. + The main purpose of this is to [support HTTP2 using a wrapper](https://github.com/szmarczak/http2-wrapper). + + @default http.request | https.request + */ + get request() { + return this._internals.request; + } + set request(value) { + distribution_assert.any([is_distribution["function"], is_distribution.undefined], value); + this._internals.request = value; + } + /** + An object representing `http`, `https` and `http2` keys for [`http.Agent`](https://nodejs.org/api/http.html#http_class_http_agent), [`https.Agent`](https://nodejs.org/api/https.html#https_class_https_agent) and [`http2wrapper.Agent`](https://github.com/szmarczak/http2-wrapper#new-http2agentoptions) instance. + This is necessary because a request to one protocol might redirect to another. + In such a scenario, Got will switch over to the right protocol agent for you. + + If a key is not present, it will default to a global agent. + + @example + ``` + import got from 'got'; + import HttpAgent from 'agentkeepalive'; + + const {HttpsAgent} = HttpAgent; + + await got('https://sindresorhus.com', { + agent: { + http: new HttpAgent(), + https: new HttpsAgent() + } + }); + ``` + */ + get agent() { + return this._internals.agent; + } + set agent(value) { + distribution_assert.plainObject(value); + // eslint-disable-next-line guard-for-in + for (const key in value) { + if (!(key in this._internals.agent)) { + throw new TypeError(`Unexpected agent option: ${key}`); } - return; + // @ts-expect-error - No idea why `value[key]` doesn't work here. + distribution_assert.any([is_distribution.object, is_distribution.undefined], value[key]); } - this.emit('response', response); - for (const destination of this._pipedServerResponses) { - if (destination.headersSent) { - continue; + if (this._merging) { + Object.assign(this._internals.agent, value); + } + else { + this._internals.agent = { ...value }; + } + } + get h2session() { + return this._internals.h2session; + } + set h2session(value) { + this._internals.h2session = value; + } + /** + Decompress the response automatically. + + This will set the `accept-encoding` header to `gzip, deflate, br` unless you set it yourself. + + If this is disabled, a compressed response is returned as a `Buffer`. + This may be useful if you want to handle decompression yourself or stream the raw compressed data. + + @default true + */ + get decompress() { + return this._internals.decompress; + } + set decompress(value) { + distribution_assert.boolean(value); + this._internals.decompress = value; + } + /** + Milliseconds to wait for the server to end the response before aborting the request with `got.TimeoutError` error (a.k.a. `request` property). + By default, there's no timeout. + + This also accepts an `object` with the following fields to constrain the duration of each phase of the request lifecycle: + + - `lookup` starts when a socket is assigned and ends when the hostname has been resolved. + Does not apply when using a Unix domain socket. + - `connect` starts when `lookup` completes (or when the socket is assigned if lookup does not apply to the request) and ends when the socket is connected. + - `secureConnect` starts when `connect` completes and ends when the handshaking process completes (HTTPS only). + - `socket` starts when the socket is connected. See [request.setTimeout](https://nodejs.org/api/http.html#http_request_settimeout_timeout_callback). + - `response` starts when the request has been written to the socket and ends when the response headers are received. + - `send` starts when the socket is connected and ends with the request has been written to the socket. + - `request` starts when the request is initiated and ends when the response's end event fires. + */ + get timeout() { + // We always return `Delays` here. + // It has to be `Delays | number`, otherwise TypeScript will error because the getter and the setter have incompatible types. + return this._internals.timeout; + } + set timeout(value) { + distribution_assert.plainObject(value); + // eslint-disable-next-line guard-for-in + for (const key in value) { + if (!(key in this._internals.timeout)) { + throw new Error(`Unexpected timeout option: ${key}`); } - // eslint-disable-next-line guard-for-in - for (const key in response.headers) { - const isAllowed = options.decompress ? key !== 'content-encoding' : true; - const value = response.headers[key]; - if (isAllowed) { - destination.setHeader(key, value); + // @ts-expect-error - No idea why `value[key]` doesn't work here. + distribution_assert.any([is_distribution.number, is_distribution.undefined], value[key]); + } + if (this._merging) { + Object.assign(this._internals.timeout, value); + } + else { + this._internals.timeout = { ...value }; + } + } + /** + When specified, `prefixUrl` will be prepended to `url`. + The prefix can be any valid URL, either relative or absolute. + A trailing slash `/` is optional - one will be added automatically. + + __Note__: `prefixUrl` will be ignored if the `url` argument is a URL instance. + + __Note__: Leading slashes in `input` are disallowed when using this option to enforce consistency and avoid confusion. + For example, when the prefix URL is `https://example.com/foo` and the input is `/bar`, there's ambiguity whether the resulting URL would become `https://example.com/foo/bar` or `https://example.com/bar`. + The latter is used by browsers. + + __Tip__: Useful when used with `got.extend()` to create niche-specific Got instances. + + __Tip__: You can change `prefixUrl` using hooks as long as the URL still includes the `prefixUrl`. + If the URL doesn't include it anymore, it will throw. + + @example + ``` + import got from 'got'; + + await got('unicorn', {prefixUrl: 'https://cats.com'}); + //=> 'https://cats.com/unicorn' + + const instance = got.extend({ + prefixUrl: 'https://google.com' + }); + + await instance('unicorn', { + hooks: { + beforeRequest: [ + options => { + options.prefixUrl = 'https://cats.com'; } - } - destination.statusCode = statusCode; + ] + } + }); + //=> 'https://cats.com/unicorn' + ``` + */ + get prefixUrl() { + // We always return `string` here. + // It has to be `string | URL`, otherwise TypeScript will error because the getter and the setter have incompatible types. + return this._internals.prefixUrl; + } + set prefixUrl(value) { + distribution_assert.any([is_distribution.string, is_distribution.urlInstance], value); + if (value === '') { + this._internals.prefixUrl = ''; + return; + } + value = value.toString(); + if (!value.endsWith('/')) { + value += '/'; + } + if (this._internals.prefixUrl && this._internals.url) { + const { href } = this._internals.url; + this._internals.url.href = value + href.slice(this._internals.prefixUrl.length); } + this._internals.prefixUrl = value; } - async _setRawBody(from = this) { - if (from.readableEnded) { - return false; + /** + __Note #1__: The `body` option cannot be used with the `json` or `form` option. + + __Note #2__: If you provide this option, `got.stream()` will be read-only. + + __Note #3__: If you provide a payload with the `GET` or `HEAD` method, it will throw a `TypeError` unless the method is `GET` and the `allowGetBody` option is set to `true`. + + __Note #4__: This option is not enumerable and will not be merged with the instance defaults. + + The `content-length` header will be automatically set if `body` is a `string` / `Buffer` / [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData) / [`form-data` instance](https://github.com/form-data/form-data), and `content-length` and `transfer-encoding` are not manually set in `options.headers`. + + Since Got 12, the `content-length` is not automatically set when `body` is a `fs.createReadStream`. + */ + get body() { + return this._internals.body; + } + set body(value) { + distribution_assert.any([is_distribution.string, is_distribution.buffer, is_distribution.nodeStream, is_distribution.generator, is_distribution.asyncGenerator, lib_isFormData, is_distribution.undefined], value); + if (is_distribution.nodeStream(value)) { + distribution_assert.truthy(value.readable); } - try { - // Errors are emitted via the `error` event - const fromArray = await from.toArray(); - const rawBody = isBuffer(fromArray.at(0)) ? external_node_buffer_namespaceObject.Buffer.concat(fromArray) : external_node_buffer_namespaceObject.Buffer.from(fromArray.join('')); - // On retry Request is destroyed with no error, therefore the above will successfully resolve. - // So in order to check if this was really successfull, we need to check if it has been properly ended. - if (!this.isAborted) { - this.response.rawBody = rawBody; - return true; - } + if (value !== undefined) { + distribution_assert.undefined(this._internals.form); + distribution_assert.undefined(this._internals.json); } - catch { } - return false; + this._internals.body = value; } - async _onResponse(response) { - try { - await this._onResponseBase(response); + /** + The form body is converted to a query string using [`(new URLSearchParams(object)).toString()`](https://nodejs.org/api/url.html#url_constructor_new_urlsearchparams_obj). + + If the `Content-Type` header is not present, it will be set to `application/x-www-form-urlencoded`. + + __Note #1__: If you provide this option, `got.stream()` will be read-only. + + __Note #2__: This option is not enumerable and will not be merged with the instance defaults. + */ + get form() { + return this._internals.form; + } + set form(value) { + distribution_assert.any([is_distribution.plainObject, is_distribution.undefined], value); + if (value !== undefined) { + distribution_assert.undefined(this._internals.body); + distribution_assert.undefined(this._internals.json); + } + this._internals.form = value; + } + /** + JSON body. If the `Content-Type` header is not set, it will be set to `application/json`. + + __Note #1__: If you provide this option, `got.stream()` will be read-only. + + __Note #2__: This option is not enumerable and will not be merged with the instance defaults. + */ + get json() { + return this._internals.json; + } + set json(value) { + if (value !== undefined) { + distribution_assert.undefined(this._internals.body); + distribution_assert.undefined(this._internals.form); + } + this._internals.json = value; + } + /** + The URL to request, as a string, a [`https.request` options object](https://nodejs.org/api/https.html#https_https_request_options_callback), or a [WHATWG `URL`](https://nodejs.org/api/url.html#url_class_url). + + Properties from `options` will override properties in the parsed `url`. + + If no protocol is specified, it will throw a `TypeError`. + + __Note__: The query string is **not** parsed as search params. + + @example + ``` + await got('https://example.com/?query=a b'); //=> https://example.com/?query=a%20b + await got('https://example.com/', {searchParams: {query: 'a b'}}); //=> https://example.com/?query=a+b + + // The query string is overridden by `searchParams` + await got('https://example.com/?query=a b', {searchParams: {query: 'a b'}}); //=> https://example.com/?query=a+b + ``` + */ + get url() { + return this._internals.url; + } + set url(value) { + distribution_assert.any([is_distribution.string, is_distribution.urlInstance, is_distribution.undefined], value); + if (value === undefined) { + this._internals.url = undefined; + return; + } + if (is_distribution.string(value) && value.startsWith('/')) { + throw new Error('`url` must not start with a slash'); + } + const urlString = `${this.prefixUrl}${value.toString()}`; + const url = new URL(urlString); + this._internals.url = url; + if (url.protocol === 'unix:') { + url.href = `http://unix${url.pathname}${url.search}`; + } + if (url.protocol !== 'http:' && url.protocol !== 'https:') { + const error = new Error(`Unsupported protocol: ${url.protocol}`); + error.code = 'ERR_UNSUPPORTED_PROTOCOL'; + throw error; + } + if (this._internals.username) { + url.username = this._internals.username; + this._internals.username = ''; + } + if (this._internals.password) { + url.password = this._internals.password; + this._internals.password = ''; } - catch (error) { - /* istanbul ignore next: better safe than sorry */ - this._beforeError(error); + if (this._internals.searchParams) { + url.search = this._internals.searchParams.toString(); + this._internals.searchParams = undefined; } - } - _onRequest(request) { - const { options } = this; - const { timeout, url } = options; - dist_source(request); - if (this.options.http2) { - // Unset stream timeout, as the `timeout` option was used only for connection timeout. - request.setTimeout(0); + if (url.hostname === 'unix') { + if (!this._internals.enableUnixSockets) { + throw new Error('Using UNIX domain sockets but option `enableUnixSockets` is not enabled'); + } + const matches = /(?.+?):(?.+)/.exec(`${url.pathname}${url.search}`); + if (matches?.groups) { + const { socketPath, path } = matches.groups; + this._unixOptions = { + socketPath, + path, + host: '', + }; + } + else { + this._unixOptions = undefined; + } + return; } - this._cancelTimeouts = timedOut(request, timeout, url); - const responseEventName = options.cache ? 'cacheableResponse' : 'response'; - request.once(responseEventName, (response) => { - void this._onResponse(response); - }); - request.once('error', (error) => { - this._aborted = true; - // Force clean-up, because some packages (e.g. nock) don't do this. - request.destroy(); - error = error instanceof timed_out_TimeoutError ? new TimeoutError(error, this.timings, this) : new RequestError(error.message, error, this); - this._beforeError(error); - }); - this._unproxyEvents = proxyEvents(request, this, proxiedRequestEvents); - this._request = request; - this.emit('uploadProgress', this.uploadProgress); - this._sendBody(); - this.emit('request', request); + this._unixOptions = undefined; } - async _asyncWrite(chunk) { - return new Promise((resolve, reject) => { - super.write(chunk, error => { - if (error) { - reject(error); - return; - } - resolve(); - }); - }); + /** + Cookie support. You don't have to care about parsing or how to store them. + + __Note__: If you provide this option, `options.headers.cookie` will be overridden. + */ + get cookieJar() { + return this._internals.cookieJar; } - _sendBody() { - // Send body - const { body } = this.options; - const currentRequest = this.redirectUrls.length === 0 ? this : this._request ?? this; - if (distribution.nodeStream(body)) { - body.pipe(currentRequest); - } - else if (distribution.generator(body) || distribution.asyncGenerator(body)) { - (async () => { - try { - for await (const chunk of body) { - await this._asyncWrite(chunk); - } - super.end(); - } - catch (error) { - this._beforeError(error); - } - })(); + set cookieJar(value) { + distribution_assert.any([is_distribution.object, is_distribution.undefined], value); + if (value === undefined) { + this._internals.cookieJar = undefined; + return; } - else if (!distribution.undefined(body)) { - this._writeRequest(body, undefined, () => { }); - currentRequest.end(); + let { setCookie, getCookieString } = value; + distribution_assert["function"](setCookie); + distribution_assert["function"](getCookieString); + /* istanbul ignore next: Horrible `tough-cookie` v3 check */ + if (setCookie.length === 4 && getCookieString.length === 0) { + setCookie = (0,external_node_util_.promisify)(setCookie.bind(value)); + getCookieString = (0,external_node_util_.promisify)(getCookieString.bind(value)); + this._internals.cookieJar = { + setCookie, + getCookieString: getCookieString, + }; } - else if (this._cannotHaveBody || this._noPipe) { - currentRequest.end(); + else { + this._internals.cookieJar = value; } } - _prepareCache(cache) { - if (!cacheableStore.has(cache)) { - const cacheableRequest = new dist(((requestOptions, handler) => { - const result = requestOptions._request(requestOptions, handler); - // TODO: remove this when `cacheable-request` supports async request functions. - if (distribution.promise(result)) { - // We only need to implement the error handler in order to support HTTP2 caching. - // The result will be a promise anyway. - // @ts-expect-error ignore - result.once = (event, handler) => { - if (event === 'error') { - (async () => { - try { - await result; - } - catch (error) { - handler(error); - } - })(); - } - else if (event === 'abort') { - // The empty catch is needed here in case when - // it rejects before it's `await`ed in `_makeRequest`. - (async () => { - try { - const request = (await result); - request.once('abort', handler); - } - catch { } - })(); - } - else { - /* istanbul ignore next: safety check */ - throw new Error(`Unknown HTTP2 promise event: ${event}`); - } - return result; - }; - } - return result; - }), cache); - cacheableStore.set(cache, cacheableRequest.request()); - } + /** + You can abort the `request` using [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController). + + @example + ``` + import got from 'got'; + + const abortController = new AbortController(); + + const request = got('https://httpbin.org/anything', { + signal: abortController.signal + }); + + setTimeout(() => { + abortController.abort(); + }, 100); + ``` + */ + get signal() { + return this._internals.signal; } - async _createCacheableRequest(url, options) { - return new Promise((resolve, reject) => { - // TODO: Remove `utils/url-to-options.ts` when `cacheable-request` is fixed - Object.assign(options, urlToOptions(url)); - let request; - // TODO: Fix `cacheable-response`. This is ugly. - const cacheRequest = cacheableStore.get(options.cache)(options, async (response) => { - response._readableState.autoDestroy = false; - if (request) { - const fix = () => { - if (response.req) { - response.complete = response.req.res.complete; - } - }; - response.prependOnceListener('end', fix); - fix(); - (await request).emit('cacheableResponse', response); - } - resolve(response); - }); - cacheRequest.once('error', reject); - cacheRequest.once('request', async (requestOrPromise) => { - request = requestOrPromise; - resolve(request); - }); - }); + set signal(value) { + distribution_assert.object(value); + this._internals.signal = value; } - async _makeRequest() { - const { options } = this; - const { headers, username, password } = options; - const cookieJar = options.cookieJar; - for (const key in headers) { - if (distribution.undefined(headers[key])) { - // eslint-disable-next-line @typescript-eslint/no-dynamic-delete - delete headers[key]; - } - else if (distribution["null"](headers[key])) { - throw new TypeError(`Use \`undefined\` instead of \`null\` to delete the \`${key}\` header`); - } - } - if (options.decompress && distribution.undefined(headers['accept-encoding'])) { - headers['accept-encoding'] = supportsBrotli ? 'gzip, deflate, br' : 'gzip, deflate'; + /** + Ignore invalid cookies instead of throwing an error. + Only useful when the `cookieJar` option has been set. Not recommended. + + @default false + */ + get ignoreInvalidCookies() { + return this._internals.ignoreInvalidCookies; + } + set ignoreInvalidCookies(value) { + distribution_assert.boolean(value); + this._internals.ignoreInvalidCookies = value; + } + /** + Query string that will be added to the request URL. + This will override the query string in `url`. + + If you need to pass in an array, you can do it using a `URLSearchParams` instance. + + @example + ``` + import got from 'got'; + + const searchParams = new URLSearchParams([['key', 'a'], ['key', 'b']]); + + await got('https://example.com', {searchParams}); + + console.log(searchParams.toString()); + //=> 'key=a&key=b' + ``` + */ + get searchParams() { + if (this._internals.url) { + return this._internals.url.searchParams; } - if (username || password) { - const credentials = external_node_buffer_namespaceObject.Buffer.from(`${username}:${password}`).toString('base64'); - headers.authorization = `Basic ${credentials}`; + if (this._internals.searchParams === undefined) { + this._internals.searchParams = new URLSearchParams(); } - // Set cookies - if (cookieJar) { - const cookieString = await cookieJar.getCookieString(options.url.toString()); - if (distribution.nonEmptyString(cookieString)) { - headers.cookie = cookieString; + return this._internals.searchParams; + } + set searchParams(value) { + distribution_assert.any([is_distribution.string, is_distribution.object, is_distribution.undefined], value); + const url = this._internals.url; + if (value === undefined) { + this._internals.searchParams = undefined; + if (url) { + url.search = ''; } + return; } - // Reset `prefixUrl` - options.prefixUrl = ''; - let request; - for (const hook of options.hooks.beforeRequest) { - // eslint-disable-next-line no-await-in-loop - const result = await hook(options); - if (!distribution.undefined(result)) { - // @ts-expect-error Skip the type mismatch to support abstract responses - request = () => result; - break; - } + const searchParameters = this.searchParams; + let updated; + if (is_distribution.string(value)) { + updated = new URLSearchParams(value); } - request ||= options.getRequestFunction(); - const url = options.url; - this._requestOptions = options.createNativeRequestOptions(); - if (options.cache) { - this._requestOptions._request = request; - this._requestOptions.cache = options.cache; - this._requestOptions.body = options.body; - this._prepareCache(options.cache); + else if (value instanceof URLSearchParams) { + updated = value; } - // Cache support - const function_ = options.cache ? this._createCacheableRequest : request; - try { - // We can't do `await fn(...)`, - // because stream `error` event can be emitted before `Promise.resolve()`. - let requestOrResponse = function_(url, this._requestOptions); - if (distribution.promise(requestOrResponse)) { - requestOrResponse = await requestOrResponse; - } - // Fallback - if (distribution.undefined(requestOrResponse)) { - requestOrResponse = options.getFallbackRequestFunction()(url, this._requestOptions); - if (distribution.promise(requestOrResponse)) { - requestOrResponse = await requestOrResponse; + else { + options_validateSearchParameters(value); + updated = new URLSearchParams(); + // eslint-disable-next-line guard-for-in + for (const key in value) { + const entry = value[key]; + if (entry === null) { + updated.append(key, ''); + } + else if (entry === undefined) { + searchParameters.delete(key); + } + else { + updated.append(key, entry); } } - if (is_client_request(requestOrResponse)) { - this._onRequest(requestOrResponse); - } - else if (this.writable) { - this.once('finish', () => { - void this._onResponse(requestOrResponse); - }); - this._sendBody(); + } + if (this._merging) { + // These keys will be replaced + for (const key of updated.keys()) { + searchParameters.delete(key); } - else { - void this._onResponse(requestOrResponse); + for (const [key, value] of updated) { + searchParameters.append(key, value); } } - catch (error) { - if (error instanceof types_CacheError) { - throw new CacheError(error, this); - } - throw error; + else if (url) { + url.search = searchParameters.toString(); + } + else { + this._internals.searchParams = searchParameters; } } - async _error(error) { - try { - if (error instanceof HTTPError && !this.options.throwHttpErrors) { - // This branch can be reached only when using the Promise API - // Skip calling the hooks on purpose. - // See https://github.com/sindresorhus/got/issues/2103 - } - else { - for (const hook of this.options.hooks.beforeError) { - // eslint-disable-next-line no-await-in-loop - error = await hook(error); - } - } + get searchParameters() { + throw new Error('The `searchParameters` option does not exist. Use `searchParams` instead.'); + } + set searchParameters(_value) { + throw new Error('The `searchParameters` option does not exist. Use `searchParams` instead.'); + } + get dnsLookup() { + return this._internals.dnsLookup; + } + set dnsLookup(value) { + distribution_assert.any([is_distribution["function"], is_distribution.undefined], value); + this._internals.dnsLookup = value; + } + /** + An instance of [`CacheableLookup`](https://github.com/szmarczak/cacheable-lookup) used for making DNS lookups. + Useful when making lots of requests to different *public* hostnames. + + `CacheableLookup` uses `dns.resolver4(..)` and `dns.resolver6(...)` under the hood and fall backs to `dns.lookup(...)` when the first two fail, which may lead to additional delay. + + __Note__: This should stay disabled when making requests to internal hostnames such as `localhost`, `database.local` etc. + + @default false + */ + get dnsCache() { + return this._internals.dnsCache; + } + set dnsCache(value) { + distribution_assert.any([is_distribution.object, is_distribution.boolean, is_distribution.undefined], value); + if (value === true) { + this._internals.dnsCache = options_getGlobalDnsCache(); } - catch (error_) { - error = new RequestError(error_.message, error_, this); + else if (value === false) { + this._internals.dnsCache = undefined; } - this.destroy(error); - } - _writeRequest(chunk, encoding, callback) { - if (!this._request || this._request.destroyed) { - // Probably the `ClientRequest` instance will throw - return; + else { + this._internals.dnsCache = value; } - this._request.write(chunk, encoding, (error) => { - // The `!destroyed` check is required to prevent `uploadProgress` being emitted after the stream was destroyed - if (!error && !this._request.destroyed) { - this._uploadedSize += external_node_buffer_namespaceObject.Buffer.byteLength(chunk, encoding); - const progress = this.uploadProgress; - if (progress.percent < 1) { - this.emit('uploadProgress', progress); - } - } - callback(error); - }); } /** - The remote IP address. + User data. `context` is shallow merged and enumerable. If it contains non-enumerable properties they will NOT be merged. + + @example + ``` + import got from 'got'; + + const instance = got.extend({ + hooks: { + beforeRequest: [ + options => { + if (!options.context || !options.context.token) { + throw new Error('Token required'); + } + + options.headers.token = options.context.token; + } + ] + } + }); + + const context = { + token: 'secret' + }; + + const response = await instance('https://httpbin.org/headers', {context}); + + // Let's see the headers + console.log(response.body); + ``` */ - get ip() { - return this.socket?.remoteAddress; + get context() { + return this._internals.context; + } + set context(value) { + distribution_assert.object(value); + if (this._merging) { + Object.assign(this._internals.context, value); + } + else { + this._internals.context = { ...value }; + } } /** - Indicates whether the request has been aborted or not. + Hooks allow modifications during the request lifecycle. + Hook functions may be async and are run serially. */ - get isAborted() { - return this._aborted; + get hooks() { + return this._internals.hooks; } - get socket() { - return this._request?.socket ?? undefined; + set hooks(value) { + distribution_assert.object(value); + // eslint-disable-next-line guard-for-in + for (const knownHookEvent in value) { + if (!(knownHookEvent in this._internals.hooks)) { + throw new Error(`Unexpected hook event: ${knownHookEvent}`); + } + const typedKnownHookEvent = knownHookEvent; + const hooks = value[typedKnownHookEvent]; + distribution_assert.any([is_distribution.array, is_distribution.undefined], hooks); + if (hooks) { + for (const hook of hooks) { + distribution_assert["function"](hook); + } + } + if (this._merging) { + if (hooks) { + // @ts-expect-error FIXME + this._internals.hooks[typedKnownHookEvent].push(...hooks); + } + } + else { + if (!hooks) { + throw new Error(`Missing hook event: ${knownHookEvent}`); + } + // @ts-expect-error FIXME + this._internals.hooks[knownHookEvent] = [...hooks]; + } + } } /** - Progress event for downloading (receiving a response). + Whether redirect responses should be followed automatically. + + Optionally, pass a function to dynamically decide based on the response object. + + Note that if a `303` is sent by the server in response to any request type (`POST`, `DELETE`, etc.), Got will automatically request the resource pointed to in the location header via `GET`. + This is in accordance with [the spec](https://tools.ietf.org/html/rfc7231#section-6.4.4). You can optionally turn on this behavior also for other redirect codes - see `methodRewriting`. + + @default true */ - get downloadProgress() { - let percent; - if (this._responseSize) { - percent = this._downloadedSize / this._responseSize; - } - else if (this._responseSize === this._downloadedSize) { - percent = 1; - } - else { - percent = 0; - } - return { - percent, - transferred: this._downloadedSize, - total: this._responseSize, - }; + get followRedirect() { + return this._internals.followRedirect; + } + set followRedirect(value) { + distribution_assert.any([is_distribution.boolean, is_distribution["function"]], value); + this._internals.followRedirect = value; + } + get followRedirects() { + throw new TypeError('The `followRedirects` option does not exist. Use `followRedirect` instead.'); + } + set followRedirects(_value) { + throw new TypeError('The `followRedirects` option does not exist. Use `followRedirect` instead.'); } /** - Progress event for uploading (sending a request). + If exceeded, the request will be aborted and a `MaxRedirectsError` will be thrown. + + @default 10 */ - get uploadProgress() { - let percent; - if (this._bodySize) { - percent = this._uploadedSize / this._bodySize; + get maxRedirects() { + return this._internals.maxRedirects; + } + set maxRedirects(value) { + distribution_assert.number(value); + this._internals.maxRedirects = value; + } + /** + A cache adapter instance for storing cached response data. + + @default false + */ + get cache() { + return this._internals.cache; + } + set cache(value) { + distribution_assert.any([is_distribution.object, is_distribution.string, is_distribution.boolean, is_distribution.undefined], value); + if (value === true) { + this._internals.cache = options_globalCache; } - else if (this._bodySize === this._uploadedSize) { - percent = 1; + else if (value === false) { + this._internals.cache = undefined; } else { - percent = 0; + this._internals.cache = value; } - return { - percent, - transferred: this._uploadedSize, - total: this._bodySize, - }; } /** - The object contains the following properties: - - - `start` - Time when the request started. - - `socket` - Time when a socket was assigned to the request. - - `lookup` - Time when the DNS lookup finished. - - `connect` - Time when the socket successfully connected. - - `secureConnect` - Time when the socket securely connected. - - `upload` - Time when the request finished uploading. - - `response` - Time when the request fired `response` event. - - `end` - Time when the response fired `end` event. - - `error` - Time when the request fired `error` event. - - `abort` - Time when the request fired `abort` event. - - `phases` - - `wait` - `timings.socket - timings.start` - - `dns` - `timings.lookup - timings.socket` - - `tcp` - `timings.connect - timings.lookup` - - `tls` - `timings.secureConnect - timings.connect` - - `request` - `timings.upload - (timings.secureConnect || timings.connect)` - - `firstByte` - `timings.response - timings.upload` - - `download` - `timings.end - timings.response` - - `total` - `(timings.end || timings.error || timings.abort) - timings.start` + Determines if a `got.HTTPError` is thrown for unsuccessful responses. - If something has not been measured yet, it will be `undefined`. + If this is disabled, requests that encounter an error status code will be resolved with the `response` instead of throwing. + This may be useful if you are checking for resource availability and are expecting error responses. - __Note__: The time is a `number` representing the milliseconds elapsed since the UNIX epoch. + @default true */ - get timings() { - return this._request?.timings; + get throwHttpErrors() { + return this._internals.throwHttpErrors; } - /** - Whether the response was retrieved from the cache. - */ - get isFromCache() { - return this._isFromCache; + set throwHttpErrors(value) { + distribution_assert.boolean(value); + this._internals.throwHttpErrors = value; } - get reusedSocket() { - return this._request?.reusedSocket; + get username() { + const url = this._internals.url; + const value = url ? url.username : this._internals.username; + return decodeURIComponent(value); } -} - -;// CONCATENATED MODULE: ./node_modules/.pnpm/got@14.4.2/node_modules/got/dist/source/as-promise/types.js - -/** -An error to be thrown when the request is aborted with `.cancel()`. -*/ -class types_CancelError extends RequestError { - constructor(request) { - super('Promise was canceled', {}, request); - this.name = 'CancelError'; - this.code = 'ERR_CANCELED'; + set username(value) { + distribution_assert.string(value); + const url = this._internals.url; + const fixedValue = encodeURIComponent(value); + if (url) { + url.username = fixedValue; + } + else { + this._internals.username = fixedValue; + } } - /** - Whether the promise is canceled. - */ - get isCanceled() { - return true; + get password() { + const url = this._internals.url; + const value = url ? url.password : this._internals.password; + return decodeURIComponent(value); } -} - -;// CONCATENATED MODULE: ./node_modules/.pnpm/got@14.4.2/node_modules/got/dist/source/as-promise/index.js - - + set password(value) { + distribution_assert.string(value); + const url = this._internals.url; + const fixedValue = encodeURIComponent(value); + if (url) { + url.password = fixedValue; + } + else { + this._internals.password = fixedValue; + } + } + /** + If set to `true`, Got will additionally accept HTTP2 requests. + It will choose either HTTP/1.1 or HTTP/2 depending on the ALPN protocol. + __Note__: This option requires Node.js 15.10.0 or newer as HTTP/2 support on older Node.js versions is very buggy. + __Note__: Overriding `options.request` will disable HTTP2 support. + @default false + @example + ``` + import got from 'got'; -const as_promise_proxiedRequestEvents = [ - 'request', - 'response', - 'redirect', - 'uploadProgress', - 'downloadProgress', -]; -function asPromise(firstRequest) { - let globalRequest; - let globalResponse; - let normalizedOptions; - const emitter = new external_node_events_.EventEmitter(); - const promise = new PCancelable((resolve, reject, onCancel) => { - onCancel(() => { - globalRequest.destroy(); - }); - onCancel.shouldReject = false; - onCancel(() => { - reject(new types_CancelError(globalRequest)); - }); - const makeRequest = (retryCount) => { - // Errors when a new request is made after the promise settles. - // Used to detect a race condition. - // See https://github.com/sindresorhus/got/issues/1489 - onCancel(() => { }); - const request = firstRequest ?? new Request(undefined, undefined, normalizedOptions); - request.retryCount = retryCount; - request._noPipe = true; - globalRequest = request; - request.once('response', async (response) => { - // Parse body - const contentEncoding = (response.headers['content-encoding'] ?? '').toLowerCase(); - const isCompressed = contentEncoding === 'gzip' || contentEncoding === 'deflate' || contentEncoding === 'br'; - const { options } = request; - if (isCompressed && !options.decompress) { - response.body = response.rawBody; - } - else { - try { - response.body = parseBody(response, options.responseType, options.parseJson, options.encoding); - } - catch (error) { - // Fall back to `utf8` - try { - response.body = response.rawBody.toString(); - } - catch (error) { - request._beforeError(new ParseError(error, response)); - return; - } - if (isResponseOk(response)) { - request._beforeError(error); - return; - } - } - } - try { - const hooks = options.hooks.afterResponse; - for (const [index, hook] of hooks.entries()) { - // @ts-expect-error TS doesn't notice that CancelableRequest is a Promise - // eslint-disable-next-line no-await-in-loop - response = await hook(response, async (updatedOptions) => { - options.merge(updatedOptions); - options.prefixUrl = ''; - if (updatedOptions.url) { - options.url = updatedOptions.url; - } - // Remove any further hooks for that request, because we'll call them anyway. - // The loop continues. We don't want duplicates (asPromise recursion). - options.hooks.afterResponse = options.hooks.afterResponse.slice(0, index); - throw new RetryError(request); - }); - if (!(distribution.object(response) && distribution.number(response.statusCode) && !distribution.nullOrUndefined(response.body))) { - throw new TypeError('The `afterResponse` hook returned an invalid value'); - } - } - } - catch (error) { - request._beforeError(error); - return; - } - globalResponse = response; - if (!isResponseOk(response)) { - request._beforeError(new HTTPError(response)); - return; - } - request.destroy(); - resolve(request.options.resolveBodyOnly ? response.body : response); - }); - const onError = (error) => { - if (promise.isCanceled) { - return; - } - const { options } = request; - if (error instanceof HTTPError && !options.throwHttpErrors) { - const { response } = error; - request.destroy(); - resolve(request.options.resolveBodyOnly ? response.body : response); - return; - } - reject(error); - }; - request.once('error', onError); - const previousBody = request.options?.body; - request.once('retry', (newRetryCount, error) => { - firstRequest = undefined; - const newBody = request.options.body; - if (previousBody === newBody && distribution.nodeStream(newBody)) { - error.message = 'Cannot retry with consumed body stream'; - onError(error); - return; - } - // This is needed! We need to reuse `request.options` because they can get modified! - // For example, by calling `promise.json()`. - normalizedOptions = request.options; - makeRequest(newRetryCount); - }); - proxyEvents(request, emitter, as_promise_proxiedRequestEvents); - if (distribution.undefined(firstRequest)) { - void request.flush(); - } - }; - makeRequest(0); - }); - promise.on = (event, function_) => { - emitter.on(event, function_); - return promise; - }; - promise.off = (event, function_) => { - emitter.off(event, function_); - return promise; - }; - const shortcut = (responseType) => { - const newPromise = (async () => { - // Wait until downloading has ended - await promise; - const { options } = globalResponse.request; - return parseBody(globalResponse, responseType, options.parseJson, options.encoding); - })(); - // eslint-disable-next-line @typescript-eslint/no-floating-promises - Object.defineProperties(newPromise, Object.getOwnPropertyDescriptors(promise)); - return newPromise; - }; - promise.json = () => { - if (globalRequest.options) { - const { headers } = globalRequest.options; - if (!globalRequest.writableFinished && !('accept' in headers)) { - headers.accept = 'application/json'; - } - } - return shortcut('json'); - }; - promise.buffer = () => shortcut('buffer'); - promise.text = () => shortcut('text'); - return promise; -} + const {headers} = await got('https://nghttp2.org/httpbin/anything', {http2: true}); -;// CONCATENATED MODULE: ./node_modules/.pnpm/got@14.4.2/node_modules/got/dist/source/create.js + console.log(headers.via); + //=> '2 nghttpx' + ``` + */ + get http2() { + return this._internals.http2; + } + set http2(value) { + distribution_assert.boolean(value); + this._internals.http2 = value; + } + /** + Set this to `true` to allow sending body for the `GET` method. + However, the [HTTP/2 specification](https://tools.ietf.org/html/rfc7540#section-8.1.3) says that `An HTTP GET request includes request header fields and no payload body`, therefore when using the HTTP/2 protocol this option will have no effect. + This option is only meant to interact with non-compliant servers when you have no other choice. + __Note__: The [RFC 7231](https://tools.ietf.org/html/rfc7231#section-4.3.1) doesn't specify any particular behavior for the GET method having a payload, therefore __it's considered an [anti-pattern](https://en.wikipedia.org/wiki/Anti-pattern)__. + @default false + */ + get allowGetBody() { + return this._internals.allowGetBody; + } + set allowGetBody(value) { + distribution_assert.boolean(value); + this._internals.allowGetBody = value; + } + /** + Request headers. + Existing headers will be overwritten. Headers set to `undefined` will be omitted. -// The `delay` package weighs 10KB (!) -const delay = async (ms) => new Promise(resolve => { - setTimeout(resolve, ms); -}); -const isGotInstance = (value) => distribution["function"](value); -const aliases = [ - 'get', - 'post', - 'put', - 'patch', - 'head', - 'delete', -]; -const create = (defaults) => { - defaults = { - options: new Options(undefined, undefined, defaults.options), - handlers: [...defaults.handlers], - mutableDefaults: defaults.mutableDefaults, - }; - Object.defineProperty(defaults, 'mutableDefaults', { - enumerable: true, - configurable: false, - writable: false, - }); - // Got interface - const got = ((url, options, defaultOptions = defaults.options) => { - const request = new Request(url, options, defaultOptions); - let promise; - const lastHandler = (normalized) => { - // Note: `options` is `undefined` when `new Options(...)` fails - request.options = normalized; - request._noPipe = !normalized?.isStream; - void request.flush(); - if (normalized?.isStream) { - return request; - } - promise ||= asPromise(request); - return promise; - }; - let iteration = 0; - const iterateHandlers = (newOptions) => { - const handler = defaults.handlers[iteration++] ?? lastHandler; - const result = handler(newOptions, iterateHandlers); - if (distribution.promise(result) && !request.options?.isStream) { - promise ||= asPromise(request); - if (result !== promise) { - const descriptors = Object.getOwnPropertyDescriptors(promise); - for (const key in descriptors) { - if (key in result) { - // eslint-disable-next-line @typescript-eslint/no-dynamic-delete - delete descriptors[key]; - } - } - // eslint-disable-next-line @typescript-eslint/no-floating-promises - Object.defineProperties(result, descriptors); - result.cancel = promise.cancel; - } - } - return result; - }; - return iterateHandlers(request.options); - }); - got.extend = (...instancesOrOptions) => { - const options = new Options(undefined, undefined, defaults.options); - const handlers = [...defaults.handlers]; - let mutableDefaults; - for (const value of instancesOrOptions) { - if (isGotInstance(value)) { - options.merge(value.defaults.options); - handlers.push(...value.defaults.handlers); - mutableDefaults = value.defaults.mutableDefaults; - } - else { - options.merge(value); - if (value.handlers) { - handlers.push(...value.handlers); - } - mutableDefaults = value.mutableDefaults; - } - } - return create({ - options, - handlers, - mutableDefaults: Boolean(mutableDefaults), - }); - }; - // Pagination - const paginateEach = (async function* (url, options) { - let normalizedOptions = new Options(url, options, defaults.options); - normalizedOptions.resolveBodyOnly = false; - const { pagination } = normalizedOptions; - assert["function"](pagination.transform); - assert["function"](pagination.shouldContinue); - assert["function"](pagination.filter); - assert["function"](pagination.paginate); - assert.number(pagination.countLimit); - assert.number(pagination.requestLimit); - assert.number(pagination.backoff); - const allItems = []; - let { countLimit } = pagination; - let numberOfRequests = 0; - while (numberOfRequests < pagination.requestLimit) { - if (numberOfRequests !== 0) { - // eslint-disable-next-line no-await-in-loop - await delay(pagination.backoff); - } - // eslint-disable-next-line no-await-in-loop - const response = (await got(undefined, undefined, normalizedOptions)); - // eslint-disable-next-line no-await-in-loop - const parsed = await pagination.transform(response); - const currentItems = []; - assert.array(parsed); - for (const item of parsed) { - if (pagination.filter({ item, currentItems, allItems })) { - if (!pagination.shouldContinue({ item, currentItems, allItems })) { - return; - } - yield item; - if (pagination.stackAllItems) { - allItems.push(item); - } - currentItems.push(item); - if (--countLimit <= 0) { - return; - } - } - } - const optionsToMerge = pagination.paginate({ - response, - currentItems, - allItems, - }); - if (optionsToMerge === false) { - return; - } - if (optionsToMerge === response.request.options) { - normalizedOptions = response.request.options; - } - else { - normalizedOptions.merge(optionsToMerge); - assert.any([distribution.urlInstance, distribution.undefined], optionsToMerge.url); - if (optionsToMerge.url !== undefined) { - normalizedOptions.prefixUrl = ''; - normalizedOptions.url = optionsToMerge.url; - } - } - numberOfRequests++; + @default {} + */ + get headers() { + return this._internals.headers; + } + set headers(value) { + distribution_assert.plainObject(value); + if (this._merging) { + Object.assign(this._internals.headers, lowercaseKeys(value)); } - }); - got.paginate = paginateEach; - got.paginate.all = (async (url, options) => { - const results = []; - for await (const item of paginateEach(url, options)) { - results.push(item); + else { + this._internals.headers = lowercaseKeys(value); } - return results; - }); - // For those who like very descriptive names - got.paginate.each = paginateEach; - // Stream API - got.stream = ((url, options) => got(url, { ...options, isStream: true })); - // Shortcuts - for (const method of aliases) { - got[method] = ((url, options) => got(url, { ...options, method })); - got.stream[method] = ((url, options) => got(url, { ...options, method, isStream: true })); } - if (!defaults.mutableDefaults) { - Object.freeze(defaults.handlers); - defaults.options.freeze(); - } - Object.defineProperty(got, 'defaults', { - value: defaults, - writable: false, - configurable: false, - enumerable: true, - }); - return got; -}; -/* harmony default export */ const source_create = (create); - -;// CONCATENATED MODULE: ./node_modules/.pnpm/got@14.4.2/node_modules/got/dist/source/index.js + /** + Specifies if the HTTP request method should be [rewritten as `GET`](https://tools.ietf.org/html/rfc7231#section-6.4) on redirects. + As the [specification](https://tools.ietf.org/html/rfc7231#section-6.4) prefers to rewrite the HTTP method only on `303` responses, this is Got's default behavior. + Setting `methodRewriting` to `true` will also rewrite `301` and `302` responses, as allowed by the spec. This is the behavior followed by `curl` and browsers. -const defaults = { - options: new Options(), - handlers: [], - mutableDefaults: false, -}; -const got = source_create(defaults); -/* harmony default export */ const got_dist_source = (got); -// TODO: Remove this in the next major version. + __Note__: Got never performs method rewriting on `307` and `308` responses, as this is [explicitly prohibited by the specification](https://www.rfc-editor.org/rfc/rfc7231#section-6.4.7). + @default false + */ + get methodRewriting() { + return this._internals.methodRewriting; + } + set methodRewriting(value) { + distribution_assert.boolean(value); + this._internals.methodRewriting = value; + } + /** + Indicates which DNS record family to use. + Values: + - `undefined`: IPv4 (if present) or IPv6 + - `4`: Only IPv4 + - `6`: Only IPv6 + @default undefined + */ + get dnsLookupIpVersion() { + return this._internals.dnsLookupIpVersion; + } + set dnsLookupIpVersion(value) { + if (value !== undefined && value !== 4 && value !== 6) { + throw new TypeError(`Invalid DNS lookup IP version: ${value}`); + } + this._internals.dnsLookupIpVersion = value; + } + /** + A function used to parse JSON responses. + @example + ``` + import got from 'got'; + import Bourne from '@hapi/bourne'; + const parsed = await got('https://example.com', { + parseJson: text => Bourne.parse(text) + }).json(); + console.log(parsed); + ``` + */ + get parseJson() { + return this._internals.parseJson; + } + set parseJson(value) { + distribution_assert["function"](value); + this._internals.parseJson = value; + } + /** + A function used to stringify the body of JSON requests. + @example + ``` + import got from 'got'; + await got.post('https://example.com', { + stringifyJson: object => JSON.stringify(object, (key, value) => { + if (key.startsWith('_')) { + return; + } + return value; + }), + json: { + some: 'payload', + _ignoreMe: 1234 + } + }); + ``` + @example + ``` + import got from 'got'; + await got.post('https://example.com', { + stringifyJson: object => JSON.stringify(object, (key, value) => { + if (typeof value === 'number') { + return value.toString(); + } -;// CONCATENATED MODULE: external "node:dns/promises" -const external_node_dns_promises_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:dns/promises"); -// EXTERNAL MODULE: ./node_modules/.pnpm/@actions+cache@3.2.4/node_modules/@actions/cache/lib/cache.js -var cache = __nccwpck_require__(6878); -;// CONCATENATED MODULE: external "node:child_process" -const external_node_child_process_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:child_process"); -;// CONCATENATED MODULE: ./node_modules/.pnpm/github.com+DeterminateSystems+detsys-ts@65dd73c562ac60a068340f8e0c040bdcf2c59afe_eek3lsas7notlem5iqjfyrzcca/node_modules/detsys-ts/dist/index.js -var __defProp = Object.defineProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; + return value; + }), + json: { + some: 'payload', + number: 1 + } + }); + ``` + */ + get stringifyJson() { + return this._internals.stringifyJson; + } + set stringifyJson(value) { + distribution_assert["function"](value); + this._internals.stringifyJson = value; + } + /** + An object representing `limit`, `calculateDelay`, `methods`, `statusCodes`, `maxRetryAfter` and `errorCodes` fields for maximum retry count, retry handler, allowed methods, allowed status codes, maximum [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) time and allowed error codes. -// package.json -var version = "1.0.0"; + Delays between retries counts with function `1000 * Math.pow(2, retry) + Math.random() * 100`, where `retry` is attempt number (starts from 1). -// src/linux-release-info.ts + The `calculateDelay` property is a `function` that receives an object with `attemptCount`, `retryOptions`, `error` and `computedValue` properties for current retry count, the retry options, error and default computed value. + The function must return a delay in milliseconds (or a Promise resolving with it) (`0` return value cancels retry). + By default, it retries *only* on the specified methods, status codes, and on these network errors: + - `ETIMEDOUT`: One of the [timeout](#timeout) limits were reached. + - `ECONNRESET`: Connection was forcibly closed by a peer. + - `EADDRINUSE`: Could not bind to any free port. + - `ECONNREFUSED`: Connection was refused by the server. + - `EPIPE`: The remote side of the stream being written has been closed. + - `ENOTFOUND`: Couldn't resolve the hostname to an IP address. + - `ENETUNREACH`: No internet connection. + - `EAI_AGAIN`: DNS lookup timed out. -var readFileAsync = (0,external_node_util_.promisify)(external_node_fs_namespaceObject.readFile); -var linuxReleaseInfoOptionsDefaults = { - mode: "async", - customFile: null, - debug: false -}; -function releaseInfo(infoOptions) { - const options = { ...linuxReleaseInfoOptionsDefaults, ...infoOptions }; - const searchOsReleaseFileList = osReleaseFileList( - options.customFile - ); - if (external_node_os_.type() !== "Linux") { - if (options.mode === "sync") { - return getOsInfo(); - } else { - return Promise.resolve(getOsInfo()); + __Note__: If `maxRetryAfter` is set to `undefined`, it will use `options.timeout`. + __Note__: If [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) header is greater than `maxRetryAfter`, it will cancel the request. + */ + get retry() { + return this._internals.retry; } - } - if (options.mode === "sync") { - return readSyncOsreleaseFile(searchOsReleaseFileList, options); - } else { - return Promise.resolve( - readAsyncOsReleaseFile(searchOsReleaseFileList, options) - ); - } -} -function formatFileData(sourceData, srcParseData) { - const lines = srcParseData.split("\n"); - for (const line of lines) { - const lineData = line.split("="); - if (lineData.length === 2) { - lineData[1] = lineData[1].replace(/["'\r]/gi, ""); - Object.defineProperty(sourceData, lineData[0].toLowerCase(), { - value: lineData[1], - writable: true, - enumerable: true, - configurable: true - }); + set retry(value) { + distribution_assert.plainObject(value); + distribution_assert.any([is_distribution["function"], is_distribution.undefined], value.calculateDelay); + distribution_assert.any([is_distribution.number, is_distribution.undefined], value.maxRetryAfter); + distribution_assert.any([is_distribution.number, is_distribution.undefined], value.limit); + distribution_assert.any([is_distribution.array, is_distribution.undefined], value.methods); + distribution_assert.any([is_distribution.array, is_distribution.undefined], value.statusCodes); + distribution_assert.any([is_distribution.array, is_distribution.undefined], value.errorCodes); + distribution_assert.any([is_distribution.number, is_distribution.undefined], value.noise); + if (value.noise && Math.abs(value.noise) > 100) { + throw new Error(`The maximum acceptable retry noise is +/- 100ms, got ${value.noise}`); + } + for (const key in value) { + if (!(key in this._internals.retry)) { + throw new Error(`Unexpected retry option: ${key}`); + } + } + if (this._merging) { + Object.assign(this._internals.retry, value); + } + else { + this._internals.retry = { ...value }; + } + const { retry } = this._internals; + retry.methods = [...new Set(retry.methods.map(method => method.toUpperCase()))]; + retry.statusCodes = [...new Set(retry.statusCodes)]; + retry.errorCodes = [...new Set(retry.errorCodes)]; } - } - return sourceData; -} -function osReleaseFileList(customFile) { - const DEFAULT_OS_RELEASE_FILES = ["/etc/os-release", "/usr/lib/os-release"]; - if (!customFile) { - return DEFAULT_OS_RELEASE_FILES; - } else { - return Array(customFile); - } -} -function getOsInfo() { - return { - type: external_node_os_.type(), - platform: external_node_os_.platform(), - hostname: external_node_os_.hostname(), - arch: external_node_os_.arch(), - release: external_node_os_.release() - }; -} -async function readAsyncOsReleaseFile(fileList, options) { - let fileData = null; - for (const osReleaseFile of fileList) { - try { - if (options.debug) { - console.log(`Trying to read '${osReleaseFile}'...`); - } - fileData = await readFileAsync(osReleaseFile, "binary"); - if (options.debug) { - console.log(`Read data: -${fileData}`); - } - break; - } catch (error3) { - if (options.debug) { - console.error(error3); - } + /** + From `http.RequestOptions`. + + The IP address used to send the request from. + */ + get localAddress() { + return this._internals.localAddress; } - } - if (fileData === null) { - throw new Error("Cannot read os-release file!"); - } - return formatFileData(getOsInfo(), fileData); -} -function readSyncOsreleaseFile(releaseFileList, options) { - let fileData = null; - for (const osReleaseFile of releaseFileList) { - try { - if (options.debug) { - console.log(`Trying to read '${osReleaseFile}'...`); - } - fileData = external_node_fs_namespaceObject.readFileSync(osReleaseFile, "binary"); - if (options.debug) { - console.log(`Read data: -${fileData}`); - } - break; - } catch (error3) { - if (options.debug) { - console.error(error3); - } + set localAddress(value) { + distribution_assert.any([is_distribution.string, is_distribution.undefined], value); + this._internals.localAddress = value; } - } - if (fileData === null) { - throw new Error("Cannot read os-release file!"); - } - return formatFileData(getOsInfo(), fileData); -} - -// src/actions-core-platform.ts - - + /** + The HTTP method used to make the request. -var getWindowsInfo = async () => { - const { stdout: version2 } = await exec.getExecOutput( - 'powershell -command "(Get-CimInstance -ClassName Win32_OperatingSystem).Version"', - void 0, - { - silent: true + @default 'GET' + */ + get method() { + return this._internals.method; } - ); - const { stdout: name } = await exec.getExecOutput( - 'powershell -command "(Get-CimInstance -ClassName Win32_OperatingSystem).Caption"', - void 0, - { - silent: true + set method(value) { + distribution_assert.string(value); + this._internals.method = value.toUpperCase(); } - ); - return { - name: name.trim(), - version: version2.trim() - }; -}; -var getMacOsInfo = async () => { - const { stdout } = await exec.getExecOutput("sw_vers", void 0, { - silent: true - }); - const version2 = stdout.match(/ProductVersion:\s*(.+)/)?.[1] ?? ""; - const name = stdout.match(/ProductName:\s*(.+)/)?.[1] ?? ""; - return { - name, - version: version2 - }; -}; -var getLinuxInfo = async () => { - let data = {}; - try { - data = releaseInfo({ mode: "sync" }); - core.debug(`Identified release info: ${JSON.stringify(data)}`); - } catch (e) { - core.debug(`Error collecting release info: ${e}`); - } - return { - name: getPropertyViaWithDefault( - data, - ["id", "name", "pretty_name", "id_like"], - "unknown" - ), - version: getPropertyViaWithDefault( - data, - ["version_id", "version", "version_codename"], - "unknown" - ) - }; -}; -function getPropertyViaWithDefault(data, names, defaultValue) { - for (const name of names) { - const ret = getPropertyWithDefault(data, name, defaultValue); - if (ret !== defaultValue) { - return ret; + get createConnection() { + return this._internals.createConnection; } - } - return defaultValue; -} -function getPropertyWithDefault(data, name, defaultValue) { - if (!data.hasOwnProperty(name)) { - return defaultValue; - } - const value = data[name]; - if (typeof value !== typeof defaultValue) { - return defaultValue; - } - return value; -} -var platform2 = external_os_.platform(); -var arch2 = external_os_.arch(); -var isWindows = platform2 === "win32"; -var isMacOS = platform2 === "darwin"; -var isLinux = platform2 === "linux"; -async function getDetails() { - return { - ...await (isWindows ? getWindowsInfo() : isMacOS ? getMacOsInfo() : getLinuxInfo()), - platform: platform2, - arch: arch2, - isWindows, - isMacOS, - isLinux - }; -} - -// src/errors.ts -function stringifyError(e) { - if (e instanceof Error) { - return e.message; - } else if (typeof e === "string") { - return e; - } else { - return JSON.stringify(e); - } -} - -// src/backtrace.ts - - - - - -async function collectBacktraces(prefixes, startTimestampMs) { - if (isMacOS) { - return await collectBacktracesMacOS(prefixes, startTimestampMs); - } - if (isLinux) { - return await collectBacktracesSystemd(prefixes, startTimestampMs); - } - return /* @__PURE__ */ new Map(); -} -async function collectBacktracesMacOS(prefixes, startTimestampMs) { - const backtraces = /* @__PURE__ */ new Map(); - try { - const { stdout: logJson } = await exec.getExecOutput( - "log", - [ - "show", - "--style", - "json", - "--last", - // Note we collect the last 1m only, because it should only take a few seconds to write the crash log. - // Therefore, any crashes before this 1m should be long done by now. - "1m", - "--no-info", - "--predicate", - "sender = 'ReportCrash'" - ], - { - silent: true - } - ); - const sussyArray = JSON.parse(logJson); - if (!Array.isArray(sussyArray)) { - throw new Error(`Log json isn't an array: ${logJson}`); + set createConnection(value) { + distribution_assert.any([is_distribution["function"], is_distribution.undefined], value); + this._internals.createConnection = value; } - if (sussyArray.length > 0) { - core.info(`Collecting crash data...`); - const delay = async (ms) => new Promise((resolve) => setTimeout(resolve, ms)); - await delay(5e3); + /** + From `http-cache-semantics` + + @default {} + */ + get cacheOptions() { + return this._internals.cacheOptions; } - } catch (e) { - core.debug( - "Failed to check logs for in-progress crash dumps; now proceeding with the assumption that all crash dumps completed." - ); - } - const dirs = [ - ["system", "/Library/Logs/DiagnosticReports/"], - ["user", `${process.env["HOME"]}/Library/Logs/DiagnosticReports/`] - ]; - for (const [source, dir] of dirs) { - const fileNames = (await (0,promises_namespaceObject.readdir)(dir)).filter((fileName) => { - return prefixes.some((prefix) => fileName.startsWith(prefix)); - }).filter((fileName) => { - return !fileName.endsWith(".diag"); - }); - const doGzip = (0,external_node_util_.promisify)(external_node_zlib_.gzip); - for (const fileName of fileNames) { - try { - if ((await (0,promises_namespaceObject.stat)(`${dir}/${fileName}`)).ctimeMs >= startTimestampMs) { - const logText = await (0,promises_namespaceObject.readFile)(`${dir}/${fileName}`); - const buf = await doGzip(logText); - backtraces.set( - `backtrace_value_${source}_${fileName}`, - buf.toString("base64") - ); + set cacheOptions(value) { + distribution_assert.plainObject(value); + distribution_assert.any([is_distribution.boolean, is_distribution.undefined], value.shared); + distribution_assert.any([is_distribution.number, is_distribution.undefined], value.cacheHeuristic); + distribution_assert.any([is_distribution.number, is_distribution.undefined], value.immutableMinTimeToLive); + distribution_assert.any([is_distribution.boolean, is_distribution.undefined], value.ignoreCargoCult); + for (const key in value) { + if (!(key in this._internals.cacheOptions)) { + throw new Error(`Cache option \`${key}\` does not exist`); + } } - } catch (innerError) { - backtraces.set( - `backtrace_failure_${source}_${fileName}`, - stringifyError(innerError) - ); - } - } - } - return backtraces; -} -async function collectBacktracesSystemd(prefixes, startTimestampMs) { - const sinceSeconds = Math.ceil((Date.now() - startTimestampMs) / 1e3); - const backtraces = /* @__PURE__ */ new Map(); - const coredumps = []; - try { - const { stdout: coredumpjson } = await exec.getExecOutput( - "coredumpctl", - ["--json=pretty", "list", "--since", `${sinceSeconds} seconds ago`], - { - silent: true - } - ); - const sussyArray = JSON.parse(coredumpjson); - if (!Array.isArray(sussyArray)) { - throw new Error(`Coredump isn't an array: ${coredumpjson}`); - } - for (const sussyObject of sussyArray) { - const keys = Object.keys(sussyObject); - if (keys.includes("exe") && keys.includes("pid")) { - if (typeof sussyObject.exe == "string" && typeof sussyObject.pid == "number") { - const execParts = sussyObject.exe.split("/"); - const binaryName = execParts[execParts.length - 1]; - if (prefixes.some((prefix) => binaryName.startsWith(prefix))) { - coredumps.push({ - exe: sussyObject.exe, - pid: sussyObject.pid - }); - } - } else { - core.debug( - `Mysterious coredump entry missing exe string and/or pid number: ${JSON.stringify(sussyObject)}` - ); + if (this._merging) { + Object.assign(this._internals.cacheOptions, value); + } + else { + this._internals.cacheOptions = { ...value }; } - } else { - core.debug( - `Mysterious coredump entry missing exe value and/or pid value: ${JSON.stringify(sussyObject)}` - ); - } } - } catch (innerError) { - core.debug( - `Cannot collect backtraces: ${stringifyError(innerError)}` - ); - return backtraces; - } - const doGzip = (0,external_node_util_.promisify)(external_node_zlib_.gzip); - for (const coredump of coredumps) { - try { - const { stdout: logText } = await exec.getExecOutput( - "coredumpctl", - ["info", `${coredump.pid}`], - { - silent: true + /** + Options for the advanced HTTPS API. + */ + get https() { + return this._internals.https; + } + set https(value) { + distribution_assert.plainObject(value); + distribution_assert.any([is_distribution.boolean, is_distribution.undefined], value.rejectUnauthorized); + distribution_assert.any([is_distribution["function"], is_distribution.undefined], value.checkServerIdentity); + distribution_assert.any([is_distribution.string, is_distribution.object, is_distribution.array, is_distribution.undefined], value.certificateAuthority); + distribution_assert.any([is_distribution.string, is_distribution.object, is_distribution.array, is_distribution.undefined], value.key); + distribution_assert.any([is_distribution.string, is_distribution.object, is_distribution.array, is_distribution.undefined], value.certificate); + distribution_assert.any([is_distribution.string, is_distribution.undefined], value.passphrase); + distribution_assert.any([is_distribution.string, is_distribution.buffer, is_distribution.array, is_distribution.undefined], value.pfx); + distribution_assert.any([is_distribution.array, is_distribution.undefined], value.alpnProtocols); + distribution_assert.any([is_distribution.string, is_distribution.undefined], value.ciphers); + distribution_assert.any([is_distribution.string, is_distribution.buffer, is_distribution.undefined], value.dhparam); + distribution_assert.any([is_distribution.string, is_distribution.undefined], value.signatureAlgorithms); + distribution_assert.any([is_distribution.string, is_distribution.undefined], value.minVersion); + distribution_assert.any([is_distribution.string, is_distribution.undefined], value.maxVersion); + distribution_assert.any([is_distribution.boolean, is_distribution.undefined], value.honorCipherOrder); + distribution_assert.any([is_distribution.number, is_distribution.undefined], value.tlsSessionLifetime); + distribution_assert.any([is_distribution.string, is_distribution.undefined], value.ecdhCurve); + distribution_assert.any([is_distribution.string, is_distribution.buffer, is_distribution.array, is_distribution.undefined], value.certificateRevocationLists); + for (const key in value) { + if (!(key in this._internals.https)) { + throw new Error(`HTTPS option \`${key}\` does not exist`); + } + } + if (this._merging) { + Object.assign(this._internals.https, value); + } + else { + this._internals.https = { ...value }; } - ); - const buf = await doGzip(logText); - backtraces.set(`backtrace_value_${coredump.pid}`, buf.toString("base64")); - } catch (innerError) { - backtraces.set( - `backtrace_failure_${coredump.pid}`, - stringifyError(innerError) - ); } - } - return backtraces; -} + /** + [Encoding](https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings) to be used on `setEncoding` of the response data. -// src/correlation.ts + To get a [`Buffer`](https://nodejs.org/api/buffer.html), you need to set `responseType` to `buffer` instead. + Don't set this option to `null`. + __Note__: This doesn't affect streams! Instead, you need to do `got.stream(...).setEncoding(encoding)`. -var OPTIONAL_VARIABLES = ["INVOCATION_ID"]; -function identify(projectName) { - const ident = { - correlation_source: "github-actions", - repository: hashEnvironmentVariables("GHR", [ - "GITHUB_SERVER_URL", - "GITHUB_REPOSITORY_OWNER", - "GITHUB_REPOSITORY_OWNER_ID", - "GITHUB_REPOSITORY", - "GITHUB_REPOSITORY_ID" - ]), - workflow: hashEnvironmentVariables("GHW", [ - "GITHUB_SERVER_URL", - "GITHUB_REPOSITORY_OWNER", - "GITHUB_REPOSITORY_OWNER_ID", - "GITHUB_REPOSITORY", - "GITHUB_REPOSITORY_ID", - "GITHUB_WORKFLOW" - ]), - job: hashEnvironmentVariables("GHWJ", [ - "GITHUB_SERVER_URL", - "GITHUB_REPOSITORY_OWNER", - "GITHUB_REPOSITORY_OWNER_ID", - "GITHUB_REPOSITORY", - "GITHUB_REPOSITORY_ID", - "GITHUB_WORKFLOW", - "GITHUB_JOB" - ]), - run: hashEnvironmentVariables("GHWJR", [ - "GITHUB_SERVER_URL", - "GITHUB_REPOSITORY_OWNER", - "GITHUB_REPOSITORY_OWNER_ID", - "GITHUB_REPOSITORY", - "GITHUB_REPOSITORY_ID", - "GITHUB_WORKFLOW", - "GITHUB_JOB", - "GITHUB_RUN_ID" - ]), - run_differentiator: hashEnvironmentVariables("GHWJA", [ - "GITHUB_SERVER_URL", - "GITHUB_REPOSITORY_OWNER", - "GITHUB_REPOSITORY_OWNER_ID", - "GITHUB_REPOSITORY", - "GITHUB_REPOSITORY_ID", - "GITHUB_WORKFLOW", - "GITHUB_JOB", - "GITHUB_RUN_ID", - "GITHUB_RUN_NUMBER", - "GITHUB_RUN_ATTEMPT", - "INVOCATION_ID" - ]), - groups: { - ci: "github-actions", - project: projectName, - github_organization: hashEnvironmentVariables("GHO", [ - "GITHUB_SERVER_URL", - "GITHUB_REPOSITORY_OWNER", - "GITHUB_REPOSITORY_OWNER_ID" - ]) + @default 'utf-8' + */ + get encoding() { + return this._internals.encoding; } - }; - core.debug("Correlation data:"); - core.debug(JSON.stringify(ident, null, 2)); - return ident; -} -function hashEnvironmentVariables(prefix, variables) { - const hash = (0,external_node_crypto_namespaceObject.createHash)("sha256"); - for (const varName of variables) { - let value = process.env[varName]; - if (value === void 0) { - if (OPTIONAL_VARIABLES.includes(varName)) { - core.debug( - `Optional environment variable not set: ${varName} -- substituting with the variable name` - ); - value = varName; - } else { - core.debug( - `Environment variable not set: ${varName} -- can't generate the requested identity` - ); - return void 0; - } + set encoding(value) { + if (value === null) { + throw new TypeError('To get a Buffer, set `options.responseType` to `buffer` instead'); + } + distribution_assert.any([is_distribution.string, is_distribution.undefined], value); + this._internals.encoding = value; } - hash.update(value); - hash.update("\0"); - } - return `${prefix}-${hash.digest("hex")}`; -} + /** + When set to `true` the promise will return the Response body instead of the Response object. -// src/ids-host.ts + @default false + */ + get resolveBodyOnly() { + return this._internals.resolveBodyOnly; + } + set resolveBodyOnly(value) { + distribution_assert.boolean(value); + this._internals.resolveBodyOnly = value; + } + /** + Returns a `Stream` instead of a `Promise`. + This is equivalent to calling `got.stream(url, options?)`. + @default false + */ + get isStream() { + return this._internals.isStream; + } + set isStream(value) { + distribution_assert.boolean(value); + this._internals.isStream = value; + } + /** + The parsing method. + The promise also has `.text()`, `.json()` and `.buffer()` methods which return another Got promise for the parsed body. -var DEFAULT_LOOKUP = "_detsys_ids._tcp.install.determinate.systems."; -var ALLOWED_SUFFIXES = [ - ".install.determinate.systems", - ".install.detsys.dev" -]; -var DEFAULT_IDS_HOST = "https://install.determinate.systems"; -var LOOKUP = process.env["IDS_LOOKUP"] ?? DEFAULT_LOOKUP; -var DEFAULT_TIMEOUT = 1e4; -var IdsHost = class { - constructor(idsProjectName, diagnosticsSuffix, runtimeDiagnosticsUrl) { - this.idsProjectName = idsProjectName; - this.diagnosticsSuffix = diagnosticsSuffix; - this.runtimeDiagnosticsUrl = runtimeDiagnosticsUrl; - this.client = void 0; - } - async getGot(recordFailoverCallback) { - if (this.client === void 0) { - this.client = got_dist_source.extend({ - timeout: { - request: DEFAULT_TIMEOUT - }, - retry: { - limit: Math.max((await this.getUrlsByPreference()).length, 3), - methods: ["GET", "HEAD"] - }, - hooks: { - beforeRetry: [ - async (error3, retryCount) => { - const prevUrl = await this.getRootUrl(); - this.markCurrentHostBroken(); - const nextUrl = await this.getRootUrl(); - if (recordFailoverCallback !== void 0) { - recordFailoverCallback(error3, prevUrl, nextUrl); - } - core.info( - `Retrying after error ${error3.code}, retry #: ${retryCount}` - ); - } - ], - beforeRequest: [ - async (options) => { - const currentUrl = options.url; - if (this.isUrlSubjectToDynamicUrls(currentUrl)) { - const newUrl = new URL(currentUrl); - const url = await this.getRootUrl(); - newUrl.host = url.host; - options.url = newUrl; - core.debug(`Transmuted ${currentUrl} into ${newUrl}`); - } else { - core.debug(`No transmutations on ${currentUrl}`); - } - } - ] + It's like setting the options to `{responseType: 'json', resolveBodyOnly: true}` but without affecting the main Got promise. + + __Note__: When using streams, this option is ignored. + + @example + ``` + const responsePromise = got(url); + const bufferPromise = responsePromise.buffer(); + const jsonPromise = responsePromise.json(); + + const [response, buffer, json] = Promise.all([responsePromise, bufferPromise, jsonPromise]); + // `response` is an instance of Got Response + // `buffer` is an instance of Buffer + // `json` is an object + ``` + + @example + ``` + // This + const body = await got(url).json(); + + // is semantically the same as this + const body = await got(url, {responseType: 'json', resolveBodyOnly: true}); + ``` + */ + get responseType() { + return this._internals.responseType; + } + set responseType(value) { + if (value === undefined) { + this._internals.responseType = 'text'; + return; } - }); + if (value !== 'text' && value !== 'buffer' && value !== 'json') { + throw new Error(`Invalid \`responseType\` option: ${value}`); + } + this._internals.responseType = value; } - return this.client; - } - markCurrentHostBroken() { - this.prioritizedURLs?.shift(); - } - setPrioritizedUrls(urls) { - this.prioritizedURLs = urls; - } - isUrlSubjectToDynamicUrls(url) { - if (url.origin === DEFAULT_IDS_HOST) { - return true; + get pagination() { + return this._internals.pagination; } - for (const suffix of ALLOWED_SUFFIXES) { - if (url.host.endsWith(suffix)) { - return true; - } + set pagination(value) { + distribution_assert.object(value); + if (this._merging) { + Object.assign(this._internals.pagination, value); + } + else { + this._internals.pagination = value; + } } - return false; - } - async getDynamicRootUrl() { - const idsHost = process.env["IDS_HOST"]; - if (idsHost !== void 0) { - try { - return new URL(idsHost); - } catch (err) { - core.error( - `IDS_HOST environment variable is not a valid URL. Ignoring. ${stringifyError(err)}` - ); - } + get auth() { + throw new Error('Parameter `auth` is deprecated. Use `username` / `password` instead.'); } - let url = void 0; - try { - const urls = await this.getUrlsByPreference(); - url = urls[0]; - } catch (err) { - core.error( - `Error collecting IDS URLs by preference: ${stringifyError(err)}` - ); + set auth(_value) { + throw new Error('Parameter `auth` is deprecated. Use `username` / `password` instead.'); } - if (url === void 0) { - return void 0; - } else { - return new URL(url); + get setHost() { + return this._internals.setHost; } - } - async getRootUrl() { - const url = await this.getDynamicRootUrl(); - if (url === void 0) { - return new URL(DEFAULT_IDS_HOST); + set setHost(value) { + distribution_assert.boolean(value); + this._internals.setHost = value; } - return url; - } - async getDiagnosticsUrl() { - if (this.runtimeDiagnosticsUrl === "") { - return void 0; + get maxHeaderSize() { + return this._internals.maxHeaderSize; } - if (this.runtimeDiagnosticsUrl !== "-" && this.runtimeDiagnosticsUrl !== void 0) { - try { - return new URL(this.runtimeDiagnosticsUrl); - } catch (err) { - core.info( - `User-provided diagnostic endpoint ignored: not a valid URL: ${stringifyError(err)}` - ); - } + set maxHeaderSize(value) { + distribution_assert.any([is_distribution.number, is_distribution.undefined], value); + this._internals.maxHeaderSize = value; } - try { - const diagnosticUrl = await this.getRootUrl(); - diagnosticUrl.pathname += this.idsProjectName; - diagnosticUrl.pathname += "/"; - diagnosticUrl.pathname += this.diagnosticsSuffix || "diagnostics"; - return diagnosticUrl; - } catch (err) { - core.info( - `Generated diagnostic endpoint ignored, and diagnostics are disabled: not a valid URL: ${stringifyError(err)}` - ); - return void 0; + get enableUnixSockets() { + return this._internals.enableUnixSockets; } - } - async getUrlsByPreference() { - if (this.prioritizedURLs === void 0) { - this.prioritizedURLs = orderRecordsByPriorityWeight( - await discoverServiceRecords() - ).flatMap((record) => recordToUrl(record) || []); + set enableUnixSockets(value) { + distribution_assert.boolean(value); + this._internals.enableUnixSockets = value; } - return this.prioritizedURLs; - } -}; -function recordToUrl(record) { - const urlStr = `https://${record.name}:${record.port}`; - try { - return new URL(urlStr); - } catch (err) { - core.debug( - `Record ${JSON.stringify(record)} produced an invalid URL: ${urlStr} (${err})` - ); - return void 0; - } -} -async function discoverServiceRecords() { - return await discoverServicesStub((0,external_node_dns_promises_namespaceObject.resolveSrv)(LOOKUP), 1e3); -} -async function discoverServicesStub(lookup, timeout) { - const defaultFallback = new Promise( - (resolve, _reject) => { - setTimeout(resolve, timeout, []); + // eslint-disable-next-line @typescript-eslint/naming-convention + toJSON() { + return { ...this._internals }; } - ); - let records; - try { - records = await Promise.race([lookup, defaultFallback]); - } catch (reason) { - core.debug(`Error resolving SRV records: ${stringifyError(reason)}`); - records = []; - } - const acceptableRecords = records.filter((record) => { - for (const suffix of ALLOWED_SUFFIXES) { - if (record.name.endsWith(suffix)) { - return true; - } + [Symbol.for('nodejs.util.inspect.custom')](_depth, options) { + return (0,external_node_util_.inspect)(this._internals, options); } - core.debug( - `Unacceptable domain due to an invalid suffix: ${record.name}` - ); - return false; - }); - if (acceptableRecords.length === 0) { - core.debug(`No records found for ${LOOKUP}`); - } else { - core.debug( - `Resolved ${LOOKUP} to ${JSON.stringify(acceptableRecords)}` - ); - } - return acceptableRecords; -} -function orderRecordsByPriorityWeight(records) { - const byPriorityWeight = /* @__PURE__ */ new Map(); - for (const record of records) { - const existing = byPriorityWeight.get(record.priority); - if (existing) { - existing.push(record); - } else { - byPriorityWeight.set(record.priority, [record]); + createNativeRequestOptions() { + const internals = this._internals; + const url = internals.url; + let agent; + if (url.protocol === 'https:') { + agent = internals.http2 ? internals.agent : internals.agent.https; + } + else { + agent = internals.agent.http; + } + const { https } = internals; + let { pfx } = https; + if (is_distribution.array(pfx) && is_distribution.plainObject(pfx[0])) { + pfx = pfx.map(object => ({ + buf: object.buffer, + passphrase: object.passphrase, + })); + } + return { + ...internals.cacheOptions, + ...this._unixOptions, + // HTTPS options + // eslint-disable-next-line @typescript-eslint/naming-convention + ALPNProtocols: https.alpnProtocols, + ca: https.certificateAuthority, + cert: https.certificate, + key: https.key, + passphrase: https.passphrase, + pfx: https.pfx, + rejectUnauthorized: https.rejectUnauthorized, + checkServerIdentity: https.checkServerIdentity ?? external_node_tls_namespaceObject.checkServerIdentity, + ciphers: https.ciphers, + honorCipherOrder: https.honorCipherOrder, + minVersion: https.minVersion, + maxVersion: https.maxVersion, + sigalgs: https.signatureAlgorithms, + sessionTimeout: https.tlsSessionLifetime, + dhparam: https.dhparam, + ecdhCurve: https.ecdhCurve, + crl: https.certificateRevocationLists, + // HTTP options + lookup: internals.dnsLookup ?? internals.dnsCache?.lookup, + family: internals.dnsLookupIpVersion, + agent, + setHost: internals.setHost, + method: internals.method, + maxHeaderSize: internals.maxHeaderSize, + localAddress: internals.localAddress, + headers: internals.headers, + createConnection: internals.createConnection, + timeout: internals.http2 ? options_getHttp2TimeoutOption(internals) : undefined, + // HTTP/2 options + h2session: internals.h2session, + }; } - } - const prioritizedRecords = []; - const keys = Array.from(byPriorityWeight.keys()).sort( - (a, b) => a - b - ); - for (const priority of keys) { - const recordsByPrio = byPriorityWeight.get(priority); - if (recordsByPrio === void 0) { - continue; + getRequestFunction() { + const url = this._internals.url; + const { request } = this._internals; + if (!request && url) { + return this.getFallbackRequestFunction(); + } + return request; } - prioritizedRecords.push(...weightedRandom(recordsByPrio)); - } - return prioritizedRecords; -} -function weightedRandom(records) { - const scratchRecords = records.slice(); - const result = []; - while (scratchRecords.length > 0) { - const weights = []; - { - for (let i = 0; i < scratchRecords.length; i++) { - weights.push( - scratchRecords[i].weight + (i > 0 ? scratchRecords[i - 1].weight : 0) - ); - } + getFallbackRequestFunction() { + const url = this._internals.url; + if (!url) { + return; + } + if (url.protocol === 'https:') { + if (this._internals.http2) { + if (options_major < 15 || (options_major === 15 && options_minor < 10)) { + const error = new Error('To use the `http2` option, install Node.js 15.10.0 or above'); + error.code = 'EUNSUPPORTED'; + throw error; + } + return http2_wrapper_source.auto; + } + return external_node_https_.request; + } + return external_node_http_.request; } - const point = Math.random() * weights[weights.length - 1]; - for (let selectedIndex = 0; selectedIndex < weights.length; selectedIndex++) { - if (weights[selectedIndex] > point) { - result.push(scratchRecords.splice(selectedIndex, 1)[0]); - break; - } + freeze() { + const options = this._internals; + Object.freeze(options); + Object.freeze(options.hooks); + Object.freeze(options.hooks.afterResponse); + Object.freeze(options.hooks.beforeError); + Object.freeze(options.hooks.beforeRedirect); + Object.freeze(options.hooks.beforeRequest); + Object.freeze(options.hooks.beforeRetry); + Object.freeze(options.hooks.init); + Object.freeze(options.https); + Object.freeze(options.cacheOptions); + Object.freeze(options.agent); + Object.freeze(options.headers); + Object.freeze(options.timeout); + Object.freeze(options.retry); + Object.freeze(options.retry.errorCodes); + Object.freeze(options.retry.methods); + Object.freeze(options.retry.statusCodes); } - } - return result; } -// src/inputs.ts -var inputs_exports = {}; -__export(inputs_exports, { - getArrayOfStrings: () => getArrayOfStrings, - getArrayOfStringsOrNull: () => getArrayOfStringsOrNull, - getBool: () => getBool, - getMultilineStringOrNull: () => getMultilineStringOrNull, - getNumberOrNull: () => getNumberOrNull, - getString: () => getString, - getStringOrNull: () => getStringOrNull, - getStringOrUndefined: () => getStringOrUndefined, - handleString: () => handleString -}); +;// CONCATENATED MODULE: ./node_modules/.pnpm/got@14.4.2/node_modules/got/dist/source/core/response.js -var getBool = (name) => { - return core.getBooleanInput(name); -}; -var getArrayOfStrings = (name, separator) => { - const original = getString(name); - return handleString(original, separator); -}; -var getArrayOfStringsOrNull = (name, separator) => { - const original = getStringOrNull(name); - if (original === null) { - return null; - } else { - return handleString(original, separator); - } -}; -var handleString = (input, separator) => { - const sepChar = separator === "comma" ? "," : /\s+/; - const trimmed = input.trim(); - if (trimmed === "") { - return []; - } - return trimmed.split(sepChar).map((s) => s.trim()); -}; -var getMultilineStringOrNull = (name) => { - const value = core.getMultilineInput(name); - if (value.length === 0) { - return null; - } else { - return value; - } -}; -var getNumberOrNull = (name) => { - const value = core.getInput(name); - if (value === "") { - return null; - } else { - return Number(value); - } -}; -var getString = (name) => { - return core.getInput(name); -}; -var getStringOrNull = (name) => { - const value = core.getInput(name); - if (value === "") { - return null; - } else { - return value; - } +const response_isResponseOk = (response) => { + const { statusCode } = response; + const { followRedirect } = response.request.options; + const shouldFollow = typeof followRedirect === 'function' ? followRedirect(response) : followRedirect; + const limitStatusCode = shouldFollow ? 299 : 399; + return (statusCode >= 200 && statusCode <= limitStatusCode) || statusCode === 304; }; -var getStringOrUndefined = (name) => { - const value = core.getInput(name); - if (value === "") { - return void 0; - } else { - return value; - } +/** +An error to be thrown when server response code is 2xx, and parsing body fails. +Includes a `response` property. +*/ +class response_ParseError extends errors_RequestError { + constructor(error, response) { + const { options } = response.request; + super(`${error.message} in "${options.url.toString()}"`, error, response.request); + this.name = 'ParseError'; + this.code = 'ERR_BODY_PARSE_FAILURE'; + } +} +const response_parseBody = (response, responseType, parseJson, encoding) => { + const { rawBody } = response; + try { + if (responseType === 'text') { + return rawBody.toString(encoding); + } + if (responseType === 'json') { + return rawBody.length === 0 ? '' : parseJson(rawBody.toString(encoding)); + } + if (responseType === 'buffer') { + return rawBody; + } + } + catch (error) { + throw new response_ParseError(error, response); + } + throw new response_ParseError({ + message: `Unknown body type '${responseType}'`, + name: 'Error', + }, response); }; -// src/platform.ts -var platform_exports = {}; -__export(platform_exports, { - getArchOs: () => getArchOs, - getNixPlatform: () => getNixPlatform -}); - -function getArchOs() { - const envArch = process.env.RUNNER_ARCH; - const envOs = process.env.RUNNER_OS; - if (envArch && envOs) { - return `${envArch}-${envOs}`; - } else { - core.error( - `Can't identify the platform: RUNNER_ARCH or RUNNER_OS undefined (${envArch}-${envOs})` - ); - throw new Error("RUNNER_ARCH and/or RUNNER_OS is not defined"); - } +;// CONCATENATED MODULE: ./node_modules/.pnpm/got@14.4.2/node_modules/got/dist/source/core/utils/is-client-request.js +function is_client_request_isClientRequest(clientRequest) { + return clientRequest.writable && !clientRequest.writableEnded; } -function getNixPlatform(archOs) { - const archOsMap = /* @__PURE__ */ new Map([ - ["X64-macOS", "x86_64-darwin"], - ["ARM64-macOS", "aarch64-darwin"], - ["X64-Linux", "x86_64-linux"], - ["ARM64-Linux", "aarch64-linux"] - ]); - const mappedTo = archOsMap.get(archOs); - if (mappedTo) { - return mappedTo; - } else { - core.error( - `ArchOs (${archOs}) doesn't map to a supported Nix platform.` - ); - throw new Error( - `Cannot convert ArchOs (${archOs}) to a supported Nix platform.` - ); - } +/* harmony default export */ const utils_is_client_request = (is_client_request_isClientRequest); + +;// CONCATENATED MODULE: ./node_modules/.pnpm/got@14.4.2/node_modules/got/dist/source/core/utils/is-unix-socket-url.js +// eslint-disable-next-line @typescript-eslint/naming-convention +function is_unix_socket_url_isUnixSocketURL(url) { + return url.protocol === 'unix:' || url.hostname === 'unix'; } -// src/sourcedef.ts +;// CONCATENATED MODULE: ./node_modules/.pnpm/got@14.4.2/node_modules/got/dist/source/core/index.js -function constructSourceParameters(legacyPrefix) { - return { - path: noisilyGetInput("path", legacyPrefix), - url: noisilyGetInput("url", legacyPrefix), - tag: noisilyGetInput("tag", legacyPrefix), - pr: noisilyGetInput("pr", legacyPrefix), - branch: noisilyGetInput("branch", legacyPrefix), - revision: noisilyGetInput("revision", legacyPrefix) - }; -} -function noisilyGetInput(suffix, legacyPrefix) { - const preferredInput = getStringOrUndefined(`source-${suffix}`); - if (!legacyPrefix) { - return preferredInput; - } - const legacyInput = getStringOrUndefined(`${legacyPrefix}-${suffix}`); - if (preferredInput && legacyInput) { - core.warning( - `The supported option source-${suffix} and the legacy option ${legacyPrefix}-${suffix} are both set. Preferring source-${suffix}. Please stop setting ${legacyPrefix}-${suffix}.` - ); - return preferredInput; - } else if (legacyInput) { - core.warning( - `The legacy option ${legacyPrefix}-${suffix} is set. Please migrate to source-${suffix}.` - ); - return legacyInput; - } else { - return preferredInput; - } -} -// src/index.ts @@ -85150,734 +90423,1384 @@ function noisilyGetInput(suffix, legacyPrefix) { -var EVENT_BACKTRACES = "backtrace"; -var EVENT_EXCEPTION = "exception"; -var EVENT_ARTIFACT_CACHE_HIT = "artifact_cache_hit"; -var EVENT_ARTIFACT_CACHE_MISS = "artifact_cache_miss"; -var EVENT_ARTIFACT_CACHE_PERSIST = "artifact_cache_persist"; -var EVENT_PREFLIGHT_REQUIRE_NIX_DENIED = "preflight-require-nix-denied"; -var FACT_ARTIFACT_FETCHED_FROM_CACHE = "artifact_fetched_from_cache"; -var FACT_ENDED_WITH_EXCEPTION = "ended_with_exception"; -var FACT_FINAL_EXCEPTION = "final_exception"; -var FACT_OS = "$os"; -var FACT_OS_VERSION = "$os_version"; -var FACT_SOURCE_URL = "source_url"; -var FACT_SOURCE_URL_ETAG = "source_url_etag"; -var FACT_NIX_LOCATION = "nix_location"; -var FACT_NIX_STORE_TRUST = "nix_store_trusted"; -var FACT_NIX_STORE_VERSION = "nix_store_version"; -var FACT_NIX_STORE_CHECK_METHOD = "nix_store_check_method"; -var FACT_NIX_STORE_CHECK_ERROR = "nix_store_check_error"; -var STATE_KEY_EXECUTION_PHASE = "detsys_action_execution_phase"; -var STATE_KEY_NIX_NOT_FOUND = "detsys_action_nix_not_found"; -var STATE_NOT_FOUND = "not-found"; -var STATE_KEY_CROSS_PHASE_ID = "detsys_cross_phase_id"; -var STATE_BACKTRACE_START_TIMESTAMP = "detsys_backtrace_start_timestamp"; -var DIAGNOSTIC_ENDPOINT_TIMEOUT_MS = 1e4; -var CHECK_IN_ENDPOINT_TIMEOUT_MS = 1e3; -var DetSysAction = class { - determineExecutionPhase() { - const currentPhase = core.getState(STATE_KEY_EXECUTION_PHASE); - if (currentPhase === "") { - core.saveState(STATE_KEY_EXECUTION_PHASE, "post"); - return "main"; - } else { - return "post"; - } - } - constructor(actionOptions) { - this.actionOptions = makeOptionsConfident(actionOptions); - this.idsHost = new IdsHost( - this.actionOptions.idsProjectName, - actionOptions.diagnosticsSuffix, - // Note: we don't use actionsCore.getInput('diagnostic-endpoint') on purpose: - // getInput silently converts absent data to an empty string. - process.env["INPUT_DIAGNOSTIC-ENDPOINT"] - ); - this.exceptionAttachments = /* @__PURE__ */ new Map(); - this.nixStoreTrust = "unknown"; - this.strictMode = getBool("_internal-strict-mode"); - this.features = {}; - this.featureEventMetadata = {}; - this.events = []; - this.getCrossPhaseId(); - this.collectBacktraceSetup(); - this.facts = { - $lib: "idslib", - $lib_version: version, - project: this.actionOptions.name, - ids_project: this.actionOptions.idsProjectName - }; - const params = [ - ["github_action_ref", "GITHUB_ACTION_REF"], - ["github_action_repository", "GITHUB_ACTION_REPOSITORY"], - ["github_event_name", "GITHUB_EVENT_NAME"], - ["$os", "RUNNER_OS"], - ["arch", "RUNNER_ARCH"] - ]; - for (const [target, env] of params) { - const value = process.env[env]; - if (value) { - this.facts[target] = value; - } - } - this.identity = identify(this.actionOptions.name); - this.archOs = getArchOs(); - this.nixSystem = getNixPlatform(this.archOs); - this.facts.arch_os = this.archOs; - this.facts.nix_system = this.nixSystem; - { - getDetails().then((details) => { - if (details.name !== "unknown") { - this.addFact(FACT_OS, details.name); + + + + + + +const core_supportsBrotli = is_distribution.string(external_node_process_.versions.brotli); +const core_methodsWithoutBody = new Set(['GET', 'HEAD']); +const core_cacheableStore = new weakable_map_WeakableMap(); +const core_redirectCodes = new Set([300, 301, 302, 303, 304, 307, 308]); +const core_proxiedRequestEvents = [ + 'socket', + 'connect', + 'continue', + 'information', + 'upgrade', +]; +const source_core_noop = () => { }; +class core_Request extends external_node_stream_.Duplex { + // @ts-expect-error - Ignoring for now. + ['constructor']; + _noPipe; + // @ts-expect-error https://github.com/microsoft/TypeScript/issues/9568 + options; + response; + requestUrl; + redirectUrls; + retryCount; + _stopRetry; + _downloadedSize; + _uploadedSize; + _stopReading; + _pipedServerResponses; + _request; + _responseSize; + _bodySize; + _unproxyEvents; + _isFromCache; + _cannotHaveBody; + _triggerRead; + _cancelTimeouts; + _removeListeners; + _nativeResponse; + _flushed; + _aborted; + // We need this because `this._request` if `undefined` when using cache + _requestInitialized; + constructor(url, options, defaults) { + super({ + // Don't destroy immediately, as the error may be emitted on unsuccessful retry + autoDestroy: false, + // It needs to be zero because we're just proxying the data to another stream + highWaterMark: 0, + }); + this._downloadedSize = 0; + this._uploadedSize = 0; + this._stopReading = false; + this._pipedServerResponses = new Set(); + this._cannotHaveBody = false; + this._unproxyEvents = source_core_noop; + this._triggerRead = false; + this._cancelTimeouts = source_core_noop; + this._removeListeners = source_core_noop; + this._jobs = []; + this._flushed = false; + this._requestInitialized = false; + this._aborted = false; + this.redirectUrls = []; + this.retryCount = 0; + this._stopRetry = source_core_noop; + this.on('pipe', (source) => { + if (source?.headers) { + Object.assign(this.options.headers, source.headers); + } + }); + this.on('newListener', event => { + if (event === 'retry' && this.listenerCount('retry') > 0) { + throw new Error('A retry listener has been attached already.'); + } + }); + try { + this.options = new options_Options(url, options, defaults); + if (!this.options.url) { + if (this.options.prefixUrl === '') { + throw new TypeError('Missing `url` property'); + } + this.options.url = ''; + } + this.requestUrl = this.options.url; } - if (details.version !== "unknown") { - this.addFact(FACT_OS_VERSION, details.version); + catch (error) { + const { options } = error; + if (options) { + this.options = options; + } + this.flush = async () => { + this.flush = async () => { }; + this.destroy(error); + }; + return; + } + // Important! If you replace `body` in a handler with another stream, make sure it's readable first. + // The below is run only once. + const { body } = this.options; + if (is_distribution.nodeStream(body)) { + body.once('error', error => { + if (this._flushed) { + this._beforeError(new errors_UploadError(error, this)); + } + else { + this.flush = async () => { + this.flush = async () => { }; + this._beforeError(new errors_UploadError(error, this)); + }; + } + }); + } + if (this.options.signal) { + const abort = () => { + this.destroy(new errors_AbortError(this)); + }; + if (this.options.signal.aborted) { + abort(); + } + else { + this.options.signal.addEventListener('abort', abort); + this._removeListeners = () => { + this.options.signal?.removeEventListener('abort', abort); + }; + } } - }).catch((e) => { - core.debug( - `Failure getting platform details: ${stringifyError2(e)}` - ); - }); } - this.executionPhase = this.determineExecutionPhase(); - this.facts.execution_phase = this.executionPhase; - if (this.actionOptions.fetchStyle === "gh-env-style") { - this.architectureFetchSuffix = this.archOs; - } else if (this.actionOptions.fetchStyle === "nix-style") { - this.architectureFetchSuffix = this.nixSystem; - } else if (this.actionOptions.fetchStyle === "universal") { - this.architectureFetchSuffix = "universal"; - } else { - throw new Error( - `fetchStyle ${this.actionOptions.fetchStyle} is not a valid style` - ); + async flush() { + if (this._flushed) { + return; + } + this._flushed = true; + try { + await this._finalizeBody(); + if (this.destroyed) { + return; + } + await this._makeRequest(); + if (this.destroyed) { + this._request?.destroy(); + return; + } + // Queued writes etc. + for (const job of this._jobs) { + job(); + } + // Prevent memory leak + this._jobs.length = 0; + this._requestInitialized = true; + } + catch (error) { + this._beforeError(error); + } } - this.sourceParameters = constructSourceParameters( - this.actionOptions.legacySourcePrefix - ); - this.recordEvent(`begin_${this.executionPhase}`); - } - /** - * Attach a file to the diagnostics data in error conditions. - * - * The file at `location` doesn't need to exist when stapleFile is called. - * - * If the file doesn't exist or is unreadable when trying to staple the attachments, the JS error will be stored in a context value at `staple_failure_{name}`. - * If the file is readable, the file's contents will be stored in a context value at `staple_value_{name}`. - */ - stapleFile(name, location) { - this.exceptionAttachments.set(name, location); - } - /** - * Execute the Action as defined. - */ - execute() { - this.executeAsync().catch((error3) => { - console.log(error3); - process.exitCode = 1; - }); - } - getTemporaryName() { - const tmpDir = process.env["RUNNER_TEMP"] || (0,external_node_os_.tmpdir)(); - return external_node_path_namespaceObject.join(tmpDir, `${this.actionOptions.name}-${(0,external_node_crypto_namespaceObject.randomUUID)()}`); - } - addFact(key, value) { - this.facts[key] = value; - } - async getDiagnosticsUrl() { - return await this.idsHost.getDiagnosticsUrl(); - } - getUniqueId() { - return this.identity.run_differentiator || process.env.RUNNER_TRACKING_ID || (0,external_node_crypto_namespaceObject.randomUUID)(); - } - // This ID will be saved in the action's state, to be persisted across phase steps - getCrossPhaseId() { - let crossPhaseId = core.getState(STATE_KEY_CROSS_PHASE_ID); - if (crossPhaseId === "") { - crossPhaseId = (0,external_node_crypto_namespaceObject.randomUUID)(); - core.saveState(STATE_KEY_CROSS_PHASE_ID, crossPhaseId); + _beforeError(error) { + if (this._stopReading) { + return; + } + const { response, options } = this; + const attemptCount = this.retryCount + (error.name === 'RetryError' ? 0 : 1); + this._stopReading = true; + if (!(error instanceof errors_RequestError)) { + error = new errors_RequestError(error.message, error, this); + } + const typedError = error; + void (async () => { + // Node.js parser is really weird. + // It emits post-request Parse Errors on the same instance as previous request. WTF. + // Therefore, we need to check if it has been destroyed as well. + // + // Furthermore, Node.js 16 `response.destroy()` doesn't immediately destroy the socket, + // but makes the response unreadable. So we additionally need to check `response.readable`. + if (response?.readable && !response.rawBody && !this._request?.socket?.destroyed) { + // @types/node has incorrect typings. `setEncoding` accepts `null` as well. + response.setEncoding(this.readableEncoding); + const success = await this._setRawBody(response); + if (success) { + response.body = response.rawBody.toString(); + } + } + if (this.listenerCount('retry') !== 0) { + let backoff; + try { + let retryAfter; + if (response && 'retry-after' in response.headers) { + retryAfter = Number(response.headers['retry-after']); + if (Number.isNaN(retryAfter)) { + retryAfter = Date.parse(response.headers['retry-after']) - Date.now(); + if (retryAfter <= 0) { + retryAfter = 1; + } + } + else { + retryAfter *= 1000; + } + } + const retryOptions = options.retry; + backoff = await retryOptions.calculateDelay({ + attemptCount, + retryOptions, + error: typedError, + retryAfter, + computedValue: core_calculate_retry_delay({ + attemptCount, + retryOptions, + error: typedError, + retryAfter, + computedValue: retryOptions.maxRetryAfter ?? options.timeout.request ?? Number.POSITIVE_INFINITY, + }), + }); + } + catch (error_) { + void this._error(new errors_RequestError(error_.message, error_, this)); + return; + } + if (backoff) { + await new Promise(resolve => { + const timeout = setTimeout(resolve, backoff); + this._stopRetry = () => { + clearTimeout(timeout); + resolve(); + }; + }); + // Something forced us to abort the retry + if (this.destroyed) { + return; + } + try { + for (const hook of this.options.hooks.beforeRetry) { + // eslint-disable-next-line no-await-in-loop + await hook(typedError, this.retryCount + 1); + } + } + catch (error_) { + void this._error(new errors_RequestError(error_.message, error, this)); + return; + } + // Something forced us to abort the retry + if (this.destroyed) { + return; + } + this.destroy(); + this.emit('retry', this.retryCount + 1, error, (updatedOptions) => { + const request = new core_Request(options.url, updatedOptions, options); + request.retryCount = this.retryCount + 1; + external_node_process_.nextTick(() => { + void request.flush(); + }); + return request; + }); + return; + } + } + void this._error(typedError); + })(); } - return crossPhaseId; - } - getCorrelationHashes() { - return this.identity; - } - recordEvent(eventName, context = {}) { - const prefixedName = eventName === "$feature_flag_called" ? eventName : `${this.actionOptions.eventPrefix}${eventName}`; - this.events.push({ - event_name: prefixedName, - context, - correlation: this.identity, - facts: this.facts, - features: this.featureEventMetadata, - timestamp: /* @__PURE__ */ new Date(), - uuid: (0,external_node_crypto_namespaceObject.randomUUID)() - }); - } - /** - * Unpacks the closure returned by `fetchArtifact()`, imports the - * contents into the Nix store, and returns the path of the executable at - * `/nix/store/STORE_PATH/bin/${bin}`. - */ - async unpackClosure(bin) { - const artifact = await this.fetchArtifact(); - const { stdout } = await (0,external_node_util_.promisify)(external_node_child_process_namespaceObject.exec)( - `cat "${artifact}" | xz -d | nix-store --import` - ); - const paths = stdout.split(external_node_os_.EOL); - const lastPath = paths.at(-2); - return `${lastPath}/bin/${bin}`; - } - /** - * Fetches the executable at the URL determined by the `source-*` inputs and - * other facts, `chmod`s it, and returns the path to the executable on disk. - */ - async fetchExecutable() { - const binaryPath = await this.fetchArtifact(); - await (0,promises_namespaceObject.chmod)(binaryPath, promises_namespaceObject.constants.S_IXUSR | promises_namespaceObject.constants.S_IXGRP); - return binaryPath; - } - get isMain() { - return this.executionPhase === "main"; - } - get isPost() { - return this.executionPhase === "post"; - } - async executeAsync() { - try { - await this.checkIn(); - process.env.DETSYS_CORRELATION = JSON.stringify( - this.getCorrelationHashes() - ); - if (!await this.preflightRequireNix()) { - this.recordEvent(EVENT_PREFLIGHT_REQUIRE_NIX_DENIED); - return; - } else { - await this.preflightNixStoreInfo(); - this.addFact(FACT_NIX_STORE_TRUST, this.nixStoreTrust); - } - if (this.isMain) { - await this.main(); - } else if (this.isPost) { - await this.post(); - } - this.addFact(FACT_ENDED_WITH_EXCEPTION, false); - } catch (e) { - this.addFact(FACT_ENDED_WITH_EXCEPTION, true); - const reportable = stringifyError2(e); - this.addFact(FACT_FINAL_EXCEPTION, reportable); - if (this.isPost) { - core.warning(reportable); - } else { - core.setFailed(reportable); - } - const doGzip = (0,external_node_util_.promisify)(external_node_zlib_.gzip); - const exceptionContext = /* @__PURE__ */ new Map(); - for (const [attachmentLabel, filePath] of this.exceptionAttachments) { - try { - const logText = (0,external_node_fs_namespaceObject.readFileSync)(filePath); - const buf = await doGzip(logText); - exceptionContext.set( - `staple_value_${attachmentLabel}`, - buf.toString("base64") - ); - } catch (innerError) { - exceptionContext.set( - `staple_failure_${attachmentLabel}`, - stringifyError2(innerError) - ); + _read() { + this._triggerRead = true; + const { response } = this; + if (response && !this._stopReading) { + // We cannot put this in the `if` above + // because `.read()` also triggers the `end` event + if (response.readableLength) { + this._triggerRead = false; + } + let data; + while ((data = response.read()) !== null) { + this._downloadedSize += data.length; // eslint-disable-line @typescript-eslint/restrict-plus-operands + const progress = this.downloadProgress; + if (progress.percent < 1) { + this.emit('downloadProgress', progress); + } + this.push(data); + } } - } - this.recordEvent(EVENT_EXCEPTION, Object.fromEntries(exceptionContext)); - } finally { - if (this.isPost) { - await this.collectBacktraces(); - } - await this.complete(); } - } - async getClient() { - return await this.idsHost.getGot( - (incitingError, prevUrl, nextUrl) => { - this.recordPlausibleTimeout(incitingError); - this.recordEvent("ids-failover", { - previousUrl: prevUrl.toString(), - nextUrl: nextUrl.toString() - }); - } - ); - } - async checkIn() { - const checkin = await this.requestCheckIn(); - if (checkin === void 0) { - return; + _write(chunk, encoding, callback) { + const write = () => { + this._writeRequest(chunk, encoding, callback); + }; + if (this._requestInitialized) { + write(); + } + else { + this._jobs.push(write); + } } - this.features = checkin.options; - for (const [key, feature] of Object.entries(this.features)) { - this.featureEventMetadata[key] = feature.variant; + _final(callback) { + const endRequest = () => { + // We need to check if `this._request` is present, + // because it isn't when we use cache. + if (!this._request || this._request.destroyed) { + callback(); + return; + } + this._request.end((error) => { + // The request has been destroyed before `_final` finished. + // See https://github.com/nodejs/node/issues/39356 + if (this._request._writableState?.errored) { + return; + } + if (!error) { + this._bodySize = this._uploadedSize; + this.emit('uploadProgress', this.uploadProgress); + this._request.emit('upload-complete'); + } + callback(error); + }); + }; + if (this._requestInitialized) { + endRequest(); + } + else { + this._jobs.push(endRequest); + } } - const impactSymbol = /* @__PURE__ */ new Map([ - ["none", "\u26AA"], - ["maintenance", "\u{1F6E0}\uFE0F"], - ["minor", "\u{1F7E1}"], - ["major", "\u{1F7E0}"], - ["critical", "\u{1F534}"] - ]); - const defaultImpactSymbol = "\u{1F535}"; - if (checkin.status !== null) { - const summaries = []; - for (const incident of checkin.status.incidents) { - summaries.push( - `${impactSymbol.get(incident.impact) || defaultImpactSymbol} ${incident.status.replace("_", " ")}: ${incident.name} (${incident.shortlink})` - ); - } - for (const maintenance of checkin.status.scheduled_maintenances) { - summaries.push( - `${impactSymbol.get(maintenance.impact) || defaultImpactSymbol} ${maintenance.status.replace("_", " ")}: ${maintenance.name} (${maintenance.shortlink})` - ); - } - if (summaries.length > 0) { - core.info( - // Bright red, Bold, Underline - `${"\x1B[0;31m"}${"\x1B[1m"}${"\x1B[4m"}${checkin.status.page.name} Status` - ); - for (const notice of summaries) { - core.info(notice); + _destroy(error, callback) { + this._stopReading = true; + this.flush = async () => { }; + // Prevent further retries + this._stopRetry(); + this._cancelTimeouts(); + this._removeListeners(); + if (this.options) { + const { body } = this.options; + if (is_distribution.nodeStream(body)) { + body.destroy(); + } } - core.info(`See: ${checkin.status.page.url}`); - core.info(``); - } + if (this._request) { + this._request.destroy(); + } + if (error !== null && !is_distribution.undefined(error) && !(error instanceof errors_RequestError)) { + error = new errors_RequestError(error.message, error, this); + } + callback(error); } - } - getFeature(name) { - if (!this.features.hasOwnProperty(name)) { - return void 0; + pipe(destination, options) { + if (destination instanceof external_node_http_.ServerResponse) { + this._pipedServerResponses.add(destination); + } + return super.pipe(destination, options); } - const result = this.features[name]; - if (result === void 0) { - return void 0; + unpipe(destination) { + if (destination instanceof external_node_http_.ServerResponse) { + this._pipedServerResponses.delete(destination); + } + super.unpipe(destination); + return this; } - this.recordEvent("$feature_flag_called", { - $feature_flag: name, - $feature_flag_response: result.variant - }); - return result; - } - /** - * Check in to install.determinate.systems, to accomplish three things: - * - * 1. Preflight the server selected from IdsHost, to increase the chances of success. - * 2. Fetch any incidents and maintenance events to let users know in case things are weird. - * 3. Get feature flag data so we can gently roll out new features. - */ - async requestCheckIn() { - for (let attemptsRemaining = 5; attemptsRemaining > 0; attemptsRemaining--) { - const checkInUrl = await this.getCheckInUrl(); - if (checkInUrl === void 0) { - return void 0; - } - try { - core.debug(`Preflighting via ${checkInUrl}`); - checkInUrl.searchParams.set("ci", "github"); - checkInUrl.searchParams.set( - "correlation", - JSON.stringify(this.identity) - ); - return (await this.getClient()).get(checkInUrl, { - timeout: { - request: CHECK_IN_ENDPOINT_TIMEOUT_MS - } - }).json(); - } catch (e) { - this.recordPlausibleTimeout(e); - core.debug(`Error checking in: ${stringifyError2(e)}`); - this.idsHost.markCurrentHostBroken(); - } + async _finalizeBody() { + const { options } = this; + const { headers } = options; + const isForm = !is_distribution.undefined(options.form); + // eslint-disable-next-line @typescript-eslint/naming-convention + const isJSON = !is_distribution.undefined(options.json); + const isBody = !is_distribution.undefined(options.body); + const cannotHaveBody = core_methodsWithoutBody.has(options.method) && !(options.method === 'GET' && options.allowGetBody); + this._cannotHaveBody = cannotHaveBody; + if (isForm || isJSON || isBody) { + if (cannotHaveBody) { + throw new TypeError(`The \`${options.method}\` method cannot be used with a body`); + } + // Serialize body + const noContentType = !is_distribution.string(headers['content-type']); + if (isBody) { + // Body is spec-compliant FormData + if (lib_isFormData(options.body)) { + const encoder = new FormDataEncoder(options.body); + if (noContentType) { + headers['content-type'] = encoder.headers['Content-Type']; + } + if ('Content-Length' in encoder.headers) { + headers['content-length'] = encoder.headers['Content-Length']; + } + options.body = encoder.encode(); + } + // Special case for https://github.com/form-data/form-data + if (utils_is_form_data_isFormData(options.body) && noContentType) { + headers['content-type'] = `multipart/form-data; boundary=${options.body.getBoundary()}`; + } + } + else if (isForm) { + if (noContentType) { + headers['content-type'] = 'application/x-www-form-urlencoded'; + } + const { form } = options; + options.form = undefined; + options.body = (new URLSearchParams(form)).toString(); + } + else { + if (noContentType) { + headers['content-type'] = 'application/json'; + } + const { json } = options; + options.json = undefined; + options.body = options.stringifyJson(json); + } + const uploadBodySize = await get_body_size_getBodySize(options.body, options.headers); + // See https://tools.ietf.org/html/rfc7230#section-3.3.2 + // A user agent SHOULD send a Content-Length in a request message when + // no Transfer-Encoding is sent and the request method defines a meaning + // for an enclosed payload body. For example, a Content-Length header + // field is normally sent in a POST request even when the value is 0 + // (indicating an empty payload body). A user agent SHOULD NOT send a + // Content-Length header field when the request message does not contain + // a payload body and the method semantics do not anticipate such a + // body. + if (is_distribution.undefined(headers['content-length']) && is_distribution.undefined(headers['transfer-encoding']) && !cannotHaveBody && !is_distribution.undefined(uploadBodySize)) { + headers['content-length'] = String(uploadBodySize); + } + } + if (options.responseType === 'json' && !('accept' in options.headers)) { + options.headers.accept = 'application/json'; + } + this._bodySize = Number(headers['content-length']) || undefined; } - return void 0; - } - recordPlausibleTimeout(e) { - if (e instanceof TimeoutError && "timings" in e && "request" in e) { - const reportContext = { - url: e.request.requestUrl?.toString(), - retry_count: e.request.retryCount - }; - for (const [key, value] of Object.entries(e.timings.phases)) { - if (Number.isFinite(value)) { - reportContext[`timing_phase_${key}`] = value; + async _onResponseBase(response) { + // This will be called e.g. when using cache so we need to check if this request has been aborted. + if (this.isAborted) { + return; + } + const { options } = this; + const { url } = options; + this._nativeResponse = response; + if (options.decompress) { + response = decompress_response(response); + } + const statusCode = response.statusCode; + const typedResponse = response; + typedResponse.statusMessage = typedResponse.statusMessage ?? external_node_http_.STATUS_CODES[statusCode]; + typedResponse.url = options.url.toString(); + typedResponse.requestUrl = this.requestUrl; + typedResponse.redirectUrls = this.redirectUrls; + typedResponse.request = this; + typedResponse.isFromCache = this._nativeResponse.fromCache ?? false; + typedResponse.ip = this.ip; + typedResponse.retryCount = this.retryCount; + typedResponse.ok = response_isResponseOk(typedResponse); + this._isFromCache = typedResponse.isFromCache; + this._responseSize = Number(response.headers['content-length']) || undefined; + this.response = typedResponse; + response.once('end', () => { + this._responseSize = this._downloadedSize; + this.emit('downloadProgress', this.downloadProgress); + }); + response.once('error', (error) => { + this._aborted = true; + // Force clean-up, because some packages don't do this. + // TODO: Fix decompress-response + response.destroy(); + this._beforeError(new errors_ReadError(error, this)); + }); + response.once('aborted', () => { + this._aborted = true; + this._beforeError(new errors_ReadError({ + name: 'Error', + message: 'The server aborted pending request', + code: 'ECONNRESET', + }, this)); + }); + this.emit('downloadProgress', this.downloadProgress); + const rawCookies = response.headers['set-cookie']; + if (is_distribution.object(options.cookieJar) && rawCookies) { + let promises = rawCookies.map(async (rawCookie) => options.cookieJar.setCookie(rawCookie, url.toString())); + if (options.ignoreInvalidCookies) { + // eslint-disable-next-line @typescript-eslint/no-floating-promises + promises = promises.map(async (promise) => { + try { + await promise; + } + catch { } + }); + } + try { + await Promise.all(promises); + } + catch (error) { + this._beforeError(error); + return; + } + } + // The above is running a promise, therefore we need to check if this request has been aborted yet again. + if (this.isAborted) { + return; + } + if (response.headers.location && core_redirectCodes.has(statusCode)) { + // We're being redirected, we don't care about the response. + // It'd be best to abort the request, but we can't because + // we would have to sacrifice the TCP connection. We don't want that. + const shouldFollow = typeof options.followRedirect === 'function' ? options.followRedirect(typedResponse) : options.followRedirect; + if (shouldFollow) { + response.resume(); + this._cancelTimeouts(); + this._unproxyEvents(); + if (this.redirectUrls.length >= options.maxRedirects) { + this._beforeError(new errors_MaxRedirectsError(this)); + return; + } + this._request = undefined; + const updatedOptions = new options_Options(undefined, undefined, this.options); + const serverRequestedGet = statusCode === 303 && updatedOptions.method !== 'GET' && updatedOptions.method !== 'HEAD'; + const canRewrite = statusCode !== 307 && statusCode !== 308; + const userRequestedGet = updatedOptions.methodRewriting && canRewrite; + if (serverRequestedGet || userRequestedGet) { + updatedOptions.method = 'GET'; + updatedOptions.body = undefined; + updatedOptions.json = undefined; + updatedOptions.form = undefined; + delete updatedOptions.headers['content-length']; + } + try { + // We need this in order to support UTF-8 + const redirectBuffer = external_node_buffer_namespaceObject.Buffer.from(response.headers.location, 'binary').toString(); + const redirectUrl = new URL(redirectBuffer, url); + if (!is_unix_socket_url_isUnixSocketURL(url) && is_unix_socket_url_isUnixSocketURL(redirectUrl)) { + this._beforeError(new errors_RequestError('Cannot redirect to UNIX socket', {}, this)); + return; + } + // Redirecting to a different site, clear sensitive data. + if (redirectUrl.hostname !== url.hostname || redirectUrl.port !== url.port) { + if ('host' in updatedOptions.headers) { + delete updatedOptions.headers.host; + } + if ('cookie' in updatedOptions.headers) { + delete updatedOptions.headers.cookie; + } + if ('authorization' in updatedOptions.headers) { + delete updatedOptions.headers.authorization; + } + if (updatedOptions.username || updatedOptions.password) { + updatedOptions.username = ''; + updatedOptions.password = ''; + } + } + else { + redirectUrl.username = updatedOptions.username; + redirectUrl.password = updatedOptions.password; + } + this.redirectUrls.push(redirectUrl); + updatedOptions.prefixUrl = ''; + updatedOptions.url = redirectUrl; + for (const hook of updatedOptions.hooks.beforeRedirect) { + // eslint-disable-next-line no-await-in-loop + await hook(updatedOptions, typedResponse); + } + this.emit('redirect', updatedOptions, typedResponse); + this.options = updatedOptions; + await this._makeRequest(); + } + catch (error) { + this._beforeError(error); + return; + } + return; + } + } + // `HTTPError`s always have `error.response.body` defined. + // Therefore, we cannot retry if `options.throwHttpErrors` is false. + // On the last retry, if `options.throwHttpErrors` is false, we would need to return the body, + // but that wouldn't be possible since the body would be already read in `error.response.body`. + if (options.isStream && options.throwHttpErrors && !response_isResponseOk(typedResponse)) { + this._beforeError(new errors_HTTPError(typedResponse)); + return; + } + response.on('readable', () => { + if (this._triggerRead) { + this._read(); + } + }); + this.on('resume', () => { + response.resume(); + }); + this.on('pause', () => { + response.pause(); + }); + response.once('end', () => { + this.push(null); + }); + if (this._noPipe) { + const success = await this._setRawBody(); + if (success) { + this.emit('response', response); + } + return; + } + this.emit('response', response); + for (const destination of this._pipedServerResponses) { + if (destination.headersSent) { + continue; + } + // eslint-disable-next-line guard-for-in + for (const key in response.headers) { + const isAllowed = options.decompress ? key !== 'content-encoding' : true; + const value = response.headers[key]; + if (isAllowed) { + destination.setHeader(key, value); + } + } + destination.statusCode = statusCode; } - } - this.recordEvent("timeout", reportContext); - } - } - /** - * Fetch an artifact, such as a tarball, from the location determined by the - * `source-*` inputs. If `source-binary` is specified, this will return a path - * to a binary on disk; otherwise, the artifact will be downloaded from the - * URL determined by the other `source-*` inputs (`source-url`, `source-pr`, - * etc.). - */ - async fetchArtifact() { - const sourceBinary = getStringOrNull("source-binary"); - if (sourceBinary !== null && sourceBinary !== "") { - core.debug(`Using the provided source binary at ${sourceBinary}`); - return sourceBinary; } - core.startGroup( - `Downloading ${this.actionOptions.name} for ${this.architectureFetchSuffix}` - ); - try { - core.info(`Fetching from ${await this.getSourceUrl()}`); - const correlatedUrl = await this.getSourceUrl(); - correlatedUrl.searchParams.set("ci", "github"); - correlatedUrl.searchParams.set( - "correlation", - JSON.stringify(this.identity) - ); - const versionCheckup = await (await this.getClient()).head(correlatedUrl); - if (versionCheckup.headers.etag) { - const v = versionCheckup.headers.etag; - this.addFact(FACT_SOURCE_URL_ETAG, v); - core.debug( - `Checking the tool cache for ${await this.getSourceUrl()} at ${v}` - ); - const cached = await this.getCachedVersion(v); - if (cached) { - this.facts[FACT_ARTIFACT_FETCHED_FROM_CACHE] = true; - core.debug(`Tool cache hit.`); - return cached; + async _setRawBody(from = this) { + if (from.readableEnded) { + return false; } - } - this.facts[FACT_ARTIFACT_FETCHED_FROM_CACHE] = false; - core.debug( - `No match from the cache, re-fetching from the redirect: ${versionCheckup.url}` - ); - const destFile = this.getTemporaryName(); - const fetchStream = await this.downloadFile( - new URL(versionCheckup.url), - destFile - ); - if (fetchStream.response?.headers.etag) { - const v = fetchStream.response.headers.etag; try { - await this.saveCachedVersion(v, destFile); - } catch (e) { - core.debug(`Error caching the artifact: ${stringifyError2(e)}`); + // Errors are emitted via the `error` event + const fromArray = await from.toArray(); + const rawBody = distribution_isBuffer(fromArray.at(0)) ? external_node_buffer_namespaceObject.Buffer.concat(fromArray) : external_node_buffer_namespaceObject.Buffer.from(fromArray.join('')); + // On retry Request is destroyed with no error, therefore the above will successfully resolve. + // So in order to check if this was really successfull, we need to check if it has been properly ended. + if (!this.isAborted) { + this.response.rawBody = rawBody; + return true; + } } - } - return destFile; - } catch (e) { - this.recordPlausibleTimeout(e); - throw e; - } finally { - core.endGroup(); + catch { } + return false; } - } - /** - * A helper function for failing on error only if strict mode is enabled. - * This is intended only for CI environments testing Actions themselves. - */ - failOnError(msg) { - if (this.strictMode) { - core.setFailed(`strict mode failure: ${msg}`); + async _onResponse(response) { + try { + await this._onResponseBase(response); + } + catch (error) { + /* istanbul ignore next: better safe than sorry */ + this._beforeError(error); + } } - } - async downloadFile(url, destination) { - const client = await this.getClient(); - return new Promise((resolve, reject) => { - let writeStream; - let failed = false; - const retry = (stream) => { - if (writeStream) { - writeStream.destroy(); + _onRequest(request) { + const { options } = this; + const { timeout, url } = options; + dist_source(request); + if (this.options.http2) { + // Unset stream timeout, as the `timeout` option was used only for connection timeout. + request.setTimeout(0); } - writeStream = (0,external_node_fs_namespaceObject.createWriteStream)(destination, { - encoding: "binary", - mode: 493 - }); - writeStream.once("error", (error3) => { - failed = true; - reject(error3); + this._cancelTimeouts = timed_out_timedOut(request, timeout, url); + const responseEventName = options.cache ? 'cacheableResponse' : 'response'; + request.once(responseEventName, (response) => { + void this._onResponse(response); }); - writeStream.on("finish", () => { - if (!failed) { - resolve(stream); - } + request.once('error', (error) => { + this._aborted = true; + // Force clean-up, because some packages (e.g. nock) don't do this. + request.destroy(); + error = error instanceof core_timed_out_TimeoutError ? new errors_TimeoutError(error, this.timings, this) : new errors_RequestError(error.message, error, this); + this._beforeError(error); }); - stream.once("retry", (_count, _error, createRetryStream) => { - retry(createRetryStream()); + this._unproxyEvents = proxy_events_proxyEvents(request, this, core_proxiedRequestEvents); + this._request = request; + this.emit('uploadProgress', this.uploadProgress); + this._sendBody(); + this.emit('request', request); + } + async _asyncWrite(chunk) { + return new Promise((resolve, reject) => { + super.write(chunk, error => { + if (error) { + reject(error); + return; + } + resolve(); + }); }); - stream.pipe(writeStream); - }; - retry(client.stream(url)); - }); - } - async complete() { - this.recordEvent(`complete_${this.executionPhase}`); - await this.submitEvents(); - } - async getCheckInUrl() { - const checkInUrl = await this.idsHost.getDynamicRootUrl(); - if (checkInUrl === void 0) { - return void 0; } - checkInUrl.pathname += "check-in"; - return checkInUrl; - } - async getSourceUrl() { - const p = this.sourceParameters; - if (p.url) { - this.addFact(FACT_SOURCE_URL, p.url); - return new URL(p.url); + _sendBody() { + // Send body + const { body } = this.options; + const currentRequest = this.redirectUrls.length === 0 ? this : this._request ?? this; + if (is_distribution.nodeStream(body)) { + body.pipe(currentRequest); + } + else if (is_distribution.generator(body) || is_distribution.asyncGenerator(body)) { + (async () => { + try { + for await (const chunk of body) { + await this._asyncWrite(chunk); + } + super.end(); + } + catch (error) { + this._beforeError(error); + } + })(); + } + else if (!is_distribution.undefined(body)) { + this._writeRequest(body, undefined, () => { }); + currentRequest.end(); + } + else if (this._cannotHaveBody || this._noPipe) { + currentRequest.end(); + } } - const fetchUrl = await this.idsHost.getRootUrl(); - fetchUrl.pathname += this.actionOptions.idsProjectName; - if (p.tag) { - fetchUrl.pathname += `/tag/${p.tag}`; - } else if (p.pr) { - fetchUrl.pathname += `/pr/${p.pr}`; - } else if (p.branch) { - fetchUrl.pathname += `/branch/${p.branch}`; - } else if (p.revision) { - fetchUrl.pathname += `/rev/${p.revision}`; - } else { - fetchUrl.pathname += `/stable`; + _prepareCache(cache) { + if (!core_cacheableStore.has(cache)) { + const cacheableRequest = new dist(((requestOptions, handler) => { + const result = requestOptions._request(requestOptions, handler); + // TODO: remove this when `cacheable-request` supports async request functions. + if (is_distribution.promise(result)) { + // We only need to implement the error handler in order to support HTTP2 caching. + // The result will be a promise anyway. + // @ts-expect-error ignore + result.once = (event, handler) => { + if (event === 'error') { + (async () => { + try { + await result; + } + catch (error) { + handler(error); + } + })(); + } + else if (event === 'abort') { + // The empty catch is needed here in case when + // it rejects before it's `await`ed in `_makeRequest`. + (async () => { + try { + const request = (await result); + request.once('abort', handler); + } + catch { } + })(); + } + else { + /* istanbul ignore next: safety check */ + throw new Error(`Unknown HTTP2 promise event: ${event}`); + } + return result; + }; + } + return result; + }), cache); + core_cacheableStore.set(cache, cacheableRequest.request()); + } } - fetchUrl.pathname += `/${this.architectureFetchSuffix}`; - this.addFact(FACT_SOURCE_URL, fetchUrl.toString()); - return fetchUrl; - } - cacheKey(version2) { - const cleanedVersion = version2.replace(/[^a-zA-Z0-9-+.]/g, ""); - return `determinatesystem-${this.actionOptions.name}-${this.architectureFetchSuffix}-${cleanedVersion}`; - } - async getCachedVersion(version2) { - const startCwd = process.cwd(); - try { - const tempDir = this.getTemporaryName(); - await (0,promises_namespaceObject.mkdir)(tempDir); - process.chdir(tempDir); - process.env.GITHUB_WORKSPACE_BACKUP = process.env.GITHUB_WORKSPACE; - delete process.env.GITHUB_WORKSPACE; - if (await cache.restoreCache( - [this.actionOptions.name], - this.cacheKey(version2), - [], - void 0, - true - )) { - this.recordEvent(EVENT_ARTIFACT_CACHE_HIT); - return `${tempDir}/${this.actionOptions.name}`; - } - this.recordEvent(EVENT_ARTIFACT_CACHE_MISS); - return void 0; - } finally { - process.env.GITHUB_WORKSPACE = process.env.GITHUB_WORKSPACE_BACKUP; - delete process.env.GITHUB_WORKSPACE_BACKUP; - process.chdir(startCwd); + async _createCacheableRequest(url, options) { + return new Promise((resolve, reject) => { + // TODO: Remove `utils/url-to-options.ts` when `cacheable-request` is fixed + Object.assign(options, url_to_options_urlToOptions(url)); + let request; + // TODO: Fix `cacheable-response`. This is ugly. + const cacheRequest = core_cacheableStore.get(options.cache)(options, async (response) => { + response._readableState.autoDestroy = false; + if (request) { + const fix = () => { + if (response.req) { + response.complete = response.req.res.complete; + } + }; + response.prependOnceListener('end', fix); + fix(); + (await request).emit('cacheableResponse', response); + } + resolve(response); + }); + cacheRequest.once('error', reject); + cacheRequest.once('request', async (requestOrPromise) => { + request = requestOrPromise; + resolve(request); + }); + }); } - } - async saveCachedVersion(version2, toolPath) { - const startCwd = process.cwd(); - try { - const tempDir = this.getTemporaryName(); - await (0,promises_namespaceObject.mkdir)(tempDir); - process.chdir(tempDir); - await (0,promises_namespaceObject.copyFile)(toolPath, `${tempDir}/${this.actionOptions.name}`); - process.env.GITHUB_WORKSPACE_BACKUP = process.env.GITHUB_WORKSPACE; - delete process.env.GITHUB_WORKSPACE; - await cache.saveCache( - [this.actionOptions.name], - this.cacheKey(version2), - void 0, - true - ); - this.recordEvent(EVENT_ARTIFACT_CACHE_PERSIST); - } finally { - process.env.GITHUB_WORKSPACE = process.env.GITHUB_WORKSPACE_BACKUP; - delete process.env.GITHUB_WORKSPACE_BACKUP; - process.chdir(startCwd); + async _makeRequest() { + const { options } = this; + const { headers, username, password } = options; + const cookieJar = options.cookieJar; + for (const key in headers) { + if (is_distribution.undefined(headers[key])) { + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete + delete headers[key]; + } + else if (is_distribution["null"](headers[key])) { + throw new TypeError(`Use \`undefined\` instead of \`null\` to delete the \`${key}\` header`); + } + } + if (options.decompress && is_distribution.undefined(headers['accept-encoding'])) { + headers['accept-encoding'] = core_supportsBrotli ? 'gzip, deflate, br' : 'gzip, deflate'; + } + if (username || password) { + const credentials = external_node_buffer_namespaceObject.Buffer.from(`${username}:${password}`).toString('base64'); + headers.authorization = `Basic ${credentials}`; + } + // Set cookies + if (cookieJar) { + const cookieString = await cookieJar.getCookieString(options.url.toString()); + if (is_distribution.nonEmptyString(cookieString)) { + headers.cookie = cookieString; + } + } + // Reset `prefixUrl` + options.prefixUrl = ''; + let request; + for (const hook of options.hooks.beforeRequest) { + // eslint-disable-next-line no-await-in-loop + const result = await hook(options); + if (!is_distribution.undefined(result)) { + // @ts-expect-error Skip the type mismatch to support abstract responses + request = () => result; + break; + } + } + request ||= options.getRequestFunction(); + const url = options.url; + this._requestOptions = options.createNativeRequestOptions(); + if (options.cache) { + this._requestOptions._request = request; + this._requestOptions.cache = options.cache; + this._requestOptions.body = options.body; + this._prepareCache(options.cache); + } + // Cache support + const function_ = options.cache ? this._createCacheableRequest : request; + try { + // We can't do `await fn(...)`, + // because stream `error` event can be emitted before `Promise.resolve()`. + let requestOrResponse = function_(url, this._requestOptions); + if (is_distribution.promise(requestOrResponse)) { + requestOrResponse = await requestOrResponse; + } + // Fallback + if (is_distribution.undefined(requestOrResponse)) { + requestOrResponse = options.getFallbackRequestFunction()(url, this._requestOptions); + if (is_distribution.promise(requestOrResponse)) { + requestOrResponse = await requestOrResponse; + } + } + if (utils_is_client_request(requestOrResponse)) { + this._onRequest(requestOrResponse); + } + else if (this.writable) { + this.once('finish', () => { + void this._onResponse(requestOrResponse); + }); + this._sendBody(); + } + else { + void this._onResponse(requestOrResponse); + } + } + catch (error) { + if (error instanceof types_CacheError) { + throw new errors_CacheError(error, this); + } + throw error; + } } - } - collectBacktraceSetup() { - if (process.env.DETSYS_BACKTRACE_COLLECTOR === "") { - core.exportVariable( - "DETSYS_BACKTRACE_COLLECTOR", - this.getCrossPhaseId() - ); - core.saveState(STATE_BACKTRACE_START_TIMESTAMP, Date.now()); + async _error(error) { + try { + if (error instanceof errors_HTTPError && !this.options.throwHttpErrors) { + // This branch can be reached only when using the Promise API + // Skip calling the hooks on purpose. + // See https://github.com/sindresorhus/got/issues/2103 + } + else { + for (const hook of this.options.hooks.beforeError) { + // eslint-disable-next-line no-await-in-loop + error = await hook(error); + } + } + } + catch (error_) { + error = new errors_RequestError(error_.message, error_, this); + } + this.destroy(error); } - } - async collectBacktraces() { - try { - if (process.env.DETSYS_BACKTRACE_COLLECTOR !== this.getCrossPhaseId()) { - return; - } - const backtraces = await collectBacktraces( - this.actionOptions.binaryNamePrefixes, - parseInt(core.getState(STATE_BACKTRACE_START_TIMESTAMP)) - ); - core.debug(`Backtraces identified: ${backtraces.size}`); - if (backtraces.size > 0) { - this.recordEvent(EVENT_BACKTRACES, Object.fromEntries(backtraces)); - } - } catch (innerError) { - core.debug( - `Error collecting backtraces: ${stringifyError2(innerError)}` - ); + _writeRequest(chunk, encoding, callback) { + if (!this._request || this._request.destroyed) { + // Probably the `ClientRequest` instance will throw + return; + } + this._request.write(chunk, encoding, (error) => { + // The `!destroyed` check is required to prevent `uploadProgress` being emitted after the stream was destroyed + if (!error && !this._request.destroyed) { + this._uploadedSize += external_node_buffer_namespaceObject.Buffer.byteLength(chunk, encoding); + const progress = this.uploadProgress; + if (progress.percent < 1) { + this.emit('uploadProgress', progress); + } + } + callback(error); + }); } - } - async preflightRequireNix() { - let nixLocation; - const pathParts = (process.env["PATH"] || "").split(":"); - for (const location of pathParts) { - const candidateNix = external_node_path_namespaceObject.join(location, "nix"); - try { - await promises_namespaceObject.access(candidateNix, promises_namespaceObject.constants.X_OK); - core.debug(`Found Nix at ${candidateNix}`); - nixLocation = candidateNix; - break; - } catch { - core.debug(`Nix not at ${candidateNix}`); - } + /** + The remote IP address. + */ + get ip() { + return this.socket?.remoteAddress; } - this.addFact(FACT_NIX_LOCATION, nixLocation || ""); - if (this.actionOptions.requireNix === "ignore") { - return true; + /** + Indicates whether the request has been aborted or not. + */ + get isAborted() { + return this._aborted; } - const currentNotFoundState = core.getState(STATE_KEY_NIX_NOT_FOUND); - if (currentNotFoundState === STATE_NOT_FOUND) { - return false; + get socket() { + return this._request?.socket ?? undefined; + } + /** + Progress event for downloading (receiving a response). + */ + get downloadProgress() { + let percent; + if (this._responseSize) { + percent = this._downloadedSize / this._responseSize; + } + else if (this._responseSize === this._downloadedSize) { + percent = 1; + } + else { + percent = 0; + } + return { + percent, + transferred: this._downloadedSize, + total: this._responseSize, + }; + } + /** + Progress event for uploading (sending a request). + */ + get uploadProgress() { + let percent; + if (this._bodySize) { + percent = this._uploadedSize / this._bodySize; + } + else if (this._bodySize === this._uploadedSize) { + percent = 1; + } + else { + percent = 0; + } + return { + percent, + transferred: this._uploadedSize, + total: this._bodySize, + }; } - if (nixLocation !== void 0) { - return true; + /** + The object contains the following properties: + + - `start` - Time when the request started. + - `socket` - Time when a socket was assigned to the request. + - `lookup` - Time when the DNS lookup finished. + - `connect` - Time when the socket successfully connected. + - `secureConnect` - Time when the socket securely connected. + - `upload` - Time when the request finished uploading. + - `response` - Time when the request fired `response` event. + - `end` - Time when the response fired `end` event. + - `error` - Time when the request fired `error` event. + - `abort` - Time when the request fired `abort` event. + - `phases` + - `wait` - `timings.socket - timings.start` + - `dns` - `timings.lookup - timings.socket` + - `tcp` - `timings.connect - timings.lookup` + - `tls` - `timings.secureConnect - timings.connect` + - `request` - `timings.upload - (timings.secureConnect || timings.connect)` + - `firstByte` - `timings.response - timings.upload` + - `download` - `timings.end - timings.response` + - `total` - `(timings.end || timings.error || timings.abort) - timings.start` + + If something has not been measured yet, it will be `undefined`. + + __Note__: The time is a `number` representing the milliseconds elapsed since the UNIX epoch. + */ + get timings() { + return this._request?.timings; } - core.saveState(STATE_KEY_NIX_NOT_FOUND, STATE_NOT_FOUND); - switch (this.actionOptions.requireNix) { - case "fail": - core.setFailed( - [ - "This action can only be used when Nix is installed.", - "Add `- uses: DeterminateSystems/nix-installer-action@main` earlier in your workflow." - ].join(" ") - ); - break; - case "warn": - core.warning( - [ - "This action is in no-op mode because Nix is not installed.", - "Add `- uses: DeterminateSystems/nix-installer-action@main` earlier in your workflow." - ].join(" ") - ); - break; + /** + Whether the response was retrieved from the cache. + */ + get isFromCache() { + return this._isFromCache; } - return false; - } - async preflightNixStoreInfo() { - let output = ""; - const options = {}; - options.silent = true; - options.listeners = { - stdout: (data) => { - output += data.toString(); - } - }; - try { - output = ""; - await exec.exec("nix", ["store", "info", "--json"], options); - this.addFact(FACT_NIX_STORE_CHECK_METHOD, "info"); - } catch { - try { - output = ""; - await exec.exec("nix", ["store", "ping", "--json"], options); - this.addFact(FACT_NIX_STORE_CHECK_METHOD, "ping"); - } catch { - this.addFact(FACT_NIX_STORE_CHECK_METHOD, "none"); - return; - } + get reusedSocket() { + return this._request?.reusedSocket; } - try { - const parsed = JSON.parse(output); - if (parsed.trusted === 1) { - this.nixStoreTrust = "trusted"; - } else if (parsed.trusted === 0) { - this.nixStoreTrust = "untrusted"; - } else if (parsed.trusted !== void 0) { - this.addFact( - FACT_NIX_STORE_CHECK_ERROR, - `Mysterious trusted value: ${JSON.stringify(parsed.trusted)}` - ); - } - this.addFact(FACT_NIX_STORE_VERSION, JSON.stringify(parsed.version)); - } catch (e) { - this.addFact(FACT_NIX_STORE_CHECK_ERROR, stringifyError2(e)); +} + +;// CONCATENATED MODULE: ./node_modules/.pnpm/got@14.4.2/node_modules/got/dist/source/as-promise/types.js + +/** +An error to be thrown when the request is aborted with `.cancel()`. +*/ +class as_promise_types_CancelError extends errors_RequestError { + constructor(request) { + super('Promise was canceled', {}, request); + this.name = 'CancelError'; + this.code = 'ERR_CANCELED'; } - } - async submitEvents() { - const diagnosticsUrl = await this.idsHost.getDiagnosticsUrl(); - if (diagnosticsUrl === void 0) { - core.debug( - "Diagnostics are disabled. Not sending the following events:" - ); - core.debug(JSON.stringify(this.events, void 0, 2)); - return; + /** + Whether the promise is canceled. + */ + get isCanceled() { + return true; } - const batch = { - type: "eventlog", - sent_at: /* @__PURE__ */ new Date(), - events: this.events +} + +;// CONCATENATED MODULE: ./node_modules/.pnpm/got@14.4.2/node_modules/got/dist/source/as-promise/index.js + + + + + + + + +const source_as_promise_proxiedRequestEvents = [ + 'request', + 'response', + 'redirect', + 'uploadProgress', + 'downloadProgress', +]; +function as_promise_asPromise(firstRequest) { + let globalRequest; + let globalResponse; + let normalizedOptions; + const emitter = new external_node_events_.EventEmitter(); + const promise = new PCancelable((resolve, reject, onCancel) => { + onCancel(() => { + globalRequest.destroy(); + }); + onCancel.shouldReject = false; + onCancel(() => { + reject(new as_promise_types_CancelError(globalRequest)); + }); + const makeRequest = (retryCount) => { + // Errors when a new request is made after the promise settles. + // Used to detect a race condition. + // See https://github.com/sindresorhus/got/issues/1489 + onCancel(() => { }); + const request = firstRequest ?? new core_Request(undefined, undefined, normalizedOptions); + request.retryCount = retryCount; + request._noPipe = true; + globalRequest = request; + request.once('response', async (response) => { + // Parse body + const contentEncoding = (response.headers['content-encoding'] ?? '').toLowerCase(); + const isCompressed = contentEncoding === 'gzip' || contentEncoding === 'deflate' || contentEncoding === 'br'; + const { options } = request; + if (isCompressed && !options.decompress) { + response.body = response.rawBody; + } + else { + try { + response.body = response_parseBody(response, options.responseType, options.parseJson, options.encoding); + } + catch (error) { + // Fall back to `utf8` + try { + response.body = response.rawBody.toString(); + } + catch (error) { + request._beforeError(new response_ParseError(error, response)); + return; + } + if (response_isResponseOk(response)) { + request._beforeError(error); + return; + } + } + } + try { + const hooks = options.hooks.afterResponse; + for (const [index, hook] of hooks.entries()) { + // @ts-expect-error TS doesn't notice that CancelableRequest is a Promise + // eslint-disable-next-line no-await-in-loop + response = await hook(response, async (updatedOptions) => { + options.merge(updatedOptions); + options.prefixUrl = ''; + if (updatedOptions.url) { + options.url = updatedOptions.url; + } + // Remove any further hooks for that request, because we'll call them anyway. + // The loop continues. We don't want duplicates (asPromise recursion). + options.hooks.afterResponse = options.hooks.afterResponse.slice(0, index); + throw new errors_RetryError(request); + }); + if (!(is_distribution.object(response) && is_distribution.number(response.statusCode) && !is_distribution.nullOrUndefined(response.body))) { + throw new TypeError('The `afterResponse` hook returned an invalid value'); + } + } + } + catch (error) { + request._beforeError(error); + return; + } + globalResponse = response; + if (!response_isResponseOk(response)) { + request._beforeError(new errors_HTTPError(response)); + return; + } + request.destroy(); + resolve(request.options.resolveBodyOnly ? response.body : response); + }); + const onError = (error) => { + if (promise.isCanceled) { + return; + } + const { options } = request; + if (error instanceof errors_HTTPError && !options.throwHttpErrors) { + const { response } = error; + request.destroy(); + resolve(request.options.resolveBodyOnly ? response.body : response); + return; + } + reject(error); + }; + request.once('error', onError); + const previousBody = request.options?.body; + request.once('retry', (newRetryCount, error) => { + firstRequest = undefined; + const newBody = request.options.body; + if (previousBody === newBody && is_distribution.nodeStream(newBody)) { + error.message = 'Cannot retry with consumed body stream'; + onError(error); + return; + } + // This is needed! We need to reuse `request.options` because they can get modified! + // For example, by calling `promise.json()`. + normalizedOptions = request.options; + makeRequest(newRetryCount); + }); + proxy_events_proxyEvents(request, emitter, source_as_promise_proxiedRequestEvents); + if (is_distribution.undefined(firstRequest)) { + void request.flush(); + } + }; + makeRequest(0); + }); + promise.on = (event, function_) => { + emitter.on(event, function_); + return promise; }; - try { - await (await this.getClient()).post(diagnosticsUrl, { - json: batch, - timeout: { - request: DIAGNOSTIC_ENDPOINT_TIMEOUT_MS + promise.off = (event, function_) => { + emitter.off(event, function_); + return promise; + }; + const shortcut = (responseType) => { + const newPromise = (async () => { + // Wait until downloading has ended + await promise; + const { options } = globalResponse.request; + return response_parseBody(globalResponse, responseType, options.parseJson, options.encoding); + })(); + // eslint-disable-next-line @typescript-eslint/no-floating-promises + Object.defineProperties(newPromise, Object.getOwnPropertyDescriptors(promise)); + return newPromise; + }; + promise.json = () => { + if (globalRequest.options) { + const { headers } = globalRequest.options; + if (!globalRequest.writableFinished && !('accept' in headers)) { + headers.accept = 'application/json'; + } } - }); - } catch (err) { - this.recordPlausibleTimeout(err); - core.debug( - `Error submitting diagnostics event to ${diagnosticsUrl}: ${stringifyError2(err)}` - ); + return shortcut('json'); + }; + promise.buffer = () => shortcut('buffer'); + promise.text = () => shortcut('text'); + return promise; +} + +;// CONCATENATED MODULE: ./node_modules/.pnpm/got@14.4.2/node_modules/got/dist/source/create.js + + + + +// The `delay` package weighs 10KB (!) +const delay = async (ms) => new Promise(resolve => { + setTimeout(resolve, ms); +}); +const create_isGotInstance = (value) => is_distribution["function"](value); +const create_aliases = [ + 'get', + 'post', + 'put', + 'patch', + 'head', + 'delete', +]; +const create_create = (defaults) => { + defaults = { + options: new options_Options(undefined, undefined, defaults.options), + handlers: [...defaults.handlers], + mutableDefaults: defaults.mutableDefaults, + }; + Object.defineProperty(defaults, 'mutableDefaults', { + enumerable: true, + configurable: false, + writable: false, + }); + // Got interface + const got = ((url, options, defaultOptions = defaults.options) => { + const request = new core_Request(url, options, defaultOptions); + let promise; + const lastHandler = (normalized) => { + // Note: `options` is `undefined` when `new Options(...)` fails + request.options = normalized; + request._noPipe = !normalized?.isStream; + void request.flush(); + if (normalized?.isStream) { + return request; + } + promise ||= as_promise_asPromise(request); + return promise; + }; + let iteration = 0; + const iterateHandlers = (newOptions) => { + const handler = defaults.handlers[iteration++] ?? lastHandler; + const result = handler(newOptions, iterateHandlers); + if (is_distribution.promise(result) && !request.options?.isStream) { + promise ||= as_promise_asPromise(request); + if (result !== promise) { + const descriptors = Object.getOwnPropertyDescriptors(promise); + for (const key in descriptors) { + if (key in result) { + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete + delete descriptors[key]; + } + } + // eslint-disable-next-line @typescript-eslint/no-floating-promises + Object.defineProperties(result, descriptors); + result.cancel = promise.cancel; + } + } + return result; + }; + return iterateHandlers(request.options); + }); + got.extend = (...instancesOrOptions) => { + const options = new options_Options(undefined, undefined, defaults.options); + const handlers = [...defaults.handlers]; + let mutableDefaults; + for (const value of instancesOrOptions) { + if (create_isGotInstance(value)) { + options.merge(value.defaults.options); + handlers.push(...value.defaults.handlers); + mutableDefaults = value.defaults.mutableDefaults; + } + else { + options.merge(value); + if (value.handlers) { + handlers.push(...value.handlers); + } + mutableDefaults = value.mutableDefaults; + } + } + return create_create({ + options, + handlers, + mutableDefaults: Boolean(mutableDefaults), + }); + }; + // Pagination + const paginateEach = (async function* (url, options) { + let normalizedOptions = new options_Options(url, options, defaults.options); + normalizedOptions.resolveBodyOnly = false; + const { pagination } = normalizedOptions; + distribution_assert["function"](pagination.transform); + distribution_assert["function"](pagination.shouldContinue); + distribution_assert["function"](pagination.filter); + distribution_assert["function"](pagination.paginate); + distribution_assert.number(pagination.countLimit); + distribution_assert.number(pagination.requestLimit); + distribution_assert.number(pagination.backoff); + const allItems = []; + let { countLimit } = pagination; + let numberOfRequests = 0; + while (numberOfRequests < pagination.requestLimit) { + if (numberOfRequests !== 0) { + // eslint-disable-next-line no-await-in-loop + await delay(pagination.backoff); + } + // eslint-disable-next-line no-await-in-loop + const response = (await got(undefined, undefined, normalizedOptions)); + // eslint-disable-next-line no-await-in-loop + const parsed = await pagination.transform(response); + const currentItems = []; + distribution_assert.array(parsed); + for (const item of parsed) { + if (pagination.filter({ item, currentItems, allItems })) { + if (!pagination.shouldContinue({ item, currentItems, allItems })) { + return; + } + yield item; + if (pagination.stackAllItems) { + allItems.push(item); + } + currentItems.push(item); + if (--countLimit <= 0) { + return; + } + } + } + const optionsToMerge = pagination.paginate({ + response, + currentItems, + allItems, + }); + if (optionsToMerge === false) { + return; + } + if (optionsToMerge === response.request.options) { + normalizedOptions = response.request.options; + } + else { + normalizedOptions.merge(optionsToMerge); + distribution_assert.any([is_distribution.urlInstance, is_distribution.undefined], optionsToMerge.url); + if (optionsToMerge.url !== undefined) { + normalizedOptions.prefixUrl = ''; + normalizedOptions.url = optionsToMerge.url; + } + } + numberOfRequests++; + } + }); + got.paginate = paginateEach; + got.paginate.all = (async (url, options) => { + const results = []; + for await (const item of paginateEach(url, options)) { + results.push(item); + } + return results; + }); + // For those who like very descriptive names + got.paginate.each = paginateEach; + // Stream API + got.stream = ((url, options) => got(url, { ...options, isStream: true })); + // Shortcuts + for (const method of create_aliases) { + got[method] = ((url, options) => got(url, { ...options, method })); + got.stream[method] = ((url, options) => got(url, { ...options, method, isStream: true })); } - this.events = []; - } + if (!defaults.mutableDefaults) { + Object.freeze(defaults.handlers); + defaults.options.freeze(); + } + Object.defineProperty(got, 'defaults', { + value: defaults, + writable: false, + configurable: false, + enumerable: true, + }); + return got; }; -function stringifyError2(error3) { - return error3 instanceof Error || typeof error3 == "string" ? error3.toString() : JSON.stringify(error3); -} -function makeOptionsConfident(actionOptions) { - const idsProjectName = actionOptions.idsProjectName ?? actionOptions.name; - const finalOpts = { - name: actionOptions.name, - idsProjectName, - eventPrefix: actionOptions.eventPrefix || "action:", - fetchStyle: actionOptions.fetchStyle, - legacySourcePrefix: actionOptions.legacySourcePrefix, - requireNix: actionOptions.requireNix, - binaryNamePrefixes: actionOptions.binaryNamePrefixes ?? [ - "nix", - "determinate-nixd", - actionOptions.name - ] - }; - core.debug("idslib options:"); - core.debug(JSON.stringify(finalOpts, void 0, 2)); - return finalOpts; -} +/* harmony default export */ const dist_source_create = (create_create); + +;// CONCATENATED MODULE: ./node_modules/.pnpm/got@14.4.2/node_modules/got/dist/source/index.js + + +const source_defaults = { + options: new options_Options(), + handlers: [], + mutableDefaults: false, +}; +const source_got = dist_source_create(source_defaults); +/* harmony default export */ const node_modules_got_dist_source = (source_got); +// TODO: Remove this in the next major version. + + + + + + + + + + + -/*! - * linux-release-info - * Get Linux release info (distribution name, version, arch, release, etc.) - * from '/etc/os-release' or '/usr/lib/os-release' files and from native os - * module. On Windows and Darwin platforms it only returns common node os module - * info (platform, hostname, release, and arch) - * - * Licensed under MIT - * Copyright (c) 2018-2020 [Samuel Carreira] - */ -//# sourceMappingURL=index.js.map // EXTERNAL MODULE: external "http" var external_http_ = __nccwpck_require__(3685); ;// CONCATENATED MODULE: ./dist/index.js @@ -85887,6 +91810,26 @@ var external_http_ = __nccwpck_require__(3685); +function getTrinaryInput(name) { + const trueValue = ["true", "True", "TRUE", "enabled"]; + const falseValue = ["false", "False", "FALSE", "disabled"]; + const noPreferenceValue = ["", "null", "no-preference"]; + const val = core.getInput(name); + if (trueValue.includes(val)) { + return "enabled"; + } + if (falseValue.includes(val)) { + return "disabled"; + } + if (noPreferenceValue.includes(val)) { + return "no-preference"; + } + const possibleValues = trueValue.concat(falseValue).concat(noPreferenceValue).join(" | "); + throw new TypeError( + `Input ${name} does not look like a trinary, which requires one of: +${possibleValues}` + ); +} function tailLog(daemonDir) { const log = new tail/* Tail */.x(external_node_path_namespaceObject.join(daemonDir, "daemon.log")); core.debug(`tailing daemon.log...`); @@ -85967,7 +91910,7 @@ var MagicNixCacheAction = class extends DetSysAction { this.hostAndPort = inputs_exports.getString("listen"); this.diffStore = inputs_exports.getBool("diff-store"); this.addFact(FACT_DIFF_STORE_ENABLED, this.diffStore); - this.httpClient = got_dist_source.extend({ + this.httpClient = node_modules_got_dist_source.extend({ retry: { limit: 1, methods: ["POST", "GET", "PUT", "HEAD", "DELETE", "OPTIONS", "TRACE"] @@ -86095,11 +92038,11 @@ var MagicNixCacheAction = class extends DetSysAction { const nixConfPath = `${process.env["HOME"]}/.config/nix/nix.conf`; const upstreamCache = inputs_exports.getString("upstream-cache"); const diagnosticEndpoint = inputs_exports.getString("diagnostic-endpoint"); - const useFlakeHub = inputs_exports.getBool("use-flakehub"); + const useFlakeHub = getTrinaryInput("use-flakehub"); const flakeHubCacheServer = inputs_exports.getString("flakehub-cache-server"); const flakeHubApiServer = inputs_exports.getString("flakehub-api-server"); const flakeHubFlakeName = inputs_exports.getString("flakehub-flake-name"); - const useGhaCache = inputs_exports.getBool("use-gha-cache"); + const useGhaCache = getTrinaryInput("use-gha-cache"); const daemonCliFlags = [ "--startup-notification-url", `http://127.0.0.1:${notifyPort}`, @@ -86110,10 +92053,13 @@ var MagicNixCacheAction = class extends DetSysAction { "--diagnostic-endpoint", diagnosticEndpoint, "--nix-conf", - nixConfPath + nixConfPath, + "--use-gha-cache", + useGhaCache, + "--use-flakehub", + useFlakeHub ].concat(this.diffStore ? ["--diff-store"] : []).concat( - useFlakeHub ? [ - "--use-flakehub", + useFlakeHub !== "disabled" ? [ "--flakehub-cache-server", flakeHubCacheServer, "--flakehub-api-server", @@ -86123,7 +92069,7 @@ var MagicNixCacheAction = class extends DetSysAction { "--flakehub-flake-name", flakeHubFlakeName ] : [] - ).concat(useGhaCache ? ["--use-gha-cache"] : []); + ); const opts = { stdio: ["ignore", output, output], env: runEnv, diff --git a/dist/index.js.map b/dist/index.js.map index bfb587f..6ceb5b0 100644 --- a/dist/index.js.map +++ b/dist/index.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/helpers.ts","../src/index.ts"],"sourcesContent":["import * as actionsCore from \"@actions/core\";\nimport * as fs from \"node:fs/promises\";\nimport * as os from \"node:os\";\nimport path from \"node:path\";\nimport { Tail } from \"tail\";\n\nexport function tailLog(daemonDir: string): Tail {\n const log = new Tail(path.join(daemonDir, \"daemon.log\"));\n actionsCore.debug(`tailing daemon.log...`);\n log.on(\"line\", (line) => {\n actionsCore.info(line);\n });\n return log;\n}\n\nexport async function netrcPath(): Promise {\n const expectedNetrcPath = path.join(\n process.env[\"RUNNER_TEMP\"] ?? os.tmpdir(),\n \"determinate-nix-installer-netrc\",\n );\n try {\n await fs.access(expectedNetrcPath);\n return expectedNetrcPath;\n } catch {\n // `nix-installer` was not used, the user may be registered with FlakeHub though.\n const destinedNetrcPath = path.join(\n process.env[\"RUNNER_TEMP\"] ?? os.tmpdir(),\n \"magic-nix-cache-netrc\",\n );\n try {\n await flakeHubLogin(destinedNetrcPath);\n } catch (e) {\n actionsCore.info(\n \"FlakeHub Cache is disabled due to missing or invalid token\",\n );\n actionsCore.info(\n `If you're signed up for FlakeHub Cache, make sure that your Actions config has a \\`permissions\\` block with \\`id-token\\` set to \"write\" and \\`contents\\` set to \"read\"`,\n );\n actionsCore.debug(`Error while logging into FlakeHub: ${e}`);\n }\n return destinedNetrcPath;\n }\n}\n\nasync function flakeHubLogin(netrc: string): Promise {\n const jwt = await actionsCore.getIDToken(\"api.flakehub.com\");\n\n await fs.writeFile(\n netrc,\n [\n `machine api.flakehub.com login flakehub password ${jwt}`,\n `machine flakehub.com login flakehub password ${jwt}`,\n `machine cache.flakehub.com login flakehub password ${jwt}`,\n ].join(\"\\n\"),\n );\n\n actionsCore.info(\"Logged in to FlakeHub.\");\n}\n","import { netrcPath, tailLog } from \"./helpers.js\";\nimport * as actionsCore from \"@actions/core\";\nimport { DetSysAction, inputs, stringifyError } from \"detsys-ts\";\nimport got, { Got, Response } from \"got\";\nimport * as http from \"http\";\nimport { SpawnOptions, spawn } from \"node:child_process\";\nimport { mkdirSync, openSync, readFileSync } from \"node:fs\";\nimport * as fs from \"node:fs/promises\";\nimport * as path from \"node:path\";\n\n// The ENV_DAEMON_DIR is intended to determine if we \"own\" the daemon or not,\n// in the case that a user has put the magic nix cache into their workflow\n// twice.\nconst ENV_DAEMON_DIR = \"MAGIC_NIX_CACHE_DAEMONDIR\";\n\nconst FACT_ENV_VARS_PRESENT = \"required_env_vars_present\";\nconst FACT_DIFF_STORE_ENABLED = \"diff_store\";\nconst FACT_ALREADY_RUNNING = \"noop_mode\";\n\nconst STATE_DAEMONDIR = \"MAGIC_NIX_CACHE_DAEMONDIR\";\nconst STATE_ERROR_IN_MAIN = \"ERROR_IN_MAIN\";\nconst STATE_STARTED = \"MAGIC_NIX_CACHE_STARTED\";\nconst STARTED_HINT = \"true\";\n\nconst TEXT_ALREADY_RUNNING =\n \"Magic Nix Cache is already running, this workflow job is in noop mode. Is the Magic Nix Cache in the workflow twice?\";\nconst TEXT_TRUST_UNTRUSTED =\n \"The Nix daemon does not consider the user running this workflow to be trusted. Magic Nix Cache is disabled.\";\nconst TEXT_TRUST_UNKNOWN =\n \"The Nix daemon may not consider the user running this workflow to be trusted. Magic Nix Cache may not start correctly.\";\n\nclass MagicNixCacheAction extends DetSysAction {\n private hostAndPort: string;\n private diffStore: boolean;\n private httpClient: Got;\n private daemonDir: string;\n private daemonStarted: boolean;\n\n // This is set to `true` if the MNC is already running, in which case the\n // workflow will use the existing process rather than starting a new one.\n private alreadyRunning: boolean;\n\n constructor() {\n super({\n name: \"magic-nix-cache\",\n fetchStyle: \"gh-env-style\",\n idsProjectName: \"magic-nix-cache-closure\",\n requireNix: \"warn\",\n diagnosticsSuffix: \"perf\",\n });\n\n this.hostAndPort = inputs.getString(\"listen\");\n this.diffStore = inputs.getBool(\"diff-store\");\n\n this.addFact(FACT_DIFF_STORE_ENABLED, this.diffStore);\n\n this.httpClient = got.extend({\n retry: {\n limit: 1,\n methods: [\"POST\", \"GET\", \"PUT\", \"HEAD\", \"DELETE\", \"OPTIONS\", \"TRACE\"],\n },\n hooks: {\n beforeRetry: [\n (error, retryCount) => {\n actionsCore.info(\n `Retrying after error ${error.code}, retry #: ${retryCount}`,\n );\n },\n ],\n },\n });\n\n this.daemonStarted = actionsCore.getState(STATE_STARTED) === STARTED_HINT;\n\n if (actionsCore.getState(STATE_DAEMONDIR) !== \"\") {\n this.daemonDir = actionsCore.getState(STATE_DAEMONDIR);\n } else {\n this.daemonDir = this.getTemporaryName();\n mkdirSync(this.daemonDir);\n actionsCore.saveState(STATE_DAEMONDIR, this.daemonDir);\n }\n\n if (process.env[ENV_DAEMON_DIR] === undefined) {\n this.alreadyRunning = false;\n actionsCore.exportVariable(ENV_DAEMON_DIR, this.daemonDir);\n } else {\n this.alreadyRunning = process.env[ENV_DAEMON_DIR] !== this.daemonDir;\n }\n this.addFact(FACT_ALREADY_RUNNING, this.alreadyRunning);\n\n this.stapleFile(\"daemon.log\", path.join(this.daemonDir, \"daemon.log\"));\n }\n\n async main(): Promise {\n if (this.alreadyRunning) {\n actionsCore.warning(TEXT_ALREADY_RUNNING);\n return;\n }\n\n if (this.nixStoreTrust === \"untrusted\") {\n actionsCore.warning(TEXT_TRUST_UNTRUSTED);\n return;\n } else if (this.nixStoreTrust === \"unknown\") {\n actionsCore.info(TEXT_TRUST_UNKNOWN);\n }\n\n await this.setUpAutoCache();\n await this.notifyAutoCache();\n }\n\n async post(): Promise {\n // If strict mode is off and there was an error in main, such as the daemon not starting,\n // then the post phase is skipped with a warning.\n if (!this.strictMode && this.errorInMain) {\n actionsCore.warning(\n `skipping post phase due to error in main phase: ${this.errorInMain}`,\n );\n return;\n }\n\n if (this.alreadyRunning) {\n actionsCore.debug(TEXT_ALREADY_RUNNING);\n return;\n }\n\n if (this.nixStoreTrust === \"untrusted\") {\n actionsCore.debug(TEXT_TRUST_UNTRUSTED);\n return;\n } else if (this.nixStoreTrust === \"unknown\") {\n actionsCore.debug(TEXT_TRUST_UNKNOWN);\n }\n\n await this.tearDownAutoCache();\n }\n\n async setUpAutoCache(): Promise {\n const requiredEnv = [\n \"ACTIONS_CACHE_URL\",\n \"ACTIONS_RUNTIME_URL\",\n \"ACTIONS_RUNTIME_TOKEN\",\n ];\n\n let anyMissing = false;\n for (const n of requiredEnv) {\n if (!process.env.hasOwnProperty(n)) {\n anyMissing = true;\n actionsCore.warning(\n `Disabling automatic caching since required environment ${n} isn't available`,\n );\n }\n }\n\n this.addFact(FACT_ENV_VARS_PRESENT, !anyMissing);\n if (anyMissing) {\n return;\n }\n\n if (this.daemonStarted) {\n actionsCore.debug(\"Already started.\");\n return;\n }\n\n actionsCore.debug(\n `GitHub Action Cache URL: ${process.env[\"ACTIONS_CACHE_URL\"]}`,\n );\n\n const daemonBin = await this.unpackClosure(\"magic-nix-cache\");\n\n let runEnv;\n if (actionsCore.isDebug()) {\n runEnv = {\n RUST_LOG: \"debug,magic_nix_cache=trace,gha_cache=trace\",\n RUST_BACKTRACE: \"full\",\n ...process.env,\n };\n } else {\n runEnv = process.env;\n }\n\n const notifyPort = inputs.getString(\"startup-notification-port\");\n\n const notifyPromise = new Promise>((resolveListening) => {\n const promise = new Promise(async (resolveQuit) => {\n const notifyServer = http.createServer((req, res) => {\n if (req.method === \"POST\" && req.url === \"/\") {\n actionsCore.debug(`Notify server shutting down.`);\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(\"{}\");\n notifyServer.close(() => {\n resolveQuit();\n });\n }\n });\n\n notifyServer.listen(notifyPort, () => {\n actionsCore.debug(`Notify server running.`);\n resolveListening(promise);\n });\n });\n });\n\n // Start tailing the daemon log.\n const outputPath = `${this.daemonDir}/daemon.log`;\n const output = openSync(outputPath, \"a\");\n const log = tailLog(this.daemonDir);\n const netrc = await netrcPath();\n const nixConfPath = `${process.env[\"HOME\"]}/.config/nix/nix.conf`;\n const upstreamCache = inputs.getString(\"upstream-cache\");\n const diagnosticEndpoint = inputs.getString(\"diagnostic-endpoint\");\n const useFlakeHub = inputs.getBool(\"use-flakehub\");\n const flakeHubCacheServer = inputs.getString(\"flakehub-cache-server\");\n const flakeHubApiServer = inputs.getString(\"flakehub-api-server\");\n const flakeHubFlakeName = inputs.getString(\"flakehub-flake-name\");\n const useGhaCache = inputs.getBool(\"use-gha-cache\");\n\n const daemonCliFlags: string[] = [\n \"--startup-notification-url\",\n `http://127.0.0.1:${notifyPort}`,\n \"--listen\",\n this.hostAndPort,\n \"--upstream\",\n upstreamCache,\n \"--diagnostic-endpoint\",\n diagnosticEndpoint,\n \"--nix-conf\",\n nixConfPath,\n ]\n .concat(this.diffStore ? [\"--diff-store\"] : [])\n .concat(\n useFlakeHub\n ? [\n \"--use-flakehub\",\n \"--flakehub-cache-server\",\n flakeHubCacheServer,\n \"--flakehub-api-server\",\n flakeHubApiServer,\n \"--flakehub-api-server-netrc\",\n netrc,\n \"--flakehub-flake-name\",\n flakeHubFlakeName,\n ]\n : [],\n )\n .concat(useGhaCache ? [\"--use-gha-cache\"] : []);\n\n const opts: SpawnOptions = {\n stdio: [\"ignore\", output, output],\n env: runEnv,\n detached: true,\n };\n\n // Display the final command for debugging purposes\n actionsCore.debug(\"Full daemon start command:\");\n actionsCore.debug(`${daemonBin} ${daemonCliFlags.join(\" \")}`);\n\n // Start the server. Once it is ready, it will notify us via the notification server.\n const daemon = spawn(daemonBin, daemonCliFlags, opts);\n\n this.daemonStarted = true;\n actionsCore.saveState(STATE_STARTED, STARTED_HINT);\n\n const pidFile = path.join(this.daemonDir, \"daemon.pid\");\n await fs.writeFile(pidFile, `${daemon.pid}`);\n\n actionsCore.info(\"Waiting for magic-nix-cache to start...\");\n\n await new Promise((resolve) => {\n notifyPromise\n // eslint-disable-next-line github/no-then\n .then((_value) => {\n resolve();\n })\n // eslint-disable-next-line github/no-then\n .catch((e: unknown) => {\n this.exitMain(`Error in notifyPromise: ${stringifyError(e)}`);\n });\n\n daemon.on(\"exit\", async (code, signal) => {\n let msg: string;\n if (signal) {\n msg = `Daemon was killed by signal ${signal}`;\n } else if (code) {\n msg = `Daemon exited with code ${code}`;\n } else {\n msg = \"Daemon unexpectedly exited\";\n }\n\n this.exitMain(msg);\n });\n });\n\n daemon.unref();\n\n actionsCore.info(\"Launched Magic Nix Cache\");\n\n log.unwatch();\n }\n\n private async notifyAutoCache(): Promise {\n if (!this.daemonStarted) {\n actionsCore.debug(\"magic-nix-cache not started - Skipping\");\n return;\n }\n\n try {\n actionsCore.debug(`Indicating workflow start`);\n const res: Response = await this.httpClient.post(\n `http://${this.hostAndPort}/api/workflow-start`,\n );\n\n actionsCore.debug(\n `Response from POST to /api/workflow-start: (status: ${res.statusCode}, body: ${res.body})`,\n );\n\n if (res.statusCode !== 200) {\n throw new Error(\n `Failed to trigger workflow start hook; expected status 200 but got (status: ${res.statusCode}, body: ${res.body})`,\n );\n }\n\n actionsCore.debug(`back from post: ${res.body}`);\n } catch (e: unknown) {\n this.exitMain(`Error starting the Magic Nix Cache: ${stringifyError(e)}`);\n }\n }\n\n async tearDownAutoCache(): Promise {\n if (!this.daemonStarted) {\n actionsCore.debug(\"magic-nix-cache not started - Skipping\");\n return;\n }\n\n const pidFile = path.join(this.daemonDir, \"daemon.pid\");\n const pid = parseInt(await fs.readFile(pidFile, { encoding: \"ascii\" }));\n actionsCore.debug(`found daemon pid: ${pid}`);\n if (!pid) {\n throw new Error(\"magic-nix-cache did not start successfully\");\n }\n\n const log = tailLog(this.daemonDir);\n\n try {\n actionsCore.debug(`about to post to localhost`);\n const res: Response = await this.httpClient.post(\n `http://${this.hostAndPort}/api/workflow-finish`,\n );\n\n actionsCore.debug(\n `Response from POST to /api/workflow-finish: (status: ${res.statusCode}, body: ${res.body})`,\n );\n\n if (res.statusCode !== 200) {\n throw new Error(\n `Failed to trigger workflow finish hook; expected status 200 but got (status: ${res.statusCode}, body: ${res.body})`,\n );\n }\n } finally {\n actionsCore.debug(`unwatching the daemon log`);\n log.unwatch();\n }\n\n actionsCore.debug(`killing daemon process ${pid}`);\n\n try {\n process.kill(pid, \"SIGTERM\");\n } catch (e: unknown) {\n if (typeof e === \"object\" && e && \"code\" in e && e.code !== \"ESRCH\") {\n // Throw an error only in strict mode, otherwise ignore because\n // we're in the post phase and shutting down after this anyway\n if (this.strictMode) {\n throw e;\n }\n }\n } finally {\n if (actionsCore.isDebug()) {\n actionsCore.info(\"Entire log:\");\n const entireLog = readFileSync(path.join(this.daemonDir, \"daemon.log\"));\n actionsCore.info(entireLog.toString());\n }\n }\n }\n\n // Exit the workflow during the main phase. If strict mode is set, fail; if not, save the error\n // message to the workflow's state and exit successfully.\n private exitMain(msg: string): void {\n if (this.strictMode) {\n actionsCore.setFailed(msg);\n } else {\n actionsCore.saveState(STATE_ERROR_IN_MAIN, msg);\n process.exit(0);\n }\n }\n\n // If the main phase threw an error (not in strict mode), this will be a non-empty\n // string available in the post phase.\n private get errorInMain(): string | undefined {\n const state = actionsCore.getState(STATE_ERROR_IN_MAIN);\n return state !== \"\" ? state : undefined;\n }\n}\n\nfunction main(): void {\n new MagicNixCacheAction().execute();\n}\n\nmain();\n"],"mappings":";AAAA,YAAY,iBAAiB;AAC7B,YAAY,QAAQ;AACpB,YAAY,QAAQ;AACpB,OAAO,UAAU;AACjB,SAAS,YAAY;AAEd,SAAS,QAAQ,WAAyB;AAC/C,QAAM,MAAM,IAAI,KAAK,KAAK,KAAK,WAAW,YAAY,CAAC;AACvD,EAAY,kBAAM,uBAAuB;AACzC,MAAI,GAAG,QAAQ,CAAC,SAAS;AACvB,IAAY,iBAAK,IAAI;AAAA,EACvB,CAAC;AACD,SAAO;AACT;AAEA,eAAsB,YAA6B;AACjD,QAAM,oBAAoB,KAAK;AAAA,IAC7B,QAAQ,IAAI,aAAa,KAAQ,UAAO;AAAA,IACxC;AAAA,EACF;AACA,MAAI;AACF,UAAS,UAAO,iBAAiB;AACjC,WAAO;AAAA,EACT,QAAQ;AAEN,UAAM,oBAAoB,KAAK;AAAA,MAC7B,QAAQ,IAAI,aAAa,KAAQ,UAAO;AAAA,MACxC;AAAA,IACF;AACA,QAAI;AACF,YAAM,cAAc,iBAAiB;AAAA,IACvC,SAAS,GAAG;AACV,MAAY;AAAA,QACV;AAAA,MACF;AACA,MAAY;AAAA,QACV;AAAA,MACF;AACA,MAAY,kBAAM,sCAAsC,CAAC,EAAE;AAAA,IAC7D;AACA,WAAO;AAAA,EACT;AACF;AAEA,eAAe,cAAc,OAA8B;AACzD,QAAM,MAAM,MAAkB,uBAAW,kBAAkB;AAE3D,QAAS;AAAA,IACP;AAAA,IACA;AAAA,MACE,oDAAoD,GAAG;AAAA,MACvD,gDAAgD,GAAG;AAAA,MACnD,sDAAsD,GAAG;AAAA,IAC3D,EAAE,KAAK,IAAI;AAAA,EACb;AAEA,EAAY,iBAAK,wBAAwB;AAC3C;;;ACxDA,YAAYA,kBAAiB;AAC7B,SAAS,cAAc,QAAQ,sBAAsB;AACrD,OAAO,SAA4B;AACnC,YAAY,UAAU;AACtB,SAAuB,aAAa;AACpC,SAAS,WAAW,UAAU,oBAAoB;AAClD,YAAYC,SAAQ;AACpB,YAAYC,WAAU;AAKtB,IAAM,iBAAiB;AAEvB,IAAM,wBAAwB;AAC9B,IAAM,0BAA0B;AAChC,IAAM,uBAAuB;AAE7B,IAAM,kBAAkB;AACxB,IAAM,sBAAsB;AAC5B,IAAM,gBAAgB;AACtB,IAAM,eAAe;AAErB,IAAM,uBACJ;AACF,IAAM,uBACJ;AACF,IAAM,qBACJ;AAEF,IAAM,sBAAN,cAAkC,aAAa;AAAA,EAW7C,cAAc;AACZ,UAAM;AAAA,MACJ,MAAM;AAAA,MACN,YAAY;AAAA,MACZ,gBAAgB;AAAA,MAChB,YAAY;AAAA,MACZ,mBAAmB;AAAA,IACrB,CAAC;AAED,SAAK,cAAc,OAAO,UAAU,QAAQ;AAC5C,SAAK,YAAY,OAAO,QAAQ,YAAY;AAE5C,SAAK,QAAQ,yBAAyB,KAAK,SAAS;AAEpD,SAAK,aAAa,IAAI,OAAO;AAAA,MAC3B,OAAO;AAAA,QACL,OAAO;AAAA,QACP,SAAS,CAAC,QAAQ,OAAO,OAAO,QAAQ,UAAU,WAAW,OAAO;AAAA,MACtE;AAAA,MACA,OAAO;AAAA,QACL,aAAa;AAAA,UACX,CAAC,OAAO,eAAe;AACrB,YAAY;AAAA,cACV,wBAAwB,MAAM,IAAI,cAAc,UAAU;AAAA,YAC5D;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,IACF,CAAC;AAED,SAAK,gBAA4B,sBAAS,aAAa,MAAM;AAE7D,QAAgB,sBAAS,eAAe,MAAM,IAAI;AAChD,WAAK,YAAwB,sBAAS,eAAe;AAAA,IACvD,OAAO;AACL,WAAK,YAAY,KAAK,iBAAiB;AACvC,gBAAU,KAAK,SAAS;AACxB,MAAY,uBAAU,iBAAiB,KAAK,SAAS;AAAA,IACvD;AAEA,QAAI,QAAQ,IAAI,cAAc,MAAM,QAAW;AAC7C,WAAK,iBAAiB;AACtB,MAAY,4BAAe,gBAAgB,KAAK,SAAS;AAAA,IAC3D,OAAO;AACL,WAAK,iBAAiB,QAAQ,IAAI,cAAc,MAAM,KAAK;AAAA,IAC7D;AACA,SAAK,QAAQ,sBAAsB,KAAK,cAAc;AAEtD,SAAK,WAAW,cAAmB,WAAK,KAAK,WAAW,YAAY,CAAC;AAAA,EACvE;AAAA,EAEA,MAAM,OAAsB;AAC1B,QAAI,KAAK,gBAAgB;AACvB,MAAY,qBAAQ,oBAAoB;AACxC;AAAA,IACF;AAEA,QAAI,KAAK,kBAAkB,aAAa;AACtC,MAAY,qBAAQ,oBAAoB;AACxC;AAAA,IACF,WAAW,KAAK,kBAAkB,WAAW;AAC3C,MAAY,kBAAK,kBAAkB;AAAA,IACrC;AAEA,UAAM,KAAK,eAAe;AAC1B,UAAM,KAAK,gBAAgB;AAAA,EAC7B;AAAA,EAEA,MAAM,OAAsB;AAG1B,QAAI,CAAC,KAAK,cAAc,KAAK,aAAa;AACxC,MAAY;AAAA,QACV,mDAAmD,KAAK,WAAW;AAAA,MACrE;AACA;AAAA,IACF;AAEA,QAAI,KAAK,gBAAgB;AACvB,MAAY,mBAAM,oBAAoB;AACtC;AAAA,IACF;AAEA,QAAI,KAAK,kBAAkB,aAAa;AACtC,MAAY,mBAAM,oBAAoB;AACtC;AAAA,IACF,WAAW,KAAK,kBAAkB,WAAW;AAC3C,MAAY,mBAAM,kBAAkB;AAAA,IACtC;AAEA,UAAM,KAAK,kBAAkB;AAAA,EAC/B;AAAA,EAEA,MAAM,iBAAgC;AACpC,UAAM,cAAc;AAAA,MAClB;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAEA,QAAI,aAAa;AACjB,eAAW,KAAK,aAAa;AAC3B,UAAI,CAAC,QAAQ,IAAI,eAAe,CAAC,GAAG;AAClC,qBAAa;AACb,QAAY;AAAA,UACV,0DAA0D,CAAC;AAAA,QAC7D;AAAA,MACF;AAAA,IACF;AAEA,SAAK,QAAQ,uBAAuB,CAAC,UAAU;AAC/C,QAAI,YAAY;AACd;AAAA,IACF;AAEA,QAAI,KAAK,eAAe;AACtB,MAAY,mBAAM,kBAAkB;AACpC;AAAA,IACF;AAEA,IAAY;AAAA,MACV,4BAA4B,QAAQ,IAAI,mBAAmB,CAAC;AAAA,IAC9D;AAEA,UAAM,YAAY,MAAM,KAAK,cAAc,iBAAiB;AAE5D,QAAI;AACJ,QAAgB,qBAAQ,GAAG;AACzB,eAAS;AAAA,QACP,UAAU;AAAA,QACV,gBAAgB;AAAA,QAChB,GAAG,QAAQ;AAAA,MACb;AAAA,IACF,OAAO;AACL,eAAS,QAAQ;AAAA,IACnB;AAEA,UAAM,aAAa,OAAO,UAAU,2BAA2B;AAE/D,UAAM,gBAAgB,IAAI,QAAuB,CAAC,qBAAqB;AACrE,YAAM,UAAU,IAAI,QAAc,OAAO,gBAAgB;AACvD,cAAM,eAAoB,kBAAa,CAAC,KAAK,QAAQ;AACnD,cAAI,IAAI,WAAW,UAAU,IAAI,QAAQ,KAAK;AAC5C,YAAY,mBAAM,8BAA8B;AAChD,gBAAI,UAAU,KAAK,EAAE,gBAAgB,mBAAmB,CAAC;AACzD,gBAAI,IAAI,IAAI;AACZ,yBAAa,MAAM,MAAM;AACvB,0BAAY;AAAA,YACd,CAAC;AAAA,UACH;AAAA,QACF,CAAC;AAED,qBAAa,OAAO,YAAY,MAAM;AACpC,UAAY,mBAAM,wBAAwB;AAC1C,2BAAiB,OAAO;AAAA,QAC1B,CAAC;AAAA,MACH,CAAC;AAAA,IACH,CAAC;AAGD,UAAM,aAAa,GAAG,KAAK,SAAS;AACpC,UAAM,SAAS,SAAS,YAAY,GAAG;AACvC,UAAM,MAAM,QAAQ,KAAK,SAAS;AAClC,UAAM,QAAQ,MAAM,UAAU;AAC9B,UAAM,cAAc,GAAG,QAAQ,IAAI,MAAM,CAAC;AAC1C,UAAM,gBAAgB,OAAO,UAAU,gBAAgB;AACvD,UAAM,qBAAqB,OAAO,UAAU,qBAAqB;AACjE,UAAM,cAAc,OAAO,QAAQ,cAAc;AACjD,UAAM,sBAAsB,OAAO,UAAU,uBAAuB;AACpE,UAAM,oBAAoB,OAAO,UAAU,qBAAqB;AAChE,UAAM,oBAAoB,OAAO,UAAU,qBAAqB;AAChE,UAAM,cAAc,OAAO,QAAQ,eAAe;AAElD,UAAM,iBAA2B;AAAA,MAC/B;AAAA,MACA,oBAAoB,UAAU;AAAA,MAC9B;AAAA,MACA,KAAK;AAAA,MACL;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF,EACG,OAAO,KAAK,YAAY,CAAC,cAAc,IAAI,CAAC,CAAC,EAC7C;AAAA,MACC,cACI;AAAA,QACE;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF,IACA,CAAC;AAAA,IACP,EACC,OAAO,cAAc,CAAC,iBAAiB,IAAI,CAAC,CAAC;AAEhD,UAAM,OAAqB;AAAA,MACzB,OAAO,CAAC,UAAU,QAAQ,MAAM;AAAA,MAChC,KAAK;AAAA,MACL,UAAU;AAAA,IACZ;AAGA,IAAY,mBAAM,4BAA4B;AAC9C,IAAY,mBAAM,GAAG,SAAS,IAAI,eAAe,KAAK,GAAG,CAAC,EAAE;AAG5D,UAAM,SAAS,MAAM,WAAW,gBAAgB,IAAI;AAEpD,SAAK,gBAAgB;AACrB,IAAY,uBAAU,eAAe,YAAY;AAEjD,UAAM,UAAe,WAAK,KAAK,WAAW,YAAY;AACtD,UAAS,cAAU,SAAS,GAAG,OAAO,GAAG,EAAE;AAE3C,IAAY,kBAAK,yCAAyC;AAE1D,UAAM,IAAI,QAAc,CAAC,YAAY;AACnC,oBAEG,KAAK,CAAC,WAAW;AAChB,gBAAQ;AAAA,MACV,CAAC,EAEA,MAAM,CAAC,MAAe;AACrB,aAAK,SAAS,2BAA2B,eAAe,CAAC,CAAC,EAAE;AAAA,MAC9D,CAAC;AAEH,aAAO,GAAG,QAAQ,OAAO,MAAM,WAAW;AACxC,YAAI;AACJ,YAAI,QAAQ;AACV,gBAAM,+BAA+B,MAAM;AAAA,QAC7C,WAAW,MAAM;AACf,gBAAM,2BAA2B,IAAI;AAAA,QACvC,OAAO;AACL,gBAAM;AAAA,QACR;AAEA,aAAK,SAAS,GAAG;AAAA,MACnB,CAAC;AAAA,IACH,CAAC;AAED,WAAO,MAAM;AAEb,IAAY,kBAAK,0BAA0B;AAE3C,QAAI,QAAQ;AAAA,EACd;AAAA,EAEA,MAAc,kBAAiC;AAC7C,QAAI,CAAC,KAAK,eAAe;AACvB,MAAY,mBAAM,wCAAwC;AAC1D;AAAA,IACF;AAEA,QAAI;AACF,MAAY,mBAAM,2BAA2B;AAC7C,YAAM,MAAwB,MAAM,KAAK,WAAW;AAAA,QAClD,UAAU,KAAK,WAAW;AAAA,MAC5B;AAEA,MAAY;AAAA,QACV,uDAAuD,IAAI,UAAU,WAAW,IAAI,IAAI;AAAA,MAC1F;AAEA,UAAI,IAAI,eAAe,KAAK;AAC1B,cAAM,IAAI;AAAA,UACR,+EAA+E,IAAI,UAAU,WAAW,IAAI,IAAI;AAAA,QAClH;AAAA,MACF;AAEA,MAAY,mBAAM,mBAAmB,IAAI,IAAI,EAAE;AAAA,IACjD,SAAS,GAAY;AACnB,WAAK,SAAS,uCAAuC,eAAe,CAAC,CAAC,EAAE;AAAA,IAC1E;AAAA,EACF;AAAA,EAEA,MAAM,oBAAmC;AACvC,QAAI,CAAC,KAAK,eAAe;AACvB,MAAY,mBAAM,wCAAwC;AAC1D;AAAA,IACF;AAEA,UAAM,UAAe,WAAK,KAAK,WAAW,YAAY;AACtD,UAAM,MAAM,SAAS,MAAS,aAAS,SAAS,EAAE,UAAU,QAAQ,CAAC,CAAC;AACtE,IAAY,mBAAM,qBAAqB,GAAG,EAAE;AAC5C,QAAI,CAAC,KAAK;AACR,YAAM,IAAI,MAAM,4CAA4C;AAAA,IAC9D;AAEA,UAAM,MAAM,QAAQ,KAAK,SAAS;AAElC,QAAI;AACF,MAAY,mBAAM,4BAA4B;AAC9C,YAAM,MAAwB,MAAM,KAAK,WAAW;AAAA,QAClD,UAAU,KAAK,WAAW;AAAA,MAC5B;AAEA,MAAY;AAAA,QACV,wDAAwD,IAAI,UAAU,WAAW,IAAI,IAAI;AAAA,MAC3F;AAEA,UAAI,IAAI,eAAe,KAAK;AAC1B,cAAM,IAAI;AAAA,UACR,gFAAgF,IAAI,UAAU,WAAW,IAAI,IAAI;AAAA,QACnH;AAAA,MACF;AAAA,IACF,UAAE;AACA,MAAY,mBAAM,2BAA2B;AAC7C,UAAI,QAAQ;AAAA,IACd;AAEA,IAAY,mBAAM,0BAA0B,GAAG,EAAE;AAEjD,QAAI;AACF,cAAQ,KAAK,KAAK,SAAS;AAAA,IAC7B,SAAS,GAAY;AACnB,UAAI,OAAO,MAAM,YAAY,KAAK,UAAU,KAAK,EAAE,SAAS,SAAS;AAGnE,YAAI,KAAK,YAAY;AACnB,gBAAM;AAAA,QACR;AAAA,MACF;AAAA,IACF,UAAE;AACA,UAAgB,qBAAQ,GAAG;AACzB,QAAY,kBAAK,aAAa;AAC9B,cAAM,YAAY,aAAkB,WAAK,KAAK,WAAW,YAAY,CAAC;AACtE,QAAY,kBAAK,UAAU,SAAS,CAAC;AAAA,MACvC;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA,EAIQ,SAAS,KAAmB;AAClC,QAAI,KAAK,YAAY;AACnB,MAAY,uBAAU,GAAG;AAAA,IAC3B,OAAO;AACL,MAAY,uBAAU,qBAAqB,GAAG;AAC9C,cAAQ,KAAK,CAAC;AAAA,IAChB;AAAA,EACF;AAAA;AAAA;AAAA,EAIA,IAAY,cAAkC;AAC5C,UAAM,QAAoB,sBAAS,mBAAmB;AACtD,WAAO,UAAU,KAAK,QAAQ;AAAA,EAChC;AACF;AAEA,SAAS,OAAa;AACpB,MAAI,oBAAoB,EAAE,QAAQ;AACpC;AAEA,KAAK;","names":["actionsCore","fs","path"]} \ No newline at end of file +{"version":3,"sources":["../src/helpers.ts","../src/index.ts"],"sourcesContent":["import * as actionsCore from \"@actions/core\";\nimport * as fs from \"node:fs/promises\";\nimport * as os from \"node:os\";\nimport path from \"node:path\";\nimport { Tail } from \"tail\";\n\nexport function getTrinaryInput(\n name: string,\n): \"enabled\" | \"disabled\" | \"no-preference\" {\n const trueValue = [\"true\", \"True\", \"TRUE\", \"enabled\"];\n const falseValue = [\"false\", \"False\", \"FALSE\", \"disabled\"];\n const noPreferenceValue = [\"\", \"null\", \"no-preference\"];\n\n const val = actionsCore.getInput(name);\n if (trueValue.includes(val)) {\n return \"enabled\";\n }\n if (falseValue.includes(val)) {\n return \"disabled\";\n }\n if (noPreferenceValue.includes(val)) {\n return \"no-preference\";\n }\n\n const possibleValues = trueValue\n .concat(falseValue)\n .concat(noPreferenceValue)\n .join(\" | \");\n throw new TypeError(\n `Input ${name} does not look like a trinary, which requires one of:\\n${possibleValues}`,\n );\n}\n\nexport function tailLog(daemonDir: string): Tail {\n const log = new Tail(path.join(daemonDir, \"daemon.log\"));\n actionsCore.debug(`tailing daemon.log...`);\n log.on(\"line\", (line) => {\n actionsCore.info(line);\n });\n return log;\n}\n\nexport async function netrcPath(): Promise {\n const expectedNetrcPath = path.join(\n process.env[\"RUNNER_TEMP\"] ?? os.tmpdir(),\n \"determinate-nix-installer-netrc\",\n );\n try {\n await fs.access(expectedNetrcPath);\n return expectedNetrcPath;\n } catch {\n // `nix-installer` was not used, the user may be registered with FlakeHub though.\n const destinedNetrcPath = path.join(\n process.env[\"RUNNER_TEMP\"] ?? os.tmpdir(),\n \"magic-nix-cache-netrc\",\n );\n try {\n await flakeHubLogin(destinedNetrcPath);\n } catch (e) {\n actionsCore.info(\n \"FlakeHub Cache is disabled due to missing or invalid token\",\n );\n actionsCore.info(\n `If you're signed up for FlakeHub Cache, make sure that your Actions config has a \\`permissions\\` block with \\`id-token\\` set to \"write\" and \\`contents\\` set to \"read\"`,\n );\n actionsCore.debug(`Error while logging into FlakeHub: ${e}`);\n }\n return destinedNetrcPath;\n }\n}\n\nasync function flakeHubLogin(netrc: string): Promise {\n const jwt = await actionsCore.getIDToken(\"api.flakehub.com\");\n\n await fs.writeFile(\n netrc,\n [\n `machine api.flakehub.com login flakehub password ${jwt}`,\n `machine flakehub.com login flakehub password ${jwt}`,\n `machine cache.flakehub.com login flakehub password ${jwt}`,\n ].join(\"\\n\"),\n );\n\n actionsCore.info(\"Logged in to FlakeHub.\");\n}\n","import { getTrinaryInput, netrcPath, tailLog } from \"./helpers.js\";\nimport * as actionsCore from \"@actions/core\";\nimport { DetSysAction, inputs, stringifyError } from \"detsys-ts\";\nimport got, { Got, Response } from \"got\";\nimport * as http from \"http\";\nimport { SpawnOptions, spawn } from \"node:child_process\";\nimport { mkdirSync, openSync, readFileSync } from \"node:fs\";\nimport * as fs from \"node:fs/promises\";\nimport * as path from \"node:path\";\n\n// The ENV_DAEMON_DIR is intended to determine if we \"own\" the daemon or not,\n// in the case that a user has put the magic nix cache into their workflow\n// twice.\nconst ENV_DAEMON_DIR = \"MAGIC_NIX_CACHE_DAEMONDIR\";\n\nconst FACT_ENV_VARS_PRESENT = \"required_env_vars_present\";\nconst FACT_DIFF_STORE_ENABLED = \"diff_store\";\nconst FACT_ALREADY_RUNNING = \"noop_mode\";\n\nconst STATE_DAEMONDIR = \"MAGIC_NIX_CACHE_DAEMONDIR\";\nconst STATE_ERROR_IN_MAIN = \"ERROR_IN_MAIN\";\nconst STATE_STARTED = \"MAGIC_NIX_CACHE_STARTED\";\nconst STARTED_HINT = \"true\";\n\nconst TEXT_ALREADY_RUNNING =\n \"Magic Nix Cache is already running, this workflow job is in noop mode. Is the Magic Nix Cache in the workflow twice?\";\nconst TEXT_TRUST_UNTRUSTED =\n \"The Nix daemon does not consider the user running this workflow to be trusted. Magic Nix Cache is disabled.\";\nconst TEXT_TRUST_UNKNOWN =\n \"The Nix daemon may not consider the user running this workflow to be trusted. Magic Nix Cache may not start correctly.\";\n\nclass MagicNixCacheAction extends DetSysAction {\n private hostAndPort: string;\n private diffStore: boolean;\n private httpClient: Got;\n private daemonDir: string;\n private daemonStarted: boolean;\n\n // This is set to `true` if the MNC is already running, in which case the\n // workflow will use the existing process rather than starting a new one.\n private alreadyRunning: boolean;\n\n constructor() {\n super({\n name: \"magic-nix-cache\",\n fetchStyle: \"gh-env-style\",\n idsProjectName: \"magic-nix-cache-closure\",\n requireNix: \"warn\",\n diagnosticsSuffix: \"perf\",\n });\n\n this.hostAndPort = inputs.getString(\"listen\");\n this.diffStore = inputs.getBool(\"diff-store\");\n\n this.addFact(FACT_DIFF_STORE_ENABLED, this.diffStore);\n\n this.httpClient = got.extend({\n retry: {\n limit: 1,\n methods: [\"POST\", \"GET\", \"PUT\", \"HEAD\", \"DELETE\", \"OPTIONS\", \"TRACE\"],\n },\n hooks: {\n beforeRetry: [\n (error, retryCount) => {\n actionsCore.info(\n `Retrying after error ${error.code}, retry #: ${retryCount}`,\n );\n },\n ],\n },\n });\n\n this.daemonStarted = actionsCore.getState(STATE_STARTED) === STARTED_HINT;\n\n if (actionsCore.getState(STATE_DAEMONDIR) !== \"\") {\n this.daemonDir = actionsCore.getState(STATE_DAEMONDIR);\n } else {\n this.daemonDir = this.getTemporaryName();\n mkdirSync(this.daemonDir);\n actionsCore.saveState(STATE_DAEMONDIR, this.daemonDir);\n }\n\n if (process.env[ENV_DAEMON_DIR] === undefined) {\n this.alreadyRunning = false;\n actionsCore.exportVariable(ENV_DAEMON_DIR, this.daemonDir);\n } else {\n this.alreadyRunning = process.env[ENV_DAEMON_DIR] !== this.daemonDir;\n }\n this.addFact(FACT_ALREADY_RUNNING, this.alreadyRunning);\n\n this.stapleFile(\"daemon.log\", path.join(this.daemonDir, \"daemon.log\"));\n }\n\n async main(): Promise {\n if (this.alreadyRunning) {\n actionsCore.warning(TEXT_ALREADY_RUNNING);\n return;\n }\n\n if (this.nixStoreTrust === \"untrusted\") {\n actionsCore.warning(TEXT_TRUST_UNTRUSTED);\n return;\n } else if (this.nixStoreTrust === \"unknown\") {\n actionsCore.info(TEXT_TRUST_UNKNOWN);\n }\n\n await this.setUpAutoCache();\n await this.notifyAutoCache();\n }\n\n async post(): Promise {\n // If strict mode is off and there was an error in main, such as the daemon not starting,\n // then the post phase is skipped with a warning.\n if (!this.strictMode && this.errorInMain) {\n actionsCore.warning(\n `skipping post phase due to error in main phase: ${this.errorInMain}`,\n );\n return;\n }\n\n if (this.alreadyRunning) {\n actionsCore.debug(TEXT_ALREADY_RUNNING);\n return;\n }\n\n if (this.nixStoreTrust === \"untrusted\") {\n actionsCore.debug(TEXT_TRUST_UNTRUSTED);\n return;\n } else if (this.nixStoreTrust === \"unknown\") {\n actionsCore.debug(TEXT_TRUST_UNKNOWN);\n }\n\n await this.tearDownAutoCache();\n }\n\n async setUpAutoCache(): Promise {\n const requiredEnv = [\n \"ACTIONS_CACHE_URL\",\n \"ACTIONS_RUNTIME_URL\",\n \"ACTIONS_RUNTIME_TOKEN\",\n ];\n\n let anyMissing = false;\n for (const n of requiredEnv) {\n if (!process.env.hasOwnProperty(n)) {\n anyMissing = true;\n actionsCore.warning(\n `Disabling automatic caching since required environment ${n} isn't available`,\n );\n }\n }\n\n this.addFact(FACT_ENV_VARS_PRESENT, !anyMissing);\n if (anyMissing) {\n return;\n }\n\n if (this.daemonStarted) {\n actionsCore.debug(\"Already started.\");\n return;\n }\n\n actionsCore.debug(\n `GitHub Action Cache URL: ${process.env[\"ACTIONS_CACHE_URL\"]}`,\n );\n\n const daemonBin = await this.unpackClosure(\"magic-nix-cache\");\n\n let runEnv;\n if (actionsCore.isDebug()) {\n runEnv = {\n RUST_LOG: \"debug,magic_nix_cache=trace,gha_cache=trace\",\n RUST_BACKTRACE: \"full\",\n ...process.env,\n };\n } else {\n runEnv = process.env;\n }\n\n const notifyPort = inputs.getString(\"startup-notification-port\");\n\n const notifyPromise = new Promise>((resolveListening) => {\n const promise = new Promise(async (resolveQuit) => {\n const notifyServer = http.createServer((req, res) => {\n if (req.method === \"POST\" && req.url === \"/\") {\n actionsCore.debug(`Notify server shutting down.`);\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(\"{}\");\n notifyServer.close(() => {\n resolveQuit();\n });\n }\n });\n\n notifyServer.listen(notifyPort, () => {\n actionsCore.debug(`Notify server running.`);\n resolveListening(promise);\n });\n });\n });\n\n // Start tailing the daemon log.\n const outputPath = `${this.daemonDir}/daemon.log`;\n const output = openSync(outputPath, \"a\");\n const log = tailLog(this.daemonDir);\n const netrc = await netrcPath();\n const nixConfPath = `${process.env[\"HOME\"]}/.config/nix/nix.conf`;\n const upstreamCache = inputs.getString(\"upstream-cache\");\n const diagnosticEndpoint = inputs.getString(\"diagnostic-endpoint\");\n const useFlakeHub = getTrinaryInput(\"use-flakehub\");\n const flakeHubCacheServer = inputs.getString(\"flakehub-cache-server\");\n const flakeHubApiServer = inputs.getString(\"flakehub-api-server\");\n const flakeHubFlakeName = inputs.getString(\"flakehub-flake-name\");\n const useGhaCache = getTrinaryInput(\"use-gha-cache\");\n\n const daemonCliFlags: string[] = [\n \"--startup-notification-url\",\n `http://127.0.0.1:${notifyPort}`,\n \"--listen\",\n this.hostAndPort,\n \"--upstream\",\n upstreamCache,\n \"--diagnostic-endpoint\",\n diagnosticEndpoint,\n \"--nix-conf\",\n nixConfPath,\n \"--use-gha-cache\",\n useGhaCache,\n \"--use-flakehub\",\n useFlakeHub,\n ]\n .concat(this.diffStore ? [\"--diff-store\"] : [])\n .concat(\n useFlakeHub !== \"disabled\"\n ? [\n \"--flakehub-cache-server\",\n flakeHubCacheServer,\n \"--flakehub-api-server\",\n flakeHubApiServer,\n \"--flakehub-api-server-netrc\",\n netrc,\n \"--flakehub-flake-name\",\n flakeHubFlakeName,\n ]\n : [],\n );\n\n const opts: SpawnOptions = {\n stdio: [\"ignore\", output, output],\n env: runEnv,\n detached: true,\n };\n\n // Display the final command for debugging purposes\n actionsCore.debug(\"Full daemon start command:\");\n actionsCore.debug(`${daemonBin} ${daemonCliFlags.join(\" \")}`);\n\n // Start the server. Once it is ready, it will notify us via the notification server.\n const daemon = spawn(daemonBin, daemonCliFlags, opts);\n\n this.daemonStarted = true;\n actionsCore.saveState(STATE_STARTED, STARTED_HINT);\n\n const pidFile = path.join(this.daemonDir, \"daemon.pid\");\n await fs.writeFile(pidFile, `${daemon.pid}`);\n\n actionsCore.info(\"Waiting for magic-nix-cache to start...\");\n\n await new Promise((resolve) => {\n notifyPromise\n // eslint-disable-next-line github/no-then\n .then((_value) => {\n resolve();\n })\n // eslint-disable-next-line github/no-then\n .catch((e: unknown) => {\n this.exitMain(`Error in notifyPromise: ${stringifyError(e)}`);\n });\n\n daemon.on(\"exit\", async (code, signal) => {\n let msg: string;\n if (signal) {\n msg = `Daemon was killed by signal ${signal}`;\n } else if (code) {\n msg = `Daemon exited with code ${code}`;\n } else {\n msg = \"Daemon unexpectedly exited\";\n }\n\n this.exitMain(msg);\n });\n });\n\n daemon.unref();\n\n actionsCore.info(\"Launched Magic Nix Cache\");\n\n log.unwatch();\n }\n\n private async notifyAutoCache(): Promise {\n if (!this.daemonStarted) {\n actionsCore.debug(\"magic-nix-cache not started - Skipping\");\n return;\n }\n\n try {\n actionsCore.debug(`Indicating workflow start`);\n const res: Response = await this.httpClient.post(\n `http://${this.hostAndPort}/api/workflow-start`,\n );\n\n actionsCore.debug(\n `Response from POST to /api/workflow-start: (status: ${res.statusCode}, body: ${res.body})`,\n );\n\n if (res.statusCode !== 200) {\n throw new Error(\n `Failed to trigger workflow start hook; expected status 200 but got (status: ${res.statusCode}, body: ${res.body})`,\n );\n }\n\n actionsCore.debug(`back from post: ${res.body}`);\n } catch (e: unknown) {\n this.exitMain(`Error starting the Magic Nix Cache: ${stringifyError(e)}`);\n }\n }\n\n async tearDownAutoCache(): Promise {\n if (!this.daemonStarted) {\n actionsCore.debug(\"magic-nix-cache not started - Skipping\");\n return;\n }\n\n const pidFile = path.join(this.daemonDir, \"daemon.pid\");\n const pid = parseInt(await fs.readFile(pidFile, { encoding: \"ascii\" }));\n actionsCore.debug(`found daemon pid: ${pid}`);\n if (!pid) {\n throw new Error(\"magic-nix-cache did not start successfully\");\n }\n\n const log = tailLog(this.daemonDir);\n\n try {\n actionsCore.debug(`about to post to localhost`);\n const res: Response = await this.httpClient.post(\n `http://${this.hostAndPort}/api/workflow-finish`,\n );\n\n actionsCore.debug(\n `Response from POST to /api/workflow-finish: (status: ${res.statusCode}, body: ${res.body})`,\n );\n\n if (res.statusCode !== 200) {\n throw new Error(\n `Failed to trigger workflow finish hook; expected status 200 but got (status: ${res.statusCode}, body: ${res.body})`,\n );\n }\n } finally {\n actionsCore.debug(`unwatching the daemon log`);\n log.unwatch();\n }\n\n actionsCore.debug(`killing daemon process ${pid}`);\n\n try {\n process.kill(pid, \"SIGTERM\");\n } catch (e: unknown) {\n if (typeof e === \"object\" && e && \"code\" in e && e.code !== \"ESRCH\") {\n // Throw an error only in strict mode, otherwise ignore because\n // we're in the post phase and shutting down after this anyway\n if (this.strictMode) {\n throw e;\n }\n }\n } finally {\n if (actionsCore.isDebug()) {\n actionsCore.info(\"Entire log:\");\n const entireLog = readFileSync(path.join(this.daemonDir, \"daemon.log\"));\n actionsCore.info(entireLog.toString());\n }\n }\n }\n\n // Exit the workflow during the main phase. If strict mode is set, fail; if not, save the error\n // message to the workflow's state and exit successfully.\n private exitMain(msg: string): void {\n if (this.strictMode) {\n actionsCore.setFailed(msg);\n } else {\n actionsCore.saveState(STATE_ERROR_IN_MAIN, msg);\n process.exit(0);\n }\n }\n\n // If the main phase threw an error (not in strict mode), this will be a non-empty\n // string available in the post phase.\n private get errorInMain(): string | undefined {\n const state = actionsCore.getState(STATE_ERROR_IN_MAIN);\n return state !== \"\" ? state : undefined;\n }\n}\n\nfunction main(): void {\n new MagicNixCacheAction().execute();\n}\n\nmain();\n"],"mappings":";AAAA,YAAY,iBAAiB;AAC7B,YAAY,QAAQ;AACpB,YAAY,QAAQ;AACpB,OAAO,UAAU;AACjB,SAAS,YAAY;AAEd,SAAS,gBACd,MAC0C;AAC1C,QAAM,YAAY,CAAC,QAAQ,QAAQ,QAAQ,SAAS;AACpD,QAAM,aAAa,CAAC,SAAS,SAAS,SAAS,UAAU;AACzD,QAAM,oBAAoB,CAAC,IAAI,QAAQ,eAAe;AAEtD,QAAM,MAAkB,qBAAS,IAAI;AACrC,MAAI,UAAU,SAAS,GAAG,GAAG;AAC3B,WAAO;AAAA,EACT;AACA,MAAI,WAAW,SAAS,GAAG,GAAG;AAC5B,WAAO;AAAA,EACT;AACA,MAAI,kBAAkB,SAAS,GAAG,GAAG;AACnC,WAAO;AAAA,EACT;AAEA,QAAM,iBAAiB,UACpB,OAAO,UAAU,EACjB,OAAO,iBAAiB,EACxB,KAAK,KAAK;AACb,QAAM,IAAI;AAAA,IACR,SAAS,IAAI;AAAA,EAA0D,cAAc;AAAA,EACvF;AACF;AAEO,SAAS,QAAQ,WAAyB;AAC/C,QAAM,MAAM,IAAI,KAAK,KAAK,KAAK,WAAW,YAAY,CAAC;AACvD,EAAY,kBAAM,uBAAuB;AACzC,MAAI,GAAG,QAAQ,CAAC,SAAS;AACvB,IAAY,iBAAK,IAAI;AAAA,EACvB,CAAC;AACD,SAAO;AACT;AAEA,eAAsB,YAA6B;AACjD,QAAM,oBAAoB,KAAK;AAAA,IAC7B,QAAQ,IAAI,aAAa,KAAQ,UAAO;AAAA,IACxC;AAAA,EACF;AACA,MAAI;AACF,UAAS,UAAO,iBAAiB;AACjC,WAAO;AAAA,EACT,QAAQ;AAEN,UAAM,oBAAoB,KAAK;AAAA,MAC7B,QAAQ,IAAI,aAAa,KAAQ,UAAO;AAAA,MACxC;AAAA,IACF;AACA,QAAI;AACF,YAAM,cAAc,iBAAiB;AAAA,IACvC,SAAS,GAAG;AACV,MAAY;AAAA,QACV;AAAA,MACF;AACA,MAAY;AAAA,QACV;AAAA,MACF;AACA,MAAY,kBAAM,sCAAsC,CAAC,EAAE;AAAA,IAC7D;AACA,WAAO;AAAA,EACT;AACF;AAEA,eAAe,cAAc,OAA8B;AACzD,QAAM,MAAM,MAAkB,uBAAW,kBAAkB;AAE3D,QAAS;AAAA,IACP;AAAA,IACA;AAAA,MACE,oDAAoD,GAAG;AAAA,MACvD,gDAAgD,GAAG;AAAA,MACnD,sDAAsD,GAAG;AAAA,IAC3D,EAAE,KAAK,IAAI;AAAA,EACb;AAEA,EAAY,iBAAK,wBAAwB;AAC3C;;;ACnFA,YAAYA,kBAAiB;AAC7B,SAAS,cAAc,QAAQ,sBAAsB;AACrD,OAAO,SAA4B;AACnC,YAAY,UAAU;AACtB,SAAuB,aAAa;AACpC,SAAS,WAAW,UAAU,oBAAoB;AAClD,YAAYC,SAAQ;AACpB,YAAYC,WAAU;AAKtB,IAAM,iBAAiB;AAEvB,IAAM,wBAAwB;AAC9B,IAAM,0BAA0B;AAChC,IAAM,uBAAuB;AAE7B,IAAM,kBAAkB;AACxB,IAAM,sBAAsB;AAC5B,IAAM,gBAAgB;AACtB,IAAM,eAAe;AAErB,IAAM,uBACJ;AACF,IAAM,uBACJ;AACF,IAAM,qBACJ;AAEF,IAAM,sBAAN,cAAkC,aAAa;AAAA,EAW7C,cAAc;AACZ,UAAM;AAAA,MACJ,MAAM;AAAA,MACN,YAAY;AAAA,MACZ,gBAAgB;AAAA,MAChB,YAAY;AAAA,MACZ,mBAAmB;AAAA,IACrB,CAAC;AAED,SAAK,cAAc,OAAO,UAAU,QAAQ;AAC5C,SAAK,YAAY,OAAO,QAAQ,YAAY;AAE5C,SAAK,QAAQ,yBAAyB,KAAK,SAAS;AAEpD,SAAK,aAAa,IAAI,OAAO;AAAA,MAC3B,OAAO;AAAA,QACL,OAAO;AAAA,QACP,SAAS,CAAC,QAAQ,OAAO,OAAO,QAAQ,UAAU,WAAW,OAAO;AAAA,MACtE;AAAA,MACA,OAAO;AAAA,QACL,aAAa;AAAA,UACX,CAAC,OAAO,eAAe;AACrB,YAAY;AAAA,cACV,wBAAwB,MAAM,IAAI,cAAc,UAAU;AAAA,YAC5D;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,IACF,CAAC;AAED,SAAK,gBAA4B,sBAAS,aAAa,MAAM;AAE7D,QAAgB,sBAAS,eAAe,MAAM,IAAI;AAChD,WAAK,YAAwB,sBAAS,eAAe;AAAA,IACvD,OAAO;AACL,WAAK,YAAY,KAAK,iBAAiB;AACvC,gBAAU,KAAK,SAAS;AACxB,MAAY,uBAAU,iBAAiB,KAAK,SAAS;AAAA,IACvD;AAEA,QAAI,QAAQ,IAAI,cAAc,MAAM,QAAW;AAC7C,WAAK,iBAAiB;AACtB,MAAY,4BAAe,gBAAgB,KAAK,SAAS;AAAA,IAC3D,OAAO;AACL,WAAK,iBAAiB,QAAQ,IAAI,cAAc,MAAM,KAAK;AAAA,IAC7D;AACA,SAAK,QAAQ,sBAAsB,KAAK,cAAc;AAEtD,SAAK,WAAW,cAAmB,WAAK,KAAK,WAAW,YAAY,CAAC;AAAA,EACvE;AAAA,EAEA,MAAM,OAAsB;AAC1B,QAAI,KAAK,gBAAgB;AACvB,MAAY,qBAAQ,oBAAoB;AACxC;AAAA,IACF;AAEA,QAAI,KAAK,kBAAkB,aAAa;AACtC,MAAY,qBAAQ,oBAAoB;AACxC;AAAA,IACF,WAAW,KAAK,kBAAkB,WAAW;AAC3C,MAAY,kBAAK,kBAAkB;AAAA,IACrC;AAEA,UAAM,KAAK,eAAe;AAC1B,UAAM,KAAK,gBAAgB;AAAA,EAC7B;AAAA,EAEA,MAAM,OAAsB;AAG1B,QAAI,CAAC,KAAK,cAAc,KAAK,aAAa;AACxC,MAAY;AAAA,QACV,mDAAmD,KAAK,WAAW;AAAA,MACrE;AACA;AAAA,IACF;AAEA,QAAI,KAAK,gBAAgB;AACvB,MAAY,mBAAM,oBAAoB;AACtC;AAAA,IACF;AAEA,QAAI,KAAK,kBAAkB,aAAa;AACtC,MAAY,mBAAM,oBAAoB;AACtC;AAAA,IACF,WAAW,KAAK,kBAAkB,WAAW;AAC3C,MAAY,mBAAM,kBAAkB;AAAA,IACtC;AAEA,UAAM,KAAK,kBAAkB;AAAA,EAC/B;AAAA,EAEA,MAAM,iBAAgC;AACpC,UAAM,cAAc;AAAA,MAClB;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAEA,QAAI,aAAa;AACjB,eAAW,KAAK,aAAa;AAC3B,UAAI,CAAC,QAAQ,IAAI,eAAe,CAAC,GAAG;AAClC,qBAAa;AACb,QAAY;AAAA,UACV,0DAA0D,CAAC;AAAA,QAC7D;AAAA,MACF;AAAA,IACF;AAEA,SAAK,QAAQ,uBAAuB,CAAC,UAAU;AAC/C,QAAI,YAAY;AACd;AAAA,IACF;AAEA,QAAI,KAAK,eAAe;AACtB,MAAY,mBAAM,kBAAkB;AACpC;AAAA,IACF;AAEA,IAAY;AAAA,MACV,4BAA4B,QAAQ,IAAI,mBAAmB,CAAC;AAAA,IAC9D;AAEA,UAAM,YAAY,MAAM,KAAK,cAAc,iBAAiB;AAE5D,QAAI;AACJ,QAAgB,qBAAQ,GAAG;AACzB,eAAS;AAAA,QACP,UAAU;AAAA,QACV,gBAAgB;AAAA,QAChB,GAAG,QAAQ;AAAA,MACb;AAAA,IACF,OAAO;AACL,eAAS,QAAQ;AAAA,IACnB;AAEA,UAAM,aAAa,OAAO,UAAU,2BAA2B;AAE/D,UAAM,gBAAgB,IAAI,QAAuB,CAAC,qBAAqB;AACrE,YAAM,UAAU,IAAI,QAAc,OAAO,gBAAgB;AACvD,cAAM,eAAoB,kBAAa,CAAC,KAAK,QAAQ;AACnD,cAAI,IAAI,WAAW,UAAU,IAAI,QAAQ,KAAK;AAC5C,YAAY,mBAAM,8BAA8B;AAChD,gBAAI,UAAU,KAAK,EAAE,gBAAgB,mBAAmB,CAAC;AACzD,gBAAI,IAAI,IAAI;AACZ,yBAAa,MAAM,MAAM;AACvB,0BAAY;AAAA,YACd,CAAC;AAAA,UACH;AAAA,QACF,CAAC;AAED,qBAAa,OAAO,YAAY,MAAM;AACpC,UAAY,mBAAM,wBAAwB;AAC1C,2BAAiB,OAAO;AAAA,QAC1B,CAAC;AAAA,MACH,CAAC;AAAA,IACH,CAAC;AAGD,UAAM,aAAa,GAAG,KAAK,SAAS;AACpC,UAAM,SAAS,SAAS,YAAY,GAAG;AACvC,UAAM,MAAM,QAAQ,KAAK,SAAS;AAClC,UAAM,QAAQ,MAAM,UAAU;AAC9B,UAAM,cAAc,GAAG,QAAQ,IAAI,MAAM,CAAC;AAC1C,UAAM,gBAAgB,OAAO,UAAU,gBAAgB;AACvD,UAAM,qBAAqB,OAAO,UAAU,qBAAqB;AACjE,UAAM,cAAc,gBAAgB,cAAc;AAClD,UAAM,sBAAsB,OAAO,UAAU,uBAAuB;AACpE,UAAM,oBAAoB,OAAO,UAAU,qBAAqB;AAChE,UAAM,oBAAoB,OAAO,UAAU,qBAAqB;AAChE,UAAM,cAAc,gBAAgB,eAAe;AAEnD,UAAM,iBAA2B;AAAA,MAC/B;AAAA,MACA,oBAAoB,UAAU;AAAA,MAC9B;AAAA,MACA,KAAK;AAAA,MACL;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF,EACG,OAAO,KAAK,YAAY,CAAC,cAAc,IAAI,CAAC,CAAC,EAC7C;AAAA,MACC,gBAAgB,aACZ;AAAA,QACE;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF,IACA,CAAC;AAAA,IACP;AAEF,UAAM,OAAqB;AAAA,MACzB,OAAO,CAAC,UAAU,QAAQ,MAAM;AAAA,MAChC,KAAK;AAAA,MACL,UAAU;AAAA,IACZ;AAGA,IAAY,mBAAM,4BAA4B;AAC9C,IAAY,mBAAM,GAAG,SAAS,IAAI,eAAe,KAAK,GAAG,CAAC,EAAE;AAG5D,UAAM,SAAS,MAAM,WAAW,gBAAgB,IAAI;AAEpD,SAAK,gBAAgB;AACrB,IAAY,uBAAU,eAAe,YAAY;AAEjD,UAAM,UAAe,WAAK,KAAK,WAAW,YAAY;AACtD,UAAS,cAAU,SAAS,GAAG,OAAO,GAAG,EAAE;AAE3C,IAAY,kBAAK,yCAAyC;AAE1D,UAAM,IAAI,QAAc,CAAC,YAAY;AACnC,oBAEG,KAAK,CAAC,WAAW;AAChB,gBAAQ;AAAA,MACV,CAAC,EAEA,MAAM,CAAC,MAAe;AACrB,aAAK,SAAS,2BAA2B,eAAe,CAAC,CAAC,EAAE;AAAA,MAC9D,CAAC;AAEH,aAAO,GAAG,QAAQ,OAAO,MAAM,WAAW;AACxC,YAAI;AACJ,YAAI,QAAQ;AACV,gBAAM,+BAA+B,MAAM;AAAA,QAC7C,WAAW,MAAM;AACf,gBAAM,2BAA2B,IAAI;AAAA,QACvC,OAAO;AACL,gBAAM;AAAA,QACR;AAEA,aAAK,SAAS,GAAG;AAAA,MACnB,CAAC;AAAA,IACH,CAAC;AAED,WAAO,MAAM;AAEb,IAAY,kBAAK,0BAA0B;AAE3C,QAAI,QAAQ;AAAA,EACd;AAAA,EAEA,MAAc,kBAAiC;AAC7C,QAAI,CAAC,KAAK,eAAe;AACvB,MAAY,mBAAM,wCAAwC;AAC1D;AAAA,IACF;AAEA,QAAI;AACF,MAAY,mBAAM,2BAA2B;AAC7C,YAAM,MAAwB,MAAM,KAAK,WAAW;AAAA,QAClD,UAAU,KAAK,WAAW;AAAA,MAC5B;AAEA,MAAY;AAAA,QACV,uDAAuD,IAAI,UAAU,WAAW,IAAI,IAAI;AAAA,MAC1F;AAEA,UAAI,IAAI,eAAe,KAAK;AAC1B,cAAM,IAAI;AAAA,UACR,+EAA+E,IAAI,UAAU,WAAW,IAAI,IAAI;AAAA,QAClH;AAAA,MACF;AAEA,MAAY,mBAAM,mBAAmB,IAAI,IAAI,EAAE;AAAA,IACjD,SAAS,GAAY;AACnB,WAAK,SAAS,uCAAuC,eAAe,CAAC,CAAC,EAAE;AAAA,IAC1E;AAAA,EACF;AAAA,EAEA,MAAM,oBAAmC;AACvC,QAAI,CAAC,KAAK,eAAe;AACvB,MAAY,mBAAM,wCAAwC;AAC1D;AAAA,IACF;AAEA,UAAM,UAAe,WAAK,KAAK,WAAW,YAAY;AACtD,UAAM,MAAM,SAAS,MAAS,aAAS,SAAS,EAAE,UAAU,QAAQ,CAAC,CAAC;AACtE,IAAY,mBAAM,qBAAqB,GAAG,EAAE;AAC5C,QAAI,CAAC,KAAK;AACR,YAAM,IAAI,MAAM,4CAA4C;AAAA,IAC9D;AAEA,UAAM,MAAM,QAAQ,KAAK,SAAS;AAElC,QAAI;AACF,MAAY,mBAAM,4BAA4B;AAC9C,YAAM,MAAwB,MAAM,KAAK,WAAW;AAAA,QAClD,UAAU,KAAK,WAAW;AAAA,MAC5B;AAEA,MAAY;AAAA,QACV,wDAAwD,IAAI,UAAU,WAAW,IAAI,IAAI;AAAA,MAC3F;AAEA,UAAI,IAAI,eAAe,KAAK;AAC1B,cAAM,IAAI;AAAA,UACR,gFAAgF,IAAI,UAAU,WAAW,IAAI,IAAI;AAAA,QACnH;AAAA,MACF;AAAA,IACF,UAAE;AACA,MAAY,mBAAM,2BAA2B;AAC7C,UAAI,QAAQ;AAAA,IACd;AAEA,IAAY,mBAAM,0BAA0B,GAAG,EAAE;AAEjD,QAAI;AACF,cAAQ,KAAK,KAAK,SAAS;AAAA,IAC7B,SAAS,GAAY;AACnB,UAAI,OAAO,MAAM,YAAY,KAAK,UAAU,KAAK,EAAE,SAAS,SAAS;AAGnE,YAAI,KAAK,YAAY;AACnB,gBAAM;AAAA,QACR;AAAA,MACF;AAAA,IACF,UAAE;AACA,UAAgB,qBAAQ,GAAG;AACzB,QAAY,kBAAK,aAAa;AAC9B,cAAM,YAAY,aAAkB,WAAK,KAAK,WAAW,YAAY,CAAC;AACtE,QAAY,kBAAK,UAAU,SAAS,CAAC;AAAA,MACvC;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA,EAIQ,SAAS,KAAmB;AAClC,QAAI,KAAK,YAAY;AACnB,MAAY,uBAAU,GAAG;AAAA,IAC3B,OAAO;AACL,MAAY,uBAAU,qBAAqB,GAAG;AAC9C,cAAQ,KAAK,CAAC;AAAA,IAChB;AAAA,EACF;AAAA;AAAA;AAAA,EAIA,IAAY,cAAkC;AAC5C,UAAM,QAAoB,sBAAS,mBAAmB;AACtD,WAAO,UAAU,KAAK,QAAQ;AAAA,EAChC;AACF;AAEA,SAAS,OAAa;AACpB,MAAI,oBAAoB,EAAE,QAAQ;AACpC;AAEA,KAAK;","names":["actionsCore","fs","path"]} \ No newline at end of file diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index b75d997..774fff9 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -13,7 +13,7 @@ dependencies: version: 1.1.1 detsys-ts: specifier: github:DeterminateSystems/detsys-ts - version: github.com/DeterminateSystems/detsys-ts/65dd73c562ac60a068340f8e0c040bdcf2c59afe + version: github.com/DeterminateSystems/detsys-ts/4280bc94c9545f31ccf08001cc16f20ccb91b770 got: specifier: ^14.4.2 version: 14.4.2 @@ -67,19 +67,18 @@ devDependencies: packages: - /@actions/cache@3.2.4: - resolution: {integrity: sha512-RuHnwfcDagtX+37s0ZWy7clbOfnZ7AlDJQ7k/9rzt2W4Gnwde3fa/qjSjVuz4vLcLIpc7fUob27CMrqiWZytYA==} + /@actions/cache@3.3.0: + resolution: {integrity: sha512-+eCsMTIZUEm+QA9GqjollOhCdvRrZ1JV8d9Rp34zVNizBkYITO8dhKczP5Xps1dFzc5n59p7vYVtZrGt18bb5Q==} dependencies: - '@actions/core': 1.10.1 + '@actions/core': 1.11.1 '@actions/exec': 1.1.1 '@actions/glob': 0.1.2 '@actions/http-client': 2.2.3 '@actions/io': 1.1.3 '@azure/abort-controller': 1.1.0 '@azure/ms-rest-js': 2.7.0 - '@azure/storage-blob': 12.24.0 + '@azure/storage-blob': 12.25.0 semver: 6.3.1 - uuid: 3.4.0 transitivePeerDependencies: - encoding - supports-color @@ -92,6 +91,13 @@ packages: uuid: 8.3.2 dev: false + /@actions/core@1.11.1: + resolution: {integrity: sha512-hXJCSrkwfA46Vd9Z3q4cpEpHB1rL5NG04+/rbqW9d3+CSvtB1tYe8UTpAlixa1vj0m/ULglfEK2UKxMGxCxv5A==} + dependencies: + '@actions/exec': 1.1.1 + '@actions/http-client': 2.2.3 + dev: false + /@actions/exec@1.1.1: resolution: {integrity: sha512-+sCcHHbVdk93a0XT19ECtO/gIXoxvdsgQLzb2fE2/5sIZmWQuluYyjPQtrtTHdU1YzTZ7bAPN4sITq2xi1679w==} dependencies: @@ -127,23 +133,23 @@ packages: resolution: {integrity: sha512-TrRLIoSQVzfAJX9H1JeFjzAoDGcoK1IYX1UImfceTZpsyYfWr09Ss1aHW1y5TrrR3iq6RZLBwJ3E24uwPhwahw==} engines: {node: '>=12.0.0'} dependencies: - tslib: 2.7.0 + tslib: 2.8.1 dev: false /@azure/abort-controller@2.1.2: resolution: {integrity: sha512-nBrLsEWm4J2u5LpAPjxADTlq3trDgVZZXHNKabeXZtpq3d3AbN/KGO82R87rdDz5/lYB024rtEf10/q0urNgsA==} engines: {node: '>=18.0.0'} dependencies: - tslib: 2.7.0 + tslib: 2.8.1 dev: false - /@azure/core-auth@1.7.2: - resolution: {integrity: sha512-Igm/S3fDYmnMq1uKS38Ae1/m37B3zigdlZw+kocwEhh5GjyKjPrXKO2J6rzpC1wAxrNil/jX9BJRqBshyjnF3g==} + /@azure/core-auth@1.9.0: + resolution: {integrity: sha512-FPwHpZywuyasDSLMqJ6fhbOK3TqUdviZNF8OqRGA4W5Ewib2lEEZ+pBsYcBa88B2NGO/SEnYPGhyBqNlE8ilSw==} engines: {node: '>=18.0.0'} dependencies: '@azure/abort-controller': 2.1.2 - '@azure/core-util': 1.9.2 - tslib: 2.7.0 + '@azure/core-util': 1.11.0 + tslib: 2.8.1 dev: false /@azure/core-client@1.9.2: @@ -151,12 +157,12 @@ packages: engines: {node: '>=18.0.0'} dependencies: '@azure/abort-controller': 2.1.2 - '@azure/core-auth': 1.7.2 - '@azure/core-rest-pipeline': 1.16.3 - '@azure/core-tracing': 1.1.2 - '@azure/core-util': 1.9.2 + '@azure/core-auth': 1.9.0 + '@azure/core-rest-pipeline': 1.17.0 + '@azure/core-tracing': 1.2.0 + '@azure/core-util': 1.11.0 '@azure/logger': 1.1.4 - tslib: 2.7.0 + tslib: 2.8.1 transitivePeerDependencies: - supports-color dev: false @@ -167,7 +173,7 @@ packages: dependencies: '@azure/abort-controller': 2.1.2 '@azure/core-client': 1.9.2 - '@azure/core-rest-pipeline': 1.16.3 + '@azure/core-rest-pipeline': 1.17.0 transitivePeerDependencies: - supports-color dev: false @@ -177,70 +183,70 @@ packages: engines: {node: '>=18.0.0'} dependencies: '@azure/abort-controller': 2.1.2 - '@azure/core-util': 1.9.2 + '@azure/core-util': 1.11.0 '@azure/logger': 1.1.4 - tslib: 2.7.0 + tslib: 2.8.1 dev: false /@azure/core-paging@1.6.2: resolution: {integrity: sha512-YKWi9YuCU04B55h25cnOYZHxXYtEvQEbKST5vqRga7hWY9ydd3FZHdeQF8pyh+acWZvppw13M/LMGx0LABUVMA==} engines: {node: '>=18.0.0'} dependencies: - tslib: 2.7.0 + tslib: 2.8.1 dev: false - /@azure/core-rest-pipeline@1.16.3: - resolution: {integrity: sha512-VxLk4AHLyqcHsfKe4MZ6IQ+D+ShuByy+RfStKfSjxJoL3WBWq17VNmrz8aT8etKzqc2nAeIyLxScjpzsS4fz8w==} + /@azure/core-rest-pipeline@1.17.0: + resolution: {integrity: sha512-62Vv8nC+uPId3j86XJ0WI+sBf0jlqTqPUFCBNrGtlaUeQUIXWV/D8GE5A1d+Qx8H7OQojn2WguC8kChD6v0shA==} engines: {node: '>=18.0.0'} dependencies: '@azure/abort-controller': 2.1.2 - '@azure/core-auth': 1.7.2 - '@azure/core-tracing': 1.1.2 - '@azure/core-util': 1.9.2 + '@azure/core-auth': 1.9.0 + '@azure/core-tracing': 1.2.0 + '@azure/core-util': 1.11.0 '@azure/logger': 1.1.4 http-proxy-agent: 7.0.2 https-proxy-agent: 7.0.5 - tslib: 2.7.0 + tslib: 2.8.1 transitivePeerDependencies: - supports-color dev: false - /@azure/core-tracing@1.1.2: - resolution: {integrity: sha512-dawW9ifvWAWmUm9/h+/UQ2jrdvjCJ7VJEuCJ6XVNudzcOwm53BFZH4Q845vjfgoUAM8ZxokvVNxNxAITc502YA==} + /@azure/core-tracing@1.2.0: + resolution: {integrity: sha512-UKTiEJPkWcESPYJz3X5uKRYyOcJD+4nYph+KpfdPRnQJVrZfk0KJgdnaAWKfhsBBtAf/D58Az4AvCJEmWgIBAg==} engines: {node: '>=18.0.0'} dependencies: - tslib: 2.7.0 + tslib: 2.8.1 dev: false - /@azure/core-util@1.9.2: - resolution: {integrity: sha512-l1Qrqhi4x1aekkV+OlcqsJa4AnAkj5p0JV8omgwjaV9OAbP41lvrMvs+CptfetKkeEaGRGSzby7sjPZEX7+kkQ==} + /@azure/core-util@1.11.0: + resolution: {integrity: sha512-DxOSLua+NdpWoSqULhjDyAZTXFdP/LKkqtYuxxz1SCN289zk3OG8UOpnCQAz/tygyACBtWp/BoO72ptK7msY8g==} engines: {node: '>=18.0.0'} dependencies: '@azure/abort-controller': 2.1.2 - tslib: 2.7.0 + tslib: 2.8.1 dev: false - /@azure/core-xml@1.4.3: - resolution: {integrity: sha512-D6G7FEmDiTctPKuWegX2WTrS1enKZwqYwdKTO6ZN6JMigcCehlT0/CYl+zWpI9vQ9frwwp7GQT3/owaEXgnOsA==} + /@azure/core-xml@1.4.4: + resolution: {integrity: sha512-J4FYAqakGXcbfeZjwjMzjNcpcH4E+JtEBv+xcV1yL0Ydn/6wbQfeFKTCHh9wttAi0lmajHw7yBbHPRG+YHckZQ==} engines: {node: '>=18.0.0'} dependencies: fast-xml-parser: 4.5.0 - tslib: 2.7.0 + tslib: 2.8.1 dev: false /@azure/logger@1.1.4: resolution: {integrity: sha512-4IXXzcCdLdlXuCG+8UKEwLA1T1NHqUfanhXYHiQTn+6sfWCZXduqbtXDGceg3Ce5QxTGo7EqmbV6Bi+aqKuClQ==} engines: {node: '>=18.0.0'} dependencies: - tslib: 2.7.0 + tslib: 2.8.1 dev: false /@azure/ms-rest-js@2.7.0: resolution: {integrity: sha512-ngbzWbqF+NmztDOpLBVDxYM+XLcUj7nKhxGbSU9WtIsXfRB//cf2ZbAG5HkOrhU9/wd/ORRB6lM/d69RKVjiyA==} dependencies: - '@azure/core-auth': 1.7.2 + '@azure/core-auth': 1.9.0 abort-controller: 3.0.0 - form-data: 2.5.1 + form-data: 2.5.2 node-fetch: 2.7.0 tslib: 1.14.1 tunnel: 0.0.6 @@ -250,23 +256,23 @@ packages: - encoding dev: false - /@azure/storage-blob@12.24.0: - resolution: {integrity: sha512-l8cmWM4C7RoNCBOImoFMxhTXe1Lr+8uQ/IgnhRNMpfoA9bAFWoLG4XrWm6O5rKXortreVQuD+fc1hbzWklOZbw==} + /@azure/storage-blob@12.25.0: + resolution: {integrity: sha512-oodouhA3nCCIh843tMMbxty3WqfNT+Vgzj3Xo5jqR9UPnzq3d7mzLjlHAYz7lW+b4km3SIgz+NAgztvhm7Z6kQ==} engines: {node: '>=18.0.0'} dependencies: - '@azure/abort-controller': 1.1.0 - '@azure/core-auth': 1.7.2 + '@azure/abort-controller': 2.1.2 + '@azure/core-auth': 1.9.0 '@azure/core-client': 1.9.2 '@azure/core-http-compat': 2.1.2 '@azure/core-lro': 2.7.2 '@azure/core-paging': 1.6.2 - '@azure/core-rest-pipeline': 1.16.3 - '@azure/core-tracing': 1.1.2 - '@azure/core-util': 1.9.2 - '@azure/core-xml': 1.4.3 + '@azure/core-rest-pipeline': 1.17.0 + '@azure/core-tracing': 1.2.0 + '@azure/core-util': 1.11.0 + '@azure/core-xml': 1.4.4 '@azure/logger': 1.1.4 events: 3.3.0 - tslib: 2.7.0 + tslib: 2.8.1 transitivePeerDependencies: - supports-color dev: false @@ -895,6 +901,11 @@ packages: engines: {node: '>=18'} dev: false + /@sindresorhus/is@7.0.1: + resolution: {integrity: sha512-QWLl2P+rsCJeofkDNIT3WFmb6NrRud1SUYW8dIhXK/46XFV8Q/g7Bsvib0Askb0reRLe+WYPeeE+l5cH7SlkuQ==} + engines: {node: '>=18'} + dev: false + /@szmarczak/http-timer@5.0.1: resolution: {integrity: sha512-+PmQX0PiAYPMeVYe237LJAYvOMYW1j2rH5YROyS3b4CTVJum34HfRvKvAzozHAQG0TnHNdUfY9nCeUyRAs//cw==} engines: {node: '>=14.16'} @@ -1109,7 +1120,7 @@ packages: resolution: {integrity: sha512-H0TSyFNDMomMNJQBn8wFV5YC/2eJ+VXECwOadZJT554xP6cODZHPX3H9QMQECxvrgiSOP1pHjy1sMWQVYJOUOA==} engines: {node: '>= 14'} dependencies: - debug: 4.3.6 + debug: 4.3.7 transitivePeerDependencies: - supports-color dev: false @@ -1502,6 +1513,19 @@ packages: optional: true dependencies: ms: 2.1.2 + dev: true + + /debug@4.3.7: + resolution: {integrity: sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==} + engines: {node: '>=6.0'} + peerDependencies: + supports-color: '*' + peerDependenciesMeta: + supports-color: + optional: true + dependencies: + ms: 2.1.3 + dev: false /decompress-response@6.0.0: resolution: {integrity: sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==} @@ -2239,13 +2263,14 @@ packages: engines: {node: '>= 18'} dev: false - /form-data@2.5.1: - resolution: {integrity: sha512-m21N3WOmEEURgk6B9GLOE4RuWOFf28Lhh9qGYeNlGq4VDXUlJy2th2slBNU8Gp8EzloYZOibZJ7t5ecIrFSjVA==} + /form-data@2.5.2: + resolution: {integrity: sha512-GgwY0PS7DbXqajuGf4OYlsrIu3zgxD6Vvql43IBhm6MahqA5SK/7mwhtNj2AdH2z35YR34ujJ7BN+3fFC3jP5Q==} engines: {node: '>= 0.12'} dependencies: asynckit: 0.4.0 combined-stream: 1.0.8 mime-types: 2.1.35 + safe-buffer: 5.2.1 dev: false /fs.realpath@1.0.0: @@ -2410,6 +2435,23 @@ packages: type-fest: 4.23.0 dev: false + /got@14.4.4: + resolution: {integrity: sha512-tqiF7eSgTBwQkxb1LxsEpva8TaMYVisbhplrFVmw9GQE3855Z+MH/mnsXLLOkDxR6hZJRFMj5VTAZ8lmTF8ZOA==} + engines: {node: '>=20'} + dependencies: + '@sindresorhus/is': 7.0.1 + '@szmarczak/http-timer': 5.0.1 + cacheable-lookup: 7.0.0 + cacheable-request: 12.0.1 + decompress-response: 6.0.0 + form-data-encoder: 4.0.2 + http2-wrapper: 2.2.1 + lowercase-keys: 3.0.0 + p-cancelable: 4.0.1 + responselike: 3.0.0 + type-fest: 4.26.1 + dev: false + /graceful-fs@4.2.11: resolution: {integrity: sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==} dev: true @@ -2471,7 +2513,7 @@ packages: engines: {node: '>= 14'} dependencies: agent-base: 7.1.1 - debug: 4.3.6 + debug: 4.3.7 transitivePeerDependencies: - supports-color dev: false @@ -2489,7 +2531,7 @@ packages: engines: {node: '>= 14'} dependencies: agent-base: 7.1.1 - debug: 4.3.6 + debug: 4.3.7 transitivePeerDependencies: - supports-color dev: false @@ -2964,10 +3006,10 @@ packages: /ms@2.1.2: resolution: {integrity: sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==} + dev: true /ms@2.1.3: resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} - dev: true /mz@2.7.0: resolution: {integrity: sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q==} @@ -3353,6 +3395,10 @@ packages: isarray: 2.0.5 dev: true + /safe-buffer@5.2.1: + resolution: {integrity: sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==} + dev: false + /safe-regex-test@1.0.3: resolution: {integrity: sha512-CdASjNJPvRa7roO6Ra/gLYBTzYzzPyyBXxIMdGW3USQLyjWEls2RgW5UBTXaQVp+OrpeCK3bLem8smtmheoRuw==} engines: {node: '>= 0.4'} @@ -3667,8 +3713,8 @@ packages: resolution: {integrity: sha512-xNvxJEOUiWPGhUuUdQgAJPKOOJfGnIyKySOc09XkKsgdUV/3E2zvwZYdejjmRgPCgcym1juLH3226yA7sEFJKQ==} dev: true - /tslib@2.7.0: - resolution: {integrity: sha512-gLXCKdN1/j47AiHiOkJN69hJmcbGTHI0ImLmbYLHykhgeN0jVGola9yVjFgzCUklsZQMW55o+dW7IXv3RCXDzA==} + /tslib@2.8.1: + resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==} dev: false /tsup@8.2.3(typescript@5.5.4): @@ -3736,8 +3782,8 @@ packages: engines: {node: '>=16'} dev: false - /type-fest@4.26.0: - resolution: {integrity: sha512-OduNjVJsFbifKb57UqZ2EMP1i4u64Xwow3NYXUtBbD4vIwJdQd4+xl8YDou1dlm4DVrtwT/7Ky8z8WyCULVfxw==} + /type-fest@4.26.1: + resolution: {integrity: sha512-yOGpmOAL7CkKe/91I5O3gPICmJNLJ1G4zFYVAsRHg7M64biSnPtRj0WNQt++bRkjYOqjWXrhnUw1utzmVErAdg==} engines: {node: '>=16'} dev: false @@ -3828,12 +3874,6 @@ packages: punycode: 2.3.1 dev: true - /uuid@3.4.0: - resolution: {integrity: sha512-HjSDRw6gZE5JMggctHBcjVak08+KEVhSIiDzFnT9S9aegmp85S/bReBVTb4QTFaRNptJ9kuYaNhnbNEOkbKb/A==} - deprecated: Please upgrade to version 7 or higher. Older versions may use Math.random() in certain circumstances, which is known to be problematic. See https://v8.dev/blog/math-random for details. - hasBin: true - dev: false - /uuid@8.3.2: resolution: {integrity: sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==} hasBin: true @@ -3964,16 +4004,16 @@ packages: engines: {node: '>=10'} dev: true - github.com/DeterminateSystems/detsys-ts/65dd73c562ac60a068340f8e0c040bdcf2c59afe: - resolution: {tarball: https://codeload.github.com/DeterminateSystems/detsys-ts/tar.gz/65dd73c562ac60a068340f8e0c040bdcf2c59afe} + github.com/DeterminateSystems/detsys-ts/4280bc94c9545f31ccf08001cc16f20ccb91b770: + resolution: {tarball: https://codeload.github.com/DeterminateSystems/detsys-ts/tar.gz/4280bc94c9545f31ccf08001cc16f20ccb91b770} name: detsys-ts version: 1.0.0 dependencies: - '@actions/cache': 3.2.4 - '@actions/core': 1.10.1 + '@actions/cache': 3.3.0 + '@actions/core': 1.11.1 '@actions/exec': 1.1.1 - got: 14.4.2 - type-fest: 4.26.0 + got: 14.4.4 + type-fest: 4.26.1 transitivePeerDependencies: - encoding - supports-color diff --git a/src/helpers.ts b/src/helpers.ts index c2a7596..0525980 100644 --- a/src/helpers.ts +++ b/src/helpers.ts @@ -4,6 +4,33 @@ import * as os from "node:os"; import path from "node:path"; import { Tail } from "tail"; +export function getTrinaryInput( + name: string, +): "enabled" | "disabled" | "no-preference" { + const trueValue = ["true", "True", "TRUE", "enabled"]; + const falseValue = ["false", "False", "FALSE", "disabled"]; + const noPreferenceValue = ["", "null", "no-preference"]; + + const val = actionsCore.getInput(name); + if (trueValue.includes(val)) { + return "enabled"; + } + if (falseValue.includes(val)) { + return "disabled"; + } + if (noPreferenceValue.includes(val)) { + return "no-preference"; + } + + const possibleValues = trueValue + .concat(falseValue) + .concat(noPreferenceValue) + .join(" | "); + throw new TypeError( + `Input ${name} does not look like a trinary, which requires one of:\n${possibleValues}`, + ); +} + export function tailLog(daemonDir: string): Tail { const log = new Tail(path.join(daemonDir, "daemon.log")); actionsCore.debug(`tailing daemon.log...`); diff --git a/src/index.ts b/src/index.ts index 7ade870..de03946 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,4 +1,4 @@ -import { netrcPath, tailLog } from "./helpers.js"; +import { getTrinaryInput, netrcPath, tailLog } from "./helpers.js"; import * as actionsCore from "@actions/core"; import { DetSysAction, inputs, stringifyError } from "detsys-ts"; import got, { Got, Response } from "got"; @@ -207,11 +207,11 @@ class MagicNixCacheAction extends DetSysAction { const nixConfPath = `${process.env["HOME"]}/.config/nix/nix.conf`; const upstreamCache = inputs.getString("upstream-cache"); const diagnosticEndpoint = inputs.getString("diagnostic-endpoint"); - const useFlakeHub = inputs.getBool("use-flakehub"); + const useFlakeHub = getTrinaryInput("use-flakehub"); const flakeHubCacheServer = inputs.getString("flakehub-cache-server"); const flakeHubApiServer = inputs.getString("flakehub-api-server"); const flakeHubFlakeName = inputs.getString("flakehub-flake-name"); - const useGhaCache = inputs.getBool("use-gha-cache"); + const useGhaCache = getTrinaryInput("use-gha-cache"); const daemonCliFlags: string[] = [ "--startup-notification-url", @@ -224,12 +224,15 @@ class MagicNixCacheAction extends DetSysAction { diagnosticEndpoint, "--nix-conf", nixConfPath, + "--use-gha-cache", + useGhaCache, + "--use-flakehub", + useFlakeHub, ] .concat(this.diffStore ? ["--diff-store"] : []) .concat( - useFlakeHub + useFlakeHub !== "disabled" ? [ - "--use-flakehub", "--flakehub-cache-server", flakeHubCacheServer, "--flakehub-api-server", @@ -240,8 +243,7 @@ class MagicNixCacheAction extends DetSysAction { flakeHubFlakeName, ] : [], - ) - .concat(useGhaCache ? ["--use-gha-cache"] : []); + ); const opts: SpawnOptions = { stdio: ["ignore", output, output],