From cd9805d5f83f7ecdf7fbd930724d59f0d31b1950 Mon Sep 17 00:00:00 2001 From: finalerock44 Date: Mon, 5 Oct 2026 12:33:49 +0100 Subject: [PATCH 1/3] chore: pin typescript to 5.9 until ncc supports TypeScript 7 The TypeScript 7.0.2 bump (#60) broke `pnpm build`, so the Release workflow's Rebuild dist job has failed on every push since, and release-please (which needs it) hasn't run. ncc 0.45, the latest release, compiles through TypeScript's JS compiler API (ts.sys), which TypeScript 7, the native Go port, does not ship: TypeError: Cannot read properties of undefined (reading 'fileExists') at findConfigFile (.../@vercel/ncc/dist/ncc/loaders/ts-loader.js...) Back to 5.9.3, the version before the bump. Dependabot now ignores typescript >= 7 so it doesn't reopen the bump. Drop the ignore once ncc supports TypeScript 7. --- .github/dependabot.yml | 7 ++ package.json | 2 +- pnpm-lock.yaml | 213 ++--------------------------------------- 3 files changed, 14 insertions(+), 208 deletions(-) diff --git a/.github/dependabot.yml b/.github/dependabot.yml index c86481c..3d316ce 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -21,6 +21,13 @@ updates: update-types: - minor - patch + ignore: + # ncc (0.45, the latest) compiles through TypeScript's JS compiler API, + # which TypeScript 7, the native Go port, does not ship: `pnpm build` + # dies with "Cannot read properties of undefined (reading 'fileExists')". + # Remove this once an ncc release supports TypeScript 7. + - dependency-name: typescript + versions: [">= 7"] # GitHub Actions used by our workflows. - package-ecosystem: github-actions diff --git a/package.json b/package.json index 02f1744..698935c 100644 --- a/package.json +++ b/package.json @@ -20,7 +20,7 @@ "devDependencies": { "@types/node": "^26.6.4", "@vercel/ncc": "^0.45.0", - "typescript": "^7.0.2", + "typescript": "^5.9.3", "vitest": "^5.0.3" }, "pnpm": { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 4b42df5..c787f65 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -26,8 +26,8 @@ importers: specifier: ^0.45.0 version: 0.45.0 typescript: - specifier: ^7.0.2 - version: 7.0.2 + specifier: ^5.9.3 + version: 5.9.3 vitest: specifier: ^5.0.3 version: 5.0.3(@types/node@26.6.4)(vite@8.0.16(@types/node@26.6.4)) @@ -242,126 +242,6 @@ packages: '@types/node@26.6.4': resolution: {integrity: sha512-ldVPDCzj7fsaGZrLB0NuHuTvJcsNasysBAqMolr/cgxrLd1xbqxIr3XJiPnHHJUCxj5sNF1vnRj9aWnrVh5Jcg==} - '@typescript/typescript-aix-ppc64@7.0.2': - resolution: {integrity: sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==} - engines: {node: '>=16.20.0'} - cpu: [ppc64] - os: [aix] - - '@typescript/typescript-darwin-arm64@7.0.2': - resolution: {integrity: sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==} - engines: {node: '>=16.20.0'} - cpu: [arm64] - os: [darwin] - - '@typescript/typescript-darwin-x64@7.0.2': - resolution: {integrity: sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==} - engines: {node: '>=16.20.0'} - cpu: [x64] - os: [darwin] - - '@typescript/typescript-freebsd-arm64@7.0.2': - resolution: {integrity: sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==} - engines: {node: '>=16.20.0'} - cpu: [arm64] - os: [freebsd] - - '@typescript/typescript-freebsd-x64@7.0.2': - resolution: {integrity: sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==} - engines: {node: '>=16.20.0'} - cpu: [x64] - os: [freebsd] - - '@typescript/typescript-linux-arm64@7.0.2': - resolution: {integrity: sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==} - engines: {node: '>=16.20.0'} - cpu: [arm64] - os: [linux] - - '@typescript/typescript-linux-arm@7.0.2': - resolution: {integrity: sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==} - engines: {node: '>=16.20.0'} - cpu: [arm] - os: [linux] - - '@typescript/typescript-linux-loong64@7.0.2': - resolution: {integrity: sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==} - engines: {node: '>=16.20.0'} - cpu: [loong64] - os: [linux] - - '@typescript/typescript-linux-mips64el@7.0.2': - resolution: {integrity: sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==} - engines: {node: '>=16.20.0'} - cpu: [mips64el] - os: [linux] - - '@typescript/typescript-linux-ppc64@7.0.2': - resolution: {integrity: sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==} - engines: {node: '>=16.20.0'} - cpu: [ppc64] - os: [linux] - - '@typescript/typescript-linux-riscv64@7.0.2': - resolution: {integrity: sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==} - engines: {node: '>=16.20.0'} - cpu: [riscv64] - os: [linux] - - '@typescript/typescript-linux-s390x@7.0.2': - resolution: {integrity: sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==} - engines: {node: '>=16.20.0'} - cpu: [s390x] - os: [linux] - - '@typescript/typescript-linux-x64@7.0.2': - resolution: {integrity: sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==} - engines: {node: '>=16.20.0'} - cpu: [x64] - os: [linux] - - '@typescript/typescript-netbsd-arm64@7.0.2': - resolution: {integrity: sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==} - engines: {node: '>=16.20.0'} - cpu: [arm64] - os: [netbsd] - - '@typescript/typescript-netbsd-x64@7.0.2': - resolution: {integrity: sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==} - engines: {node: '>=16.20.0'} - cpu: [x64] - os: [netbsd] - - '@typescript/typescript-openbsd-arm64@7.0.2': - resolution: {integrity: sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==} - engines: {node: '>=16.20.0'} - cpu: [arm64] - os: [openbsd] - - '@typescript/typescript-openbsd-x64@7.0.2': - resolution: {integrity: sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==} - engines: {node: '>=16.20.0'} - cpu: [x64] - os: [openbsd] - - '@typescript/typescript-sunos-x64@7.0.2': - resolution: {integrity: sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==} - engines: {node: '>=16.20.0'} - cpu: [x64] - os: [sunos] - - '@typescript/typescript-win32-arm64@7.0.2': - resolution: {integrity: sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==} - engines: {node: '>=16.20.0'} - cpu: [arm64] - os: [win32] - - '@typescript/typescript-win32-x64@7.0.2': - resolution: {integrity: sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==} - engines: {node: '>=16.20.0'} - cpu: [x64] - os: [win32] - '@vercel/ncc@0.45.0': resolution: {integrity: sha512-8zPi1yO2mHpoKTD+e+Bf0ZT3e+sWHSOyGapm9s7b5R0gxJi3CiFTqmeQiMEyu6ejrz2s09M8JkEoUaTWjBJPQQ==} hasBin: true @@ -554,9 +434,9 @@ packages: resolution: {integrity: sha512-1h/Lnq9yajKY2PEbBadPXj3VxsDDu844OnaAo52UVmIzIvwwtBPIuNvkjuzBlTWpfJyUbG3ez0KSBibQkj4ojg==} engines: {node: '>=0.6.11 <=0.7.0 || >=0.7.3'} - typescript@7.0.2: - resolution: {integrity: sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==} - engines: {node: '>=16.20.0'} + typescript@5.9.3: + resolution: {integrity: sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==} + engines: {node: '>=14.17'} hasBin: true undici-types@8.9.0: @@ -852,66 +732,6 @@ snapshots: dependencies: undici-types: 8.9.0 - '@typescript/typescript-aix-ppc64@7.0.2': - optional: true - - '@typescript/typescript-darwin-arm64@7.0.2': - optional: true - - '@typescript/typescript-darwin-x64@7.0.2': - optional: true - - '@typescript/typescript-freebsd-arm64@7.0.2': - optional: true - - '@typescript/typescript-freebsd-x64@7.0.2': - optional: true - - '@typescript/typescript-linux-arm64@7.0.2': - optional: true - - '@typescript/typescript-linux-arm@7.0.2': - optional: true - - '@typescript/typescript-linux-loong64@7.0.2': - optional: true - - '@typescript/typescript-linux-mips64el@7.0.2': - optional: true - - '@typescript/typescript-linux-ppc64@7.0.2': - optional: true - - '@typescript/typescript-linux-riscv64@7.0.2': - optional: true - - '@typescript/typescript-linux-s390x@7.0.2': - optional: true - - '@typescript/typescript-linux-x64@7.0.2': - optional: true - - '@typescript/typescript-netbsd-arm64@7.0.2': - optional: true - - '@typescript/typescript-netbsd-x64@7.0.2': - optional: true - - '@typescript/typescript-openbsd-arm64@7.0.2': - optional: true - - '@typescript/typescript-openbsd-x64@7.0.2': - optional: true - - '@typescript/typescript-sunos-x64@7.0.2': - optional: true - - '@typescript/typescript-win32-arm64@7.0.2': - optional: true - - '@typescript/typescript-win32-x64@7.0.2': - optional: true - '@vercel/ncc@0.45.0': {} '@vitest/mocker@5.0.3(vite@8.0.16(@types/node@26.6.4))': @@ -1058,28 +878,7 @@ snapshots: tunnel@0.0.6: {} - typescript@7.0.2: - optionalDependencies: - '@typescript/typescript-aix-ppc64': 7.0.2 - '@typescript/typescript-darwin-arm64': 7.0.2 - '@typescript/typescript-darwin-x64': 7.0.2 - '@typescript/typescript-freebsd-arm64': 7.0.2 - '@typescript/typescript-freebsd-x64': 7.0.2 - '@typescript/typescript-linux-arm': 7.0.2 - '@typescript/typescript-linux-arm64': 7.0.2 - '@typescript/typescript-linux-loong64': 7.0.2 - '@typescript/typescript-linux-mips64el': 7.0.2 - '@typescript/typescript-linux-ppc64': 7.0.2 - '@typescript/typescript-linux-riscv64': 7.0.2 - '@typescript/typescript-linux-s390x': 7.0.2 - '@typescript/typescript-linux-x64': 7.0.2 - '@typescript/typescript-netbsd-arm64': 7.0.2 - '@typescript/typescript-netbsd-x64': 7.0.2 - '@typescript/typescript-openbsd-arm64': 7.0.2 - '@typescript/typescript-openbsd-x64': 7.0.2 - '@typescript/typescript-sunos-x64': 7.0.2 - '@typescript/typescript-win32-arm64': 7.0.2 - '@typescript/typescript-win32-x64': 7.0.2 + typescript@5.9.3: {} undici-types@8.9.0: {} From 48f8996b3c71436dc6a42c2a45c574172d8c4ee6 Mon Sep 17 00:00:00 2001 From: finalerock44 Date: Mon, 5 Oct 2026 12:33:49 +0100 Subject: [PATCH 2/3] fix: bundle the ESM-only @actions/core 3 and @actions/github 9 With TypeScript back on 5.9, ncc builds and exits 0, but dist/index.js shrinks from 1.7 MB to 36 kB and fails on its first line: Error: Cannot find module '@actions/core' @actions/core 3 (#58) and @actions/github 9 (#59) are ESM-only: their `exports` have just an `import` condition. With "module": "commonjs", TypeScript turns our imports into require() calls, webpack resolves those with the `require` condition, finds nothing, and ncc bundles a stub that throws at runtime rather than failing the build. Emit ES modules ("module": "esnext") and resolve the way a bundler does ("moduleResolution": "bundler"), so webpack follows the `import` condition. ncc still writes a CommonJS dist/index.js, so __dirname (readWrapperVersion) still works. "lib" goes to es2022 for the ErrorOptions type that @octokit/request-error now uses. That only affects type checking, and node24 runs ES2022 natively. Checked by running the old and new bundles with fake npx/npm on PATH. Both build the same `dcd cloud` command from the same inputs and PR event, report wrapper version 2.6.0, and write the same four GITHUB_OUTPUT values. The new bundle requires the same Node builtins as the old one. tsc --noEmit is now clean; under node10 resolution it could not find @octokit/core/types. --- dist/index.js | 25884 ++++++++++++++++++++++++------------------------ tsconfig.json | 5 +- 2 files changed, 13203 insertions(+), 12686 deletions(-) diff --git a/dist/index.js b/dist/index.js index 8ef269b..abce719 100644 --- a/dist/index.js +++ b/dist/index.js @@ -1,146 +1,12 @@ /******/ (() => { // webpackBootstrap /******/ var __webpack_modules__ = ({ -/***/ 7213: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || (function () { - 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); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - 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; - }; -})(); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.issueCommand = issueCommand; -exports.issue = issue; -const os = __importStar(__nccwpck_require__(857)); -const utils_1 = __nccwpck_require__(6001); -/** - * Issues a command to the GitHub Actions runner - * - * @param command - The command name to issue - * @param properties - Additional properties for the command (key-value pairs) - * @param message - The message to include with the command - * @remarks - * This function outputs a specially formatted string to stdout that the Actions - * runner interprets as a command. These commands can control workflow behavior, - * set outputs, create annotations, mask values, and more. - * - * Command Format: - * ::name key=value,key=value::message - * - * @example - * ```typescript - * // Issue a warning annotation - * issueCommand('warning', {}, 'This is a warning message'); - * // Output: ::warning::This is a warning message - * - * // Set an environment variable - * issueCommand('set-env', { name: 'MY_VAR' }, 'some value'); - * // Output: ::set-env name=MY_VAR::some value - * - * // Add a secret mask - * issueCommand('add-mask', {}, 'secretValue123'); - * // Output: ::add-mask::secretValue123 - * ``` - * - * @internal - * This is an internal utility function that powers the public API functions - * such as setSecret, warning, error, and exportVariable. - */ -function issueCommand(command, properties, message) { - const cmd = new Command(command, properties, message); - process.stdout.write(cmd.toString() + os.EOL); -} -function issue(name, message = '') { - issueCommand(name, {}, message); -} -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 - -/***/ }), - -/***/ 7153: +/***/ 2504: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; +/* 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); @@ -184,10648 +50,7898 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.platform = exports.toPlatformPath = exports.toWin32Path = exports.toPosixPath = exports.markdownSummary = exports.summary = exports.ExitCode = void 0; -exports.exportVariable = exportVariable; -exports.setSecret = setSecret; -exports.addPath = addPath; -exports.getInput = getInput; -exports.getMultilineInput = getMultilineInput; -exports.getBooleanInput = getBooleanInput; -exports.setOutput = setOutput; -exports.setCommandEcho = setCommandEcho; -exports.setFailed = setFailed; -exports.isDebug = isDebug; -exports.debug = debug; -exports.error = error; -exports.warning = warning; -exports.notice = notice; -exports.info = info; -exports.startGroup = startGroup; -exports.endGroup = endGroup; -exports.group = group; -exports.saveState = saveState; -exports.getState = getState; -exports.getIDToken = getIDToken; -const command_1 = __nccwpck_require__(7213); -const file_command_1 = __nccwpck_require__(5552); -const utils_1 = __nccwpck_require__(6001); -const os = __importStar(__nccwpck_require__(857)); -const path = __importStar(__nccwpck_require__(6928)); -const oidc_utils_1 = __nccwpck_require__(3591); -/** - * 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.HttpClient = exports.HttpClientResponse = exports.HttpClientError = exports.MediaTypes = exports.Headers = exports.HttpCodes = void 0; +exports.getProxyUrl = getProxyUrl; +exports.isHttps = isHttps; +const http = __importStar(__nccwpck_require__(8611)); +const https = __importStar(__nccwpck_require__(5692)); +const pm = __importStar(__nccwpck_require__(568)); +const tunnel = __importStar(__nccwpck_require__(7013)); +const undici_1 = __nccwpck_require__(1889); +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 = {})); /** - * Registers a secret which will get masked from logs - * - * @param secret - Value of the secret to be masked - * @remarks - * This function instructs the Actions runner to mask the specified value in any - * logs produced during the workflow run. Once registered, the secret value will - * be replaced with asterisks (***) whenever it appears in console output, logs, - * or error messages. - * - * This is useful for protecting sensitive information such as: - * - API keys - * - Access tokens - * - Authentication credentials - * - URL parameters containing signatures (SAS tokens) - * - * Note that masking only affects future logs; any previous appearances of the - * secret in logs before calling this function will remain unmasked. - * - * @example - * ```typescript - * // Register an API token as a secret - * const apiToken = "abc123xyz456"; - * setSecret(apiToken); - * - * // Now any logs containing this value will show *** instead - * console.log(`Using token: ${apiToken}`); // Outputs: "Using token: ***" - * ``` + * 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 setSecret(secret) { - (0, command_1.issueCommand)('add-mask', {}, secret); +function getProxyUrl(serverUrl) { + const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ''; } -/** - * 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); +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); } - process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`; } -/** - * 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 name name of the input to get - * @param options optional. See InputOptions. - * @returns string - */ -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; +exports.HttpClientError = HttpClientError; +class HttpClientResponse { + constructor(message) { + this.message = message; } - return val.trim(); -} -/** - * 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; + 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()); + }); + })); + }); } - return inputs.map(input => input.trim()); -} -/** - * 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\``); -} -/** - * 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)); + 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)); + }); + })); + }); } - process.stdout.write(os.EOL); - (0, command_1.issueCommand)('set-output', { name }, (0, utils_1.toCommandValue)(value)); -} -/** - * 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'); -} -//----------------------------------------------------------------------- -// 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); -} -//----------------------------------------------------------------------- -// Logging Commands -//----------------------------------------------------------------------- -/** - * Gets whether Actions Step Debug is on or not - */ -function isDebug() { - return process.env['RUNNER_DEBUG'] === '1'; -} -/** - * Writes debug message to user log - * @param message debug message - */ -function debug(message) { - (0, command_1.issueCommand)('debug', {}, message); -} -/** - * 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); -} -/** - * 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); -} -/** - * 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); -} -/** - * Writes info to log with console.log. - * @param message info message - */ -function info(message) { - process.stdout.write(message + os.EOL); -} -/** - * 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); } -/** - * End an output group. - */ -function endGroup() { - (0, command_1.issue)('endgroup'); +exports.HttpClientResponse = HttpClientResponse; +function isHttps(requestUrl) { + const parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === 'https:'; } -/** - * 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* () { - startGroup(name); - let result; - try { - result = yield fn(); - } - finally { - endGroup(); +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 = this._getUserAgentWithOrchestrationId(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; + } + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + } + 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 result; - }); -} -//----------------------------------------------------------------------- -// Wrapper action state -//----------------------------------------------------------------------- -/** - * Saves state for current action, the state can only be retrieved by this action's post job execution. - * - * @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 - */ -// 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)); -} -/** - * 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}`] || ''; -} -function getIDToken(aud) { - return __awaiter(this, void 0, void 0, function* () { - return yield oidc_utils_1.OidcClient.getIDToken(aud); - }); -} -/** - * Summary exports - */ -var summary_1 = __nccwpck_require__(4224); -Object.defineProperty(exports, "summary", ({ enumerable: true, get: function () { return summary_1.summary; } })); -/** - * @deprecated use core.summary - */ -var summary_2 = __nccwpck_require__(4224); -Object.defineProperty(exports, "markdownSummary", ({ enumerable: true, get: function () { return summary_2.markdownSummary; } })); -/** - * Path exports - */ -var path_utils_1 = __nccwpck_require__(5245); -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__(2437)); -//# sourceMappingURL=core.js.map - -/***/ }), - -/***/ 5552: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -// For internal use, subject to change. -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 () { - 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); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - 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; - }; -})(); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.issueFileCommand = issueFileCommand; -exports.prepareKeyValueMessage = prepareKeyValueMessage; -// We use any as a valid input type -/* eslint-disable @typescript-eslint/no-explicit-any */ -const crypto = __importStar(__nccwpck_require__(6982)); -const fs = __importStar(__nccwpck_require__(9896)); -const os = __importStar(__nccwpck_require__(857)); -const utils_1 = __nccwpck_require__(6001); -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}`); + options(requestUrl, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('OPTIONS', requestUrl, null, additionalHeaders || {}); + }); } - fs.appendFileSync(filePath, `${(0, utils_1.toCommandValue)(message)}${os.EOL}`, { - encoding: 'utf8' - }); -} -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}"`); + get(requestUrl, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('GET', requestUrl, null, additionalHeaders || {}); + }); } - if (convertedValue.includes(delimiter)) { - throw new Error(`Unexpected input: value should not contain the delimiter "${delimiter}"`); + del(requestUrl, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('DELETE', requestUrl, null, additionalHeaders || {}); + }); } - return `${key}<<${delimiter}${os.EOL}${convertedValue}${os.EOL}${delimiter}`; -} -//# sourceMappingURL=file-command.js.map - -/***/ }), - -/***/ 3591: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -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.OidcClient = void 0; -const http_client_1 = __nccwpck_require__(7708); -const auth_1 = __nccwpck_require__(1960); -const core_1 = __nccwpck_require__(7153); -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); + post(requestUrl, data, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('POST', requestUrl, data, additionalHeaders || {}); + }); } - 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 token; + patch(requestUrl, data, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('PATCH', requestUrl, data, additionalHeaders || {}); + }); } - 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; + put(requestUrl, data, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('PUT', requestUrl, data, additionalHeaders || {}); + }); } - static getCall(id_token_url) { + head(requestUrl, additionalHeaders) { return __awaiter(this, void 0, void 0, function* () { - var _a; - 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 id_token; + return this.request('HEAD', requestUrl, null, additionalHeaders || {}); }); } - static getIDToken(audience) { + sendStream(verb, requestUrl, stream, additionalHeaders) { 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}`; - } - (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; - } - catch (error) { - throw new Error(`Error message: ${error.message}`); - } + return this.request(verb, requestUrl, stream, additionalHeaders); }); } -} -exports.OidcClient = OidcClient; -//# sourceMappingURL=oidc-utils.js.map - -/***/ }), - -/***/ 5245: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; + /** + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + */ + getJson(requestUrl_1) { + return __awaiter(this, arguments, void 0, function* (requestUrl, additionalHeaders = {}) { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + const res = yield this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - 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 () { - 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); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - 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; - }; -})(); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.toPosixPath = toPosixPath; -exports.toWin32Path = toWin32Path; -exports.toPlatformPath = toPlatformPath; -const path = __importStar(__nccwpck_require__(6928)); -/** - * 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, '/'); -} -/** - * 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, '\\'); -} -/** - * 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); -} -//# sourceMappingURL=path-utils.js.map - -/***/ }), - -/***/ 2437: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; + postJson(requestUrl_1, obj_1) { + return __awaiter(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = + this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson); + const res = yield this.post(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - 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 () { - 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); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - 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; - }; -})(); -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.isLinux = exports.isMacOS = exports.isWindows = exports.arch = exports.platform = void 0; -exports.getDetails = getDetails; -const os_1 = __importDefault(__nccwpck_require__(857)); -const exec = __importStar(__nccwpck_require__(4154)); -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 }); - }); -} -//# sourceMappingURL=platform.js.map - -/***/ }), - -/***/ 4224: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -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__(857); -const fs_1 = __nccwpck_require__(9896); -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 = ''; + putJson(requestUrl_1, obj_1) { + return __awaiter(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = + this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson); + const res = yield this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + patchJson(requestUrl_1, obj_1) { + return __awaiter(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = + this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson); + const res = yield this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } /** - * 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 + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch */ - filePath() { + request(verb, requestUrl, data, headers) { return __awaiter(this, void 0, void 0, function* () { - if (this._filePath) { - return this._filePath; - } - 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.`); - } - try { - yield access(pathFromEnv, fs_1.constants.R_OK | fs_1.constants.W_OK); - } - catch (_a) { - throw new Error(`Unable to access summary file: '${pathFromEnv}'. Check if the file has correct read/write permissions.`); + if (this._disposed) { + throw new Error('Client has already been disposed.'); } - this._filePath = pathFromEnv; - return this._filePath; + 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; }); } /** - * 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 + * Needs to be called if keepAlive is set to true in request options. */ - wrap(tag, content, attrs = {}) { - const htmlAttrs = Object.entries(attrs) - .map(([key, value]) => ` ${key}="${value}"`) - .join(''); - if (!content) { - return `<${tag}${htmlAttrs}>`; + dispose() { + if (this._agent) { + this._agent.destroy(); } - return `<${tag}${htmlAttrs}>${content}`; + this._disposed = true; } /** - * 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 + * Raw request. + * @param info + * @param data */ - write(options) { + requestRaw(info, data) { 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(); - }); - } - /** - * Clears the summary buffer and wipes the summary file - * - * @returns {Summary} summary instance - */ - clear() { - return __awaiter(this, void 0, void 0, function* () { - return this.emptyBuffer().write({ overwrite: true }); + 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); + }); }); } /** - * Returns the current summary buffer as a string - * - * @returns {string} string of summary buffer - */ - stringify() { - return this._buffer; - } - /** - * If the summary buffer is empty - * - * @returns {boolen} true if the buffer is empty + * Raw request with callback. + * @param info + * @param data + * @param onResult */ - isEmptyBuffer() { - return this._buffer.length === 0; + 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); + } + } + 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(); + } + 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(); + } } /** - * Resets the summary buffer without writing to summary file - * - * @returns {Summary} summary instance + * 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 */ - emptyBuffer() { - this._buffer = ''; - return this; + getAgent(serverUrl) { + const parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); } - /** - * 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; + 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); } - /** - * Adds the operating system-specific end-of-line marker to the buffer - * - * @returns {Summary} summary instance - */ - addEOL() { - return this.addRaw(os_1.EOL); + _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; } - /** - * 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(); + _mergeHeaders(headers) { + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); + } + return lowercaseKeys(headers || {}); } /** - * 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 + * Gets an existing header value or returns a default. + * Handles converting number header values to strings since HTTP headers must be strings. + * Note: This returns string | string[] since some headers can have multiple values. + * For headers that must always be a single string (like Content-Type), use the + * specialized _getExistingOrDefaultContentTypeHeader method instead. */ - 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(); + _getExistingOrDefaultHeader(additionalHeaders, header, _default) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + const headerValue = lowercaseKeys(this.requestOptions.headers)[header]; + if (headerValue) { + clientHeader = + typeof headerValue === 'number' ? headerValue.toString() : headerValue; + } + } + const additionalValue = additionalHeaders[header]; + if (additionalValue !== undefined) { + return typeof additionalValue === 'number' + ? additionalValue.toString() + : additionalValue; + } + if (clientHeader !== undefined) { + return clientHeader; + } + return _default; } /** - * Adds an HTML table to the summary buffer - * - * @param {SummaryTableCell[]} rows table rows - * - * @returns {Summary} summary instance + * Specialized version of _getExistingOrDefaultHeader for Content-Type header. + * Always returns a single string (not an array) since Content-Type should be a single value. + * Converts arrays to comma-separated strings and numbers to strings to ensure type safety. + * This was split from _getExistingOrDefaultHeader to provide stricter typing for callers + * that assign the result to places expecting a string (e.g., additionalHeaders[Headers.ContentType]). */ - addTable(rows) { - const tableBody = rows - .map(row => { - const cells = row - .map(cell => { - if (typeof cell === 'string') { - return this.wrap('td', cell); + _getExistingOrDefaultContentTypeHeader(additionalHeaders, _default) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + const headerValue = lowercaseKeys(this.requestOptions.headers)[Headers.ContentType]; + if (headerValue) { + if (typeof headerValue === 'number') { + clientHeader = String(headerValue); } - 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(); + else if (Array.isArray(headerValue)) { + clientHeader = headerValue.join(', '); + } + else { + clientHeader = headerValue; + } + } + } + const additionalValue = additionalHeaders[Headers.ContentType]; + // Return the first non-undefined value, converting numbers or arrays to strings if necessary + if (additionalValue !== undefined) { + if (typeof additionalValue === 'number') { + return String(additionalValue); + } + else if (Array.isArray(additionalValue)) { + return additionalValue.join(', '); + } + else { + return additionalValue; + } + } + if (clientHeader !== undefined) { + return clientHeader; + } + return _default; } - /** - * 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(); + _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; } - /** - * 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(); + _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; } - /** - * 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(); + _getUserAgentWithOrchestrationId(userAgent) { + const baseUserAgent = userAgent || 'actions/http-client'; + const orchId = process.env['ACTIONS_ORCHESTRATION_ID']; + if (orchId) { + // Sanitize the orchestration ID to ensure it contains only valid characters + // Valid characters: 0-9, a-z, _, -, . + const sanitizedId = orchId.replace(/[^a-z0-9_.-]/gi, '_'); + return `${baseUserAgent} actions_orchestration_id/${sanitizedId}`; + } + return baseUserAgent; } - /** - * 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(); + _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)); + }); } - /** - * 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(); + _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); + } + })); + }); } } -const _summary = new Summary(); -/** - * @deprecated use `core.summary` - */ -exports.markdownSummary = _summary; -exports.summary = _summary; -//# sourceMappingURL=summary.js.map +exports.HttpClient = HttpClient; +const lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); +//# sourceMappingURL=index.js.map /***/ }), -/***/ 6001: +/***/ 568: /***/ ((__unused_webpack_module, exports) => { "use strict"; -// We use any as a valid input type -/* eslint-disable @typescript-eslint/no-explicit-any */ Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.toCommandValue = toCommandValue; -exports.toCommandProperties = toCommandProperties; -/** - * Sanitizes an input into a string so it can be passed into issueCommand safely - * @param input input to sanitize into a string - */ -function toCommandValue(input) { - if (input === null || input === undefined) { - return ''; +exports.getProxyUrl = getProxyUrl; +exports.checkBypass = checkBypass; +function getProxyUrl(reqUrl) { + const usingSsl = reqUrl.protocol === 'https:'; + if (checkBypass(reqUrl)) { + return undefined; } - else if (typeof input === 'string' || input instanceof String) { - return input; + 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; } - return JSON.stringify(input); } -/** - * - * @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 toCommandProperties(annotationProperties) { - if (!Object.keys(annotationProperties).length) { - return {}; +function checkBypass(reqUrl) { + if (!reqUrl.hostname) { + return false; } - return { - title: annotationProperties.title, - file: annotationProperties.file, - line: annotationProperties.startLine, - endLine: annotationProperties.endLine, - col: annotationProperties.startColumn, - endColumn: annotationProperties.endColumn - }; + 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; + } + } + return false; } -//# sourceMappingURL=utils.js.map +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); + } + get username() { + return this._decodedUsername; + } + get password() { + return this._decodedPassword; + } +} +//# sourceMappingURL=proxy.js.map /***/ }), -/***/ 4154: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 7013: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +module.exports = __nccwpck_require__(8479); + + +/***/ }), + +/***/ 8479: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || (function () { - 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); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - 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; - }; -})(); -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.exec = exec; -exports.getExecOutput = getExecOutput; -const string_decoder_1 = __nccwpck_require__(3193); -const tr = __importStar(__nccwpck_require__(2771)); -/** - * 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(); - }); + +var net = __nccwpck_require__(9278); +var tls = __nccwpck_require__(4756); +var http = __nccwpck_require__(8611); +var https = __nccwpck_require__(5692); +var events = __nccwpck_require__(4434); +var assert = __nccwpck_require__(2613); +var util = __nccwpck_require__(9023); + + +exports.httpOverHttp = httpOverHttp; +exports.httpsOverHttp = httpsOverHttp; +exports.httpOverHttps = httpOverHttps; +exports.httpsOverHttps = httpsOverHttps; + + +function httpOverHttp(options) { + var agent = new TunnelingAgent(options); + agent.request = http.request; + return agent; } -/** - * 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 - */ -function getExecOutput(commandLine, args, options) { - return __awaiter(this, void 0, void 0, function* () { - var _a, _b; - 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 - }; - }); + +function httpsOverHttp(options) { + var agent = new TunnelingAgent(options); + agent.request = http.request; + agent.createSocket = createSecureSocket; + agent.defaultPort = 443; + return agent; } -//# sourceMappingURL=exec.js.map -/***/ }), +function httpOverHttps(options) { + var agent = new TunnelingAgent(options); + agent.request = https.request; + return agent; +} -/***/ 2771: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +function httpsOverHttps(options) { + var agent = new TunnelingAgent(options); + agent.request = https.request; + agent.createSocket = createSecureSocket; + agent.defaultPort = 443; + return agent; +} -"use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || (function () { - 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); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - 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; - }; -})(); -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.ToolRunner = void 0; -exports.argStringToArray = argStringToArray; -const os = __importStar(__nccwpck_require__(857)); -const events = __importStar(__nccwpck_require__(4434)); -const child = __importStar(__nccwpck_require__(5317)); -const path = __importStar(__nccwpck_require__(6928)); -const io = __importStar(__nccwpck_require__(6893)); -const ioUtil = __importStar(__nccwpck_require__(9610)); -const timers_1 = __nccwpck_require__(3557); -/* 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 || {}; +function TunnelingAgent(options) { + var self = this; + self.options = options || {}; + self.proxyOptions = self.options.proxy || {}; + self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets; + self.requests = []; + self.sockets = []; + + self.on('free', function onFree(socket, host, port, localAddress) { + var options = toOptions(host, port, localAddress); + for (var i = 0, len = self.requests.length; i < len; ++i) { + var pending = self.requests[i]; + if (pending.host === options.host && pending.port === options.port) { + // Detect the request to connect same origin server, + // reuse the connection. + self.requests.splice(i, 1); + pending.request.onSocket(socket); + return; + } } - _debug(message) { - if (this.options.listeners && this.options.listeners.debug) { - this.options.listeners.debug(message); - } + socket.destroy(); + self.removeSocket(socket); + }); +} +util.inherits(TunnelingAgent, events.EventEmitter); + +TunnelingAgent.prototype.addRequest = function addRequest(req, host, port, localAddress) { + var self = this; + var options = mergeOptions({request: req}, self.options, toOptions(host, port, localAddress)); + + if (self.sockets.length >= this.maxSockets) { + // We are over limit so we'll add it to the queue. + self.requests.push(options); + return; + } + + // If we are under maxSockets create a new one. + self.createSocket(options, function(socket) { + socket.on('free', onFree); + socket.on('close', onCloseOrRemove); + socket.on('agentRemove', onCloseOrRemove); + req.onSocket(socket); + + function onFree() { + self.emit('free', socket, options); } - _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}`; - } - } - return cmd; + + function onCloseOrRemove(err) { + self.removeSocket(socket); + socket.removeListener('free', onFree); + socket.removeListener('close', onCloseOrRemove); + socket.removeListener('agentRemove', onCloseOrRemove); } - _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 ''; - } + }); +}; + +TunnelingAgent.prototype.createSocket = function createSocket(options, cb) { + var self = this; + var placeholder = {}; + self.sockets.push(placeholder); + + var connectOptions = mergeOptions({}, self.proxyOptions, { + method: 'CONNECT', + path: options.host + ':' + options.port, + agent: false, + headers: { + host: options.host + ':' + options.port } - _getSpawnFileName() { - if (IS_WINDOWS) { - if (this._isCmdFile()) { - return process.env['COMSPEC'] || 'cmd.exe'; - } - } - return this.toolPath; + }); + if (options.localAddress) { + connectOptions.localAddress = options.localAddress; + } + if (connectOptions.proxyAuth) { + connectOptions.headers = connectOptions.headers || {}; + connectOptions.headers['Proxy-Authorization'] = 'Basic ' + + new Buffer(connectOptions.proxyAuth).toString('base64'); + } + + debug('making CONNECT request'); + var connectReq = self.request(connectOptions); + connectReq.useChunkedEncodingByDefault = false; // for v0.6 + connectReq.once('response', onResponse); // for v0.6 + connectReq.once('upgrade', onUpgrade); // for v0.6 + connectReq.once('connect', onConnect); // for v0.7 or later + connectReq.once('error', onError); + connectReq.end(); + + function onResponse(res) { + // Very hacky. This is necessary to avoid http-parser leaks. + res.upgrade = true; + } + + function onUpgrade(res, socket, head) { + // Hacky. + process.nextTick(function() { + onConnect(res, socket, head); + }); + } + + function onConnect(res, socket, head) { + connectReq.removeAllListeners(); + socket.removeAllListeners(); + + if (res.statusCode !== 200) { + debug('tunneling socket could not be established, statusCode=%d', + res.statusCode); + socket.destroy(); + var error = new Error('tunneling socket could not be established, ' + + 'statusCode=' + res.statusCode); + error.code = 'ECONNRESET'; + options.request.emit('error', error); + self.removeSocket(placeholder); + return; } - _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]; - } - } - return this.args; + if (head.length > 0) { + debug('got illegal response body from proxy'); + socket.destroy(); + var error = new Error('got illegal response body from proxy'); + error.code = 'ECONNRESET'; + options.request.emit('error', error); + self.removeSocket(placeholder); + return; } - _endsWith(str, end) { - return str.endsWith(end); + debug('tunneling connection has established'); + self.sockets[self.sockets.indexOf(placeholder)] = socket; + return cb(socket); + } + + function onError(cause) { + connectReq.removeAllListeners(); + + debug('tunneling socket could not be established, cause=%s\n', + cause.message, cause.stack); + var error = new Error('tunneling socket could not be established, ' + + 'cause=' + cause.message); + error.code = 'ECONNRESET'; + options.request.emit('error', error); + self.removeSocket(placeholder); + } +}; + +TunnelingAgent.prototype.removeSocket = function removeSocket(socket) { + var pos = this.sockets.indexOf(socket) + if (pos === -1) { + return; + } + this.sockets.splice(pos, 1); + + var pending = this.requests.shift(); + if (pending) { + // If we have pending requests and a socket gets closed a new one + // needs to be created to take over in the pool for the one that closed. + this.createSocket(pending, function(socket) { + pending.request.onSocket(socket); + }); + } +}; + +function createSecureSocket(options, cb) { + var self = this; + TunnelingAgent.prototype.createSocket.call(self, options, function(socket) { + var hostHeader = options.request.getHeader('host'); + var tlsOptions = mergeOptions({}, self.options, { + socket: socket, + servername: hostHeader ? hostHeader.replace(/:.*$/, '') : options.host + }); + + // 0 is dummy port for v0.6 + var secureSocket = tls.connect(0, tlsOptions); + self.sockets[self.sockets.indexOf(socket)] = secureSocket; + cb(secureSocket); + }); +} + + +function toOptions(host, port, localAddress) { + if (typeof host === 'string') { // since v0.10 + return { + host: host, + port: port, + localAddress: localAddress + }; + } + return host; // for v0.11 or later +} + +function mergeOptions(target) { + for (var i = 1, len = arguments.length; i < len; ++i) { + var overrides = arguments[i]; + if (typeof overrides === 'object') { + var keys = Object.keys(overrides); + for (var j = 0, keyLen = keys.length; j < keyLen; ++j) { + var k = keys[j]; + if (overrides[k] !== undefined) { + target[k] = overrides[k]; + } + } } - _isCmdFile() { - const upperToolPath = this.toolPath.toUpperCase(); - return (this._endsWith(upperToolPath, '.CMD') || - this._endsWith(upperToolPath, '.BAT')); + } + return target; +} + + +var debug; +if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) { + debug = function() { + var args = Array.prototype.slice.call(arguments); + if (typeof args[0] === 'string') { + args[0] = 'TUNNEL: ' + args[0]; + } else { + args.unshift('TUNNEL:'); } - _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; - } - } - // 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(''); + console.error.apply(console, args); + } +} else { + debug = function() {}; +} +exports.debug = debug; // for test + + +/***/ }), + +/***/ 1889: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const Client = __nccwpck_require__(1696) +const Dispatcher = __nccwpck_require__(1178) +const Pool = __nccwpck_require__(3469) +const BalancedPool = __nccwpck_require__(9586) +const RoundRobinPool = __nccwpck_require__(5905) +const Agent = __nccwpck_require__(1470) +const Dispatcher1Wrapper = __nccwpck_require__(5241) +const ProxyAgent = __nccwpck_require__(6983) +const Socks5ProxyAgent = __nccwpck_require__(958) +const EnvHttpProxyAgent = __nccwpck_require__(6956) +const RetryAgent = __nccwpck_require__(525) +const H2CClient = __nccwpck_require__(5506) +const errors = __nccwpck_require__(4882) +const util = __nccwpck_require__(9277) +const { InvalidArgumentError } = errors +const api = __nccwpck_require__(3514) +const buildConnector = __nccwpck_require__(8203) +const MockClient = __nccwpck_require__(3950) +const { MockCallHistory, MockCallHistoryLog } = __nccwpck_require__(5980) +const MockAgent = __nccwpck_require__(9096) +const MockPool = __nccwpck_require__(7763) +const SnapshotAgent = __nccwpck_require__(5790) +const mockErrors = __nccwpck_require__(170) +const RetryHandler = __nccwpck_require__(9217) +const { getGlobalDispatcher, setGlobalDispatcher } = __nccwpck_require__(7078) +const DecoratorHandler = __nccwpck_require__(6834) +const RedirectHandler = __nccwpck_require__(8201) + +Object.assign(Dispatcher.prototype, api) + +module.exports.Dispatcher = Dispatcher +module.exports.Client = Client +module.exports.Pool = Pool +module.exports.BalancedPool = BalancedPool +module.exports.RoundRobinPool = RoundRobinPool +module.exports.Agent = Agent +module.exports.Dispatcher1Wrapper = Dispatcher1Wrapper +module.exports.ProxyAgent = ProxyAgent +module.exports.Socks5ProxyAgent = Socks5ProxyAgent +module.exports.EnvHttpProxyAgent = EnvHttpProxyAgent +module.exports.RetryAgent = RetryAgent +module.exports.H2CClient = H2CClient +module.exports.RetryHandler = RetryHandler + +module.exports.DecoratorHandler = DecoratorHandler +module.exports.RedirectHandler = RedirectHandler +module.exports.interceptors = { + redirect: __nccwpck_require__(3853), + responseError: __nccwpck_require__(4325), + retry: __nccwpck_require__(4987), + dump: __nccwpck_require__(8355), + dns: __nccwpck_require__(9410), + cache: __nccwpck_require__(2395), + decompress: __nccwpck_require__(6170), + deduplicate: __nccwpck_require__(4221) +} + +module.exports.cacheStores = { + MemoryCacheStore: __nccwpck_require__(750) +} + +const SqliteCacheStore = __nccwpck_require__(6169) +module.exports.cacheStores.SqliteCacheStore = SqliteCacheStore + +module.exports.buildConnector = buildConnector +module.exports.errors = errors +module.exports.util = { + parseHeaders: util.parseHeaders, + headerNameToString: util.headerNameToString +} + +function makeDispatcher (fn) { + return (url, opts, handler) => { + if (typeof opts === 'function') { + handler = opts + opts = null } - _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}"`; - } - // 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(''); + + if (!url || (typeof url !== 'string' && typeof url !== 'object' && !(url instanceof URL))) { + throw new InvalidArgumentError('invalid url') } - _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; + + if (opts != null && typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') } - _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; + + if (opts && opts.path != null) { + if (typeof opts.path !== 'string') { + throw new InvalidArgumentError('invalid opts.path') + } + + let path = opts.path + if (!opts.path.startsWith('/')) { + path = `/${path}` + } + + url = new URL(util.parseOrigin(url).origin + path) + } else { + if (!opts) { + opts = typeof url === 'object' ? url : {} + } + + url = util.parseURL(url) } - /** - * 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 - */ - 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; - } - 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 (arg.length > 0) { - args.push(arg.trim()); - } - return args; -} -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; - } - } - CheckComplete() { - if (this.done) { - return; - } - if (this.processClosed) { - this._setResult(); - } - else if (this.processExited) { - this.timeout = (0, timers_1.setTimeout)(ExecState.HandleTimeout, this.delay, this); - } - } - _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}`); - } - 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); - } - 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(); + + const { agent, dispatcher = getGlobalDispatcher(), ...restOpts } = opts + + if (agent) { + throw new InvalidArgumentError('unsupported opts.agent. Did you mean opts.client?') } + + return fn.call(dispatcher, { + ...restOpts, + origin: url.origin, + path: url.search ? `${url.pathname}${url.search}` : url.pathname, + method: opts.method || (opts.body ? 'PUT' : 'GET') + }, handler) + } } -//# sourceMappingURL=toolrunner.js.map -/***/ }), +module.exports.setGlobalDispatcher = setGlobalDispatcher +module.exports.getGlobalDispatcher = getGlobalDispatcher -/***/ 8663: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +const fetchImpl = (__nccwpck_require__(7683).fetch) -"use strict"; +// Capture __filename at module load time for stack trace augmentation. +// This may be undefined when bundled in environments like Node.js internals. +const currentFilename = typeof __filename !== 'undefined' ? __filename : undefined -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Context = void 0; -const fs_1 = __nccwpck_require__(9896); -const os_1 = __nccwpck_require__(857); -class Context { - /** - * Hydrate the context from the environment - */ - constructor() { - var _a, _b, _c; - this.payload = {}; - if (process.env.GITHUB_EVENT_PATH) { - if ((0, fs_1.existsSync)(process.env.GITHUB_EVENT_PATH)) { - this.payload = JSON.parse((0, fs_1.readFileSync)(process.env.GITHUB_EVENT_PATH, { encoding: 'utf8' })); - } - else { - const path = process.env.GITHUB_EVENT_PATH; - process.stdout.write(`GITHUB_EVENT_PATH ${path} does not exist${os_1.EOL}`); - } - } - this.eventName = process.env.GITHUB_EVENT_NAME; - this.sha = process.env.GITHUB_SHA; - this.ref = process.env.GITHUB_REF; - this.workflow = process.env.GITHUB_WORKFLOW; - this.action = process.env.GITHUB_ACTION; - this.actor = process.env.GITHUB_ACTOR; - this.job = process.env.GITHUB_JOB; - this.runAttempt = parseInt(process.env.GITHUB_RUN_ATTEMPT, 10); - this.runNumber = parseInt(process.env.GITHUB_RUN_NUMBER, 10); - this.runId = parseInt(process.env.GITHUB_RUN_ID, 10); - this.apiUrl = (_a = process.env.GITHUB_API_URL) !== null && _a !== void 0 ? _a : `https://api.github.com`; - this.serverUrl = (_b = process.env.GITHUB_SERVER_URL) !== null && _b !== void 0 ? _b : `https://github.com`; - this.graphqlUrl = - (_c = process.env.GITHUB_GRAPHQL_URL) !== null && _c !== void 0 ? _c : `https://api.github.com/graphql`; - } - get issue() { - const payload = this.payload; - return Object.assign(Object.assign({}, this.repo), { number: (payload.issue || payload.pull_request || payload).number }); - } - get repo() { - if (process.env.GITHUB_REPOSITORY) { - const [owner, repo] = process.env.GITHUB_REPOSITORY.split('/'); - return { owner, repo }; - } - if (this.payload.repository) { - return { - owner: this.payload.repository.owner.login, - repo: this.payload.repository.name - }; - } - throw new Error("context.repo requires a GITHUB_REPOSITORY environment variable like 'owner/repo'"); +function appendFetchStackTrace (err, filename) { + if (!err || typeof err !== 'object') { + return + } + + const stack = typeof err.stack === 'string' ? err.stack : '' + const normalizedFilename = filename.replace(/\\/g, '/') + + if (stack && (stack.includes(filename) || stack.includes(normalizedFilename))) { + return + } + + const capture = {} + Error.captureStackTrace(capture, appendFetchStackTrace) + + if (!capture.stack) { + return + } + + const captureLines = capture.stack.split('\n').slice(1).join('\n') + + err.stack = stack ? `${stack}\n${captureLines}` : capture.stack +} + +module.exports.fetch = function fetch (init, options = undefined) { + return fetchImpl(init, options).catch(err => { + if (currentFilename) { + appendFetchStackTrace(err, currentFilename) + } else if (err && typeof err === 'object') { + Error.captureStackTrace(err, module.exports.fetch) } + throw err + }) } -exports.Context = Context; -//# sourceMappingURL=context.js.map +module.exports.Headers = __nccwpck_require__(2133).Headers +module.exports.Response = __nccwpck_require__(7148).Response +module.exports.Request = __nccwpck_require__(7442).Request +module.exports.FormData = __nccwpck_require__(5801).FormData -/***/ }), +const { setGlobalOrigin, getGlobalOrigin } = __nccwpck_require__(1684) -/***/ 6137: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +module.exports.setGlobalOrigin = setGlobalOrigin +module.exports.getGlobalOrigin = getGlobalOrigin -"use strict"; +const { CacheStorage } = __nccwpck_require__(9722) +const { kConstruct } = __nccwpck_require__(228) -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 () { - 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); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - 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; - }; -})(); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.context = void 0; -exports.getOctokit = getOctokit; -const Context = __importStar(__nccwpck_require__(8663)); -const utils_1 = __nccwpck_require__(6653); -exports.context = new Context.Context(); -/** - * Returns a hydrated octokit ready to use for GitHub Actions - * - * @param token the repo PAT or GITHUB_TOKEN - * @param options other options to set - */ -function getOctokit(token, options, ...additionalPlugins) { - const GitHubWithPlugins = utils_1.GitHub.plugin(...additionalPlugins); - return new GitHubWithPlugins((0, utils_1.getOctokitOptions)(token, options)); +module.exports.caches = new CacheStorage(kConstruct) + +const { deleteCookie, getCookies, getSetCookies, setCookie, parseCookie } = __nccwpck_require__(4360) + +module.exports.deleteCookie = deleteCookie +module.exports.getCookies = getCookies +module.exports.getSetCookies = getSetCookies +module.exports.setCookie = setCookie +module.exports.parseCookie = parseCookie + +const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(9199) + +module.exports.parseMIMEType = parseMIMEType +module.exports.serializeAMimeType = serializeAMimeType + +const { CloseEvent, ErrorEvent, MessageEvent } = __nccwpck_require__(8935) +const { WebSocket, ping } = __nccwpck_require__(9723) +module.exports.WebSocket = WebSocket +module.exports.CloseEvent = CloseEvent +module.exports.ErrorEvent = ErrorEvent +module.exports.MessageEvent = MessageEvent +module.exports.ping = ping + +module.exports.WebSocketStream = __nccwpck_require__(3134).WebSocketStream +module.exports.WebSocketError = __nccwpck_require__(1506).WebSocketError + +module.exports.request = makeDispatcher(api.request) +module.exports.stream = makeDispatcher(api.stream) +module.exports.pipeline = makeDispatcher(api.pipeline) +module.exports.connect = makeDispatcher(api.connect) +module.exports.upgrade = makeDispatcher(api.upgrade) + +module.exports.MockClient = MockClient +module.exports.MockCallHistory = MockCallHistory +module.exports.MockCallHistoryLog = MockCallHistoryLog +module.exports.MockPool = MockPool +module.exports.MockAgent = MockAgent +module.exports.SnapshotAgent = SnapshotAgent +module.exports.mockErrors = mockErrors + +const { EventSource } = __nccwpck_require__(3715) + +module.exports.EventSource = EventSource + +function install () { + globalThis.fetch = module.exports.fetch + globalThis.Headers = module.exports.Headers + globalThis.Response = module.exports.Response + globalThis.Request = module.exports.Request + globalThis.FormData = module.exports.FormData + globalThis.WebSocket = module.exports.WebSocket + globalThis.CloseEvent = module.exports.CloseEvent + globalThis.ErrorEvent = module.exports.ErrorEvent + globalThis.MessageEvent = module.exports.MessageEvent + globalThis.EventSource = module.exports.EventSource } -//# sourceMappingURL=github.js.map + +module.exports.install = install + /***/ }), -/***/ 1365: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 5697: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || (function () { - 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); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - 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; - }; -})(); -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.getAuthString = getAuthString; -exports.getProxyAgent = getProxyAgent; -exports.getProxyAgentDispatcher = getProxyAgentDispatcher; -exports.getProxyFetch = getProxyFetch; -exports.getApiBaseUrl = getApiBaseUrl; -const httpClient = __importStar(__nccwpck_require__(7708)); -const undici_1 = __nccwpck_require__(2293); -function getAuthString(token, options) { - if (!token && !options.auth) { - throw new Error('Parameter token or opts.auth is required'); - } - else if (token && options.auth) { - throw new Error('Parameters token and opts.auth may not both be specified'); - } - return typeof options.auth === 'string' ? options.auth : `token ${token}`; -} -function getProxyAgent(destinationUrl) { - const hc = new httpClient.HttpClient(); - return hc.getAgent(destinationUrl); + +const { addAbortListener } = __nccwpck_require__(9277) +const { RequestAbortedError } = __nccwpck_require__(4882) + +const kListener = Symbol('kListener') +const kSignal = Symbol('kSignal') + +function abort (self) { + if (self.abort) { + self.abort(self[kSignal]?.reason) + } else { + self.reason = self[kSignal]?.reason ?? new RequestAbortedError() + } + removeSignal(self) } -function getProxyAgentDispatcher(destinationUrl) { - const hc = new httpClient.HttpClient(); - return hc.getAgentDispatcher(destinationUrl); + +function addSignal (self, signal) { + self.reason = null + + self[kSignal] = null + self[kListener] = null + + if (!signal) { + return + } + + if (signal.aborted) { + abort(self) + return + } + + self[kSignal] = signal + self[kListener] = () => { + abort(self) + } + + addAbortListener(self[kSignal], self[kListener]) } -function getProxyFetch(destinationUrl) { - const httpDispatcher = getProxyAgentDispatcher(destinationUrl); - const proxyFetch = (url, opts) => __awaiter(this, void 0, void 0, function* () { - return (0, undici_1.fetch)(url, Object.assign(Object.assign({}, opts), { dispatcher: httpDispatcher })); - }); - return proxyFetch; + +function removeSignal (self) { + if (!self[kSignal]) { + return + } + + if ('removeEventListener' in self[kSignal]) { + self[kSignal].removeEventListener('abort', self[kListener]) + } else { + self[kSignal].removeListener('abort', self[kListener]) + } + + self[kSignal] = null + self[kListener] = null } -function getApiBaseUrl() { - return process.env['GITHUB_API_URL'] || 'https://api.github.com'; + +module.exports = { + addSignal, + removeSignal } -//# sourceMappingURL=utils.js.map + /***/ }), -/***/ 6653: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 6685: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; + +const assert = __nccwpck_require__(4589) +const { AsyncResource } = __nccwpck_require__(6698) +const { InvalidArgumentError, SocketError } = __nccwpck_require__(4882) +const util = __nccwpck_require__(9277) +const { addSignal, removeSignal } = __nccwpck_require__(5697) + +class ConnectHandler extends AsyncResource { + constructor (opts, callback) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') } - 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 () { - 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); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - 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; - }; -})(); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.GitHub = exports.defaults = exports.context = void 0; -exports.getOctokitOptions = getOctokitOptions; -const Context = __importStar(__nccwpck_require__(8663)); -const Utils = __importStar(__nccwpck_require__(1365)); -// octokit + plugins -const core_1 = __nccwpck_require__(6895); -const plugin_rest_endpoint_methods_1 = __nccwpck_require__(9289); -const plugin_paginate_rest_1 = __nccwpck_require__(6212); -exports.context = new Context.Context(); -const baseUrl = Utils.getApiBaseUrl(); -exports.defaults = { - baseUrl, - request: { - agent: Utils.getProxyAgent(baseUrl), - fetch: Utils.getProxyFetch(baseUrl) + + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') } -}; -exports.GitHub = core_1.Octokit.plugin(plugin_rest_endpoint_methods_1.restEndpointMethods, plugin_paginate_rest_1.paginateRest).defaults(exports.defaults); -/** - * Convience function to correctly format Octokit Options to pass into the constructor. - * - * @param token the repo PAT or GITHUB_TOKEN - * @param options other options to set - */ -function getOctokitOptions(token, options) { - const opts = Object.assign({}, options || {}); // Shallow clone - don't mutate the object provided by the caller - // Auth - const auth = Utils.getAuthString(token, opts); - if (auth) { - opts.auth = auth; + + const { signal, opaque, responseHeaders } = opts + + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') } - return opts; -} -//# sourceMappingURL=utils.js.map -/***/ }), + super('UNDICI_CONNECT') -/***/ 1960: -/***/ (function(__unused_webpack_module, exports) { + this.opaque = opaque || null + this.responseHeaders = responseHeaders || null + this.callback = callback + this.abort = null -"use strict"; + addSignal(this, signal) + } -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}`; + onRequestStart (controller, context) { + if (this.reason) { + controller.abort(this.reason) + return } - // This handler cannot handle 401 - canHandleAuthentication() { - return false; + + assert(this.callback) + + this.abort = (reason) => controller.abort(reason) + this.context = context + } + + onResponseStart () { + throw new SocketError('bad connect', null) + } + + onRequestUpgrade (controller, statusCode, headers, socket) { + const { callback, opaque, context } = this + + removeSignal(this) + + this.callback = null + + let responseHeaders = headers + const rawHeaders = controller?.rawHeaders + // Indicates is an HTTP2Session + if (responseHeaders != null) { + responseHeaders = this.responseHeaders === 'raw' + ? util.parseRawHeaders(rawHeaders) + : headers } - handleAuthentication() { - return __awaiter(this, void 0, void 0, function* () { - throw new Error('not implemented'); - }); + + this.runInAsyncScope(callback, null, null, { + statusCode, + headers: responseHeaders, + socket, + opaque, + context + }) + } + + onResponseError (_controller, err) { + const { callback, opaque } = this + + removeSignal(this) + + if (callback) { + this.callback = null + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }) + }) } + } } -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'); - }); + +function connect (opts, callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + connect.call(this, opts, (err, data) => { + return err ? reject(err) : resolve(data) + }) + }) + } + + try { + const connectHandler = new ConnectHandler(opts, callback) + const connectOptions = { ...opts, method: 'CONNECT' } + this.dispatch(connectOptions, connectHandler) + } catch (err) { + if (typeof callback !== 'function') { + throw err } + const opaque = opts?.opaque + queueMicrotask(() => callback(err, { opaque })) + } } -exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler; -//# sourceMappingURL=auth.js.map + +module.exports = connect + /***/ }), -/***/ 7708: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 4421: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -/* 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 () { - 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); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - 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; - }; -})(); -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.HttpClientResponse = exports.HttpClientError = exports.MediaTypes = exports.Headers = exports.HttpCodes = void 0; -exports.getProxyUrl = getProxyUrl; -exports.isHttps = isHttps; -const http = __importStar(__nccwpck_require__(8611)); -const https = __importStar(__nccwpck_require__(5692)); -const pm = __importStar(__nccwpck_require__(8188)); -const tunnel = __importStar(__nccwpck_require__(329)); -const undici_1 = __nccwpck_require__(2293); -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 : ''; -} -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); + +const { + Readable, + Duplex, + PassThrough +} = __nccwpck_require__(7075) +const assert = __nccwpck_require__(4589) +const { AsyncResource } = __nccwpck_require__(6698) +const { + InvalidArgumentError, + InvalidReturnValueError, + RequestAbortedError +} = __nccwpck_require__(4882) +const util = __nccwpck_require__(9277) +const { kBodyUsed } = __nccwpck_require__(228) +const { addSignal, removeSignal } = __nccwpck_require__(5697) + +function noop () {} + +const kResume = Symbol('resume') + +class PipelineRequest extends Readable { + constructor () { + super({ autoDestroy: true }) + + this[kResume] = null + // Pipeline request bodies come from a live writable side and cannot be + // replayed across redirects or retries, even before any bytes are read. + this[kBodyUsed] = true + } + + _read () { + const { [kResume]: resume } = this + + if (resume) { + this[kResume] = null + resume() } + } + + _destroy (err, callback) { + this._read() + + callback(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)); - }); - })); - }); + +class PipelineResponse extends Readable { + constructor (resume) { + super({ autoDestroy: true }) + this[kResume] = resume + } + + _read () { + this[kResume]() + } + + _destroy (err, callback) { + if (!err && !this._readableState.endEmitted) { + err = new RequestAbortedError() } + + callback(err) + } } -exports.HttpClientResponse = HttpClientResponse; -function isHttps(requestUrl) { - const parsedUrl = new URL(requestUrl); - return parsedUrl.protocol === 'https:'; -} -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 = this._getUserAgentWithOrchestrationId(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; - } - if (requestOptions.maxRedirects != null) { - this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); - } - if (requestOptions.keepAlive != null) { - this._keepAlive = requestOptions.keepAlive; - } - if (requestOptions.allowRetries != null) { - this._allowRetries = requestOptions.allowRetries; - } - if (requestOptions.maxRetries != null) { - this._maxRetries = requestOptions.maxRetries; - } - } + +class PipelineHandler extends AsyncResource { + constructor (opts, handler) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') } - options(requestUrl, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('OPTIONS', requestUrl, null, additionalHeaders || {}); - }); + + if (typeof handler !== 'function') { + throw new InvalidArgumentError('invalid handler') } - get(requestUrl, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('GET', requestUrl, null, additionalHeaders || {}); - }); + + const { signal, method, opaque, onInfo, responseHeaders } = opts + + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') } - del(requestUrl, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('DELETE', requestUrl, null, additionalHeaders || {}); - }); + + if (method === 'CONNECT') { + throw new InvalidArgumentError('invalid method') } - post(requestUrl, data, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('POST', requestUrl, data, additionalHeaders || {}); - }); + + if (onInfo && typeof onInfo !== 'function') { + throw new InvalidArgumentError('invalid onInfo callback') } - patch(requestUrl, data, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('PATCH', requestUrl, data, additionalHeaders || {}); - }); + + super('UNDICI_PIPELINE') + + this.opaque = opaque || null + this.responseHeaders = responseHeaders || null + this.handler = handler + this.abort = null + this.context = null + this.onInfo = onInfo || null + + this.req = new PipelineRequest().on('error', noop) + + this.ret = new Duplex({ + readableObjectMode: opts.objectMode, + autoDestroy: true, + read: () => { + const { body } = this + + if (body?.resume) { + body.resume() + } + }, + write: (chunk, encoding, callback) => { + const { req } = this + + if (req.push(chunk, encoding) || req._readableState.destroyed) { + callback() + } else { + req[kResume] = callback + } + }, + destroy: (err, callback) => { + const { body, req, res, ret, abort } = this + + if (!err && !ret._readableState.endEmitted) { + err = new RequestAbortedError() + } + + if (abort && err) { + abort() + } + + util.destroy(body, err) + util.destroy(req, err) + util.destroy(res, err) + + removeSignal(this) + + callback(err) + } + }).on('prefinish', () => { + const { req } = this + + // Node < 15 does not call _final in same tick. + req.push(null) + }) + + this.res = null + + addSignal(this, signal) + } + + onRequestStart (controller, context) { + const { res } = this + + if (this.reason) { + controller.abort(this.reason) + return } - put(requestUrl, data, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('PUT', requestUrl, data, additionalHeaders || {}); - }); + + assert(!res, 'pipeline cannot be retried') + + this.abort = (reason) => controller.abort(reason) + this.context = context + } + + onResponseStart (controller, statusCode, headers, _statusMessage) { + const { opaque, handler, context } = this + + if (statusCode < 200) { + if (this.onInfo) { + const rawHeaders = controller?.rawHeaders + const responseHeaders = this.responseHeaders === 'raw' + ? util.parseRawHeaders(rawHeaders) + : headers + this.onInfo({ statusCode, headers: responseHeaders }) + } + return } - head(requestUrl, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('HEAD', requestUrl, null, additionalHeaders || {}); - }); + + this.res = new PipelineResponse(() => controller.resume()) + + let body + try { + this.handler = null + const rawHeaders = controller?.rawHeaders + const responseHeaders = this.responseHeaders === 'raw' + ? util.parseRawHeaders(rawHeaders) + : headers + body = this.runInAsyncScope(handler, null, { + statusCode, + headers: responseHeaders, + opaque, + body: this.res, + context + }) + } catch (err) { + this.res.on('error', noop) + throw err } - sendStream(verb, requestUrl, stream, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request(verb, requestUrl, stream, additionalHeaders); - }); + + if (!body || typeof body.on !== 'function') { + throw new InvalidReturnValueError('expected Readable') } - /** - * Gets a typed object from an endpoint - * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise - */ - getJson(requestUrl_1) { - return __awaiter(this, arguments, void 0, function* (requestUrl, additionalHeaders = {}) { - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - const res = yield this.get(requestUrl, additionalHeaders); - return this._processResponse(res, this.requestOptions); - }); + + body + .on('data', (chunk) => { + const { ret, body } = this + + if (!ret.push(chunk) && body.pause) { + body.pause() + } + }) + .on('error', (err) => { + const { ret } = this + + util.destroy(ret, err) + }) + .on('end', () => { + const { ret } = this + + ret.push(null) + }) + .on('close', () => { + const { ret } = this + + if (!ret._readableState.ended) { + util.destroy(ret, new RequestAbortedError()) + } + }) + + this.body = body + } + + onResponseData (controller, chunk) { + const { res } = this + + if (res.push(chunk) === false) { + controller.pause() } - postJson(requestUrl_1, obj_1) { - return __awaiter(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { - const data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = - this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson); - const res = yield this.post(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - }); + } + + onResponseEnd (_controller, _trailers) { + const { res } = this + res.push(null) + } + + onResponseError (_controller, err) { + const { ret } = this + this.handler = null + util.destroy(ret, err) + } +} + +function pipeline (opts, handler) { + try { + const pipelineHandler = new PipelineHandler(opts, handler) + this.dispatch({ ...opts, body: pipelineHandler.req }, pipelineHandler) + return pipelineHandler.ret + } catch (err) { + return new PassThrough().destroy(err) + } +} + +module.exports = pipeline + + +/***/ }), + +/***/ 2550: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const assert = __nccwpck_require__(4589) +const { AsyncResource } = __nccwpck_require__(6698) +const { Readable } = __nccwpck_require__(5472) +const { InvalidArgumentError, RequestAbortedError } = __nccwpck_require__(4882) +const util = __nccwpck_require__(9277) + +function noop () {} + +class RequestHandler extends AsyncResource { + constructor (opts, callback) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') } - putJson(requestUrl_1, obj_1) { - return __awaiter(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { - const data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = - this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson); - const res = yield this.put(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - }); + + const { signal, method, opaque, body, onInfo, responseHeaders, highWaterMark } = opts + + try { + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } + + if (highWaterMark != null && (!Number.isFinite(highWaterMark) || highWaterMark < 0)) { + throw new InvalidArgumentError('invalid highWaterMark') + } + + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } + + if (method === 'CONNECT') { + throw new InvalidArgumentError('invalid method') + } + + if (onInfo && typeof onInfo !== 'function') { + throw new InvalidArgumentError('invalid onInfo callback') + } + + super('UNDICI_REQUEST') + } catch (err) { + if (util.isStream(body)) { + util.destroy(body.on('error', noop), err) + } + throw err } - patchJson(requestUrl_1, obj_1) { - return __awaiter(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { - const data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = - this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson); - const res = yield this.patch(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - }); + + this.method = method + this.responseHeaders = responseHeaders || null + this.opaque = opaque || null + this.callback = callback + this.res = null + this.abort = null + this.body = body + this.trailers = {} + this.context = null + this.controller = null + this.onInfo = onInfo || null + this.highWaterMark = highWaterMark + this.reason = null + this.removeAbortListener = null + + if (signal?.aborted) { + this.reason = signal.reason ?? new RequestAbortedError() + } else if (signal) { + this.removeAbortListener = util.addAbortListener(signal, () => { + this.reason = signal.reason ?? new RequestAbortedError() + if (this.res) { + // Null the reference before destroying, mirroring onResponseError, so + // that chunks flushed after the abort (e.g. an async decompressor + // flush) are dropped by the `!this.res` guard in onResponseData + // instead of being pushed into the torn-down stream. + const res = this.res + this.res = null + util.destroy(res.on('error', noop), this.reason) + } else if (this.abort) { + this.abort(this.reason) + } + }) } - /** - * 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; - }); + } + + onRequestStart (controller, context) { + if (this.reason) { + controller.abort(this.reason) + return } - /** - * Needs to be called if keepAlive is set to true in request options. - */ - dispose() { - if (this._agent) { - this._agent.destroy(); - } - this._disposed = true; + + assert(this.callback) + + this.controller = controller + this.abort = (reason) => controller.abort(reason) + this.context = context + } + + onResponseStart (controller, statusCode, headers, statusText) { + const { callback, opaque, context, responseHeaders, highWaterMark } = this + + const rawHeaders = controller?.rawHeaders + const responseHeaderData = responseHeaders === 'raw' + ? util.parseRawHeaders(rawHeaders) + : headers + + if (statusCode < 200) { + if (this.onInfo) { + this.onInfo({ statusCode, headers: responseHeaderData }) + } + return } - /** - * 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); - }); - }); + + const parsedHeaders = headers + const contentType = parsedHeaders?.['content-type'] + const contentLength = parsedHeaders?.['content-length'] + const res = new Readable({ + resume: () => controller.resume(), + abort: (reason) => controller.abort(reason), + contentType, + contentLength: this.method !== 'HEAD' && contentLength + ? Number(contentLength) + : null, + highWaterMark + }) + + if (this.removeAbortListener) { + res.on('close', this.removeAbortListener) + this.removeAbortListener = null } - /** - * Raw request with callback. - * @param info - * @param data - * @param onResult - */ - 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); - } - } - 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(); - } - 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(); - } + + this.callback = null + this.res = res + if (callback !== null) { + try { + this.runInAsyncScope(callback, null, null, { + statusCode, + statusText, + headers: responseHeaderData, + trailers: this.trailers, + opaque, + body: res, + context + }) + } catch (err) { + // If the callback throws synchronously, we need to handle it + // Remove reference to res to allow res being garbage collected + this.res = null + + // Destroy the response stream + util.destroy(res.on('error', noop), err) + + // Use queueMicrotask to re-throw the error so it reaches uncaughtException + queueMicrotask(() => { + throw err + }) + } } - /** - * 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 - */ - getAgent(serverUrl) { - const parsedUrl = new URL(serverUrl); - return this._getAgent(parsedUrl); + } + + onResponseData (controller, chunk) { + if (!this.res) { + return } - 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); + + if (this.res.push(chunk) === false) { + controller.pause() } - _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); - } + } + + onResponseEnd (_controller, trailers) { + if (trailers && typeof trailers === 'object') { + for (const key of Object.keys(trailers)) { + if (key === '__proto__') { + Object.defineProperty(this.trailers, key, { + value: trailers[key], + enumerable: true, + configurable: true, + writable: true + }) + } else { + this.trailers[key] = trailers[key] } - return info; + } } - _mergeHeaders(headers) { - if (this.requestOptions && this.requestOptions.headers) { - return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); - } - return lowercaseKeys(headers || {}); - } - /** - * Gets an existing header value or returns a default. - * Handles converting number header values to strings since HTTP headers must be strings. - * Note: This returns string | string[] since some headers can have multiple values. - * For headers that must always be a single string (like Content-Type), use the - * specialized _getExistingOrDefaultContentTypeHeader method instead. - */ - _getExistingOrDefaultHeader(additionalHeaders, header, _default) { - let clientHeader; - if (this.requestOptions && this.requestOptions.headers) { - const headerValue = lowercaseKeys(this.requestOptions.headers)[header]; - if (headerValue) { - clientHeader = - typeof headerValue === 'number' ? headerValue.toString() : headerValue; - } - } - const additionalValue = additionalHeaders[header]; - if (additionalValue !== undefined) { - return typeof additionalValue === 'number' - ? additionalValue.toString() - : additionalValue; - } - if (clientHeader !== undefined) { - return clientHeader; - } - return _default; - } - /** - * Specialized version of _getExistingOrDefaultHeader for Content-Type header. - * Always returns a single string (not an array) since Content-Type should be a single value. - * Converts arrays to comma-separated strings and numbers to strings to ensure type safety. - * This was split from _getExistingOrDefaultHeader to provide stricter typing for callers - * that assign the result to places expecting a string (e.g., additionalHeaders[Headers.ContentType]). - */ - _getExistingOrDefaultContentTypeHeader(additionalHeaders, _default) { - let clientHeader; - if (this.requestOptions && this.requestOptions.headers) { - const headerValue = lowercaseKeys(this.requestOptions.headers)[Headers.ContentType]; - if (headerValue) { - if (typeof headerValue === 'number') { - clientHeader = String(headerValue); - } - else if (Array.isArray(headerValue)) { - clientHeader = headerValue.join(', '); - } - else { - clientHeader = headerValue; - } - } - } - const additionalValue = additionalHeaders[Headers.ContentType]; - // Return the first non-undefined value, converting numbers or arrays to strings if necessary - if (additionalValue !== undefined) { - if (typeof additionalValue === 'number') { - return String(additionalValue); - } - else if (Array.isArray(additionalValue)) { - return additionalValue.join(', '); - } - else { - return additionalValue; - } - } - if (clientHeader !== undefined) { - return clientHeader; - } - return _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; + this.res?.push(null) + } + + onResponseError (_controller, err) { + const { res, callback, body, opaque } = this + + if (callback) { + // TODO: Does this need queueMicrotask? + this.callback = null + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }) + }) } - _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; + + if (res) { + this.res = null + // Ensure all queued handlers are invoked before destroying res. + queueMicrotask(() => { + util.destroy(res.on('error', noop), err) + }) } - _getUserAgentWithOrchestrationId(userAgent) { - const baseUserAgent = userAgent || 'actions/http-client'; - const orchId = process.env['ACTIONS_ORCHESTRATION_ID']; - if (orchId) { - // Sanitize the orchestration ID to ensure it contains only valid characters - // Valid characters: 0-9, a-z, _, -, . - const sanitizedId = orchId.replace(/[^a-z0-9_.-]/gi, '_'); - return `${baseUserAgent} actions_orchestration_id/${sanitizedId}`; - } - return baseUserAgent; + + if (body) { + this.body = null + + if (util.isStream(body)) { + body.on('error', noop) + util.destroy(body, err) + } } - _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)); - }); + + if (this.removeAbortListener) { + this.removeAbortListener() + this.removeAbortListener = null } - _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); - } - })); - }); + } +} + +function request (opts, callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + request.call(this, opts, (err, data) => { + return err ? reject(err) : resolve(data) + }) + }) + } + + try { + const handler = new RequestHandler(opts, callback) + + this.dispatch(opts, handler) + } catch (err) { + if (typeof callback !== 'function') { + throw err } + const opaque = opts?.opaque + queueMicrotask(() => callback(err, { opaque })) + } } -exports.HttpClient = HttpClient; -const lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); -//# sourceMappingURL=index.js.map + +module.exports = request +module.exports.RequestHandler = RequestHandler + /***/ }), -/***/ 8188: -/***/ ((__unused_webpack_module, exports) => { +/***/ 2475: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getProxyUrl = getProxyUrl; -exports.checkBypass = checkBypass; -function getProxyUrl(reqUrl) { - const usingSsl = reqUrl.protocol === 'https:'; - if (checkBypass(reqUrl)) { - return undefined; - } - 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; - } -} -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; - } - } - return false; + +const assert = __nccwpck_require__(4589) +const { AsyncResource } = __nccwpck_require__(6698) +const { InvalidArgumentError, InvalidReturnValueError } = __nccwpck_require__(4882) +const util = __nccwpck_require__(9277) +const { addSignal, removeSignal } = __nccwpck_require__(5697) + +function noop () {} + +function getWritableError (stream) { + return stream.errored ?? stream.writableErrored ?? stream._writableState?.errored } -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]')); + +function createPrematureCloseError () { + const err = new Error('Premature close') + err.code = 'ERR_STREAM_PREMATURE_CLOSE' + return err } -class DecodedURL extends URL { - constructor(url, base) { - super(url, base); - this._decodedUsername = decodeURIComponent(super.username); - this._decodedPassword = decodeURIComponent(super.password); + +function trackWritableLifecycle (stream, callback) { + let done = false + + const cleanup = () => { + stream.removeListener('close', onClose) + stream.removeListener('error', onError) + stream.removeListener('finish', onFinish) + } + + const finish = (err, fromErrorEvent = false) => { + if (done) { + return } - get username() { - return this._decodedUsername; + + done = true + cleanup() + callback(err, fromErrorEvent) + } + + const onClose = () => { + const err = getWritableError(stream) + finish(err ?? (!stream.writableFinished ? createPrematureCloseError() : undefined)) + } + + const onError = (err) => finish(err, true) + const onFinish = () => finish() + + stream.on('close', onClose) + stream.on('error', onError) + stream.on('finish', onFinish) + + if (stream.closed) { + process.nextTick(onClose) + } else if (stream.writableFinished) { + process.nextTick(onFinish) + } +} + +class StreamHandler extends AsyncResource { + constructor (opts, factory, callback) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') } - get password() { - return this._decodedPassword; + + const { signal, method, opaque, body, onInfo, responseHeaders } = opts + + try { + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } + + if (typeof factory !== 'function') { + throw new InvalidArgumentError('invalid factory') + } + + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } + + if (method === 'CONNECT') { + throw new InvalidArgumentError('invalid method') + } + + if (onInfo && typeof onInfo !== 'function') { + throw new InvalidArgumentError('invalid onInfo callback') + } + + super('UNDICI_STREAM') + } catch (err) { + if (util.isStream(body)) { + util.destroy(body.on('error', noop), err) + } + throw err } -} -//# sourceMappingURL=proxy.js.map -/***/ }), + this.responseHeaders = responseHeaders || null + this.opaque = opaque || null + this.factory = factory + this.callback = callback + this.res = null + this.abort = null + this.context = null + this.controller = null + this.trailers = null + this.body = body + this.onInfo = onInfo || null -/***/ 9610: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + if (util.isStream(body)) { + body.on('error', (err) => { + this.onResponseError(this.controller, err) + }) + } -"use strict"; + addSignal(this, signal) + } -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]; } }; + onRequestStart (controller, context) { + if (this.reason) { + controller.abort(this.reason) + return } - 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 () { - 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); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - 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; - }; -})(); -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.READONLY = exports.UV_FS_O_EXLOCK = exports.IS_WINDOWS = exports.unlink = exports.symlink = exports.stat = exports.rmdir = exports.rm = exports.rename = exports.readdir = exports.open = exports.mkdir = exports.lstat = exports.copyFile = exports.chmod = void 0; -exports.readlink = readlink; -exports.exists = exists; -exports.isDirectory = isDirectory; -exports.isRooted = isRooted; -exports.tryGetExecutablePath = tryGetExecutablePath; -exports.getCmdPath = getCmdPath; -const fs = __importStar(__nccwpck_require__(9896)); -const path = __importStar(__nccwpck_require__(6928)); -_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.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'; -/** - * Custom implementation of readlink to ensure Windows junctions - * maintain trailing backslash for backward compatibility with Node.js < 24 - * - * In Node.js 20, Windows junctions (directory symlinks) always returned paths - * with trailing backslashes. Node.js 24 removed this behavior, which breaks - * code that relied on this format for path operations. - * - * This implementation restores the Node 20 behavior by adding a trailing - * backslash to all junction results on Windows. - */ -function readlink(fsPath) { - return __awaiter(this, void 0, void 0, function* () { - const result = yield fs.promises.readlink(fsPath); - // On Windows, restore Node 20 behavior: add trailing backslash to all results - // since junctions on Windows are always directory links - if (exports.IS_WINDOWS && !result.endsWith('\\')) { - return `${result}\\`; - } - return result; - }); -} -// 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 (0, exports.stat)(fsPath); - } - catch (err) { - if (err.code === 'ENOENT') { - return false; - } - throw err; - } - return true; - }); -} -function isDirectory(fsPath_1) { - return __awaiter(this, arguments, void 0, function* (fsPath, useStat = false) { - const stats = useStat ? yield (0, exports.stat)(fsPath) : yield (0, exports.lstat)(fsPath); - return stats.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'); - } - 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('/'); -} -/** - * 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 (0, 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 (0, 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 (0, 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; - } - } - } - } - return ''; - }); -} -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, '/'); -} -// 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 && - process.getgid !== undefined && - stats.gid === process.getgid()) || - ((stats.mode & 64) > 0 && - process.getuid !== undefined && - 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`; -} -//# sourceMappingURL=io-util.js.map -/***/ }), + assert(this.callback) -/***/ 6893: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + this.controller = controller + this.abort = (reason) => controller.abort(reason) + this.context = context + } -"use strict"; + onResponseStart (controller, statusCode, headers, _statusMessage) { + const { factory, opaque, context, responseHeaders } = this -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]; } }; + const rawHeaders = controller?.rawHeaders + const responseHeaderData = responseHeaders === 'raw' + ? util.parseRawHeaders(rawHeaders) + : headers + + if (statusCode < 200) { + if (this.onInfo) { + this.onInfo({ statusCode, headers: responseHeaderData }) + } + return } - 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 () { - 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); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - 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; - }; -})(); -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.cp = cp; -exports.mv = mv; -exports.rmRF = rmRF; -exports.mkdirP = mkdirP; -exports.which = which; -exports.findInPath = findInPath; -const assert_1 = __nccwpck_require__(2613); -const path = __importStar(__nccwpck_require__(6928)); -const ioUtil = __importStar(__nccwpck_require__(9610)); -/** - * 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 cp(source_1, dest_1) { - return __awaiter(this, arguments, void 0, function* (source, dest, options = {}) { - 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); - } - }); -} -/** - * Moves a path. - * - * @param source source path - * @param dest destination path - * @param options optional. See MoveOptions. - */ -function mv(source_1, dest_1) { - return __awaiter(this, arguments, void 0, function* (source, dest, options = {}) { - 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); - }); -} -/** - * 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}`); - } - }); -} -/** - * 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* () { - (0, assert_1.ok)(fsPath, 'a path argument must be provided'); - yield ioUtil.mkdir(fsPath, { recursive: true }); - }); -} -/** - * 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.`); - } - } - return result; - } - const matches = yield findInPath(tool); - if (matches && matches.length > 0) { - return matches[0]; - } - return ''; - }); -} -/** - * 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); - } - } - } - // 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; - }); -} -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 -/***/ }), + this.factory = null -/***/ 329: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (factory === null) { + return + } -module.exports = __nccwpck_require__(4179); + const res = this.runInAsyncScope(factory, null, { + statusCode, + headers: responseHeaderData, + opaque, + context + }) + if ( + !res || + typeof res.write !== 'function' || + typeof res.end !== 'function' || + typeof res.on !== 'function' + ) { + throw new InvalidReturnValueError('expected Writable') + } -/***/ }), + trackWritableLifecycle(res, (err, fromErrorEvent) => { + const { callback, res, opaque, trailers, abort } = this -/***/ 4179: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + this.res = null + if (err || !res?.readable) { + util.destroy(res, fromErrorEvent ? undefined : err) + } -"use strict"; + this.callback = null + this.runInAsyncScope(callback, null, err || null, { opaque, trailers }) + if (err) { + abort(err) + } + }) -var net = __nccwpck_require__(9278); -var tls = __nccwpck_require__(4756); -var http = __nccwpck_require__(8611); -var https = __nccwpck_require__(5692); -var events = __nccwpck_require__(4434); -var assert = __nccwpck_require__(2613); -var util = __nccwpck_require__(9023); + res.on('drain', () => controller.resume()) + this.res = res -exports.httpOverHttp = httpOverHttp; -exports.httpsOverHttp = httpsOverHttp; -exports.httpOverHttps = httpOverHttps; -exports.httpsOverHttps = httpsOverHttps; - - -function httpOverHttp(options) { - var agent = new TunnelingAgent(options); - agent.request = http.request; - return agent; -} - -function httpsOverHttp(options) { - var agent = new TunnelingAgent(options); - agent.request = http.request; - agent.createSocket = createSecureSocket; - agent.defaultPort = 443; - return agent; -} - -function httpOverHttps(options) { - var agent = new TunnelingAgent(options); - agent.request = https.request; - return agent; -} - -function httpsOverHttps(options) { - var agent = new TunnelingAgent(options); - agent.request = https.request; - agent.createSocket = createSecureSocket; - agent.defaultPort = 443; - return agent; -} - - -function TunnelingAgent(options) { - var self = this; - self.options = options || {}; - self.proxyOptions = self.options.proxy || {}; - self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets; - self.requests = []; - self.sockets = []; + const needDrain = res.writableNeedDrain !== undefined + ? res.writableNeedDrain + : res._writableState?.needDrain - self.on('free', function onFree(socket, host, port, localAddress) { - var options = toOptions(host, port, localAddress); - for (var i = 0, len = self.requests.length; i < len; ++i) { - var pending = self.requests[i]; - if (pending.host === options.host && pending.port === options.port) { - // Detect the request to connect same origin server, - // reuse the connection. - self.requests.splice(i, 1); - pending.request.onSocket(socket); - return; - } + if (needDrain === true) { + controller.pause() } - socket.destroy(); - self.removeSocket(socket); - }); -} -util.inherits(TunnelingAgent, events.EventEmitter); - -TunnelingAgent.prototype.addRequest = function addRequest(req, host, port, localAddress) { - var self = this; - var options = mergeOptions({request: req}, self.options, toOptions(host, port, localAddress)); - - if (self.sockets.length >= this.maxSockets) { - // We are over limit so we'll add it to the queue. - self.requests.push(options); - return; } - // If we are under maxSockets create a new one. - self.createSocket(options, function(socket) { - socket.on('free', onFree); - socket.on('close', onCloseOrRemove); - socket.on('agentRemove', onCloseOrRemove); - req.onSocket(socket); - - function onFree() { - self.emit('free', socket, options); - } + onResponseData (controller, chunk) { + const { res } = this - function onCloseOrRemove(err) { - self.removeSocket(socket); - socket.removeListener('free', onFree); - socket.removeListener('close', onCloseOrRemove); - socket.removeListener('agentRemove', onCloseOrRemove); + if (!res) { + return } - }); -}; - -TunnelingAgent.prototype.createSocket = function createSocket(options, cb) { - var self = this; - var placeholder = {}; - self.sockets.push(placeholder); - var connectOptions = mergeOptions({}, self.proxyOptions, { - method: 'CONNECT', - path: options.host + ':' + options.port, - agent: false, - headers: { - host: options.host + ':' + options.port + if (res.write(chunk) === false) { + controller.pause() } - }); - if (options.localAddress) { - connectOptions.localAddress = options.localAddress; - } - if (connectOptions.proxyAuth) { - connectOptions.headers = connectOptions.headers || {}; - connectOptions.headers['Proxy-Authorization'] = 'Basic ' + - new Buffer(connectOptions.proxyAuth).toString('base64'); } - debug('making CONNECT request'); - var connectReq = self.request(connectOptions); - connectReq.useChunkedEncodingByDefault = false; // for v0.6 - connectReq.once('response', onResponse); // for v0.6 - connectReq.once('upgrade', onUpgrade); // for v0.6 - connectReq.once('connect', onConnect); // for v0.7 or later - connectReq.once('error', onError); - connectReq.end(); - - function onResponse(res) { - // Very hacky. This is necessary to avoid http-parser leaks. - res.upgrade = true; - } - - function onUpgrade(res, socket, head) { - // Hacky. - process.nextTick(function() { - onConnect(res, socket, head); - }); - } + onResponseEnd (_controller, trailers) { + const { res } = this - function onConnect(res, socket, head) { - connectReq.removeAllListeners(); - socket.removeAllListeners(); + removeSignal(this) - if (res.statusCode !== 200) { - debug('tunneling socket could not be established, statusCode=%d', - res.statusCode); - socket.destroy(); - var error = new Error('tunneling socket could not be established, ' + - 'statusCode=' + res.statusCode); - error.code = 'ECONNRESET'; - options.request.emit('error', error); - self.removeSocket(placeholder); - return; - } - if (head.length > 0) { - debug('got illegal response body from proxy'); - socket.destroy(); - var error = new Error('got illegal response body from proxy'); - error.code = 'ECONNRESET'; - options.request.emit('error', error); - self.removeSocket(placeholder); - return; + if (!res) { + return } - debug('tunneling connection has established'); - self.sockets[self.sockets.indexOf(placeholder)] = socket; - return cb(socket); - } - - function onError(cause) { - connectReq.removeAllListeners(); - debug('tunneling socket could not be established, cause=%s\n', - cause.message, cause.stack); - var error = new Error('tunneling socket could not be established, ' + - 'cause=' + cause.message); - error.code = 'ECONNRESET'; - options.request.emit('error', error); - self.removeSocket(placeholder); - } -}; + if (trailers && typeof trailers === 'object') { + this.trailers = trailers + } -TunnelingAgent.prototype.removeSocket = function removeSocket(socket) { - var pos = this.sockets.indexOf(socket) - if (pos === -1) { - return; + res.end() } - this.sockets.splice(pos, 1); - var pending = this.requests.shift(); - if (pending) { - // If we have pending requests and a socket gets closed a new one - // needs to be created to take over in the pool for the one that closed. - this.createSocket(pending, function(socket) { - pending.request.onSocket(socket); - }); - } -}; + onResponseError (_controller, err) { + const { res, callback, opaque, body } = this -function createSecureSocket(options, cb) { - var self = this; - TunnelingAgent.prototype.createSocket.call(self, options, function(socket) { - var hostHeader = options.request.getHeader('host'); - var tlsOptions = mergeOptions({}, self.options, { - socket: socket, - servername: hostHeader ? hostHeader.replace(/:.*$/, '') : options.host - }); + removeSignal(this) - // 0 is dummy port for v0.6 - var secureSocket = tls.connect(0, tlsOptions); - self.sockets[self.sockets.indexOf(socket)] = secureSocket; - cb(secureSocket); - }); -} + this.factory = null + if (res) { + this.res = null + util.destroy(res, err) + } else if (callback) { + this.callback = null + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }) + }) + } -function toOptions(host, port, localAddress) { - if (typeof host === 'string') { // since v0.10 - return { - host: host, - port: port, - localAddress: localAddress - }; + if (body) { + this.body = null + util.destroy(body, err) + } } - return host; // for v0.11 or later } -function mergeOptions(target) { - for (var i = 1, len = arguments.length; i < len; ++i) { - var overrides = arguments[i]; - if (typeof overrides === 'object') { - var keys = Object.keys(overrides); - for (var j = 0, keyLen = keys.length; j < keyLen; ++j) { - var k = keys[j]; - if (overrides[k] !== undefined) { - target[k] = overrides[k]; - } - } - } +function stream (opts, factory, callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + stream.call(this, opts, factory, (err, data) => { + return err ? reject(err) : resolve(data) + }) + }) } - return target; -} + try { + const handler = new StreamHandler(opts, factory, callback) -var debug; -if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) { - debug = function() { - var args = Array.prototype.slice.call(arguments); - if (typeof args[0] === 'string') { - args[0] = 'TUNNEL: ' + args[0]; - } else { - args.unshift('TUNNEL:'); + this.dispatch(opts, handler) + } catch (err) { + if (typeof callback !== 'function') { + throw err } - console.error.apply(console, args); + const opaque = opts?.opaque + queueMicrotask(() => callback(err, { opaque })) } -} else { - debug = function() {}; } -exports.debug = debug; // for test + +module.exports = stream /***/ }), -/***/ 2293: +/***/ 6143: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const Client = __nccwpck_require__(940) -const Dispatcher = __nccwpck_require__(9342) -const Pool = __nccwpck_require__(737) -const BalancedPool = __nccwpck_require__(6022) -const RoundRobinPool = __nccwpck_require__(5877) -const Agent = __nccwpck_require__(4722) -const Dispatcher1Wrapper = __nccwpck_require__(4925) -const ProxyAgent = __nccwpck_require__(8251) -const Socks5ProxyAgent = __nccwpck_require__(4258) -const EnvHttpProxyAgent = __nccwpck_require__(7968) -const RetryAgent = __nccwpck_require__(7273) -const H2CClient = __nccwpck_require__(1334) -const errors = __nccwpck_require__(7062) -const util = __nccwpck_require__(9705) -const { InvalidArgumentError } = errors -const api = __nccwpck_require__(4806) -const buildConnector = __nccwpck_require__(4463) -const MockClient = __nccwpck_require__(4882) -const { MockCallHistory, MockCallHistoryLog } = __nccwpck_require__(1112) -const MockAgent = __nccwpck_require__(676) -const MockPool = __nccwpck_require__(2719) -const SnapshotAgent = __nccwpck_require__(818) -const mockErrors = __nccwpck_require__(7102) -const RetryHandler = __nccwpck_require__(8077) -const { getGlobalDispatcher, setGlobalDispatcher } = __nccwpck_require__(3034) -const DecoratorHandler = __nccwpck_require__(6150) -const RedirectHandler = __nccwpck_require__(1789) - -Object.assign(Dispatcher.prototype, api) - -module.exports.Dispatcher = Dispatcher -module.exports.Client = Client -module.exports.Pool = Pool -module.exports.BalancedPool = BalancedPool -module.exports.RoundRobinPool = RoundRobinPool -module.exports.Agent = Agent -module.exports.Dispatcher1Wrapper = Dispatcher1Wrapper -module.exports.ProxyAgent = ProxyAgent -module.exports.Socks5ProxyAgent = Socks5ProxyAgent -module.exports.EnvHttpProxyAgent = EnvHttpProxyAgent -module.exports.RetryAgent = RetryAgent -module.exports.H2CClient = H2CClient -module.exports.RetryHandler = RetryHandler - -module.exports.DecoratorHandler = DecoratorHandler -module.exports.RedirectHandler = RedirectHandler -module.exports.interceptors = { - redirect: __nccwpck_require__(3721), - responseError: __nccwpck_require__(1257), - retry: __nccwpck_require__(6207), - dump: __nccwpck_require__(951), - dns: __nccwpck_require__(4230), - cache: __nccwpck_require__(3191), - decompress: __nccwpck_require__(1790), - deduplicate: __nccwpck_require__(7305) -} - -module.exports.cacheStores = { - MemoryCacheStore: __nccwpck_require__(3330) -} - -const SqliteCacheStore = __nccwpck_require__(6901) -module.exports.cacheStores.SqliteCacheStore = SqliteCacheStore - -module.exports.buildConnector = buildConnector -module.exports.errors = errors -module.exports.util = { - parseHeaders: util.parseHeaders, - headerNameToString: util.headerNameToString -} +const { InvalidArgumentError, SocketError } = __nccwpck_require__(4882) +const { AsyncResource } = __nccwpck_require__(6698) +const assert = __nccwpck_require__(4589) +const util = __nccwpck_require__(9277) +const { kHTTP2Stream } = __nccwpck_require__(228) +const { addSignal, removeSignal } = __nccwpck_require__(5697) -function makeDispatcher (fn) { - return (url, opts, handler) => { - if (typeof opts === 'function') { - handler = opts - opts = null +class UpgradeHandler extends AsyncResource { + constructor (opts, callback) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') } - if (!url || (typeof url !== 'string' && typeof url !== 'object' && !(url instanceof URL))) { - throw new InvalidArgumentError('invalid url') + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') } - if (opts != null && typeof opts !== 'object') { - throw new InvalidArgumentError('invalid opts') + const { signal, opaque, responseHeaders } = opts + + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') } - if (opts && opts.path != null) { - if (typeof opts.path !== 'string') { - throw new InvalidArgumentError('invalid opts.path') - } + super('UNDICI_UPGRADE') - let path = opts.path - if (!opts.path.startsWith('/')) { - path = `/${path}` - } + this.responseHeaders = responseHeaders || null + this.opaque = opaque || null + this.callback = callback + this.abort = null + this.context = null - url = new URL(util.parseOrigin(url).origin + path) - } else { - if (!opts) { - opts = typeof url === 'object' ? url : {} - } + addSignal(this, signal) + } - url = util.parseURL(url) + onRequestStart (controller, context) { + if (this.reason) { + controller.abort(this.reason) + return } - const { agent, dispatcher = getGlobalDispatcher(), ...restOpts } = opts - - if (agent) { - throw new InvalidArgumentError('unsupported opts.agent. Did you mean opts.client?') - } + assert(this.callback) - return fn.call(dispatcher, { - ...restOpts, - origin: url.origin, - path: url.search ? `${url.pathname}${url.search}` : url.pathname, - method: opts.method || (opts.body ? 'PUT' : 'GET') - }, handler) + this.abort = (reason) => controller.abort(reason) + this.context = context } -} -module.exports.setGlobalDispatcher = setGlobalDispatcher -module.exports.getGlobalDispatcher = getGlobalDispatcher + onResponseStart () { + throw new SocketError('bad upgrade', null) + } -const fetchImpl = (__nccwpck_require__(7343).fetch) + onRequestUpgrade (controller, statusCode, headers, socket) { + const expectedStatusCode = socket[kHTTP2Stream] === true ? 200 : 101 -// Capture __filename at module load time for stack trace augmentation. -// This may be undefined when bundled in environments like Node.js internals. -const currentFilename = typeof __filename !== 'undefined' ? __filename : undefined + if (statusCode !== expectedStatusCode) { + const socketInfo = socket[kHTTP2Stream] === true ? null : util.getSocketInfo(socket) + controller.abort(new SocketError('bad upgrade', socketInfo)) + return + } -function appendFetchStackTrace (err, filename) { - if (!err || typeof err !== 'object') { - return - } + const { callback, opaque, context } = this - const stack = typeof err.stack === 'string' ? err.stack : '' - const normalizedFilename = filename.replace(/\\/g, '/') + removeSignal(this) - if (stack && (stack.includes(filename) || stack.includes(normalizedFilename))) { - return - } + this.callback = null - const capture = {} - Error.captureStackTrace(capture, appendFetchStackTrace) + const rawHeaders = controller?.rawHeaders + const responseHeaders = this.responseHeaders === 'raw' + ? util.parseRawHeaders(rawHeaders) + : headers - if (!capture.stack) { - return + this.runInAsyncScope(callback, null, null, { + headers: responseHeaders, + socket, + opaque, + context + }) } - const captureLines = capture.stack.split('\n').slice(1).join('\n') + onResponseError (_controller, err) { + const { callback, opaque } = this - err.stack = stack ? `${stack}\n${captureLines}` : capture.stack -} + removeSignal(this) -module.exports.fetch = function fetch (init, options = undefined) { - return fetchImpl(init, options).catch(err => { - if (currentFilename) { - appendFetchStackTrace(err, currentFilename) - } else if (err && typeof err === 'object') { - Error.captureStackTrace(err, module.exports.fetch) + if (callback) { + this.callback = null + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }) + }) } - throw err - }) + } } -module.exports.Headers = __nccwpck_require__(5825).Headers -module.exports.Response = __nccwpck_require__(3976).Response -module.exports.Request = __nccwpck_require__(518).Request -module.exports.FormData = __nccwpck_require__(4333).FormData -const { setGlobalOrigin, getGlobalOrigin } = __nccwpck_require__(2912) - -module.exports.setGlobalOrigin = setGlobalOrigin -module.exports.getGlobalOrigin = getGlobalOrigin - -const { CacheStorage } = __nccwpck_require__(8574) -const { kConstruct } = __nccwpck_require__(7480) - -module.exports.caches = new CacheStorage(kConstruct) - -const { deleteCookie, getCookies, getSetCookies, setCookie, parseCookie } = __nccwpck_require__(9876) - -module.exports.deleteCookie = deleteCookie -module.exports.getCookies = getCookies -module.exports.getSetCookies = getSetCookies -module.exports.setCookie = setCookie -module.exports.parseCookie = parseCookie - -const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(2403) - -module.exports.parseMIMEType = parseMIMEType -module.exports.serializeAMimeType = serializeAMimeType +function upgrade (opts, callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + upgrade.call(this, opts, (err, data) => { + return err ? reject(err) : resolve(data) + }) + }) + } -const { CloseEvent, ErrorEvent, MessageEvent } = __nccwpck_require__(1003) -const { WebSocket, ping } = __nccwpck_require__(9127) -module.exports.WebSocket = WebSocket -module.exports.CloseEvent = CloseEvent -module.exports.ErrorEvent = ErrorEvent -module.exports.MessageEvent = MessageEvent -module.exports.ping = ping + try { + const upgradeHandler = new UpgradeHandler(opts, callback) + const upgradeOpts = { + ...opts, + method: opts.method || 'GET', + upgrade: opts.protocol || 'Websocket' + } + this.dispatch(upgradeOpts, upgradeHandler) + } catch (err) { + if (typeof callback !== 'function') { + throw err + } + const opaque = opts?.opaque + queueMicrotask(() => callback(err, { opaque })) + } +} -module.exports.WebSocketStream = __nccwpck_require__(5818).WebSocketStream -module.exports.WebSocketError = __nccwpck_require__(174).WebSocketError +module.exports = upgrade -module.exports.request = makeDispatcher(api.request) -module.exports.stream = makeDispatcher(api.stream) -module.exports.pipeline = makeDispatcher(api.pipeline) -module.exports.connect = makeDispatcher(api.connect) -module.exports.upgrade = makeDispatcher(api.upgrade) -module.exports.MockClient = MockClient -module.exports.MockCallHistory = MockCallHistory -module.exports.MockCallHistoryLog = MockCallHistoryLog -module.exports.MockPool = MockPool -module.exports.MockAgent = MockAgent -module.exports.SnapshotAgent = SnapshotAgent -module.exports.mockErrors = mockErrors +/***/ }), -const { EventSource } = __nccwpck_require__(5663) +/***/ 3514: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -module.exports.EventSource = EventSource +"use strict"; -function install () { - globalThis.fetch = module.exports.fetch - globalThis.Headers = module.exports.Headers - globalThis.Response = module.exports.Response - globalThis.Request = module.exports.Request - globalThis.FormData = module.exports.FormData - globalThis.WebSocket = module.exports.WebSocket - globalThis.CloseEvent = module.exports.CloseEvent - globalThis.ErrorEvent = module.exports.ErrorEvent - globalThis.MessageEvent = module.exports.MessageEvent - globalThis.EventSource = module.exports.EventSource -} -module.exports.install = install +module.exports.request = __nccwpck_require__(2550) +module.exports.stream = __nccwpck_require__(2475) +module.exports.pipeline = __nccwpck_require__(4421) +module.exports.upgrade = __nccwpck_require__(6143) +module.exports.connect = __nccwpck_require__(6685) /***/ }), -/***/ 3741: +/***/ 5472: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const { addAbortListener } = __nccwpck_require__(9705) -const { RequestAbortedError } = __nccwpck_require__(7062) +const assert = __nccwpck_require__(4589) +const { addAbortListener } = __nccwpck_require__(8474) +const { Readable } = __nccwpck_require__(7075) +const { RequestAbortedError, NotSupportedError, InvalidArgumentError, AbortError } = __nccwpck_require__(4882) +const util = __nccwpck_require__(9277) -const kListener = Symbol('kListener') -const kSignal = Symbol('kSignal') - -function abort (self) { - if (self.abort) { - self.abort(self[kSignal]?.reason) - } else { - self.reason = self[kSignal]?.reason ?? new RequestAbortedError() - } - removeSignal(self) -} - -function addSignal (self, signal) { - self.reason = null - - self[kSignal] = null - self[kListener] = null - - if (!signal) { - return - } - - if (signal.aborted) { - abort(self) - return - } - - self[kSignal] = signal - self[kListener] = () => { - abort(self) - } +const kConsume = Symbol('kConsume') +const kReading = Symbol('kReading') +const kBody = Symbol('kBody') +const kAbort = Symbol('kAbort') +const kContentType = Symbol('kContentType') +const kContentLength = Symbol('kContentLength') +const kUsed = Symbol('kUsed') +const kBytesRead = Symbol('kBytesRead') - addAbortListener(self[kSignal], self[kListener]) -} +const noop = () => {} -function removeSignal (self) { - if (!self[kSignal]) { - return - } +/** + * @class + * @extends {Readable} + * @see https://fetch.spec.whatwg.org/#body + */ +class BodyReadable extends Readable { + /** + * @param {object} opts + * @param {(this: Readable, size: number) => void} opts.resume + * @param {() => (void | null)} opts.abort + * @param {string} [opts.contentType = ''] + * @param {number} [opts.contentLength] + * @param {number} [opts.highWaterMark = 64 * 1024] + */ + constructor ({ + resume, + abort, + contentType = '', + contentLength, + highWaterMark = 64 * 1024 // Same as nodejs fs streams. + }) { + super({ + autoDestroy: true, + read: resume, + highWaterMark + }) - if ('removeEventListener' in self[kSignal]) { - self[kSignal].removeEventListener('abort', self[kListener]) - } else { - self[kSignal].removeListener('abort', self[kListener]) - } + this._readableState.dataEmitted = false - self[kSignal] = null - self[kListener] = null -} + this[kAbort] = abort -module.exports = { - addSignal, - removeSignal -} + /** @type {Consume | null} */ + this[kConsume] = null + /** @type {number} */ + this[kBytesRead] = 0 -/***/ }), + /** @type {ReadableStream|null} */ + this[kBody] = null -/***/ 9105: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + /** @type {boolean} */ + this[kUsed] = false -"use strict"; + /** @type {string} */ + this[kContentType] = contentType + /** @type {number|null} */ + this[kContentLength] = Number.isFinite(contentLength) ? contentLength : null -const assert = __nccwpck_require__(4589) -const { AsyncResource } = __nccwpck_require__(6698) -const { InvalidArgumentError, SocketError } = __nccwpck_require__(7062) -const util = __nccwpck_require__(9705) -const { addSignal, removeSignal } = __nccwpck_require__(3741) + /** + * Is stream being consumed through Readable API? + * This is an optimization so that we avoid checking + * for 'data' and 'readable' listeners in the hot path + * inside push(). + * + * @type {boolean} + */ + this[kReading] = false + } -class ConnectHandler extends AsyncResource { - constructor (opts, callback) { - if (!opts || typeof opts !== 'object') { - throw new InvalidArgumentError('invalid opts') + /** + * @param {Error|null} err + * @param {(error:(Error|null)) => void} callback + * @returns {void} + */ + _destroy (err, callback) { + if (!err && !this._readableState.endEmitted) { + err = new RequestAbortedError() } - if (typeof callback !== 'function') { - throw new InvalidArgumentError('invalid callback') + if (err) { + this[kAbort]() } - const { signal, opaque, responseHeaders } = opts - - if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { - throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + // Workaround for Node "bug". If the stream is destroyed in same + // tick as it is created, then a user who is waiting for a + // promise (i.e micro tick) for installing an 'error' listener will + // never get a chance and will always encounter an unhandled exception. + if (!this[kUsed]) { + setImmediate(callback, err) + } else { + callback(err) } - - super('UNDICI_CONNECT') - - this.opaque = opaque || null - this.responseHeaders = responseHeaders || null - this.callback = callback - this.abort = null - - addSignal(this, signal) } - onRequestStart (controller, context) { - if (this.reason) { - controller.abort(this.reason) - return + /** + * @param {string|symbol} event + * @param {(...args: any[]) => void} listener + * @returns {this} + */ + on (event, listener) { + if (event === 'data' || event === 'readable') { + this[kReading] = true + this[kUsed] = true } - - assert(this.callback) - - this.abort = (reason) => controller.abort(reason) - this.context = context + return super.on(event, listener) } - onResponseStart () { - throw new SocketError('bad connect', null) + /** + * @param {string|symbol} event + * @param {(...args: any[]) => void} listener + * @returns {this} + */ + addListener (event, listener) { + return this.on(event, listener) } - onRequestUpgrade (controller, statusCode, headers, socket) { - const { callback, opaque, context } = this - - removeSignal(this) - - this.callback = null - - let responseHeaders = headers - const rawHeaders = controller?.rawHeaders - // Indicates is an HTTP2Session - if (responseHeaders != null) { - responseHeaders = this.responseHeaders === 'raw' - ? util.parseRawHeaders(rawHeaders) - : headers + /** + * @param {string|symbol} event + * @param {(...args: any[]) => void} listener + * @returns {this} + */ + off (event, listener) { + const ret = super.off(event, listener) + if (event === 'data' || event === 'readable') { + this[kReading] = ( + this.listenerCount('data') > 0 || + this.listenerCount('readable') > 0 + ) } - - this.runInAsyncScope(callback, null, null, { - statusCode, - headers: responseHeaders, - socket, - opaque, - context - }) + return ret } - onResponseError (_controller, err) { - const { callback, opaque } = this - - removeSignal(this) + /** + * @param {string|symbol} event + * @param {(...args: any[]) => void} listener + * @returns {this} + */ + removeListener (event, listener) { + return this.off(event, listener) + } - if (callback) { - this.callback = null - queueMicrotask(() => { - this.runInAsyncScope(callback, null, err, { opaque }) - }) + /** + * @param {Buffer|null} chunk + * @returns {boolean} + */ + push (chunk) { + if (chunk) { + this[kBytesRead] += chunk.length + if (this[kConsume]) { + consumePush(this[kConsume], chunk) + return this[kReading] ? super.push(chunk) : true + } } - } -} -function connect (opts, callback) { - if (callback === undefined) { - return new Promise((resolve, reject) => { - connect.call(this, opts, (err, data) => { - return err ? reject(err) : resolve(data) - }) - }) + return super.push(chunk) } - try { - const connectHandler = new ConnectHandler(opts, callback) - const connectOptions = { ...opts, method: 'CONNECT' } - this.dispatch(connectOptions, connectHandler) - } catch (err) { - if (typeof callback !== 'function') { - throw err - } - const opaque = opts?.opaque - queueMicrotask(() => callback(err, { opaque })) + /** + * Consumes and returns the body as a string. + * + * @see https://fetch.spec.whatwg.org/#dom-body-text + * @returns {Promise} + */ + text () { + return consume(this, 'text') } -} - -module.exports = connect - - -/***/ }), - -/***/ 6793: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const { - Readable, - Duplex, - PassThrough -} = __nccwpck_require__(7075) -const assert = __nccwpck_require__(4589) -const { AsyncResource } = __nccwpck_require__(6698) -const { - InvalidArgumentError, - InvalidReturnValueError, - RequestAbortedError -} = __nccwpck_require__(7062) -const util = __nccwpck_require__(9705) -const { kBodyUsed } = __nccwpck_require__(7480) -const { addSignal, removeSignal } = __nccwpck_require__(3741) - -function noop () {} - -const kResume = Symbol('resume') - -class PipelineRequest extends Readable { - constructor () { - super({ autoDestroy: true }) - this[kResume] = null - // Pipeline request bodies come from a live writable side and cannot be - // replayed across redirects or retries, even before any bytes are read. - this[kBodyUsed] = true + /** + * Consumes and returns the body as a JavaScript Object. + * + * @see https://fetch.spec.whatwg.org/#dom-body-json + * @returns {Promise} + */ + json () { + return consume(this, 'json') } - _read () { - const { [kResume]: resume } = this - - if (resume) { - this[kResume] = null - resume() - } + /** + * Consumes and returns the body as a Blob + * + * @see https://fetch.spec.whatwg.org/#dom-body-blob + * @returns {Promise} + */ + blob () { + return consume(this, 'blob') } - _destroy (err, callback) { - this._read() + /** + * Consumes and returns the body as an Uint8Array. + * + * @see https://fetch.spec.whatwg.org/#dom-body-bytes + * @returns {Promise} + */ + bytes () { + return consume(this, 'bytes') + } - callback(err) + /** + * Consumes and returns the body as an ArrayBuffer. + * + * @see https://fetch.spec.whatwg.org/#dom-body-arraybuffer + * @returns {Promise} + */ + arrayBuffer () { + return consume(this, 'arrayBuffer') } -} -class PipelineResponse extends Readable { - constructor (resume) { - super({ autoDestroy: true }) - this[kResume] = resume + /** + * Not implemented + * + * @see https://fetch.spec.whatwg.org/#dom-body-formdata + * @throws {NotSupportedError} + */ + async formData () { + // TODO: Implement. + throw new NotSupportedError() } - _read () { - this[kResume]() + /** + * Returns true if the body is not null and the body has been consumed. + * Otherwise, returns false. + * + * @see https://fetch.spec.whatwg.org/#dom-body-bodyused + * @readonly + * @returns {boolean} + */ + get bodyUsed () { + return util.isDisturbed(this) } - _destroy (err, callback) { - if (!err && !this._readableState.endEmitted) { - err = new RequestAbortedError() + /** + * @see https://fetch.spec.whatwg.org/#dom-body-body + * @readonly + * @returns {ReadableStream} + */ + get body () { + if (!this[kBody]) { + this[kBody] = ReadableStream.from(this) + if (this[kConsume]) { + // TODO: Is this the best way to force a lock? + this[kBody].getReader() // Ensure stream is locked. + assert(this[kBody].locked) + } } - - callback(err) + return this[kBody] } -} -class PipelineHandler extends AsyncResource { - constructor (opts, handler) { - if (!opts || typeof opts !== 'object') { - throw new InvalidArgumentError('invalid opts') - } + /** + * Dumps the response body by reading `limit` number of bytes. + * @param {object} opts + * @param {number} [opts.limit = 131072] Number of bytes to read. + * @param {AbortSignal} [opts.signal] An AbortSignal to cancel the dump. + * @returns {Promise} + */ + dump (opts) { + const signal = opts?.signal - if (typeof handler !== 'function') { - throw new InvalidArgumentError('invalid handler') + if (signal != null && (typeof signal !== 'object' || !('aborted' in signal))) { + return Promise.reject(new InvalidArgumentError('signal must be an AbortSignal')) } - const { signal, method, opaque, onInfo, responseHeaders } = opts - - if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { - throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') - } + const limit = opts?.limit && Number.isFinite(opts.limit) + ? opts.limit + : 128 * 1024 - if (method === 'CONNECT') { - throw new InvalidArgumentError('invalid method') + if (signal?.aborted) { + return Promise.reject(signal.reason ?? new AbortError()) } - if (onInfo && typeof onInfo !== 'function') { - throw new InvalidArgumentError('invalid onInfo callback') + if (this._readableState.closeEmitted) { + return Promise.resolve(null) } - super('UNDICI_PIPELINE') - - this.opaque = opaque || null - this.responseHeaders = responseHeaders || null - this.handler = handler - this.abort = null - this.context = null - this.onInfo = onInfo || null - - this.req = new PipelineRequest().on('error', noop) - - this.ret = new Duplex({ - readableObjectMode: opts.objectMode, - autoDestroy: true, - read: () => { - const { body } = this - - if (body?.resume) { - body.resume() - } - }, - write: (chunk, encoding, callback) => { - const { req } = this - - if (req.push(chunk, encoding) || req._readableState.destroyed) { - callback() - } else { - req[kResume] = callback - } - }, - destroy: (err, callback) => { - const { body, req, res, ret, abort } = this - - if (!err && !ret._readableState.endEmitted) { - err = new RequestAbortedError() - } + return new Promise((resolve, reject) => { + if ( + (this[kContentLength] && (this[kContentLength] > limit)) || + this[kBytesRead] > limit + ) { + this.destroy(new AbortError()) + } - if (abort && err) { - abort() + if (signal) { + const onAbort = () => { + this.destroy(signal.reason ?? new AbortError()) } - - util.destroy(body, err) - util.destroy(req, err) - util.destroy(res, err) - - removeSignal(this) - - callback(err) + const abortListener = addAbortListener(signal, onAbort) + this + .on('close', function () { + abortListener[Symbol.dispose]() + if (signal.aborted) { + reject(signal.reason ?? new AbortError()) + } else { + resolve(null) + } + }) + } else { + this.on('close', resolve) } - }).on('prefinish', () => { - const { req } = this - // Node < 15 does not call _final in same tick. - req.push(null) + this + .on('error', noop) + .on('data', () => { + if (this[kBytesRead] > limit) { + this.destroy() + } + }) + .resume() }) - - this.res = null - - addSignal(this, signal) } - onRequestStart (controller, context) { - const { res } = this - - if (this.reason) { - controller.abort(this.reason) - return + /** + * @param {BufferEncoding} encoding + * @returns {this} + */ + setEncoding (encoding) { + if (Buffer.isEncoding(encoding)) { + // Delegate to Node.js Readable.setEncoding() which initializes a + // StringDecoder and re-encodes already-buffered chunks. This properly + // handles multi-byte sequences split at chunk boundaries for the + // for-await / on('data') paths. Without this, Node.js uses + // buf.toString(encoding) on each chunk, producing U+FFFD for split chars. + // + // The consume path (body.text(), body.json(), ...) copes with the + // decoded strings this leaves in state.buffer, see consumeStart(). + super.setEncoding(encoding) } + return this + } +} - assert(!res, 'pipeline cannot be retried') +/** + * @see https://streams.spec.whatwg.org/#readablestream-locked + * @param {BodyReadable} bodyReadable + * @returns {boolean} + */ +function isLocked (bodyReadable) { + // Consume is an implicit lock. + return bodyReadable[kBody]?.locked === true || bodyReadable[kConsume] !== null +} - this.abort = (reason) => controller.abort(reason) - this.context = context - } +/** + * @see https://fetch.spec.whatwg.org/#body-unusable + * @param {BodyReadable} bodyReadable + * @returns {boolean} + */ +function isUnusable (bodyReadable) { + return util.isDisturbed(bodyReadable) || isLocked(bodyReadable) +} - onResponseStart (controller, statusCode, headers, _statusMessage) { - const { opaque, handler, context } = this +/** + * @typedef {'text' | 'json' | 'blob' | 'bytes' | 'arrayBuffer'} ConsumeType + */ - if (statusCode < 200) { - if (this.onInfo) { - const rawHeaders = controller?.rawHeaders - const responseHeaders = this.responseHeaders === 'raw' - ? util.parseRawHeaders(rawHeaders) - : headers - this.onInfo({ statusCode, headers: responseHeaders }) +/** + * @template {ConsumeType} T + * @typedef {T extends 'text' ? string : + * T extends 'json' ? unknown : + * T extends 'blob' ? Blob : + * T extends 'arrayBuffer' ? ArrayBuffer : + * T extends 'bytes' ? Uint8Array : + * never + * } ConsumeReturnType + */ +/** + * @typedef {object} Consume + * @property {ConsumeType} type + * @property {BodyReadable} stream + * @property {((value?: any) => void)} resolve + * @property {((err: Error) => void)} reject + * @property {number} length + * @property {Buffer[]} body + */ + +/** + * @template {ConsumeType} T + * @param {BodyReadable} stream + * @param {T} type + * @returns {Promise>} + */ +function consume (stream, type) { + assert(!stream[kConsume]) + + return new Promise((resolve, reject) => { + if (isUnusable(stream)) { + const rState = stream._readableState + if (rState.destroyed && rState.closeEmitted === false) { + stream + .on('error', reject) + .on('close', () => { + reject(new TypeError('unusable')) + }) + } else { + reject(rState.errored ?? new TypeError('unusable')) } - return - } + } else { + queueMicrotask(() => { + stream[kConsume] = { + type, + stream, + resolve, + reject, + length: 0, + body: [] + } - this.res = new PipelineResponse(() => controller.resume()) + stream + .on('error', function (err) { + consumeFinish(this[kConsume], err) + }) + .on('close', function () { + if (this[kConsume].body !== null) { + consumeFinish(this[kConsume], new RequestAbortedError()) + } + }) - let body - try { - this.handler = null - const rawHeaders = controller?.rawHeaders - const responseHeaders = this.responseHeaders === 'raw' - ? util.parseRawHeaders(rawHeaders) - : headers - body = this.runInAsyncScope(handler, null, { - statusCode, - headers: responseHeaders, - opaque, - body: this.res, - context + consumeStart(stream[kConsume]) }) - } catch (err) { - this.res.on('error', noop) - throw err } + }) +} - if (!body || typeof body.on !== 'function') { - throw new InvalidReturnValueError('expected Readable') - } +/** + * @param {Consume} consume + * @returns {void} + */ +function consumeStart (consume) { + if (consume.body === null) { + return + } - body - .on('data', (chunk) => { - const { ret, body } = this + const { _readableState: state } = consume.stream - if (!ret.push(chunk) && body.pause) { - body.pause() - } - }) - .on('error', (err) => { - const { ret } = this + if (state.bufferIndex) { + const start = state.bufferIndex + const end = state.buffer.length + for (let n = start; n < end; n++) { + consumePush(consume, state.buffer[n]) + } + } else { + for (const chunk of state.buffer) { + consumePush(consume, chunk) + } + } - util.destroy(ret, err) - }) - .on('end', () => { - const { ret } = this + // If setEncoding() was called, state.buffer holds decoded strings, which + // consumePush() turns back into bytes. The trailing bytes of a multi-byte + // sequence split across a chunk boundary are not part of any of those + // strings, they are held inside the decoder until the rest arrives, so + // take them from there. + const decoder = state.decoder + if (decoder != null && decoder.lastNeed > 0) { + consumePush(consume, Buffer.from(decoder.lastChar.subarray(0, decoder.lastTotal - decoder.lastNeed))) + } - ret.push(null) - }) - .on('close', () => { - const { ret } = this + if (state.endEmitted) { + // No `this` to read the consume off here: consumeStart is a free function, called from + // the queueMicrotask above. The callback below does have one, because the emitter passes + // the stream as its receiver. Returning matters too - consumeEnd() clears consume.stream, + // which the resume() below would then dereference. + consumeEnd(consume, state.encoding) + return + } - if (!ret._readableState.ended) { - util.destroy(ret, new RequestAbortedError()) - } - }) + consume.stream.on('end', function () { + consumeEnd(this[kConsume], this._readableState.encoding) + }) - this.body = body + consume.stream.resume() + + while (consume.stream.read() != null) { + // Loop } +} - onResponseData (controller, chunk) { - const { res } = this +/** + * @param {Buffer[]} chunks + * @param {number} length + * @param {BufferEncoding} [encoding='utf8'] + * @returns {string} + */ +function chunksDecode (chunks, length, encoding) { + if (chunks.length === 0 || length === 0) { + return '' + } + const buffer = chunks.length === 1 ? chunks[0] : Buffer.concat(chunks, length) + const bufferLength = buffer.length - if (res.push(chunk) === false) { - controller.pause() - } + // Skip BOM. + const start = + bufferLength > 2 && + buffer[0] === 0xef && + buffer[1] === 0xbb && + buffer[2] === 0xbf + ? 3 + : 0 + if (!encoding || encoding === 'utf8' || encoding === 'utf-8') { + return buffer.utf8Slice(start, bufferLength) + } else { + return buffer.subarray(start, bufferLength).toString(encoding) } +} - onResponseEnd (_controller, _trailers) { - const { res } = this - res.push(null) +/** + * @param {Buffer[]} chunks + * @param {number} length + * @returns {Uint8Array} + */ +function chunksConcat (chunks, length) { + if (chunks.length === 0 || length === 0) { + return new Uint8Array(0) + } + if (chunks.length === 1) { + // fast-path + return new Uint8Array(chunks[0]) } + const buffer = new Uint8Array(Buffer.allocUnsafeSlow(length).buffer) - onResponseError (_controller, err) { - const { ret } = this - this.handler = null - util.destroy(ret, err) + let offset = 0 + for (let i = 0; i < chunks.length; ++i) { + const chunk = chunks[i] + buffer.set(chunk, offset) + offset += chunk.length } + + return buffer } -function pipeline (opts, handler) { +/** + * @param {Consume} consume + * @param {BufferEncoding} encoding + * @returns {void} + */ +function consumeEnd (consume, encoding) { + const { type, body, resolve, stream, length } = consume + try { - const pipelineHandler = new PipelineHandler(opts, handler) - this.dispatch({ ...opts, body: pipelineHandler.req }, pipelineHandler) - return pipelineHandler.ret + if (type === 'text') { + resolve(chunksDecode(body, length, encoding)) + } else if (type === 'json') { + resolve(JSON.parse(chunksDecode(body, length, encoding))) + } else if (type === 'arrayBuffer') { + resolve(chunksConcat(body, length).buffer) + } else if (type === 'blob') { + resolve(new Blob(body, { type: stream[kContentType] })) + } else if (type === 'bytes') { + resolve(chunksConcat(body, length)) + } + + consumeFinish(consume) } catch (err) { - return new PassThrough().destroy(err) + stream.destroy(err) } } -module.exports = pipeline +/** + * @param {Consume} consume + * @param {Buffer|string} chunk + * @returns {void} + */ +function consumePush (consume, chunk) { + if (consume.body === null) { + return + } + if (typeof chunk === 'string') { + // Buffered before the consume started, while an encoding was set. + // consume.length has to stay a byte count and chunksDecode()/chunksConcat() + // only work on bytes, so re-encode. A string's own length is in UTF-16 code + // units and Uint8Array.prototype.set() ignores a string argument entirely. + chunk = Buffer.from(chunk, consume.stream._readableState.encoding) + } -/***/ }), + consume.length += chunk.length + consume.body.push(chunk) +} -/***/ 9570: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/** + * @param {Consume} consume + * @param {Error} [err] + * @returns {void} + */ +function consumeFinish (consume, err) { + if (consume.body === null) { + return + } -"use strict"; + if (err) { + consume.reject(err) + } else { + consume.resolve() + } + // Reset the consume object to allow for garbage collection. + consume.type = null + consume.stream = null + consume.resolve = null + consume.reject = null + consume.length = 0 + consume.body = null +} -const assert = __nccwpck_require__(4589) -const { AsyncResource } = __nccwpck_require__(6698) -const { Readable } = __nccwpck_require__(2316) -const { InvalidArgumentError, RequestAbortedError } = __nccwpck_require__(7062) -const util = __nccwpck_require__(9705) +module.exports = { + Readable: BodyReadable, + chunksDecode +} -function noop () {} -class RequestHandler extends AsyncResource { - constructor (opts, callback) { - if (!opts || typeof opts !== 'object') { - throw new InvalidArgumentError('invalid opts') - } +/***/ }), - const { signal, method, opaque, body, onInfo, responseHeaders, highWaterMark } = opts +/***/ 750: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - try { - if (typeof callback !== 'function') { - throw new InvalidArgumentError('invalid callback') - } +"use strict"; - if (highWaterMark != null && (!Number.isFinite(highWaterMark) || highWaterMark < 0)) { - throw new InvalidArgumentError('invalid highWaterMark') - } - if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { - throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') - } +const { Writable } = __nccwpck_require__(7075) +const { EventEmitter } = __nccwpck_require__(8474) +const { assertCacheKey, assertCacheValue } = __nccwpck_require__(1164) - if (method === 'CONNECT') { - throw new InvalidArgumentError('invalid method') - } +/** + * @typedef {import('../../types/cache-interceptor.d.ts').default.CacheKey} CacheKey + * @typedef {import('../../types/cache-interceptor.d.ts').default.CacheValue} CacheValue + * @typedef {import('../../types/cache-interceptor.d.ts').default.CacheStore} CacheStore + * @typedef {import('../../types/cache-interceptor.d.ts').default.GetResult} GetResult + */ - if (onInfo && typeof onInfo !== 'function') { - throw new InvalidArgumentError('invalid onInfo callback') +/** + * @implements {CacheStore} + * @extends {EventEmitter} + */ +class MemoryCacheStore extends EventEmitter { + #maxCount = 1024 + #maxSize = 104857600 // 100MB + #maxEntrySize = 5242880 // 5MB + + #size = 0 + #count = 0 + #entries = new Map() + #hasEmittedMaxSizeEvent = false + + /** + * @param {import('../../types/cache-interceptor.d.ts').default.MemoryCacheStoreOpts | undefined} [opts] + */ + constructor (opts) { + super() + if (opts) { + if (typeof opts !== 'object') { + throw new TypeError('MemoryCacheStore options must be an object') } - super('UNDICI_REQUEST') - } catch (err) { - if (util.isStream(body)) { - util.destroy(body.on('error', noop), err) + if (opts.maxCount !== undefined) { + if ( + typeof opts.maxCount !== 'number' || + !Number.isInteger(opts.maxCount) || + opts.maxCount < 0 + ) { + throw new TypeError('MemoryCacheStore options.maxCount must be a non-negative integer') + } + this.#maxCount = opts.maxCount } - throw err - } - this.method = method - this.responseHeaders = responseHeaders || null - this.opaque = opaque || null - this.callback = callback - this.res = null - this.abort = null - this.body = body - this.trailers = {} - this.context = null - this.controller = null - this.onInfo = onInfo || null - this.highWaterMark = highWaterMark - this.reason = null - this.removeAbortListener = null + if (opts.maxSize !== undefined) { + if ( + typeof opts.maxSize !== 'number' || + !Number.isInteger(opts.maxSize) || + opts.maxSize < 0 + ) { + throw new TypeError('MemoryCacheStore options.maxSize must be a non-negative integer') + } + this.#maxSize = opts.maxSize + } - if (signal?.aborted) { - this.reason = signal.reason ?? new RequestAbortedError() - } else if (signal) { - this.removeAbortListener = util.addAbortListener(signal, () => { - this.reason = signal.reason ?? new RequestAbortedError() - if (this.res) { - // Null the reference before destroying, mirroring onResponseError, so - // that chunks flushed after the abort (e.g. an async decompressor - // flush) are dropped by the `!this.res` guard in onResponseData - // instead of being pushed into the torn-down stream. - const res = this.res - this.res = null - util.destroy(res.on('error', noop), this.reason) - } else if (this.abort) { - this.abort(this.reason) + if (opts.maxEntrySize !== undefined) { + if ( + typeof opts.maxEntrySize !== 'number' || + !Number.isInteger(opts.maxEntrySize) || + opts.maxEntrySize < 0 + ) { + throw new TypeError('MemoryCacheStore options.maxEntrySize must be a non-negative integer') } - }) + this.#maxEntrySize = opts.maxEntrySize + } } } - onRequestStart (controller, context) { - if (this.reason) { - controller.abort(this.reason) - return - } - - assert(this.callback) + /** + * Get the current size of the cache in bytes + * @returns {number} The current size of the cache in bytes + */ + get size () { + return this.#size + } - this.controller = controller - this.abort = (reason) => controller.abort(reason) - this.context = context + /** + * Check if the cache is full (either max size or max count reached) + * @returns {boolean} True if the cache is full, false otherwise + */ + isFull () { + return this.#size >= this.#maxSize || this.#count >= this.#maxCount } - onResponseStart (controller, statusCode, headers, statusText) { - const { callback, opaque, context, responseHeaders, highWaterMark } = this + /** + * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key + * @returns {import('../../types/cache-interceptor.d.ts').default.GetResult | undefined} + */ + get (key) { + assertCacheKey(key) - const rawHeaders = controller?.rawHeaders - const responseHeaderData = responseHeaders === 'raw' - ? util.parseRawHeaders(rawHeaders) - : headers + const topLevelKey = `${key.origin}:${key.path}` - if (statusCode < 200) { - if (this.onInfo) { - this.onInfo({ statusCode, headers: responseHeaderData }) - } - return - } + const now = Date.now() + const entries = this.#entries.get(topLevelKey) - const parsedHeaders = headers - const contentType = parsedHeaders?.['content-type'] - const contentLength = parsedHeaders?.['content-length'] - const res = new Readable({ - resume: () => controller.resume(), - abort: (reason) => controller.abort(reason), - contentType, - contentLength: this.method !== 'HEAD' && contentLength - ? Number(contentLength) - : null, - highWaterMark - }) + const entry = entries ? findEntry(key, entries, now) : null - if (this.removeAbortListener) { - res.on('close', this.removeAbortListener) - this.removeAbortListener = null - } + return entry == null + ? undefined + : { + statusMessage: entry.statusMessage, + statusCode: entry.statusCode, + headers: entry.headers, + body: entry.body, + vary: entry.vary ? entry.vary : undefined, + etag: entry.etag, + cacheControlDirectives: entry.cacheControlDirectives, + cachedAt: entry.cachedAt, + staleAt: entry.staleAt, + deleteAt: entry.deleteAt + } + } - this.callback = null - this.res = res - if (callback !== null) { - try { - this.runInAsyncScope(callback, null, null, { - statusCode, - statusText, - headers: responseHeaderData, - trailers: this.trailers, - opaque, - body: res, - context - }) - } catch (err) { - // If the callback throws synchronously, we need to handle it - // Remove reference to res to allow res being garbage collected - this.res = null + /** + * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key + * @param {import('../../types/cache-interceptor.d.ts').default.CacheValue} val + * @returns {Writable | undefined} + */ + createWriteStream (key, val) { + assertCacheKey(key) + assertCacheValue(val) - // Destroy the response stream - util.destroy(res.on('error', noop), err) + const topLevelKey = `${key.origin}:${key.path}` - // Use queueMicrotask to re-throw the error so it reaches uncaughtException - queueMicrotask(() => { - throw err - }) - } - } - } + const store = this + const entry = { ...key, ...val, body: [], size: 0 } - onResponseData (controller, chunk) { - if (!this.res) { - return - } + return new Writable({ + write (chunk, encoding, callback) { + if (typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding) + } - if (this.res.push(chunk) === false) { - controller.pause() - } - } + entry.size += chunk.byteLength - onResponseEnd (_controller, trailers) { - if (trailers && typeof trailers === 'object') { - for (const key of Object.keys(trailers)) { - if (key === '__proto__') { - Object.defineProperty(this.trailers, key, { - value: trailers[key], - enumerable: true, - configurable: true, - writable: true - }) + if (entry.size > store.#maxEntrySize) { + this.destroy() } else { - this.trailers[key] = trailers[key] + entry.body.push(chunk) } - } - } - this.res?.push(null) - } - - onResponseError (_controller, err) { - const { res, callback, body, opaque } = this - if (callback) { - // TODO: Does this need queueMicrotask? - this.callback = null - queueMicrotask(() => { - this.runInAsyncScope(callback, null, err, { opaque }) - }) - } + callback(null) + }, + final (callback) { + let entries = store.#entries.get(topLevelKey) + if (!entries) { + entries = [] + store.#entries.set(topLevelKey, entries) + } + const previousEntry = findEntry(key, entries, Date.now()) + if (previousEntry) { + const index = entries.indexOf(previousEntry) + entries.splice(index, 1, entry) + store.#size -= previousEntry.size + } else { + entries.push(entry) + store.#count += 1 + } - if (res) { - this.res = null - // Ensure all queued handlers are invoked before destroying res. - queueMicrotask(() => { - util.destroy(res.on('error', noop), err) - }) - } + store.#size += entry.size - if (body) { - this.body = null + // Check if cache is full and emit event if needed + if (store.#size > store.#maxSize || store.#count > store.#maxCount) { + // Emit maxSizeExceeded event if we haven't already + if (!store.#hasEmittedMaxSizeEvent) { + store.emit('maxSizeExceeded', { + size: store.#size, + maxSize: store.#maxSize, + count: store.#count, + maxCount: store.#maxCount + }) + store.#hasEmittedMaxSizeEvent = true + } - if (util.isStream(body)) { - body.on('error', noop) - util.destroy(body, err) - } - } + // Perform eviction + for (const [key, entries] of store.#entries) { + for (const entry of entries.splice(0, Math.ceil(entries.length / 2))) { + store.#size -= entry.size + store.#count -= 1 + } + if (entries.length === 0) { + store.#entries.delete(key) + } + } - if (this.removeAbortListener) { - this.removeAbortListener() - this.removeAbortListener = null - } - } -} + // Reset the event flag after eviction + if (store.#size < store.#maxSize && store.#count < store.#maxCount) { + store.#hasEmittedMaxSizeEvent = false + } + } -function request (opts, callback) { - if (callback === undefined) { - return new Promise((resolve, reject) => { - request.call(this, opts, (err, data) => { - return err ? reject(err) : resolve(data) - }) + callback(null) + } }) } - try { - const handler = new RequestHandler(opts, callback) - - this.dispatch(opts, handler) - } catch (err) { - if (typeof callback !== 'function') { - throw err + /** + * @param {CacheKey} key + */ + delete (key) { + if (typeof key !== 'object') { + throw new TypeError(`expected key to be object, got ${typeof key}`) } - const opaque = opts?.opaque - queueMicrotask(() => callback(err, { opaque })) - } -} - -module.exports = request -module.exports.RequestHandler = RequestHandler - - -/***/ }), - -/***/ 551: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -const assert = __nccwpck_require__(4589) -const { AsyncResource } = __nccwpck_require__(6698) -const { InvalidArgumentError, InvalidReturnValueError } = __nccwpck_require__(7062) -const util = __nccwpck_require__(9705) -const { addSignal, removeSignal } = __nccwpck_require__(3741) - -function noop () {} + const topLevelKey = `${key.origin}:${key.path}` -function getWritableError (stream) { - return stream.errored ?? stream.writableErrored ?? stream._writableState?.errored + for (const entry of this.#entries.get(topLevelKey) ?? []) { + this.#size -= entry.size + this.#count -= 1 + } + this.#entries.delete(topLevelKey) + } } -function createPrematureCloseError () { - const err = new Error('Premature close') - err.code = 'ERR_STREAM_PREMATURE_CLOSE' - return err +function findEntry (key, entries, now) { + for (let i = 0; i < entries.length; i++) { + const entry = entries[i] + if ( + entry.deleteAt > now && + entry.method === key.method && + varyMatches(key, entry) + ) { + return entry + } + } } -function trackWritableLifecycle (stream, callback) { - let done = false - - const cleanup = () => { - stream.removeListener('close', onClose) - stream.removeListener('error', onError) - stream.removeListener('finish', onFinish) +function varyMatches (key, entry) { + if (entry.vary == null) { + return true } - const finish = (err, fromErrorEvent = false) => { - if (done) { - return + for (const headerName in entry.vary) { + if (Object.hasOwn(entry.vary, headerName) && !headerValueEquals(key.headers?.[headerName], entry.vary[headerName])) { + return false } - - done = true - cleanup() - callback(err, fromErrorEvent) - } - - const onClose = () => { - const err = getWritableError(stream) - finish(err ?? (!stream.writableFinished ? createPrematureCloseError() : undefined)) } - const onError = (err) => finish(err, true) - const onFinish = () => finish() + return true +} - stream.on('close', onClose) - stream.on('error', onError) - stream.on('finish', onFinish) +/** + * @param {string|string[]|null|undefined} lhs + * @param {string|string[]|null|undefined} rhs + * @returns {boolean} + */ +function headerValueEquals (lhs, rhs) { + if (lhs == null && rhs == null) { + return true + } - if (stream.closed) { - process.nextTick(onClose) - } else if (stream.writableFinished) { - process.nextTick(onFinish) + if ((lhs == null && rhs != null) || + (lhs != null && rhs == null)) { + return false } -} -class StreamHandler extends AsyncResource { - constructor (opts, factory, callback) { - if (!opts || typeof opts !== 'object') { - throw new InvalidArgumentError('invalid opts') + if (Array.isArray(lhs) && Array.isArray(rhs)) { + if (lhs.length !== rhs.length) { + return false } - const { signal, method, opaque, body, onInfo, responseHeaders } = opts - - try { - if (typeof callback !== 'function') { - throw new InvalidArgumentError('invalid callback') + for (let i = 0; i < lhs.length; i++) { + if (lhs[i] !== rhs[i]) { + return false } + } - if (typeof factory !== 'function') { - throw new InvalidArgumentError('invalid factory') - } + return true + } - if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { - throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') - } + return lhs === rhs +} - if (method === 'CONNECT') { - throw new InvalidArgumentError('invalid method') - } +module.exports = MemoryCacheStore - if (onInfo && typeof onInfo !== 'function') { - throw new InvalidArgumentError('invalid onInfo callback') - } - super('UNDICI_STREAM') - } catch (err) { - if (util.isStream(body)) { - util.destroy(body.on('error', noop), err) - } - throw err - } +/***/ }), - this.responseHeaders = responseHeaders || null - this.opaque = opaque || null - this.factory = factory - this.callback = callback - this.res = null - this.abort = null - this.context = null - this.controller = null - this.trailers = null - this.body = body - this.onInfo = onInfo || null +/***/ 6169: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (util.isStream(body)) { - body.on('error', (err) => { - this.onResponseError(this.controller, err) - }) - } +"use strict"; - addSignal(this, signal) - } - onRequestStart (controller, context) { - if (this.reason) { - controller.abort(this.reason) - return - } +const { Writable } = __nccwpck_require__(7075) +const { assertCacheKey, assertCacheValue } = __nccwpck_require__(1164) - assert(this.callback) +let DatabaseSync - this.controller = controller - this.abort = (reason) => controller.abort(reason) - this.context = context - } +const VERSION = 3 - onResponseStart (controller, statusCode, headers, _statusMessage) { - const { factory, opaque, context, responseHeaders } = this +// 2gb +const MAX_ENTRY_SIZE = 2 * 1000 * 1000 * 1000 - const rawHeaders = controller?.rawHeaders - const responseHeaderData = responseHeaders === 'raw' - ? util.parseRawHeaders(rawHeaders) - : headers +/** + * @typedef {import('../../types/cache-interceptor.d.ts').default.CacheStore} CacheStore + * @implements {CacheStore} + * + * @typedef {{ + * id: Readonly, + * body?: Uint8Array + * statusCode: number + * statusMessage: string + * headers?: string + * vary?: string + * etag?: string + * cacheControlDirectives?: string + * cachedAt: number + * staleAt: number + * deleteAt: number + * }} SqliteStoreValue + */ +module.exports = class SqliteCacheStore { + #maxEntrySize = MAX_ENTRY_SIZE + #maxCount = Infinity - if (statusCode < 200) { - if (this.onInfo) { - this.onInfo({ statusCode, headers: responseHeaderData }) - } - return - } + /** + * @type {import('node:sqlite').DatabaseSync} + */ + #db - this.factory = null + /** + * @type {import('node:sqlite').StatementSync} + */ + #getValuesQuery - if (factory === null) { - return - } + /** + * @type {import('node:sqlite').StatementSync} + */ + #updateValueQuery - const res = this.runInAsyncScope(factory, null, { - statusCode, - headers: responseHeaderData, - opaque, - context - }) + /** + * @type {import('node:sqlite').StatementSync} + */ + #insertValueQuery - if ( - !res || - typeof res.write !== 'function' || - typeof res.end !== 'function' || - typeof res.on !== 'function' - ) { - throw new InvalidReturnValueError('expected Writable') - } + /** + * @type {import('node:sqlite').StatementSync} + */ + #deleteExpiredValuesQuery - trackWritableLifecycle(res, (err, fromErrorEvent) => { - const { callback, res, opaque, trailers, abort } = this + /** + * @type {import('node:sqlite').StatementSync} + */ + #deleteByUrlQuery - this.res = null - if (err || !res?.readable) { - util.destroy(res, fromErrorEvent ? undefined : err) - } + /** + * @type {import('node:sqlite').StatementSync} + */ + #countEntriesQuery - this.callback = null - this.runInAsyncScope(callback, null, err || null, { opaque, trailers }) + /** + * @type {import('node:sqlite').StatementSync | null} + */ + #deleteOldValuesQuery - if (err) { - abort(err) + /** + * @param {import('../../types/cache-interceptor.d.ts').default.SqliteCacheStoreOpts | undefined} opts + */ + constructor (opts) { + if (opts) { + if (typeof opts !== 'object') { + throw new TypeError('SqliteCacheStore options must be an object') } - }) - - res.on('drain', () => controller.resume()) - this.res = res - - const needDrain = res.writableNeedDrain !== undefined - ? res.writableNeedDrain - : res._writableState?.needDrain + if (opts.maxEntrySize !== undefined) { + if ( + typeof opts.maxEntrySize !== 'number' || + !Number.isInteger(opts.maxEntrySize) || + opts.maxEntrySize < 0 + ) { + throw new TypeError('SqliteCacheStore options.maxEntrySize must be a non-negative integer') + } - if (needDrain === true) { - controller.pause() - } - } + if (opts.maxEntrySize > MAX_ENTRY_SIZE) { + throw new TypeError('SqliteCacheStore options.maxEntrySize must be less than 2gb') + } - onResponseData (controller, chunk) { - const { res } = this + this.#maxEntrySize = opts.maxEntrySize + } - if (!res) { - return + if (opts.maxCount !== undefined) { + if ( + typeof opts.maxCount !== 'number' || + !Number.isInteger(opts.maxCount) || + opts.maxCount < 0 + ) { + throw new TypeError('SqliteCacheStore options.maxCount must be a non-negative integer') + } + this.#maxCount = opts.maxCount + } } - if (res.write(chunk) === false) { - controller.pause() + if (!DatabaseSync) { + DatabaseSync = (__nccwpck_require__(99).DatabaseSync) } - } - - onResponseEnd (_controller, trailers) { - const { res } = this + this.#db = new DatabaseSync(opts?.location ?? ':memory:') - removeSignal(this) + this.#db.exec(` + PRAGMA journal_mode = WAL; + PRAGMA synchronous = NORMAL; + PRAGMA temp_store = memory; + PRAGMA optimize; - if (!res) { - return - } + CREATE TABLE IF NOT EXISTS cacheInterceptorV${VERSION} ( + -- Data specific to us + id INTEGER PRIMARY KEY AUTOINCREMENT, + url TEXT NOT NULL, + method TEXT NOT NULL, - if (trailers && typeof trailers === 'object') { - this.trailers = trailers - } + -- Data returned to the interceptor + body BUF NULL, + deleteAt INTEGER NOT NULL, + statusCode INTEGER NOT NULL, + statusMessage TEXT NOT NULL, + headers TEXT NULL, + cacheControlDirectives TEXT NULL, + etag TEXT NULL, + vary TEXT NULL, + cachedAt INTEGER NOT NULL, + staleAt INTEGER NOT NULL + ); - res.end() - } + CREATE INDEX IF NOT EXISTS idx_cacheInterceptorV${VERSION}_getValuesQuery ON cacheInterceptorV${VERSION}(url, method, deleteAt); + CREATE INDEX IF NOT EXISTS idx_cacheInterceptorV${VERSION}_deleteByUrlQuery ON cacheInterceptorV${VERSION}(deleteAt); + `) - onResponseError (_controller, err) { - const { res, callback, opaque, body } = this + this.#getValuesQuery = this.#db.prepare(` + SELECT + id, + body, + deleteAt, + statusCode, + statusMessage, + headers, + etag, + cacheControlDirectives, + vary, + cachedAt, + staleAt + FROM cacheInterceptorV${VERSION} + WHERE + url = ? + AND method = ? + ORDER BY + deleteAt ASC + `) - removeSignal(this) + this.#updateValueQuery = this.#db.prepare(` + UPDATE cacheInterceptorV${VERSION} SET + body = ?, + deleteAt = ?, + statusCode = ?, + statusMessage = ?, + headers = ?, + etag = ?, + cacheControlDirectives = ?, + vary = ?, + cachedAt = ?, + staleAt = ? + WHERE + id = ? + `) - this.factory = null + this.#insertValueQuery = this.#db.prepare(` + INSERT INTO cacheInterceptorV${VERSION} ( + url, + method, + body, + deleteAt, + statusCode, + statusMessage, + headers, + etag, + cacheControlDirectives, + vary, + cachedAt, + staleAt + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + `) - if (res) { - this.res = null - util.destroy(res, err) - } else if (callback) { - this.callback = null - queueMicrotask(() => { - this.runInAsyncScope(callback, null, err, { opaque }) - }) - } + this.#deleteByUrlQuery = this.#db.prepare( + `DELETE FROM cacheInterceptorV${VERSION} WHERE url = ?` + ) - if (body) { - this.body = null - util.destroy(body, err) - } + this.#countEntriesQuery = this.#db.prepare( + `SELECT COUNT(*) AS total FROM cacheInterceptorV${VERSION}` + ) + + this.#deleteExpiredValuesQuery = this.#db.prepare( + `DELETE FROM cacheInterceptorV${VERSION} WHERE deleteAt <= ?` + ) + + this.#deleteOldValuesQuery = this.#maxCount === Infinity + ? null + : this.#db.prepare(` + DELETE FROM cacheInterceptorV${VERSION} + WHERE id IN ( + SELECT + id + FROM cacheInterceptorV${VERSION} + ORDER BY cachedAt ASC + LIMIT ? + ) + `) } -} -function stream (opts, factory, callback) { - if (callback === undefined) { - return new Promise((resolve, reject) => { - stream.call(this, opts, factory, (err, data) => { - return err ? reject(err) : resolve(data) - }) - }) + close () { + this.#db.close() } - try { - const handler = new StreamHandler(opts, factory, callback) + /** + * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key + * @returns {(import('../../types/cache-interceptor.d.ts').default.GetResult & { body?: Buffer }) | undefined} + */ + get (key) { + assertCacheKey(key) - this.dispatch(opts, handler) - } catch (err) { - if (typeof callback !== 'function') { - throw err - } - const opaque = opts?.opaque - queueMicrotask(() => callback(err, { opaque })) + const value = this.#findValue(key) + return value + ? { + body: value.body ? Buffer.from(value.body.buffer, value.body.byteOffset, value.body.byteLength) : undefined, + statusCode: value.statusCode, + statusMessage: value.statusMessage, + headers: value.headers ? JSON.parse(value.headers) : undefined, + etag: value.etag ? value.etag : undefined, + vary: value.vary ? JSON.parse(value.vary) : undefined, + cacheControlDirectives: value.cacheControlDirectives + ? JSON.parse(value.cacheControlDirectives) + : undefined, + cachedAt: value.cachedAt, + staleAt: value.staleAt, + deleteAt: value.deleteAt + } + : undefined } -} - -module.exports = stream + /** + * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key + * @param {import('../../types/cache-interceptor.d.ts').default.CacheValue & { body: null | Buffer | Array}} value + */ + set (key, value) { + assertCacheKey(key) -/***/ }), + const url = this.#makeValueUrl(key) + const body = Array.isArray(value.body) ? Buffer.concat(value.body) : value.body + const size = body?.byteLength -/***/ 5947: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (size && size > this.#maxEntrySize) { + return + } -"use strict"; + const existingValue = this.#findValue(key, true) + if (existingValue) { + // Updating an existing response, let's overwrite it + this.#updateValueQuery.run( + body, + value.deleteAt, + value.statusCode, + value.statusMessage, + value.headers ? JSON.stringify(value.headers) : null, + value.etag ? value.etag : null, + value.cacheControlDirectives ? JSON.stringify(value.cacheControlDirectives) : null, + value.vary ? JSON.stringify(value.vary) : null, + value.cachedAt, + value.staleAt, + existingValue.id + ) + } else { + // New response, let's insert it + this.#insertValueQuery.run( + url, + key.method, + body, + value.deleteAt, + value.statusCode, + value.statusMessage, + value.headers ? JSON.stringify(value.headers) : null, + value.etag ? value.etag : null, + value.cacheControlDirectives ? JSON.stringify(value.cacheControlDirectives) : null, + value.vary ? JSON.stringify(value.vary) : null, + value.cachedAt, + value.staleAt + ) + this.#prune() + } + } + /** + * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key + * @param {import('../../types/cache-interceptor.d.ts').default.CacheValue} value + * @returns {Writable | undefined} + */ + createWriteStream (key, value) { + assertCacheKey(key) + assertCacheValue(value) -const { InvalidArgumentError, SocketError } = __nccwpck_require__(7062) -const { AsyncResource } = __nccwpck_require__(6698) -const assert = __nccwpck_require__(4589) -const util = __nccwpck_require__(9705) -const { kHTTP2Stream } = __nccwpck_require__(7480) -const { addSignal, removeSignal } = __nccwpck_require__(3741) + let size = 0 + /** + * @type {Buffer[] | null} + */ + const body = [] + const store = this -class UpgradeHandler extends AsyncResource { - constructor (opts, callback) { - if (!opts || typeof opts !== 'object') { - throw new InvalidArgumentError('invalid opts') - } + return new Writable({ + decodeStrings: true, + write (chunk, encoding, callback) { + size += chunk.byteLength - if (typeof callback !== 'function') { - throw new InvalidArgumentError('invalid callback') - } + if (size <= store.#maxEntrySize) { + body.push(chunk) + } else { + this.destroy() + } - const { signal, opaque, responseHeaders } = opts + callback() + }, + final (callback) { + store.set(key, { ...value, body }) + callback() + } + }) + } - if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { - throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + /** + * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key + */ + delete (key) { + if (typeof key !== 'object') { + throw new TypeError(`expected key to be object, got ${typeof key}`) } - super('UNDICI_UPGRADE') - - this.responseHeaders = responseHeaders || null - this.opaque = opaque || null - this.callback = callback - this.abort = null - this.context = null - - addSignal(this, signal) + this.#deleteByUrlQuery.run(this.#makeValueUrl(key)) } - onRequestStart (controller, context) { - if (this.reason) { - controller.abort(this.reason) - return + #prune () { + if (Number.isFinite(this.#maxCount) && this.size <= this.#maxCount) { + return 0 } - assert(this.callback) + { + const removed = this.#deleteExpiredValuesQuery.run(Date.now()).changes + if (removed) { + return removed + } + } - this.abort = (reason) => controller.abort(reason) - this.context = context - } + { + const removed = this.#deleteOldValuesQuery?.run(Math.max(Math.floor(this.#maxCount * 0.1), 1)).changes + if (removed) { + return removed + } + } - onResponseStart () { - throw new SocketError('bad upgrade', null) + return 0 } - onRequestUpgrade (controller, statusCode, headers, socket) { - const expectedStatusCode = socket[kHTTP2Stream] === true ? 200 : 101 + /** + * Counts the number of rows in the cache + * @returns {Number} + */ + get size () { + const { total } = this.#countEntriesQuery.get() + return total + } - if (statusCode !== expectedStatusCode) { - const socketInfo = socket[kHTTP2Stream] === true ? null : util.getSocketInfo(socket) - controller.abort(new SocketError('bad upgrade', socketInfo)) - return - } + /** + * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key + * @returns {string} + */ + #makeValueUrl (key) { + return `${key.origin}/${key.path}` + } - const { callback, opaque, context } = this + /** + * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key + * @param {boolean} [canBeExpired=false] + * @returns {SqliteStoreValue | undefined} + */ + #findValue (key, canBeExpired = false) { + const url = this.#makeValueUrl(key) + const { headers, method } = key - removeSignal(this) + /** + * @type {SqliteStoreValue[]} + */ + const values = this.#getValuesQuery.all(url, method) - this.callback = null + if (values.length === 0) { + return undefined + } - const rawHeaders = controller?.rawHeaders - const responseHeaders = this.responseHeaders === 'raw' - ? util.parseRawHeaders(rawHeaders) - : headers + const now = Date.now() + for (const value of values) { + if (now >= value.deleteAt && !canBeExpired) { + continue + } - this.runInAsyncScope(callback, null, null, { - headers: responseHeaders, - socket, - opaque, - context - }) - } + let matches = true - onResponseError (_controller, err) { - const { callback, opaque } = this + if (value.vary) { + const vary = JSON.parse(value.vary) - removeSignal(this) + for (const header in vary) { + if (!headerValueEquals(headers[header], vary[header])) { + matches = false + break + } + } + } - if (callback) { - this.callback = null - queueMicrotask(() => { - this.runInAsyncScope(callback, null, err, { opaque }) - }) + if (matches) { + return value + } } + + return undefined } } -function upgrade (opts, callback) { - if (callback === undefined) { - return new Promise((resolve, reject) => { - upgrade.call(this, opts, (err, data) => { - return err ? reject(err) : resolve(data) - }) - }) +/** + * @param {string|string[]|null|undefined} lhs + * @param {string|string[]|null|undefined} rhs + * @returns {boolean} + */ +function headerValueEquals (lhs, rhs) { + if (lhs == null && rhs == null) { + return true } - try { - const upgradeHandler = new UpgradeHandler(opts, callback) - const upgradeOpts = { - ...opts, - method: opts.method || 'GET', - upgrade: opts.protocol || 'Websocket' - } - this.dispatch(upgradeOpts, upgradeHandler) - } catch (err) { - if (typeof callback !== 'function') { - throw err - } - const opaque = opts?.opaque - queueMicrotask(() => callback(err, { opaque })) + if ((lhs == null && rhs != null) || + (lhs != null && rhs == null)) { + return false } -} - -module.exports = upgrade - - -/***/ }), -/***/ 4806: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (Array.isArray(lhs) && Array.isArray(rhs)) { + if (lhs.length !== rhs.length) { + return false + } -"use strict"; + for (let i = 0; i < lhs.length; i++) { + if (lhs[i] !== rhs[i]) { + return false + } + } + return true + } -module.exports.request = __nccwpck_require__(9570) -module.exports.stream = __nccwpck_require__(551) -module.exports.pipeline = __nccwpck_require__(6793) -module.exports.upgrade = __nccwpck_require__(5947) -module.exports.connect = __nccwpck_require__(9105) + return lhs === rhs +} /***/ }), -/***/ 2316: +/***/ 8203: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; +const net = __nccwpck_require__(7030) const assert = __nccwpck_require__(4589) -const { addAbortListener } = __nccwpck_require__(8474) -const { Readable } = __nccwpck_require__(7075) -const { RequestAbortedError, NotSupportedError, InvalidArgumentError, AbortError } = __nccwpck_require__(7062) -const util = __nccwpck_require__(9705) +const util = __nccwpck_require__(9277) +const { InvalidArgumentError, ConnectTimeoutError } = __nccwpck_require__(4882) -const kConsume = Symbol('kConsume') -const kReading = Symbol('kReading') -const kBody = Symbol('kBody') -const kAbort = Symbol('kAbort') -const kContentType = Symbol('kContentType') -const kContentLength = Symbol('kContentLength') -const kUsed = Symbol('kUsed') -const kBytesRead = Symbol('kBytesRead') +let tls // include tls conditionally since it is not always available -const noop = () => {} +// TODO: session re-use does not wait for the first +// connection to resolve the session and might therefore +// resolve the same servername multiple times even when +// re-use is enabled. -/** - * @class - * @extends {Readable} - * @see https://fetch.spec.whatwg.org/#body - */ -class BodyReadable extends Readable { - /** - * @param {object} opts - * @param {(this: Readable, size: number) => void} opts.resume - * @param {() => (void | null)} opts.abort - * @param {string} [opts.contentType = ''] - * @param {number} [opts.contentLength] - * @param {number} [opts.highWaterMark = 64 * 1024] - */ - constructor ({ - resume, - abort, - contentType = '', - contentLength, - highWaterMark = 64 * 1024 // Same as nodejs fs streams. - }) { - super({ - autoDestroy: true, - read: resume, - highWaterMark - }) +const SessionCache = class WeakSessionCache { + constructor (maxCachedSessions) { + this._maxCachedSessions = maxCachedSessions + this._sessionCache = new Map() + this._sessionRegistry = new FinalizationRegistry((key) => { + if (this._sessionCache.size < this._maxCachedSessions) { + return + } - this._readableState.dataEmitted = false + const ref = this._sessionCache.get(key) + if (ref !== undefined && ref.deref() === undefined) { + this._sessionCache.delete(key) + } + }) + } - this[kAbort] = abort + get (sessionKey) { + const ref = this._sessionCache.get(sessionKey) + return ref ? ref.deref() : null + } - /** @type {Consume | null} */ - this[kConsume] = null + set (sessionKey, session) { + if (this._maxCachedSessions === 0) { + return + } - /** @type {number} */ - this[kBytesRead] = 0 + if (this._sessionCache.has(sessionKey)) { + this._sessionCache.delete(sessionKey) + } else if (this._sessionCache.size >= this._maxCachedSessions) { + for (const [key, ref] of this._sessionCache) { + if (ref.deref() === undefined) { + this._sessionCache.delete(key) + return + } + } - /** @type {ReadableStream|null} */ - this[kBody] = null - - /** @type {boolean} */ - this[kUsed] = false - - /** @type {string} */ - this[kContentType] = contentType - - /** @type {number|null} */ - this[kContentLength] = Number.isFinite(contentLength) ? contentLength : null - - /** - * Is stream being consumed through Readable API? - * This is an optimization so that we avoid checking - * for 'data' and 'readable' listeners in the hot path - * inside push(). - * - * @type {boolean} - */ - this[kReading] = false - } - - /** - * @param {Error|null} err - * @param {(error:(Error|null)) => void} callback - * @returns {void} - */ - _destroy (err, callback) { - if (!err && !this._readableState.endEmitted) { - err = new RequestAbortedError() - } - - if (err) { - this[kAbort]() - } - - // Workaround for Node "bug". If the stream is destroyed in same - // tick as it is created, then a user who is waiting for a - // promise (i.e micro tick) for installing an 'error' listener will - // never get a chance and will always encounter an unhandled exception. - if (!this[kUsed]) { - setImmediate(callback, err) - } else { - callback(err) - } - } - - /** - * @param {string|symbol} event - * @param {(...args: any[]) => void} listener - * @returns {this} - */ - on (event, listener) { - if (event === 'data' || event === 'readable') { - this[kReading] = true - this[kUsed] = true + const oldest = this._sessionCache.keys().next() + if (!oldest.done) { + this._sessionCache.delete(oldest.value) + } } - return super.on(event, listener) - } - - /** - * @param {string|symbol} event - * @param {(...args: any[]) => void} listener - * @returns {this} - */ - addListener (event, listener) { - return this.on(event, listener) - } - /** - * @param {string|symbol} event - * @param {(...args: any[]) => void} listener - * @returns {this} - */ - off (event, listener) { - const ret = super.off(event, listener) - if (event === 'data' || event === 'readable') { - this[kReading] = ( - this.listenerCount('data') > 0 || - this.listenerCount('readable') > 0 - ) - } - return ret + this._sessionCache.set(sessionKey, new WeakRef(session)) + this._sessionRegistry.register(session, sessionKey) } +} - /** - * @param {string|symbol} event - * @param {(...args: any[]) => void} listener - * @returns {this} - */ - removeListener (event, listener) { - return this.off(event, listener) +function buildConnector ({ allowH2, preferH2, useH2c, maxCachedSessions, socketPath, timeout, session: customSession, ...opts }) { + if (maxCachedSessions != null && (!Number.isInteger(maxCachedSessions) || maxCachedSessions < 0)) { + throw new InvalidArgumentError('maxCachedSessions must be a positive integer or zero') } - /** - * @param {Buffer|null} chunk - * @returns {boolean} - */ - push (chunk) { - if (chunk) { - this[kBytesRead] += chunk.length - if (this[kConsume]) { - consumePush(this[kConsume], chunk) - return this[kReading] ? super.push(chunk) : true + const options = { path: socketPath, ...opts } + const sessionCache = new SessionCache(maxCachedSessions == null ? 100 : maxCachedSessions) + timeout = timeout == null ? 10e3 : timeout + allowH2 = allowH2 != null ? allowH2 : true + return function connect ({ hostname, host, protocol, port, servername, localAddress, httpSocket }, callback) { + let socket + if (protocol === 'https:') { + if (!tls) { + tls = __nccwpck_require__(1692) } - } - - return super.push(chunk) - } - - /** - * Consumes and returns the body as a string. - * - * @see https://fetch.spec.whatwg.org/#dom-body-text - * @returns {Promise} - */ - text () { - return consume(this, 'text') - } + servername = servername || options.servername || util.getServerName(host) || null - /** - * Consumes and returns the body as a JavaScript Object. - * - * @see https://fetch.spec.whatwg.org/#dom-body-json - * @returns {Promise} - */ - json () { - return consume(this, 'json') - } + const sessionKey = servername || hostname + assert(sessionKey) - /** - * Consumes and returns the body as a Blob - * - * @see https://fetch.spec.whatwg.org/#dom-body-blob - * @returns {Promise} - */ - blob () { - return consume(this, 'blob') - } + const session = customSession || sessionCache.get(sessionKey) || null - /** - * Consumes and returns the body as an Uint8Array. - * - * @see https://fetch.spec.whatwg.org/#dom-body-bytes - * @returns {Promise} - */ - bytes () { - return consume(this, 'bytes') - } + port = port || 443 - /** - * Consumes and returns the body as an ArrayBuffer. - * - * @see https://fetch.spec.whatwg.org/#dom-body-arraybuffer - * @returns {Promise} - */ - arrayBuffer () { - return consume(this, 'arrayBuffer') - } + socket = tls.connect({ + highWaterMark: 16384, // TLS in node can't have bigger HWM anyway... + ...options, + servername, + session, + localAddress, + ALPNProtocols: allowH2 ? (preferH2 ? ['h2', 'http/1.1'] : ['http/1.1', 'h2']) : ['http/1.1'], + socket: httpSocket, // upgrade socket connection + port, + host: hostname + }) - /** - * Not implemented - * - * @see https://fetch.spec.whatwg.org/#dom-body-formdata - * @throws {NotSupportedError} - */ - async formData () { - // TODO: Implement. - throw new NotSupportedError() - } + socket + .on('session', function (session) { + // TODO (fix): Can a session become invalid once established? Don't think so? + sessionCache.set(sessionKey, session) + }) + } else { + assert(!httpSocket, 'httpSocket can only be sent on TLS update') - /** - * Returns true if the body is not null and the body has been consumed. - * Otherwise, returns false. - * - * @see https://fetch.spec.whatwg.org/#dom-body-bodyused - * @readonly - * @returns {boolean} - */ - get bodyUsed () { - return util.isDisturbed(this) - } + port = port || 80 - /** - * @see https://fetch.spec.whatwg.org/#dom-body-body - * @readonly - * @returns {ReadableStream} - */ - get body () { - if (!this[kBody]) { - this[kBody] = ReadableStream.from(this) - if (this[kConsume]) { - // TODO: Is this the best way to force a lock? - this[kBody].getReader() // Ensure stream is locked. - assert(this[kBody].locked) + const connectOptions = { + highWaterMark: 64 * 1024, // Same as nodejs fs streams. + ...options, + localAddress, + port, + host: hostname } - } - return this[kBody] - } - /** - * Dumps the response body by reading `limit` number of bytes. - * @param {object} opts - * @param {number} [opts.limit = 131072] Number of bytes to read. - * @param {AbortSignal} [opts.signal] An AbortSignal to cancel the dump. - * @returns {Promise} - */ - dump (opts) { - const signal = opts?.signal + const family = net.isIP(hostname) + if (family !== 0 && servername && servername !== hostname) { + connectOptions.host = servername + connectOptions.lookup = (_hostname, lookupOptions, cb) => { + if (lookupOptions.all) { + cb(null, [{ address: hostname, family }]) + } else { + cb(null, hostname, family) + } + } + } - if (signal != null && (typeof signal !== 'object' || !('aborted' in signal))) { - return Promise.reject(new InvalidArgumentError('signal must be an AbortSignal')) + socket = net.connect(connectOptions) + if (useH2c === true) { + socket.alpnProtocol = 'h2' + } } - const limit = opts?.limit && Number.isFinite(opts.limit) - ? opts.limit - : 128 * 1024 - - if (signal?.aborted) { - return Promise.reject(signal.reason ?? new AbortError()) + // Set TCP keep alive options on the socket here instead of in connect() for the case of assigning the socket + if (options.keepAlive == null || options.keepAlive) { + const keepAliveInitialDelay = options.keepAliveInitialDelay === undefined ? 60e3 : options.keepAliveInitialDelay + socket.setKeepAlive(true, keepAliveInitialDelay) } - if (this._readableState.closeEmitted) { - return Promise.resolve(null) - } + const clearConnectTimeout = util.setupConnectTimeout(new WeakRef(socket), { timeout, hostname, port }) - return new Promise((resolve, reject) => { - if ( - (this[kContentLength] && (this[kContentLength] > limit)) || - this[kBytesRead] > limit - ) { - this.destroy(new AbortError()) - } + socket + .setNoDelay(true) + .once(protocol === 'https:' ? 'secureConnect' : 'connect', function () { + queueMicrotask(clearConnectTimeout) - if (signal) { - const onAbort = () => { - this.destroy(signal.reason ?? new AbortError()) + if (callback) { + const cb = callback + callback = null + cb(null, this) } - const abortListener = addAbortListener(signal, onAbort) - this - .on('close', function () { - abortListener[Symbol.dispose]() - if (signal.aborted) { - reject(signal.reason ?? new AbortError()) - } else { - resolve(null) - } - }) - } else { - this.on('close', resolve) - } + }) + .on('error', function (err) { + queueMicrotask(clearConnectTimeout) - this - .on('error', noop) - .on('data', () => { - if (this[kBytesRead] > limit) { - this.destroy() - } - }) - .resume() - }) - } + if (callback) { + const cb = callback + callback = null + cb(maybeNormalizeConnectError(err, this, { timeout, hostname, port })) + } + }) - /** - * @param {BufferEncoding} encoding - * @returns {this} - */ - setEncoding (encoding) { - if (Buffer.isEncoding(encoding)) { - // Delegate to Node.js Readable.setEncoding() which initializes a - // StringDecoder and re-encodes already-buffered chunks. This properly - // handles multi-byte sequences split at chunk boundaries for the - // for-await / on('data') paths. Without this, Node.js uses - // buf.toString(encoding) on each chunk, producing U+FFFD for split chars. - // - // The consume path (body.text(), body.json(), ...) copes with the - // decoded strings this leaves in state.buffer, see consumeStart(). - super.setEncoding(encoding) - } - return this + return socket } } -/** - * @see https://streams.spec.whatwg.org/#readablestream-locked - * @param {BodyReadable} bodyReadable - * @returns {boolean} - */ -function isLocked (bodyReadable) { - // Consume is an implicit lock. - return bodyReadable[kBody]?.locked === true || bodyReadable[kConsume] !== null -} - -/** - * @see https://fetch.spec.whatwg.org/#body-unusable - * @param {BodyReadable} bodyReadable - * @returns {boolean} - */ -function isUnusable (bodyReadable) { - return util.isDisturbed(bodyReadable) || isLocked(bodyReadable) -} - -/** - * @typedef {'text' | 'json' | 'blob' | 'bytes' | 'arrayBuffer'} ConsumeType - */ - -/** - * @template {ConsumeType} T - * @typedef {T extends 'text' ? string : - * T extends 'json' ? unknown : - * T extends 'blob' ? Blob : - * T extends 'arrayBuffer' ? ArrayBuffer : - * T extends 'bytes' ? Uint8Array : - * never - * } ConsumeReturnType - */ -/** - * @typedef {object} Consume - * @property {ConsumeType} type - * @property {BodyReadable} stream - * @property {((value?: any) => void)} resolve - * @property {((err: Error) => void)} reject - * @property {number} length - * @property {Buffer[]} body - */ - -/** - * @template {ConsumeType} T - * @param {BodyReadable} stream - * @param {T} type - * @returns {Promise>} - */ -function consume (stream, type) { - assert(!stream[kConsume]) - - return new Promise((resolve, reject) => { - if (isUnusable(stream)) { - const rState = stream._readableState - if (rState.destroyed && rState.closeEmitted === false) { - stream - .on('error', reject) - .on('close', () => { - reject(new TypeError('unusable')) - }) - } else { - reject(rState.errored ?? new TypeError('unusable')) - } +// `net.connect` with `autoSelectFamily` raises an `AggregateError` when every +// attempted address fails. If any of those failures is a timeout, surface the +// error as a `ConnectTimeoutError` so callers see the same error regardless of +// which timer (Node's internal one or undici's `connectTimeout`) wins the race. +// The original `AggregateError` is preserved on `.cause`. +function maybeNormalizeConnectError (err, socket, opts) { + if ( + err instanceof AggregateError && + (err.code === 'ETIMEDOUT' || err.errors.some((e) => e != null && e.code === 'ETIMEDOUT')) + ) { + let message = 'Connect Timeout Error' + if (Array.isArray(socket.autoSelectFamilyAttemptedAddresses)) { + message += ` (attempted addresses: ${socket.autoSelectFamilyAttemptedAddresses.join(', ')},` } else { - queueMicrotask(() => { - stream[kConsume] = { - type, - stream, - resolve, - reject, - length: 0, - body: [] - } - - stream - .on('error', function (err) { - consumeFinish(this[kConsume], err) - }) - .on('close', function () { - if (this[kConsume].body !== null) { - consumeFinish(this[kConsume], new RequestAbortedError()) - } - }) - - consumeStart(stream[kConsume]) - }) + message += ` (attempted address: ${opts.hostname}:${opts.port},` } - }) -} + message += ` timeout: ${opts.timeout}ms)` -/** - * @param {Consume} consume - * @returns {void} - */ -function consumeStart (consume) { - if (consume.body === null) { - return + const wrapped = new ConnectTimeoutError(message) + wrapped.cause = err + return wrapped } + return err +} - const { _readableState: state } = consume.stream - - if (state.bufferIndex) { - const start = state.bufferIndex - const end = state.buffer.length - for (let n = start; n < end; n++) { - consumePush(consume, state.buffer[n]) - } - } else { - for (const chunk of state.buffer) { - consumePush(consume, chunk) - } - } +module.exports = buildConnector - // If setEncoding() was called, state.buffer holds decoded strings, which - // consumePush() turns back into bytes. The trailing bytes of a multi-byte - // sequence split across a chunk boundary are not part of any of those - // strings, they are held inside the decoder until the rest arrives, so - // take them from there. - const decoder = state.decoder - if (decoder != null && decoder.lastNeed > 0) { - consumePush(consume, Buffer.from(decoder.lastChar.subarray(0, decoder.lastTotal - decoder.lastNeed))) - } - if (state.endEmitted) { - // No `this` to read the consume off here: consumeStart is a free function, called from - // the queueMicrotask above. The callback below does have one, because the emitter passes - // the stream as its receiver. Returning matters too - consumeEnd() clears consume.stream, - // which the resume() below would then dereference. - consumeEnd(consume, state.encoding) - return - } +/***/ }), - consume.stream.on('end', function () { - consumeEnd(this[kConsume], this._readableState.encoding) - }) +/***/ 5188: +/***/ ((module) => { - consume.stream.resume() +"use strict"; - while (consume.stream.read() != null) { - // Loop - } -} /** - * @param {Buffer[]} chunks - * @param {number} length - * @param {BufferEncoding} [encoding='utf8'] - * @returns {string} + * @see https://developer.mozilla.org/docs/Web/HTTP/Headers */ -function chunksDecode (chunks, length, encoding) { - if (chunks.length === 0 || length === 0) { - return '' - } - const buffer = chunks.length === 1 ? chunks[0] : Buffer.concat(chunks, length) - const bufferLength = buffer.length - - // Skip BOM. - const start = - bufferLength > 2 && - buffer[0] === 0xef && - buffer[1] === 0xbb && - buffer[2] === 0xbf - ? 3 - : 0 - if (!encoding || encoding === 'utf8' || encoding === 'utf-8') { - return buffer.utf8Slice(start, bufferLength) - } else { - return buffer.subarray(start, bufferLength).toString(encoding) - } -} +const wellknownHeaderNames = /** @type {const} */ ([ + 'Accept', + 'Accept-Encoding', + 'Accept-Language', + 'Accept-Ranges', + 'Access-Control-Allow-Credentials', + 'Access-Control-Allow-Headers', + 'Access-Control-Allow-Methods', + 'Access-Control-Allow-Origin', + 'Access-Control-Expose-Headers', + 'Access-Control-Max-Age', + 'Access-Control-Request-Headers', + 'Access-Control-Request-Method', + 'Age', + 'Allow', + 'Alt-Svc', + 'Alt-Used', + 'Authorization', + 'Cache-Control', + 'Clear-Site-Data', + 'Connection', + 'Content-Disposition', + 'Content-Encoding', + 'Content-Language', + 'Content-Length', + 'Content-Location', + 'Content-Range', + 'Content-Security-Policy', + 'Content-Security-Policy-Report-Only', + 'Content-Type', + 'Cookie', + 'Cross-Origin-Embedder-Policy', + 'Cross-Origin-Opener-Policy', + 'Cross-Origin-Resource-Policy', + 'Date', + 'Device-Memory', + 'Downlink', + 'ECT', + 'ETag', + 'Expect', + 'Expect-CT', + 'Expires', + 'Forwarded', + 'From', + 'Host', + 'If-Match', + 'If-Modified-Since', + 'If-None-Match', + 'If-Range', + 'If-Unmodified-Since', + 'Keep-Alive', + 'Last-Modified', + 'Link', + 'Location', + 'Max-Forwards', + 'Origin', + 'Permissions-Policy', + 'Pragma', + 'Proxy-Authenticate', + 'Proxy-Authorization', + 'RTT', + 'Range', + 'Referer', + 'Referrer-Policy', + 'Refresh', + 'Retry-After', + 'Sec-WebSocket-Accept', + 'Sec-WebSocket-Extensions', + 'Sec-WebSocket-Key', + 'Sec-WebSocket-Protocol', + 'Sec-WebSocket-Version', + 'Server', + 'Server-Timing', + 'Service-Worker-Allowed', + 'Service-Worker-Navigation-Preload', + 'Set-Cookie', + 'SourceMap', + 'Strict-Transport-Security', + 'Supports-Loading-Mode', + 'TE', + 'Timing-Allow-Origin', + 'Trailer', + 'Transfer-Encoding', + 'Upgrade', + 'Upgrade-Insecure-Requests', + 'User-Agent', + 'Vary', + 'Via', + 'WWW-Authenticate', + 'X-Content-Type-Options', + 'X-DNS-Prefetch-Control', + 'X-Frame-Options', + 'X-Permitted-Cross-Domain-Policies', + 'X-Powered-By', + 'X-Requested-With', + 'X-XSS-Protection' +]) -/** - * @param {Buffer[]} chunks - * @param {number} length - * @returns {Uint8Array} - */ -function chunksConcat (chunks, length) { - if (chunks.length === 0 || length === 0) { - return new Uint8Array(0) - } - if (chunks.length === 1) { - // fast-path - return new Uint8Array(chunks[0]) - } - const buffer = new Uint8Array(Buffer.allocUnsafeSlow(length).buffer) +/** @type {Record, string>} */ +const headerNameLowerCasedRecord = {} - let offset = 0 - for (let i = 0; i < chunks.length; ++i) { - const chunk = chunks[i] - buffer.set(chunk, offset) - offset += chunk.length - } +// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`. +Object.setPrototypeOf(headerNameLowerCasedRecord, null) - return buffer +for (let i = 0; i < wellknownHeaderNames.length; ++i) { + const key = wellknownHeaderNames[i] + const lowerCasedKey = key.toLowerCase() + headerNameLowerCasedRecord[key] = headerNameLowerCasedRecord[lowerCasedKey] = + lowerCasedKey } -/** - * @param {Consume} consume - * @param {BufferEncoding} encoding - * @returns {void} - */ -function consumeEnd (consume, encoding) { - const { type, body, resolve, stream, length } = consume +module.exports = { + wellknownHeaderNames, + headerNameLowerCasedRecord +} - try { - if (type === 'text') { - resolve(chunksDecode(body, length, encoding)) - } else if (type === 'json') { - resolve(JSON.parse(chunksDecode(body, length, encoding))) - } else if (type === 'arrayBuffer') { - resolve(chunksConcat(body, length).buffer) - } else if (type === 'blob') { - resolve(new Blob(body, { type: stream[kContentType] })) - } else if (type === 'bytes') { - resolve(chunksConcat(body, length)) - } - consumeFinish(consume) - } catch (err) { - stream.destroy(err) - } +/***/ }), + +/***/ 185: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const diagnosticsChannel = __nccwpck_require__(3053) +const util = __nccwpck_require__(7975) + +const undiciDebugLog = util.debuglog('undici') +const fetchDebuglog = util.debuglog('fetch') +const websocketDebuglog = util.debuglog('websocket') + +const channels = { + // Client + beforeConnect: diagnosticsChannel.channel('undici:client:beforeConnect'), + connected: diagnosticsChannel.channel('undici:client:connected'), + connectError: diagnosticsChannel.channel('undici:client:connectError'), + sendHeaders: diagnosticsChannel.channel('undici:client:sendHeaders'), + // Request + create: diagnosticsChannel.channel('undici:request:create'), + bodySent: diagnosticsChannel.channel('undici:request:bodySent'), + bodyChunkSent: diagnosticsChannel.channel('undici:request:bodyChunkSent'), + bodyChunkReceived: diagnosticsChannel.channel('undici:request:bodyChunkReceived'), + headers: diagnosticsChannel.channel('undici:request:headers'), + trailers: diagnosticsChannel.channel('undici:request:trailers'), + error: diagnosticsChannel.channel('undici:request:error'), + // WebSocket + open: diagnosticsChannel.channel('undici:websocket:open'), + close: diagnosticsChannel.channel('undici:websocket:close'), + socketError: diagnosticsChannel.channel('undici:websocket:socket_error'), + ping: diagnosticsChannel.channel('undici:websocket:ping'), + pong: diagnosticsChannel.channel('undici:websocket:pong'), + // ProxyAgent + proxyConnected: diagnosticsChannel.channel('undici:proxy:connected') } -/** - * @param {Consume} consume - * @param {Buffer|string} chunk - * @returns {void} - */ -function consumePush (consume, chunk) { - if (consume.body === null) { +let isTrackingClientEvents = false + +function trackClientEvents (debugLog = undiciDebugLog) { + if (isTrackingClientEvents) { return } - if (typeof chunk === 'string') { - // Buffered before the consume started, while an encoding was set. - // consume.length has to stay a byte count and chunksDecode()/chunksConcat() - // only work on bytes, so re-encode. A string's own length is in UTF-16 code - // units and Uint8Array.prototype.set() ignores a string argument entirely. - chunk = Buffer.from(chunk, consume.stream._readableState.encoding) + // Check if any of the channels already have subscribers to prevent duplicate subscriptions + // This can happen when both Node.js built-in undici and undici as a dependency are present + if (channels.beforeConnect.hasSubscribers || channels.connected.hasSubscribers || + channels.connectError.hasSubscribers || channels.sendHeaders.hasSubscribers) { + isTrackingClientEvents = true + return } - consume.length += chunk.length - consume.body.push(chunk) + isTrackingClientEvents = true + + diagnosticsChannel.subscribe('undici:client:beforeConnect', + evt => { + const { + connectParams: { version, protocol, port, host } + } = evt + debugLog( + 'connecting to %s%s using %s%s', + host, + port ? `:${port}` : '', + protocol, + version + ) + }) + + diagnosticsChannel.subscribe('undici:client:connected', + evt => { + const { + connectParams: { version, protocol, port, host } + } = evt + debugLog( + 'connected to %s%s using %s%s', + host, + port ? `:${port}` : '', + protocol, + version + ) + }) + + diagnosticsChannel.subscribe('undici:client:connectError', + evt => { + const { + connectParams: { version, protocol, port, host }, + error + } = evt + debugLog( + 'connection to %s%s using %s%s errored - %s', + host, + port ? `:${port}` : '', + protocol, + version, + error.message + ) + }) + + diagnosticsChannel.subscribe('undici:client:sendHeaders', + evt => { + const { + request: { method, path, origin } + } = evt + debugLog('sending request to %s %s%s', method, origin, path) + }) } -/** - * @param {Consume} consume - * @param {Error} [err] - * @returns {void} - */ -function consumeFinish (consume, err) { - if (consume.body === null) { +let isTrackingRequestEvents = false + +function trackRequestEvents (debugLog = undiciDebugLog) { + if (isTrackingRequestEvents) { return } - if (err) { - consume.reject(err) - } else { - consume.resolve() + // Check if any of the channels already have subscribers to prevent duplicate subscriptions + // This can happen when both Node.js built-in undici and undici as a dependency are present + if (channels.headers.hasSubscribers || channels.trailers.hasSubscribers || + channels.error.hasSubscribers) { + isTrackingRequestEvents = true + return } - // Reset the consume object to allow for garbage collection. - consume.type = null - consume.stream = null - consume.resolve = null - consume.reject = null - consume.length = 0 - consume.body = null -} + isTrackingRequestEvents = true -module.exports = { - Readable: BodyReadable, - chunksDecode + diagnosticsChannel.subscribe('undici:request:headers', + evt => { + const { + request: { method, path, origin }, + response: { statusCode } + } = evt + debugLog( + 'received response to %s %s%s - HTTP %d', + method, + origin, + path, + statusCode + ) + }) + + diagnosticsChannel.subscribe('undici:request:trailers', + evt => { + const { + request: { method, path, origin } + } = evt + debugLog('trailers received from %s %s%s', method, origin, path) + }) + + diagnosticsChannel.subscribe('undici:request:error', + evt => { + const { + request: { method, path, origin }, + error + } = evt + debugLog( + 'request to %s %s%s errored - %s', + method, + origin, + path, + error.message + ) + }) } +let isTrackingWebSocketEvents = false -/***/ }), +function trackWebSocketEvents (debugLog = websocketDebuglog) { + if (isTrackingWebSocketEvents) { + return + } -/***/ 3330: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // Check if any of the channels already have subscribers to prevent duplicate subscriptions + // This can happen when both Node.js built-in undici and undici as a dependency are present + if (channels.open.hasSubscribers || channels.close.hasSubscribers || + channels.socketError.hasSubscribers || channels.ping.hasSubscribers || + channels.pong.hasSubscribers) { + isTrackingWebSocketEvents = true + return + } -"use strict"; + isTrackingWebSocketEvents = true + diagnosticsChannel.subscribe('undici:websocket:open', + evt => { + if (evt.address != null) { + const { address, port } = evt.address + debugLog('connection opened %s%s', address, port ? `:${port}` : '') + } else { + debugLog('connection opened') + } + }) -const { Writable } = __nccwpck_require__(7075) -const { EventEmitter } = __nccwpck_require__(8474) -const { assertCacheKey, assertCacheValue } = __nccwpck_require__(3816) + diagnosticsChannel.subscribe('undici:websocket:close', + evt => { + const { websocket, code, reason } = evt + debugLog( + 'closed connection to %s - %s %s', + websocket.url, + code, + reason + ) + }) -/** - * @typedef {import('../../types/cache-interceptor.d.ts').default.CacheKey} CacheKey - * @typedef {import('../../types/cache-interceptor.d.ts').default.CacheValue} CacheValue - * @typedef {import('../../types/cache-interceptor.d.ts').default.CacheStore} CacheStore - * @typedef {import('../../types/cache-interceptor.d.ts').default.GetResult} GetResult - */ + diagnosticsChannel.subscribe('undici:websocket:socket_error', + err => { + debugLog('connection errored - %s', err.message) + }) -/** - * @implements {CacheStore} - * @extends {EventEmitter} - */ -class MemoryCacheStore extends EventEmitter { - #maxCount = 1024 - #maxSize = 104857600 // 100MB - #maxEntrySize = 5242880 // 5MB + diagnosticsChannel.subscribe('undici:websocket:ping', + evt => { + debugLog('ping received') + }) - #size = 0 - #count = 0 - #entries = new Map() - #hasEmittedMaxSizeEvent = false + diagnosticsChannel.subscribe('undici:websocket:pong', + evt => { + debugLog('pong received') + }) +} - /** - * @param {import('../../types/cache-interceptor.d.ts').default.MemoryCacheStoreOpts | undefined} [opts] - */ - constructor (opts) { - super() - if (opts) { - if (typeof opts !== 'object') { - throw new TypeError('MemoryCacheStore options must be an object') - } +if (undiciDebugLog.enabled || fetchDebuglog.enabled) { + trackClientEvents(fetchDebuglog.enabled ? fetchDebuglog : undiciDebugLog) + trackRequestEvents(fetchDebuglog.enabled ? fetchDebuglog : undiciDebugLog) +} - if (opts.maxCount !== undefined) { - if ( - typeof opts.maxCount !== 'number' || - !Number.isInteger(opts.maxCount) || - opts.maxCount < 0 - ) { - throw new TypeError('MemoryCacheStore options.maxCount must be a non-negative integer') - } - this.#maxCount = opts.maxCount - } +if (websocketDebuglog.enabled) { + trackClientEvents(undiciDebugLog.enabled ? undiciDebugLog : websocketDebuglog) + trackWebSocketEvents(websocketDebuglog) +} - if (opts.maxSize !== undefined) { - if ( - typeof opts.maxSize !== 'number' || - !Number.isInteger(opts.maxSize) || - opts.maxSize < 0 - ) { - throw new TypeError('MemoryCacheStore options.maxSize must be a non-negative integer') - } - this.#maxSize = opts.maxSize - } +module.exports = { + channels +} - if (opts.maxEntrySize !== undefined) { - if ( - typeof opts.maxEntrySize !== 'number' || - !Number.isInteger(opts.maxEntrySize) || - opts.maxEntrySize < 0 - ) { - throw new TypeError('MemoryCacheStore options.maxEntrySize must be a non-negative integer') - } - this.#maxEntrySize = opts.maxEntrySize - } - } - } - /** - * Get the current size of the cache in bytes - * @returns {number} The current size of the cache in bytes - */ - get size () { - return this.#size - } +/***/ }), - /** - * Check if the cache is full (either max size or max count reached) - * @returns {boolean} True if the cache is full, false otherwise - */ - isFull () { - return this.#size >= this.#maxSize || this.#count >= this.#maxCount - } +/***/ 4882: +/***/ ((module) => { - /** - * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key - * @returns {import('../../types/cache-interceptor.d.ts').default.GetResult | undefined} - */ - get (key) { - assertCacheKey(key) +"use strict"; - const topLevelKey = `${key.origin}:${key.path}` - const now = Date.now() - const entries = this.#entries.get(topLevelKey) +const kUndiciError = Symbol.for('undici.error.UND_ERR') +class UndiciError extends Error { + constructor (message, options) { + super(message, options) + this.name = 'UndiciError' + this.code = 'UND_ERR' + } - const entry = entries ? findEntry(key, entries, now) : null + static [Symbol.hasInstance] (instance) { + return instance && instance[kUndiciError] === true + } - return entry == null - ? undefined - : { - statusMessage: entry.statusMessage, - statusCode: entry.statusCode, - headers: entry.headers, - body: entry.body, - vary: entry.vary ? entry.vary : undefined, - etag: entry.etag, - cacheControlDirectives: entry.cacheControlDirectives, - cachedAt: entry.cachedAt, - staleAt: entry.staleAt, - deleteAt: entry.deleteAt - } + get [kUndiciError] () { + return true } +} - /** - * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key - * @param {import('../../types/cache-interceptor.d.ts').default.CacheValue} val - * @returns {Writable | undefined} - */ - createWriteStream (key, val) { - assertCacheKey(key) - assertCacheValue(val) +const kConnectTimeoutError = Symbol.for('undici.error.UND_ERR_CONNECT_TIMEOUT') +class ConnectTimeoutError extends UndiciError { + constructor (message) { + super(message) + this.name = 'ConnectTimeoutError' + this.message = message || 'Connect Timeout Error' + this.code = 'UND_ERR_CONNECT_TIMEOUT' + } - const topLevelKey = `${key.origin}:${key.path}` + static [Symbol.hasInstance] (instance) { + return instance && instance[kConnectTimeoutError] === true + } - const store = this - const entry = { ...key, ...val, body: [], size: 0 } + get [kConnectTimeoutError] () { + return true + } +} - return new Writable({ - write (chunk, encoding, callback) { - if (typeof chunk === 'string') { - chunk = Buffer.from(chunk, encoding) - } +const kHeadersTimeoutError = Symbol.for('undici.error.UND_ERR_HEADERS_TIMEOUT') +class HeadersTimeoutError extends UndiciError { + constructor (message) { + super(message) + this.name = 'HeadersTimeoutError' + this.message = message || 'Headers Timeout Error' + this.code = 'UND_ERR_HEADERS_TIMEOUT' + } - entry.size += chunk.byteLength + static [Symbol.hasInstance] (instance) { + return instance && instance[kHeadersTimeoutError] === true + } - if (entry.size > store.#maxEntrySize) { - this.destroy() - } else { - entry.body.push(chunk) - } + get [kHeadersTimeoutError] () { + return true + } +} - callback(null) - }, - final (callback) { - let entries = store.#entries.get(topLevelKey) - if (!entries) { - entries = [] - store.#entries.set(topLevelKey, entries) - } - const previousEntry = findEntry(key, entries, Date.now()) - if (previousEntry) { - const index = entries.indexOf(previousEntry) - entries.splice(index, 1, entry) - store.#size -= previousEntry.size - } else { - entries.push(entry) - store.#count += 1 - } +const kHeadersOverflowError = Symbol.for('undici.error.UND_ERR_HEADERS_OVERFLOW') +class HeadersOverflowError extends UndiciError { + constructor (message) { + super(message) + this.name = 'HeadersOverflowError' + this.message = message || 'Headers Overflow Error' + this.code = 'UND_ERR_HEADERS_OVERFLOW' + } - store.#size += entry.size + static [Symbol.hasInstance] (instance) { + return instance && instance[kHeadersOverflowError] === true + } - // Check if cache is full and emit event if needed - if (store.#size > store.#maxSize || store.#count > store.#maxCount) { - // Emit maxSizeExceeded event if we haven't already - if (!store.#hasEmittedMaxSizeEvent) { - store.emit('maxSizeExceeded', { - size: store.#size, - maxSize: store.#maxSize, - count: store.#count, - maxCount: store.#maxCount - }) - store.#hasEmittedMaxSizeEvent = true - } + get [kHeadersOverflowError] () { + return true + } +} - // Perform eviction - for (const [key, entries] of store.#entries) { - for (const entry of entries.splice(0, Math.ceil(entries.length / 2))) { - store.#size -= entry.size - store.#count -= 1 - } - if (entries.length === 0) { - store.#entries.delete(key) - } - } +const kBodyTimeoutError = Symbol.for('undici.error.UND_ERR_BODY_TIMEOUT') +class BodyTimeoutError extends UndiciError { + constructor (message) { + super(message) + this.name = 'BodyTimeoutError' + this.message = message || 'Body Timeout Error' + this.code = 'UND_ERR_BODY_TIMEOUT' + } - // Reset the event flag after eviction - if (store.#size < store.#maxSize && store.#count < store.#maxCount) { - store.#hasEmittedMaxSizeEvent = false - } - } + static [Symbol.hasInstance] (instance) { + return instance && instance[kBodyTimeoutError] === true + } - callback(null) - } - }) + get [kBodyTimeoutError] () { + return true } +} - /** - * @param {CacheKey} key - */ - delete (key) { - if (typeof key !== 'object') { - throw new TypeError(`expected key to be object, got ${typeof key}`) - } +const kInvalidArgumentError = Symbol.for('undici.error.UND_ERR_INVALID_ARG') +class InvalidArgumentError extends UndiciError { + constructor (message) { + super(message) + this.name = 'InvalidArgumentError' + this.message = message || 'Invalid Argument Error' + this.code = 'UND_ERR_INVALID_ARG' + } - const topLevelKey = `${key.origin}:${key.path}` + static [Symbol.hasInstance] (instance) { + return instance && instance[kInvalidArgumentError] === true + } - for (const entry of this.#entries.get(topLevelKey) ?? []) { - this.#size -= entry.size - this.#count -= 1 - } - this.#entries.delete(topLevelKey) + get [kInvalidArgumentError] () { + return true } } -function findEntry (key, entries, now) { - for (let i = 0; i < entries.length; i++) { - const entry = entries[i] - if ( - entry.deleteAt > now && - entry.method === key.method && - varyMatches(key, entry) - ) { - return entry - } +const kInvalidReturnValueError = Symbol.for('undici.error.UND_ERR_INVALID_RETURN_VALUE') +class InvalidReturnValueError extends UndiciError { + constructor (message) { + super(message) + this.name = 'InvalidReturnValueError' + this.message = message || 'Invalid Return Value Error' + this.code = 'UND_ERR_INVALID_RETURN_VALUE' } -} -function varyMatches (key, entry) { - if (entry.vary == null) { + static [Symbol.hasInstance] (instance) { + return instance && instance[kInvalidReturnValueError] === true + } + + get [kInvalidReturnValueError] () { return true } +} - for (const headerName in entry.vary) { - if (Object.hasOwn(entry.vary, headerName) && !headerValueEquals(key.headers?.[headerName], entry.vary[headerName])) { - return false - } +const kAbortError = Symbol.for('undici.error.UND_ERR_ABORT') +class AbortError extends UndiciError { + constructor (message) { + super(message) + this.name = 'AbortError' + this.message = message || 'The operation was aborted' + this.code = 'UND_ERR_ABORT' } - return true -} + static [Symbol.hasInstance] (instance) { + return instance && instance[kAbortError] === true + } -/** - * @param {string|string[]|null|undefined} lhs - * @param {string|string[]|null|undefined} rhs - * @returns {boolean} - */ -function headerValueEquals (lhs, rhs) { - if (lhs == null && rhs == null) { + get [kAbortError] () { return true } +} - if ((lhs == null && rhs != null) || - (lhs != null && rhs == null)) { - return false +const kRequestAbortedError = Symbol.for('undici.error.UND_ERR_ABORTED') +class RequestAbortedError extends AbortError { + constructor (message) { + super(message) + this.name = 'AbortError' + this.message = message || 'Request aborted' + this.code = 'UND_ERR_ABORTED' } - if (Array.isArray(lhs) && Array.isArray(rhs)) { - if (lhs.length !== rhs.length) { - return false - } - - for (let i = 0; i < lhs.length; i++) { - if (lhs[i] !== rhs[i]) { - return false - } - } + static [Symbol.hasInstance] (instance) { + return instance && instance[kRequestAbortedError] === true + } + get [kRequestAbortedError] () { return true } - - return lhs === rhs } -module.exports = MemoryCacheStore +const kInformationalError = Symbol.for('undici.error.UND_ERR_INFO') +class InformationalError extends UndiciError { + constructor (message, options) { + super(message, options) + this.name = 'InformationalError' + this.message = message || 'Request information' + this.code = 'UND_ERR_INFO' + } + static [Symbol.hasInstance] (instance) { + return instance && instance[kInformationalError] === true + } -/***/ }), + get [kInformationalError] () { + return true + } +} -/***/ 6901: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +const kRequestContentLengthMismatchError = Symbol.for('undici.error.UND_ERR_REQ_CONTENT_LENGTH_MISMATCH') +class RequestContentLengthMismatchError extends UndiciError { + constructor (message) { + super(message) + this.name = 'RequestContentLengthMismatchError' + this.message = message || 'Request body length does not match content-length header' + this.code = 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH' + } -"use strict"; + static [Symbol.hasInstance] (instance) { + return instance && instance[kRequestContentLengthMismatchError] === true + } + get [kRequestContentLengthMismatchError] () { + return true + } +} -const { Writable } = __nccwpck_require__(7075) -const { assertCacheKey, assertCacheValue } = __nccwpck_require__(3816) +const kResponseContentLengthMismatchError = Symbol.for('undici.error.UND_ERR_RES_CONTENT_LENGTH_MISMATCH') +class ResponseContentLengthMismatchError extends UndiciError { + constructor (message) { + super(message) + this.name = 'ResponseContentLengthMismatchError' + this.message = message || 'Response body length does not match content-length header' + this.code = 'UND_ERR_RES_CONTENT_LENGTH_MISMATCH' + } -let DatabaseSync + static [Symbol.hasInstance] (instance) { + return instance && instance[kResponseContentLengthMismatchError] === true + } -const VERSION = 3 + get [kResponseContentLengthMismatchError] () { + return true + } +} -// 2gb -const MAX_ENTRY_SIZE = 2 * 1000 * 1000 * 1000 +const kClientDestroyedError = Symbol.for('undici.error.UND_ERR_DESTROYED') +class ClientDestroyedError extends UndiciError { + constructor (message) { + super(message) + this.name = 'ClientDestroyedError' + this.message = message || 'The client is destroyed' + this.code = 'UND_ERR_DESTROYED' + } -/** - * @typedef {import('../../types/cache-interceptor.d.ts').default.CacheStore} CacheStore - * @implements {CacheStore} - * - * @typedef {{ - * id: Readonly, - * body?: Uint8Array - * statusCode: number - * statusMessage: string - * headers?: string - * vary?: string - * etag?: string - * cacheControlDirectives?: string - * cachedAt: number - * staleAt: number - * deleteAt: number - * }} SqliteStoreValue - */ -module.exports = class SqliteCacheStore { - #maxEntrySize = MAX_ENTRY_SIZE - #maxCount = Infinity + static [Symbol.hasInstance] (instance) { + return instance && instance[kClientDestroyedError] === true + } - /** - * @type {import('node:sqlite').DatabaseSync} - */ - #db + get [kClientDestroyedError] () { + return true + } +} - /** - * @type {import('node:sqlite').StatementSync} - */ - #getValuesQuery +const kClientClosedError = Symbol.for('undici.error.UND_ERR_CLOSED') +class ClientClosedError extends UndiciError { + constructor (message) { + super(message) + this.name = 'ClientClosedError' + this.message = message || 'The client is closed' + this.code = 'UND_ERR_CLOSED' + } - /** - * @type {import('node:sqlite').StatementSync} - */ - #updateValueQuery + static [Symbol.hasInstance] (instance) { + return instance && instance[kClientClosedError] === true + } - /** - * @type {import('node:sqlite').StatementSync} - */ - #insertValueQuery + get [kClientClosedError] () { + return true + } +} - /** - * @type {import('node:sqlite').StatementSync} - */ - #deleteExpiredValuesQuery +const kSocketError = Symbol.for('undici.error.UND_ERR_SOCKET') +class SocketError extends UndiciError { + constructor (message, socket) { + super(message) + this.name = 'SocketError' + this.message = message || 'Socket error' + this.code = 'UND_ERR_SOCKET' + this.socket = socket + } - /** - * @type {import('node:sqlite').StatementSync} - */ - #deleteByUrlQuery + static [Symbol.hasInstance] (instance) { + return instance && instance[kSocketError] === true + } - /** - * @type {import('node:sqlite').StatementSync} - */ - #countEntriesQuery + get [kSocketError] () { + return true + } +} - /** - * @type {import('node:sqlite').StatementSync | null} - */ - #deleteOldValuesQuery +const kNotSupportedError = Symbol.for('undici.error.UND_ERR_NOT_SUPPORTED') +class NotSupportedError extends UndiciError { + constructor (message) { + super(message) + this.name = 'NotSupportedError' + this.message = message || 'Not supported error' + this.code = 'UND_ERR_NOT_SUPPORTED' + } - /** - * @param {import('../../types/cache-interceptor.d.ts').default.SqliteCacheStoreOpts | undefined} opts - */ - constructor (opts) { - if (opts) { - if (typeof opts !== 'object') { - throw new TypeError('SqliteCacheStore options must be an object') - } + static [Symbol.hasInstance] (instance) { + return instance && instance[kNotSupportedError] === true + } - if (opts.maxEntrySize !== undefined) { - if ( - typeof opts.maxEntrySize !== 'number' || - !Number.isInteger(opts.maxEntrySize) || - opts.maxEntrySize < 0 - ) { - throw new TypeError('SqliteCacheStore options.maxEntrySize must be a non-negative integer') - } + get [kNotSupportedError] () { + return true + } +} - if (opts.maxEntrySize > MAX_ENTRY_SIZE) { - throw new TypeError('SqliteCacheStore options.maxEntrySize must be less than 2gb') - } +const kBalancedPoolMissingUpstreamError = Symbol.for('undici.error.UND_ERR_BPL_MISSING_UPSTREAM') +class BalancedPoolMissingUpstreamError extends UndiciError { + constructor (message) { + super(message) + this.name = 'MissingUpstreamError' + this.message = message || 'No upstream has been added to the BalancedPool' + this.code = 'UND_ERR_BPL_MISSING_UPSTREAM' + } - this.#maxEntrySize = opts.maxEntrySize - } + static [Symbol.hasInstance] (instance) { + return instance && instance[kBalancedPoolMissingUpstreamError] === true + } - if (opts.maxCount !== undefined) { - if ( - typeof opts.maxCount !== 'number' || - !Number.isInteger(opts.maxCount) || - opts.maxCount < 0 - ) { - throw new TypeError('SqliteCacheStore options.maxCount must be a non-negative integer') - } - this.#maxCount = opts.maxCount - } - } + get [kBalancedPoolMissingUpstreamError] () { + return true + } +} - if (!DatabaseSync) { - DatabaseSync = (__nccwpck_require__(99).DatabaseSync) - } - this.#db = new DatabaseSync(opts?.location ?? ':memory:') +const kHTTPParserError = Symbol.for('undici.error.UND_ERR_HTTP_PARSER') +class HTTPParserError extends Error { + constructor (message, code, data) { + super(message) + this.name = 'HTTPParserError' + this.code = code ? `HPE_${code}` : undefined + this.data = data ? data.toString() : undefined + } - this.#db.exec(` - PRAGMA journal_mode = WAL; - PRAGMA synchronous = NORMAL; - PRAGMA temp_store = memory; - PRAGMA optimize; + static [Symbol.hasInstance] (instance) { + return instance && instance[kHTTPParserError] === true + } - CREATE TABLE IF NOT EXISTS cacheInterceptorV${VERSION} ( - -- Data specific to us - id INTEGER PRIMARY KEY AUTOINCREMENT, - url TEXT NOT NULL, - method TEXT NOT NULL, + get [kHTTPParserError] () { + return true + } +} - -- Data returned to the interceptor - body BUF NULL, - deleteAt INTEGER NOT NULL, - statusCode INTEGER NOT NULL, - statusMessage TEXT NOT NULL, - headers TEXT NULL, - cacheControlDirectives TEXT NULL, - etag TEXT NULL, - vary TEXT NULL, - cachedAt INTEGER NOT NULL, - staleAt INTEGER NOT NULL - ); +const kResponseExceededMaxSizeError = Symbol.for('undici.error.UND_ERR_RES_EXCEEDED_MAX_SIZE') +class ResponseExceededMaxSizeError extends UndiciError { + constructor (message) { + super(message) + this.name = 'ResponseExceededMaxSizeError' + this.message = message || 'Response content exceeded max size' + this.code = 'UND_ERR_RES_EXCEEDED_MAX_SIZE' + } - CREATE INDEX IF NOT EXISTS idx_cacheInterceptorV${VERSION}_getValuesQuery ON cacheInterceptorV${VERSION}(url, method, deleteAt); - CREATE INDEX IF NOT EXISTS idx_cacheInterceptorV${VERSION}_deleteByUrlQuery ON cacheInterceptorV${VERSION}(deleteAt); - `) - - this.#getValuesQuery = this.#db.prepare(` - SELECT - id, - body, - deleteAt, - statusCode, - statusMessage, - headers, - etag, - cacheControlDirectives, - vary, - cachedAt, - staleAt - FROM cacheInterceptorV${VERSION} - WHERE - url = ? - AND method = ? - ORDER BY - deleteAt ASC - `) - - this.#updateValueQuery = this.#db.prepare(` - UPDATE cacheInterceptorV${VERSION} SET - body = ?, - deleteAt = ?, - statusCode = ?, - statusMessage = ?, - headers = ?, - etag = ?, - cacheControlDirectives = ?, - vary = ?, - cachedAt = ?, - staleAt = ? - WHERE - id = ? - `) - - this.#insertValueQuery = this.#db.prepare(` - INSERT INTO cacheInterceptorV${VERSION} ( - url, - method, - body, - deleteAt, - statusCode, - statusMessage, - headers, - etag, - cacheControlDirectives, - vary, - cachedAt, - staleAt - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - `) - - this.#deleteByUrlQuery = this.#db.prepare( - `DELETE FROM cacheInterceptorV${VERSION} WHERE url = ?` - ) - - this.#countEntriesQuery = this.#db.prepare( - `SELECT COUNT(*) AS total FROM cacheInterceptorV${VERSION}` - ) - - this.#deleteExpiredValuesQuery = this.#db.prepare( - `DELETE FROM cacheInterceptorV${VERSION} WHERE deleteAt <= ?` - ) - - this.#deleteOldValuesQuery = this.#maxCount === Infinity - ? null - : this.#db.prepare(` - DELETE FROM cacheInterceptorV${VERSION} - WHERE id IN ( - SELECT - id - FROM cacheInterceptorV${VERSION} - ORDER BY cachedAt ASC - LIMIT ? - ) - `) + static [Symbol.hasInstance] (instance) { + return instance && instance[kResponseExceededMaxSizeError] === true } - close () { - this.#db.close() + get [kResponseExceededMaxSizeError] () { + return true } +} - /** - * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key - * @returns {(import('../../types/cache-interceptor.d.ts').default.GetResult & { body?: Buffer }) | undefined} - */ - get (key) { - assertCacheKey(key) - - const value = this.#findValue(key) - return value - ? { - body: value.body ? Buffer.from(value.body.buffer, value.body.byteOffset, value.body.byteLength) : undefined, - statusCode: value.statusCode, - statusMessage: value.statusMessage, - headers: value.headers ? JSON.parse(value.headers) : undefined, - etag: value.etag ? value.etag : undefined, - vary: value.vary ? JSON.parse(value.vary) : undefined, - cacheControlDirectives: value.cacheControlDirectives - ? JSON.parse(value.cacheControlDirectives) - : undefined, - cachedAt: value.cachedAt, - staleAt: value.staleAt, - deleteAt: value.deleteAt - } - : undefined +const kRequestRetryError = Symbol.for('undici.error.UND_ERR_REQ_RETRY') +class RequestRetryError extends UndiciError { + constructor (message, code, { headers, data }) { + super(message) + this.name = 'RequestRetryError' + this.message = message || 'Request retry error' + this.code = 'UND_ERR_REQ_RETRY' + this.statusCode = code + this.data = data + this.headers = headers } - /** - * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key - * @param {import('../../types/cache-interceptor.d.ts').default.CacheValue & { body: null | Buffer | Array}} value - */ - set (key, value) { - assertCacheKey(key) - - const url = this.#makeValueUrl(key) - const body = Array.isArray(value.body) ? Buffer.concat(value.body) : value.body - const size = body?.byteLength - - if (size && size > this.#maxEntrySize) { - return - } - - const existingValue = this.#findValue(key, true) - if (existingValue) { - // Updating an existing response, let's overwrite it - this.#updateValueQuery.run( - body, - value.deleteAt, - value.statusCode, - value.statusMessage, - value.headers ? JSON.stringify(value.headers) : null, - value.etag ? value.etag : null, - value.cacheControlDirectives ? JSON.stringify(value.cacheControlDirectives) : null, - value.vary ? JSON.stringify(value.vary) : null, - value.cachedAt, - value.staleAt, - existingValue.id - ) - } else { - // New response, let's insert it - this.#insertValueQuery.run( - url, - key.method, - body, - value.deleteAt, - value.statusCode, - value.statusMessage, - value.headers ? JSON.stringify(value.headers) : null, - value.etag ? value.etag : null, - value.cacheControlDirectives ? JSON.stringify(value.cacheControlDirectives) : null, - value.vary ? JSON.stringify(value.vary) : null, - value.cachedAt, - value.staleAt - ) - this.#prune() - } + static [Symbol.hasInstance] (instance) { + return instance && instance[kRequestRetryError] === true } - /** - * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key - * @param {import('../../types/cache-interceptor.d.ts').default.CacheValue} value - * @returns {Writable | undefined} - */ - createWriteStream (key, value) { - assertCacheKey(key) - assertCacheValue(value) - - let size = 0 - /** - * @type {Buffer[] | null} - */ - const body = [] - const store = this - - return new Writable({ - decodeStrings: true, - write (chunk, encoding, callback) { - size += chunk.byteLength - - if (size <= store.#maxEntrySize) { - body.push(chunk) - } else { - this.destroy() - } - - callback() - }, - final (callback) { - store.set(key, { ...value, body }) - callback() - } - }) + get [kRequestRetryError] () { + return true } +} - /** - * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key - */ - delete (key) { - if (typeof key !== 'object') { - throw new TypeError(`expected key to be object, got ${typeof key}`) - } - - this.#deleteByUrlQuery.run(this.#makeValueUrl(key)) +const kResponseError = Symbol.for('undici.error.UND_ERR_RESPONSE') +class ResponseError extends UndiciError { + constructor (message, code, { headers, body }) { + super(message) + this.name = 'ResponseError' + this.message = message || 'Response error' + this.code = 'UND_ERR_RESPONSE' + this.statusCode = code + this.body = body + this.headers = headers } - #prune () { - if (Number.isFinite(this.#maxCount) && this.size <= this.#maxCount) { - return 0 - } - - { - const removed = this.#deleteExpiredValuesQuery.run(Date.now()).changes - if (removed) { - return removed - } - } - - { - const removed = this.#deleteOldValuesQuery?.run(Math.max(Math.floor(this.#maxCount * 0.1), 1)).changes - if (removed) { - return removed - } - } - - return 0 + static [Symbol.hasInstance] (instance) { + return instance && instance[kResponseError] === true } - /** - * Counts the number of rows in the cache - * @returns {Number} - */ - get size () { - const { total } = this.#countEntriesQuery.get() - return total + get [kResponseError] () { + return true } +} - /** - * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key - * @returns {string} - */ - #makeValueUrl (key) { - return `${key.origin}/${key.path}` +const kSecureProxyConnectionError = Symbol.for('undici.error.UND_ERR_PRX_TLS') +class SecureProxyConnectionError extends UndiciError { + constructor (cause, message, options = {}) { + super(message, { cause, ...options }) + this.name = 'SecureProxyConnectionError' + this.message = message || 'Secure Proxy Connection failed' + this.code = 'UND_ERR_PRX_TLS' + this.cause = cause } - /** - * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key - * @param {boolean} [canBeExpired=false] - * @returns {SqliteStoreValue | undefined} - */ - #findValue (key, canBeExpired = false) { - const url = this.#makeValueUrl(key) - const { headers, method } = key - - /** - * @type {SqliteStoreValue[]} - */ - const values = this.#getValuesQuery.all(url, method) - - if (values.length === 0) { - return undefined - } + static [Symbol.hasInstance] (instance) { + return instance && instance[kSecureProxyConnectionError] === true + } - const now = Date.now() - for (const value of values) { - if (now >= value.deleteAt && !canBeExpired) { - continue - } + get [kSecureProxyConnectionError] () { + return true + } +} - let matches = true +const kProxyConnectionError = Symbol.for('undici.error.UND_ERR_PRX_CONN') +class ProxyConnectionError extends UndiciError { + constructor (cause, message, options = {}) { + super(message, { cause, ...options }) + this.name = 'ProxyConnectionError' + this.message = message || 'Proxy Connection failed' + this.code = 'UND_ERR_PRX_CONN' + this.cause = cause + } - if (value.vary) { - const vary = JSON.parse(value.vary) + static [Symbol.hasInstance] (instance) { + return instance && instance[kProxyConnectionError] === true + } - for (const header in vary) { - if (!headerValueEquals(headers[header], vary[header])) { - matches = false - break - } - } - } + get [kProxyConnectionError] () { + return true + } +} - if (matches) { - return value - } - } +const kMaxOriginsReachedError = Symbol.for('undici.error.UND_ERR_MAX_ORIGINS_REACHED') +class MaxOriginsReachedError extends UndiciError { + constructor (message) { + super(message) + this.name = 'MaxOriginsReachedError' + this.message = message || 'Maximum allowed origins reached' + this.code = 'UND_ERR_MAX_ORIGINS_REACHED' + } - return undefined + static [Symbol.hasInstance] (instance) { + return instance && instance[kMaxOriginsReachedError] === true } -} -/** - * @param {string|string[]|null|undefined} lhs - * @param {string|string[]|null|undefined} rhs - * @returns {boolean} - */ -function headerValueEquals (lhs, rhs) { - if (lhs == null && rhs == null) { + get [kMaxOriginsReachedError] () { return true } +} - if ((lhs == null && rhs != null) || - (lhs != null && rhs == null)) { - return false +class Socks5ProxyError extends UndiciError { + constructor (message, code) { + super(message) + this.name = 'Socks5ProxyError' + this.message = message || 'SOCKS5 proxy error' + this.code = code || 'UND_ERR_SOCKS5' } +} - if (Array.isArray(lhs) && Array.isArray(rhs)) { - if (lhs.length !== rhs.length) { - return false - } +const kMessageSizeExceededError = Symbol.for('undici.error.UND_ERR_WS_MESSAGE_SIZE_EXCEEDED') +class MessageSizeExceededError extends UndiciError { + constructor (message) { + super(message) + this.name = 'MessageSizeExceededError' + this.message = message || 'Max decompressed message size exceeded' + this.code = 'UND_ERR_WS_MESSAGE_SIZE_EXCEEDED' + } - for (let i = 0; i < lhs.length; i++) { - if (lhs[i] !== rhs[i]) { - return false - } - } + static [Symbol.hasInstance] (instance) { + return instance && instance[kMessageSizeExceededError] === true + } + get [kMessageSizeExceededError] () { return true } +} - return lhs === rhs +module.exports = { + AbortError, + HTTPParserError, + UndiciError, + HeadersTimeoutError, + HeadersOverflowError, + BodyTimeoutError, + RequestContentLengthMismatchError, + ConnectTimeoutError, + InvalidArgumentError, + InvalidReturnValueError, + RequestAbortedError, + ClientDestroyedError, + ClientClosedError, + InformationalError, + SocketError, + NotSupportedError, + ResponseContentLengthMismatchError, + BalancedPoolMissingUpstreamError, + ResponseExceededMaxSizeError, + RequestRetryError, + ResponseError, + SecureProxyConnectionError, + ProxyConnectionError, + MaxOriginsReachedError, + Socks5ProxyError, + MessageSizeExceededError } /***/ }), -/***/ 4463: +/***/ 5960: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const net = __nccwpck_require__(7030) +const { + InvalidArgumentError, + NotSupportedError +} = __nccwpck_require__(4882) const assert = __nccwpck_require__(4589) -const util = __nccwpck_require__(9705) -const { InvalidArgumentError, ConnectTimeoutError } = __nccwpck_require__(7062) - -let tls // include tls conditionally since it is not always available - -// TODO: session re-use does not wait for the first -// connection to resolve the session and might therefore -// resolve the same servername multiple times even when -// re-use is enabled. +const { + isValidHTTPToken, + isValidHeaderValue, + isStream, + destroy, + isBuffer, + isFormDataLike, + isIterable, + hasSafeIterator, + isBlobLike, + serializePathWithQuery, + parseHeaders, + assertRequestHandler, + getServerName, + normalizedMethodRecords, + getProtocolFromUrlString +} = __nccwpck_require__(9277) +const { channels } = __nccwpck_require__(185) +const { headerNameLowerCasedRecord } = __nccwpck_require__(5188) -const SessionCache = class WeakSessionCache { - constructor (maxCachedSessions) { - this._maxCachedSessions = maxCachedSessions - this._sessionCache = new Map() - this._sessionRegistry = new FinalizationRegistry((key) => { - if (this._sessionCache.size < this._maxCachedSessions) { - return - } +// Verifies that a given path is valid does not contain control chars \x00 to \x20 +const invalidPathRegex = /[^\u0021-\u00ff]/ - const ref = this._sessionCache.get(key) - if (ref !== undefined && ref.deref() === undefined) { - this._sessionCache.delete(key) - } - }) +function isValidContentLengthHeaderValue (val) { + if (typeof val !== 'string' || val.length === 0) { + return false } - get (sessionKey) { - const ref = this._sessionCache.get(sessionKey) - return ref ? ref.deref() : null + for (let i = 0; i < val.length; i++) { + const charCode = val.charCodeAt(i) + if (charCode < 48 || charCode > 57) { + return false + } } - set (sessionKey, session) { - if (this._maxCachedSessions === 0) { - return - } + return true +} - if (this._sessionCache.has(sessionKey)) { - this._sessionCache.delete(sessionKey) - } else if (this._sessionCache.size >= this._maxCachedSessions) { - for (const [key, ref] of this._sessionCache) { - if (ref.deref() === undefined) { - this._sessionCache.delete(key) - return - } - } +const kHandler = Symbol('handler') +const kController = Symbol('controller') +const kResume = Symbol('resume') - const oldest = this._sessionCache.keys().next() - if (!oldest.done) { - this._sessionCache.delete(oldest.value) - } - } +class RequestController { + #paused = false + #reason = null + #aborted = false + #abort - this._sessionCache.set(sessionKey, new WeakRef(session)) - this._sessionRegistry.register(session, sessionKey) + [kResume] = null + + rawHeaders = null + rawTrailers = null + + constructor (abort) { + this.#abort = abort } -} -function buildConnector ({ allowH2, preferH2, useH2c, maxCachedSessions, socketPath, timeout, session: customSession, ...opts }) { - if (maxCachedSessions != null && (!Number.isInteger(maxCachedSessions) || maxCachedSessions < 0)) { - throw new InvalidArgumentError('maxCachedSessions must be a positive integer or zero') + pause () { + this.#paused = true } - const options = { path: socketPath, ...opts } - const sessionCache = new SessionCache(maxCachedSessions == null ? 100 : maxCachedSessions) - timeout = timeout == null ? 10e3 : timeout - allowH2 = allowH2 != null ? allowH2 : true - return function connect ({ hostname, host, protocol, port, servername, localAddress, httpSocket }, callback) { - let socket - if (protocol === 'https:') { - if (!tls) { - tls = __nccwpck_require__(1692) - } - servername = servername || options.servername || util.getServerName(host) || null - - const sessionKey = servername || hostname - assert(sessionKey) - - const session = customSession || sessionCache.get(sessionKey) || null - - port = port || 443 - - socket = tls.connect({ - highWaterMark: 16384, // TLS in node can't have bigger HWM anyway... - ...options, - servername, - session, - localAddress, - ALPNProtocols: allowH2 ? (preferH2 ? ['h2', 'http/1.1'] : ['http/1.1', 'h2']) : ['http/1.1'], - socket: httpSocket, // upgrade socket connection - port, - host: hostname - }) + resume () { + if (this.#paused) { + this.#paused = false + this[kResume]?.() + } + } - socket - .on('session', function (session) { - // TODO (fix): Can a session become invalid once established? Don't think so? - sessionCache.set(sessionKey, session) - }) - } else { - assert(!httpSocket, 'httpSocket can only be sent on TLS update') + abort (reason) { + if (!this.#aborted) { + this.#aborted = true + this.#reason = reason + this.#abort(reason) + } + } - port = port || 80 + get aborted () { + return this.#aborted + } - const connectOptions = { - highWaterMark: 64 * 1024, // Same as nodejs fs streams. - ...options, - localAddress, - port, - host: hostname - } + get reason () { + return this.#reason + } - const family = net.isIP(hostname) - if (family !== 0 && servername && servername !== hostname) { - connectOptions.host = servername - connectOptions.lookup = (_hostname, lookupOptions, cb) => { - if (lookupOptions.all) { - cb(null, [{ address: hostname, family }]) - } else { - cb(null, hostname, family) - } - } - } + get paused () { + return this.#paused + } +} - socket = net.connect(connectOptions) - if (useH2c === true) { - socket.alpnProtocol = 'h2' - } +class Request { + constructor (origin, { + path, + method, + body, + headers, + query, + idempotent, + blocking, + upgrade, + headersTimeout, + bodyTimeout, + reset, + expectContinue, + servername, + throwOnError, + maxRedirections, + typeOfService + }, handler) { + if (typeof path !== 'string') { + throw new InvalidArgumentError('path must be a string') + } else if ( + path[0] !== '/' && + !(path.startsWith('http://') || path.startsWith('https://')) && + method !== 'CONNECT' + ) { + throw new InvalidArgumentError('path must be an absolute URL or start with a slash') + } else if (invalidPathRegex.test(path)) { + throw new InvalidArgumentError('invalid request path') } - // Set TCP keep alive options on the socket here instead of in connect() for the case of assigning the socket - if (options.keepAlive == null || options.keepAlive) { - const keepAliveInitialDelay = options.keepAliveInitialDelay === undefined ? 60e3 : options.keepAliveInitialDelay - socket.setKeepAlive(true, keepAliveInitialDelay) + if (typeof method !== 'string') { + throw new InvalidArgumentError('method must be a string') + } else if (normalizedMethodRecords[method] === undefined && !isValidHTTPToken(method)) { + throw new InvalidArgumentError('invalid request method') } - const clearConnectTimeout = util.setupConnectTimeout(new WeakRef(socket), { timeout, hostname, port }) - - socket - .setNoDelay(true) - .once(protocol === 'https:' ? 'secureConnect' : 'connect', function () { - queueMicrotask(clearConnectTimeout) + if (upgrade && typeof upgrade !== 'string') { + throw new InvalidArgumentError('upgrade must be a string') + } - if (callback) { - const cb = callback - callback = null - cb(null, this) - } - }) - .on('error', function (err) { - queueMicrotask(clearConnectTimeout) + if (upgrade && !isValidHeaderValue(upgrade)) { + throw new InvalidArgumentError('invalid upgrade header') + } - if (callback) { - const cb = callback - callback = null - cb(maybeNormalizeConnectError(err, this, { timeout, hostname, port })) - } - }) + if (headersTimeout != null && (!Number.isFinite(headersTimeout) || headersTimeout < 0)) { + throw new InvalidArgumentError('invalid headersTimeout') + } - return socket - } -} + if (bodyTimeout != null && (!Number.isFinite(bodyTimeout) || bodyTimeout < 0)) { + throw new InvalidArgumentError('invalid bodyTimeout') + } -// `net.connect` with `autoSelectFamily` raises an `AggregateError` when every -// attempted address fails. If any of those failures is a timeout, surface the -// error as a `ConnectTimeoutError` so callers see the same error regardless of -// which timer (Node's internal one or undici's `connectTimeout`) wins the race. -// The original `AggregateError` is preserved on `.cause`. -function maybeNormalizeConnectError (err, socket, opts) { - if ( - err instanceof AggregateError && - (err.code === 'ETIMEDOUT' || err.errors.some((e) => e != null && e.code === 'ETIMEDOUT')) - ) { - let message = 'Connect Timeout Error' - if (Array.isArray(socket.autoSelectFamilyAttemptedAddresses)) { - message += ` (attempted addresses: ${socket.autoSelectFamilyAttemptedAddresses.join(', ')},` - } else { - message += ` (attempted address: ${opts.hostname}:${opts.port},` + if (reset != null && typeof reset !== 'boolean') { + throw new InvalidArgumentError('invalid reset') } - message += ` timeout: ${opts.timeout}ms)` - const wrapped = new ConnectTimeoutError(message) - wrapped.cause = err - return wrapped - } - return err -} + if (expectContinue != null && typeof expectContinue !== 'boolean') { + throw new InvalidArgumentError('invalid expectContinue') + } -module.exports = buildConnector + if (throwOnError != null) { + throw new InvalidArgumentError('invalid throwOnError') + } + if (maxRedirections != null && maxRedirections !== 0) { + throw new InvalidArgumentError('maxRedirections is not supported, use the redirect interceptor') + } -/***/ }), + if (typeOfService != null && (!Number.isInteger(typeOfService) || typeOfService < 0 || typeOfService > 255)) { + throw new InvalidArgumentError('typeOfService must be an integer between 0 and 255') + } -/***/ 5368: -/***/ ((module) => { + this.headersTimeout = headersTimeout -"use strict"; + this.bodyTimeout = bodyTimeout + this.method = method -/** - * @see https://developer.mozilla.org/docs/Web/HTTP/Headers - */ -const wellknownHeaderNames = /** @type {const} */ ([ - 'Accept', - 'Accept-Encoding', - 'Accept-Language', - 'Accept-Ranges', - 'Access-Control-Allow-Credentials', - 'Access-Control-Allow-Headers', - 'Access-Control-Allow-Methods', - 'Access-Control-Allow-Origin', - 'Access-Control-Expose-Headers', - 'Access-Control-Max-Age', - 'Access-Control-Request-Headers', - 'Access-Control-Request-Method', - 'Age', - 'Allow', - 'Alt-Svc', - 'Alt-Used', - 'Authorization', - 'Cache-Control', - 'Clear-Site-Data', - 'Connection', - 'Content-Disposition', - 'Content-Encoding', - 'Content-Language', - 'Content-Length', - 'Content-Location', - 'Content-Range', - 'Content-Security-Policy', - 'Content-Security-Policy-Report-Only', - 'Content-Type', - 'Cookie', - 'Cross-Origin-Embedder-Policy', - 'Cross-Origin-Opener-Policy', - 'Cross-Origin-Resource-Policy', - 'Date', - 'Device-Memory', - 'Downlink', - 'ECT', - 'ETag', - 'Expect', - 'Expect-CT', - 'Expires', - 'Forwarded', - 'From', - 'Host', - 'If-Match', - 'If-Modified-Since', - 'If-None-Match', - 'If-Range', - 'If-Unmodified-Since', - 'Keep-Alive', - 'Last-Modified', - 'Link', - 'Location', - 'Max-Forwards', - 'Origin', - 'Permissions-Policy', - 'Pragma', - 'Proxy-Authenticate', - 'Proxy-Authorization', - 'RTT', - 'Range', - 'Referer', - 'Referrer-Policy', - 'Refresh', - 'Retry-After', - 'Sec-WebSocket-Accept', - 'Sec-WebSocket-Extensions', - 'Sec-WebSocket-Key', - 'Sec-WebSocket-Protocol', - 'Sec-WebSocket-Version', - 'Server', - 'Server-Timing', - 'Service-Worker-Allowed', - 'Service-Worker-Navigation-Preload', - 'Set-Cookie', - 'SourceMap', - 'Strict-Transport-Security', - 'Supports-Loading-Mode', - 'TE', - 'Timing-Allow-Origin', - 'Trailer', - 'Transfer-Encoding', - 'Upgrade', - 'Upgrade-Insecure-Requests', - 'User-Agent', - 'Vary', - 'Via', - 'WWW-Authenticate', - 'X-Content-Type-Options', - 'X-DNS-Prefetch-Control', - 'X-Frame-Options', - 'X-Permitted-Cross-Domain-Policies', - 'X-Powered-By', - 'X-Requested-With', - 'X-XSS-Protection' -]) + this.typeOfService = typeOfService -/** @type {Record, string>} */ -const headerNameLowerCasedRecord = {} + this.abort = null -// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`. -Object.setPrototypeOf(headerNameLowerCasedRecord, null) + if (body == null) { + this.body = null + } else if (isStream(body)) { + this.body = body -for (let i = 0; i < wellknownHeaderNames.length; ++i) { - const key = wellknownHeaderNames[i] - const lowerCasedKey = key.toLowerCase() - headerNameLowerCasedRecord[key] = headerNameLowerCasedRecord[lowerCasedKey] = - lowerCasedKey -} + const rState = this.body._readableState + if (!rState || !rState.autoDestroy) { + this.endHandler = function autoDestroy () { + destroy(this) + } + this.body.on('end', this.endHandler) + } -module.exports = { - wellknownHeaderNames, - headerNameLowerCasedRecord -} + this.errorHandler = err => { + if (this.abort) { + this.abort(err) + } else { + this.error = err + } + } + this.body.on('error', this.errorHandler) + } else if (isBuffer(body)) { + this.body = body.byteLength ? body : null + } else if (ArrayBuffer.isView(body)) { + this.body = body.buffer.byteLength ? Buffer.from(body.buffer, body.byteOffset, body.byteLength) : null + } else if (body instanceof ArrayBuffer) { + this.body = body.byteLength ? Buffer.from(body) : null + } else if (typeof body === 'string') { + this.body = body.length ? Buffer.from(body) : null + } else if (isFormDataLike(body) || isIterable(body) || isBlobLike(body)) { + this.body = body + } else { + throw new InvalidArgumentError('body must be a string, a Buffer, a Readable stream, an iterable, or an async iterable') + } + this.completed = false + this.aborted = false -/***/ }), + this.upgrade = upgrade || null -/***/ 4765: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + this.path = query ? serializePathWithQuery(path, query) : path -"use strict"; + // TODO: shall we maybe standardize it to an URL object? + this.origin = origin + this.protocol = getProtocolFromUrlString(origin) -const diagnosticsChannel = __nccwpck_require__(3053) -const util = __nccwpck_require__(7975) + this.idempotent = idempotent == null + ? method === 'HEAD' || method === 'GET' || method === 'QUERY' + : idempotent -const undiciDebugLog = util.debuglog('undici') -const fetchDebuglog = util.debuglog('fetch') -const websocketDebuglog = util.debuglog('websocket') + this.blocking = blocking ?? this.method !== 'HEAD' -const channels = { - // Client - beforeConnect: diagnosticsChannel.channel('undici:client:beforeConnect'), - connected: diagnosticsChannel.channel('undici:client:connected'), - connectError: diagnosticsChannel.channel('undici:client:connectError'), - sendHeaders: diagnosticsChannel.channel('undici:client:sendHeaders'), - // Request - create: diagnosticsChannel.channel('undici:request:create'), - bodySent: diagnosticsChannel.channel('undici:request:bodySent'), - bodyChunkSent: diagnosticsChannel.channel('undici:request:bodyChunkSent'), - bodyChunkReceived: diagnosticsChannel.channel('undici:request:bodyChunkReceived'), - headers: diagnosticsChannel.channel('undici:request:headers'), - trailers: diagnosticsChannel.channel('undici:request:trailers'), - error: diagnosticsChannel.channel('undici:request:error'), - // WebSocket - open: diagnosticsChannel.channel('undici:websocket:open'), - close: diagnosticsChannel.channel('undici:websocket:close'), - socketError: diagnosticsChannel.channel('undici:websocket:socket_error'), - ping: diagnosticsChannel.channel('undici:websocket:ping'), - pong: diagnosticsChannel.channel('undici:websocket:pong'), - // ProxyAgent - proxyConnected: diagnosticsChannel.channel('undici:proxy:connected') -} + this.reset = reset == null ? null : reset -let isTrackingClientEvents = false + this.host = null -function trackClientEvents (debugLog = undiciDebugLog) { - if (isTrackingClientEvents) { - return - } + this.contentLength = null - // Check if any of the channels already have subscribers to prevent duplicate subscriptions - // This can happen when both Node.js built-in undici and undici as a dependency are present - if (channels.beforeConnect.hasSubscribers || channels.connected.hasSubscribers || - channels.connectError.hasSubscribers || channels.sendHeaders.hasSubscribers) { - isTrackingClientEvents = true - return - } + this.contentType = null - isTrackingClientEvents = true + this.headers = [] - diagnosticsChannel.subscribe('undici:client:beforeConnect', - evt => { - const { - connectParams: { version, protocol, port, host } - } = evt - debugLog( - 'connecting to %s%s using %s%s', - host, - port ? `:${port}` : '', - protocol, - version - ) - }) + // Only for H2 + this.expectContinue = expectContinue != null ? expectContinue : false - diagnosticsChannel.subscribe('undici:client:connected', - evt => { - const { - connectParams: { version, protocol, port, host } - } = evt - debugLog( - 'connected to %s%s using %s%s', - host, - port ? `:${port}` : '', - protocol, - version - ) - }) + if (Array.isArray(headers)) { + if (headers.length % 2 !== 0) { + throw new InvalidArgumentError('headers array must be even') + } + for (let i = 0; i < headers.length; i += 2) { + processHeader(this, headers[i], headers[i + 1]) + } + } else if (headers && typeof headers === 'object') { + if (hasSafeIterator(headers)) { + for (const header of headers) { + if (!Array.isArray(header) || header.length !== 2) { + throw new InvalidArgumentError('headers must be in key-value pair format') + } + processHeader(this, header[0], header[1]) + } + } else { + const keys = Object.keys(headers) + for (let i = 0; i < keys.length; ++i) { + processHeader(this, keys[i], headers[keys[i]]) + } + } + } else if (headers != null) { + throw new InvalidArgumentError('headers must be an object or an array') + } - diagnosticsChannel.subscribe('undici:client:connectError', - evt => { - const { - connectParams: { version, protocol, port, host }, - error - } = evt - debugLog( - 'connection to %s%s using %s%s errored - %s', - host, - port ? `:${port}` : '', - protocol, - version, - error.message - ) - }) + assertRequestHandler(handler, method, upgrade) - diagnosticsChannel.subscribe('undici:client:sendHeaders', - evt => { - const { - request: { method, path, origin } - } = evt - debugLog('sending request to %s %s%s', method, origin, path) - }) -} + this.servername = servername || getServerName(this.host) || null -let isTrackingRequestEvents = false + this[kHandler] = handler -function trackRequestEvents (debugLog = undiciDebugLog) { - if (isTrackingRequestEvents) { - return + if (channels.create.hasSubscribers) { + channels.create.publish({ request: this }) + } } - // Check if any of the channels already have subscribers to prevent duplicate subscriptions - // This can happen when both Node.js built-in undici and undici as a dependency are present - if (channels.headers.hasSubscribers || channels.trailers.hasSubscribers || - channels.error.hasSubscribers) { - isTrackingRequestEvents = true - return + onBodySent (chunk) { + if (channels.bodyChunkSent.hasSubscribers) { + channels.bodyChunkSent.publish({ request: this, chunk }) + } + if (this[kHandler].onBodySent) { + try { + return this[kHandler].onBodySent(chunk) + } catch (err) { + this.abort(err) + } + } } - isTrackingRequestEvents = true + onRequestSent () { + if (channels.bodySent.hasSubscribers) { + channels.bodySent.publish({ request: this }) + } - diagnosticsChannel.subscribe('undici:request:headers', - evt => { - const { - request: { method, path, origin }, - response: { statusCode } - } = evt - debugLog( - 'received response to %s %s%s - HTTP %d', - method, - origin, - path, - statusCode - ) - }) + if (this[kHandler].onRequestSent) { + try { + return this[kHandler].onRequestSent() + } catch (err) { + this.abort(err) + } + } + } - diagnosticsChannel.subscribe('undici:request:trailers', - evt => { - const { - request: { method, path, origin } - } = evt - debugLog('trailers received from %s %s%s', method, origin, path) - }) + onRequestStart (abort, context) { + assert(!this.aborted) + assert(!this.completed) - diagnosticsChannel.subscribe('undici:request:error', - evt => { - const { - request: { method, path, origin }, - error - } = evt - debugLog( - 'request to %s %s%s errored - %s', - method, - origin, - path, - error.message - ) - }) -} + this[kController] = new RequestController(abort) -let isTrackingWebSocketEvents = false + if (this.error) { + this[kController].abort(this.error) + return + } -function trackWebSocketEvents (debugLog = websocketDebuglog) { - if (isTrackingWebSocketEvents) { - return + this.abort = abort + return this[kHandler].onRequestStart(this[kController], context) } - // Check if any of the channels already have subscribers to prevent duplicate subscriptions - // This can happen when both Node.js built-in undici and undici as a dependency are present - if (channels.open.hasSubscribers || channels.close.hasSubscribers || - channels.socketError.hasSubscribers || channels.ping.hasSubscribers || - channels.pong.hasSubscribers) { - isTrackingWebSocketEvents = true - return + onResponseStarted () { + return this[kHandler].onResponseStarted?.() } - isTrackingWebSocketEvents = true - - diagnosticsChannel.subscribe('undici:websocket:open', - evt => { - if (evt.address != null) { - const { address, port } = evt.address - debugLog('connection opened %s%s', address, port ? `:${port}` : '') - } else { - debugLog('connection opened') - } - }) - - diagnosticsChannel.subscribe('undici:websocket:close', - evt => { - const { websocket, code, reason } = evt - debugLog( - 'closed connection to %s - %s %s', - websocket.url, - code, - reason - ) - }) + onResponseStart (statusCode, headers, resume, statusText) { + assert(!this.aborted) + assert(!this.completed) - diagnosticsChannel.subscribe('undici:websocket:socket_error', - err => { - debugLog('connection errored - %s', err.message) - }) + if (channels.headers.hasSubscribers) { + channels.headers.publish({ request: this, response: { statusCode, headers, statusText } }) + } - diagnosticsChannel.subscribe('undici:websocket:ping', - evt => { - debugLog('ping received') - }) + const controller = this[kController] + if (controller) { + controller[kResume] = resume + controller.rawHeaders = headers + } - diagnosticsChannel.subscribe('undici:websocket:pong', - evt => { - debugLog('pong received') - }) -} + const parsedHeaders = Array.isArray(headers) ? parseHeaders(headers) : headers -if (undiciDebugLog.enabled || fetchDebuglog.enabled) { - trackClientEvents(fetchDebuglog.enabled ? fetchDebuglog : undiciDebugLog) - trackRequestEvents(fetchDebuglog.enabled ? fetchDebuglog : undiciDebugLog) -} + try { + this[kHandler].onResponseStart?.(controller, statusCode, parsedHeaders, statusText) + return !controller?.paused + } catch (err) { + this.abort(err) + return false + } + } -if (websocketDebuglog.enabled) { - trackClientEvents(undiciDebugLog.enabled ? undiciDebugLog : websocketDebuglog) - trackWebSocketEvents(websocketDebuglog) -} + onResponseData (chunk) { + assert(!this.aborted) + assert(!this.completed) -module.exports = { - channels -} + if (channels.bodyChunkReceived.hasSubscribers) { + channels.bodyChunkReceived.publish({ request: this, chunk }) + } + const controller = this[kController] + try { + this[kHandler].onResponseData?.(controller, chunk) + return !controller?.paused + } catch (err) { + this.abort(err) + return false + } + } -/***/ }), + /** + * @param {number} statusCode + * @param {Buffer[]|string[]|import('../../types/header.d.ts').IncomingHttpHeaders} headers + * @param {import('node:stream').Duplex} socket + * @param {string} [statusText] + */ + onRequestUpgrade (statusCode, headers, socket, statusText = '') { + this.onFinally() -/***/ 7062: -/***/ ((module) => { + assert(!this.aborted) + assert(!this.completed) -"use strict"; + if (channels.headers.hasSubscribers) { + channels.headers.publish({ request: this, response: { statusCode, headers, statusText } }) + } + const controller = this[kController] + if (controller) { + controller.rawHeaders = headers + } -const kUndiciError = Symbol.for('undici.error.UND_ERR') -class UndiciError extends Error { - constructor (message, options) { - super(message, options) - this.name = 'UndiciError' - this.code = 'UND_ERR' - } + const parsedHeaders = Array.isArray(headers) ? parseHeaders(headers) : headers - static [Symbol.hasInstance] (instance) { - return instance && instance[kUndiciError] === true - } + const result = this[kHandler].onRequestUpgrade?.(controller, statusCode, parsedHeaders, socket) - get [kUndiciError] () { - return true - } -} + if (!this.aborted) { + this.completed = true + if (channels.trailers.hasSubscribers) { + channels.trailers.publish({ request: this, trailers: [] }) + } + } -const kConnectTimeoutError = Symbol.for('undici.error.UND_ERR_CONNECT_TIMEOUT') -class ConnectTimeoutError extends UndiciError { - constructor (message) { - super(message) - this.name = 'ConnectTimeoutError' - this.message = message || 'Connect Timeout Error' - this.code = 'UND_ERR_CONNECT_TIMEOUT' + return result } - static [Symbol.hasInstance] (instance) { - return instance && instance[kConnectTimeoutError] === true - } + onResponseEnd (trailers) { + this.onFinally() - get [kConnectTimeoutError] () { - return true - } -} + assert(!this.aborted) + assert(!this.completed) -const kHeadersTimeoutError = Symbol.for('undici.error.UND_ERR_HEADERS_TIMEOUT') -class HeadersTimeoutError extends UndiciError { - constructor (message) { - super(message) - this.name = 'HeadersTimeoutError' - this.message = message || 'Headers Timeout Error' - this.code = 'UND_ERR_HEADERS_TIMEOUT' - } + this.completed = true + if (channels.trailers.hasSubscribers) { + channels.trailers.publish({ request: this, trailers }) + } - static [Symbol.hasInstance] (instance) { - return instance && instance[kHeadersTimeoutError] === true - } + const controller = this[kController] + if (controller) { + controller.rawTrailers = trailers + } - get [kHeadersTimeoutError] () { - return true - } -} + const parsedTrailers = Array.isArray(trailers) ? parseHeaders(trailers) : trailers -const kHeadersOverflowError = Symbol.for('undici.error.UND_ERR_HEADERS_OVERFLOW') -class HeadersOverflowError extends UndiciError { - constructor (message) { - super(message) - this.name = 'HeadersOverflowError' - this.message = message || 'Headers Overflow Error' - this.code = 'UND_ERR_HEADERS_OVERFLOW' + try { + return this[kHandler].onResponseEnd?.(controller, parsedTrailers) + } catch (err) { + // TODO (fix): This might be a bad idea? + this.onResponseError(err) + } } - static [Symbol.hasInstance] (instance) { - return instance && instance[kHeadersOverflowError] === true - } + onResponseError (error) { + this.onFinally() - get [kHeadersOverflowError] () { - return true - } -} + if (channels.error.hasSubscribers) { + channels.error.publish({ request: this, error }) + } -const kBodyTimeoutError = Symbol.for('undici.error.UND_ERR_BODY_TIMEOUT') -class BodyTimeoutError extends UndiciError { - constructor (message) { - super(message) - this.name = 'BodyTimeoutError' - this.message = message || 'Body Timeout Error' - this.code = 'UND_ERR_BODY_TIMEOUT' - } + if (this.aborted) { + return + } + this.aborted = true - static [Symbol.hasInstance] (instance) { - return instance && instance[kBodyTimeoutError] === true - } + const controller = this[kController] - get [kBodyTimeoutError] () { - return true + return this[kHandler].onResponseError?.(controller, error) } -} -const kInvalidArgumentError = Symbol.for('undici.error.UND_ERR_INVALID_ARG') -class InvalidArgumentError extends UndiciError { - constructor (message) { - super(message) - this.name = 'InvalidArgumentError' - this.message = message || 'Invalid Argument Error' - this.code = 'UND_ERR_INVALID_ARG' - } + onFinally () { + if (this.errorHandler) { + this.body.off('error', this.errorHandler) + this.errorHandler = null + } - static [Symbol.hasInstance] (instance) { - return instance && instance[kInvalidArgumentError] === true + if (this.endHandler) { + this.body.off('end', this.endHandler) + this.endHandler = null + } } - get [kInvalidArgumentError] () { - return true + addHeader (key, value) { + processHeader(this, key, value) + return this } } -const kInvalidReturnValueError = Symbol.for('undici.error.UND_ERR_INVALID_RETURN_VALUE') -class InvalidReturnValueError extends UndiciError { - constructor (message) { - super(message) - this.name = 'InvalidReturnValueError' - this.message = message || 'Invalid Return Value Error' - this.code = 'UND_ERR_INVALID_RETURN_VALUE' +function processHeader (request, key, val) { + if (val && (typeof val === 'object' && !Array.isArray(val))) { + throw new InvalidArgumentError(`invalid ${key} header`) + } else if (val === undefined) { + return } - static [Symbol.hasInstance] (instance) { - return instance && instance[kInvalidReturnValueError] === true - } + let headerName = headerNameLowerCasedRecord[key] - get [kInvalidReturnValueError] () { - return true + if (headerName === undefined) { + headerName = key.toLowerCase() + if (headerNameLowerCasedRecord[headerName] === undefined && !isValidHTTPToken(headerName)) { + throw new InvalidArgumentError('invalid header key') + } } -} -const kAbortError = Symbol.for('undici.error.UND_ERR_ABORT') -class AbortError extends UndiciError { - constructor (message) { - super(message) - this.name = 'AbortError' - this.message = message || 'The operation was aborted' - this.code = 'UND_ERR_ABORT' + if (Array.isArray(val)) { + const arr = [] + for (let i = 0; i < val.length; i++) { + if (typeof val[i] === 'string') { + if (!isValidHeaderValue(val[i])) { + throw new InvalidArgumentError(`invalid ${key} header`) + } + arr.push(val[i]) + } else if (val[i] === null) { + arr.push('') + } else if (typeof val[i] === 'object') { + throw new InvalidArgumentError(`invalid ${key} header`) + } else { + // Coerce primitives (and reject unsafe coercions such as functions + // with a crafted toString/Symbol.toPrimitive). + const str = `${val[i]}` + if (!isValidHeaderValue(str)) { + throw new InvalidArgumentError(`invalid ${key} header`) + } + arr.push(str) + } + } + val = arr + } else if (typeof val === 'string') { + if (!isValidHeaderValue(val)) { + throw new InvalidArgumentError(`invalid ${key} header`) + } + } else if (val === null) { + val = '' + } else { + // Coerce primitives (and reject unsafe coercions such as functions + // with a crafted toString/Symbol.toPrimitive). + val = `${val}` + if (!isValidHeaderValue(val)) { + throw new InvalidArgumentError(`invalid ${key} header`) + } } - static [Symbol.hasInstance] (instance) { - return instance && instance[kAbortError] === true - } + if (headerName === 'host') { + if (request.host !== null) { + throw new InvalidArgumentError('duplicate host header') + } + if (typeof val !== 'string') { + throw new InvalidArgumentError('invalid host header') + } + // Consumed by Client + request.host = val + } else if (headerName === 'content-length') { + if (request.contentLength !== null) { + throw new InvalidArgumentError('duplicate content-length header') + } + if (!isValidContentLengthHeaderValue(val)) { + throw new InvalidArgumentError('invalid content-length header') + } + request.contentLength = parseInt(val, 10) + } else if (request.contentType === null && headerName === 'content-type') { + request.contentType = val + request.headers.push(key, val) + } else if (headerName === 'transfer-encoding' || headerName === 'keep-alive' || headerName === 'upgrade') { + throw new InvalidArgumentError(`invalid ${headerName} header`) + } else if (headerName === 'connection') { + // Per RFC 7230 Section 6.1, Connection header can contain + // a comma-separated list of connection option tokens (header names) + const value = typeof val === 'string' ? val : null + if (value === null) { + throw new InvalidArgumentError('invalid connection header') + } - get [kAbortError] () { - return true + for (const token of value.toLowerCase().split(',')) { + const trimmed = token.trim() + if (!isValidHTTPToken(trimmed)) { + throw new InvalidArgumentError('invalid connection header') + } + if (trimmed === 'close') { + request.reset = true + } + } + } else if (headerName === 'expect') { + throw new NotSupportedError('expect header not supported') + } else { + request.headers.push(key, val) } } -const kRequestAbortedError = Symbol.for('undici.error.UND_ERR_ABORTED') -class RequestAbortedError extends AbortError { - constructor (message) { - super(message) - this.name = 'AbortError' - this.message = message || 'Request aborted' - this.code = 'UND_ERR_ABORTED' - } - - static [Symbol.hasInstance] (instance) { - return instance && instance[kRequestAbortedError] === true - } +module.exports = Request - get [kRequestAbortedError] () { - return true - } -} -const kInformationalError = Symbol.for('undici.error.UND_ERR_INFO') -class InformationalError extends UndiciError { - constructor (message, options) { - super(message, options) - this.name = 'InformationalError' - this.message = message || 'Request information' - this.code = 'UND_ERR_INFO' - } +/***/ }), - static [Symbol.hasInstance] (instance) { - return instance && instance[kInformationalError] === true - } +/***/ 4037: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - get [kInformationalError] () { - return true - } -} +"use strict"; -const kRequestContentLengthMismatchError = Symbol.for('undici.error.UND_ERR_REQ_CONTENT_LENGTH_MISMATCH') -class RequestContentLengthMismatchError extends UndiciError { - constructor (message) { - super(message) - this.name = 'RequestContentLengthMismatchError' - this.message = message || 'Request body length does not match content-length header' - this.code = 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH' - } - static [Symbol.hasInstance] (instance) { - return instance && instance[kRequestContentLengthMismatchError] === true - } +const { EventEmitter } = __nccwpck_require__(8474) +const { Buffer } = __nccwpck_require__(4573) +const { InvalidArgumentError, Socks5ProxyError } = __nccwpck_require__(4882) +const { debuglog } = __nccwpck_require__(7975) +const { parseAddress } = __nccwpck_require__(4933) - get [kRequestContentLengthMismatchError] () { - return true - } -} +const debug = debuglog('undici:socks5') +const EMPTY_BUFFER = Buffer.alloc(0) -const kResponseContentLengthMismatchError = Symbol.for('undici.error.UND_ERR_RES_CONTENT_LENGTH_MISMATCH') -class ResponseContentLengthMismatchError extends UndiciError { - constructor (message) { - super(message) - this.name = 'ResponseContentLengthMismatchError' - this.message = message || 'Response body length does not match content-length header' - this.code = 'UND_ERR_RES_CONTENT_LENGTH_MISMATCH' - } +// SOCKS5 constants +const SOCKS_VERSION = 0x05 - static [Symbol.hasInstance] (instance) { - return instance && instance[kResponseContentLengthMismatchError] === true - } +// Authentication methods +const AUTH_METHODS = { + NO_AUTH: 0x00, + GSSAPI: 0x01, + USERNAME_PASSWORD: 0x02, + NO_ACCEPTABLE: 0xFF +} - get [kResponseContentLengthMismatchError] () { - return true - } +// SOCKS5 commands +const COMMANDS = { + CONNECT: 0x01, + BIND: 0x02, + UDP_ASSOCIATE: 0x03 } -const kClientDestroyedError = Symbol.for('undici.error.UND_ERR_DESTROYED') -class ClientDestroyedError extends UndiciError { - constructor (message) { - super(message) - this.name = 'ClientDestroyedError' - this.message = message || 'The client is destroyed' - this.code = 'UND_ERR_DESTROYED' - } +// Address types +const ADDRESS_TYPES = { + IPV4: 0x01, + DOMAIN: 0x03, + IPV6: 0x04 +} - static [Symbol.hasInstance] (instance) { - return instance && instance[kClientDestroyedError] === true - } - - get [kClientDestroyedError] () { - return true - } +// Reply codes +const REPLY_CODES = { + SUCCEEDED: 0x00, + GENERAL_FAILURE: 0x01, + CONNECTION_NOT_ALLOWED: 0x02, + NETWORK_UNREACHABLE: 0x03, + HOST_UNREACHABLE: 0x04, + CONNECTION_REFUSED: 0x05, + TTL_EXPIRED: 0x06, + COMMAND_NOT_SUPPORTED: 0x07, + ADDRESS_TYPE_NOT_SUPPORTED: 0x08 } -const kClientClosedError = Symbol.for('undici.error.UND_ERR_CLOSED') -class ClientClosedError extends UndiciError { - constructor (message) { - super(message) - this.name = 'ClientClosedError' - this.message = message || 'The client is closed' - this.code = 'UND_ERR_CLOSED' - } +// State machine states +const STATES = { + INITIAL: 'initial', + HANDSHAKING: 'handshaking', + AUTHENTICATING: 'authenticating', + AUTHENTICATED: 'authenticated', + CONNECTING: 'connecting', + CONNECTED: 'connected', + ERROR: 'error', + CLOSED: 'closed' +} - static [Symbol.hasInstance] (instance) { - return instance && instance[kClientClosedError] === true - } +/** + * SOCKS5 client implementation + * Handles SOCKS5 protocol negotiation and connection establishment + */ +class Socks5Client extends EventEmitter { + constructor (socket, options = {}) { + super() - get [kClientClosedError] () { - return true - } -} + if (!socket) { + throw new InvalidArgumentError('socket is required') + } -const kSocketError = Symbol.for('undici.error.UND_ERR_SOCKET') -class SocketError extends UndiciError { - constructor (message, socket) { - super(message) - this.name = 'SocketError' - this.message = message || 'Socket error' - this.code = 'UND_ERR_SOCKET' this.socket = socket - } + this.options = options + this.state = STATES.INITIAL + this.buffer = EMPTY_BUFFER + this.onSocketData = this.onData.bind(this) + this.onSocketError = this.onError.bind(this) + this.onSocketClose = this.onClose.bind(this) - static [Symbol.hasInstance] (instance) { - return instance && instance[kSocketError] === true - } + // Authentication settings + this.authMethods = [] + if (options.username && options.password) { + this.authMethods.push(AUTH_METHODS.USERNAME_PASSWORD) + } + this.authMethods.push(AUTH_METHODS.NO_AUTH) - get [kSocketError] () { - return true + // Socket event handlers + this.socket.on('data', this.onSocketData) + this.socket.on('error', this.onSocketError) + this.socket.on('close', this.onSocketClose) } -} -const kNotSupportedError = Symbol.for('undici.error.UND_ERR_NOT_SUPPORTED') -class NotSupportedError extends UndiciError { - constructor (message) { - super(message) - this.name = 'NotSupportedError' - this.message = message || 'Not supported error' - this.code = 'UND_ERR_NOT_SUPPORTED' - } + /** + * Handle incoming data from the socket + */ + onData (data) { + debug('received data', data.length, 'bytes in state', this.state) + this.buffer = Buffer.concat([this.buffer, data]) - static [Symbol.hasInstance] (instance) { - return instance && instance[kNotSupportedError] === true + try { + switch (this.state) { + case STATES.HANDSHAKING: + this.handleHandshakeResponse() + break + case STATES.AUTHENTICATING: + this.handleAuthResponse() + break + case STATES.CONNECTING: + this.handleConnectResponse() + break + } + } catch (err) { + this.onError(err) + } } - get [kNotSupportedError] () { - return true + /** + * Handle socket errors + */ + onError (err) { + debug('socket error', err) + this.state = STATES.ERROR + this.emit('error', err) + this.destroy() } -} -const kBalancedPoolMissingUpstreamError = Symbol.for('undici.error.UND_ERR_BPL_MISSING_UPSTREAM') -class BalancedPoolMissingUpstreamError extends UndiciError { - constructor (message) { - super(message) - this.name = 'MissingUpstreamError' - this.message = message || 'No upstream has been added to the BalancedPool' - this.code = 'UND_ERR_BPL_MISSING_UPSTREAM' + /** + * Handle socket close + */ + onClose () { + debug('socket closed') + this.state = STATES.CLOSED + this.emit('close') } - static [Symbol.hasInstance] (instance) { - return instance && instance[kBalancedPoolMissingUpstreamError] === true + /** + * Destroy the client and underlying socket + */ + destroy () { + if (this.socket && !this.socket.destroyed) { + this.socket.destroy() + } } - get [kBalancedPoolMissingUpstreamError] () { - return true + markAuthenticated () { + this.state = STATES.AUTHENTICATED + this.emit('authenticated') } -} -const kHTTPParserError = Symbol.for('undici.error.UND_ERR_HTTP_PARSER') -class HTTPParserError extends Error { - constructor (message, code, data) { - super(message) - this.name = 'HTTPParserError' - this.code = code ? `HPE_${code}` : undefined - this.data = data ? data.toString() : undefined - } + /** + * Start the SOCKS5 handshake + */ + handshake () { + if (this.state !== STATES.INITIAL) { + throw new InvalidArgumentError('Handshake already started') + } - static [Symbol.hasInstance] (instance) { - return instance && instance[kHTTPParserError] === true - } + debug('starting handshake with', this.authMethods.length, 'auth methods') + this.state = STATES.HANDSHAKING - get [kHTTPParserError] () { - return true - } -} + // Build handshake request + // +----+----------+----------+ + // |VER | NMETHODS | METHODS | + // +----+----------+----------+ + // | 1 | 1 | 1 to 255 | + // +----+----------+----------+ + const request = Buffer.alloc(2 + this.authMethods.length) + request[0] = SOCKS_VERSION + request[1] = this.authMethods.length + this.authMethods.forEach((method, i) => { + request[2 + i] = method + }) -const kResponseExceededMaxSizeError = Symbol.for('undici.error.UND_ERR_RES_EXCEEDED_MAX_SIZE') -class ResponseExceededMaxSizeError extends UndiciError { - constructor (message) { - super(message) - this.name = 'ResponseExceededMaxSizeError' - this.message = message || 'Response content exceeded max size' - this.code = 'UND_ERR_RES_EXCEEDED_MAX_SIZE' + this.socket.write(request) } - static [Symbol.hasInstance] (instance) { - return instance && instance[kResponseExceededMaxSizeError] === true - } + /** + * Handle handshake response from server + */ + handleHandshakeResponse () { + if (this.buffer.length < 2) { + return // Not enough data yet + } - get [kResponseExceededMaxSizeError] () { - return true - } -} + const version = this.buffer[0] + const method = this.buffer[1] -const kRequestRetryError = Symbol.for('undici.error.UND_ERR_REQ_RETRY') -class RequestRetryError extends UndiciError { - constructor (message, code, { headers, data }) { - super(message) - this.name = 'RequestRetryError' - this.message = message || 'Request retry error' - this.code = 'UND_ERR_REQ_RETRY' - this.statusCode = code - this.data = data - this.headers = headers - } + if (version !== SOCKS_VERSION) { + throw new Socks5ProxyError(`Invalid SOCKS version: ${version}`, 'UND_ERR_SOCKS5_VERSION') + } - static [Symbol.hasInstance] (instance) { - return instance && instance[kRequestRetryError] === true - } + if (method === AUTH_METHODS.NO_ACCEPTABLE) { + throw new Socks5ProxyError('No acceptable authentication method', 'UND_ERR_SOCKS5_AUTH_REJECTED') + } - get [kRequestRetryError] () { - return true - } -} + this.buffer = this.buffer.subarray(2) + debug('server selected auth method', method) -const kResponseError = Symbol.for('undici.error.UND_ERR_RESPONSE') -class ResponseError extends UndiciError { - constructor (message, code, { headers, body }) { - super(message) - this.name = 'ResponseError' - this.message = message || 'Response error' - this.code = 'UND_ERR_RESPONSE' - this.statusCode = code - this.body = body - this.headers = headers + if (method === AUTH_METHODS.NO_AUTH) { + this.markAuthenticated() + } else if (method === AUTH_METHODS.USERNAME_PASSWORD) { + this.state = STATES.AUTHENTICATING + this.sendAuthRequest() + } else { + throw new Socks5ProxyError(`Unsupported authentication method: ${method}`, 'UND_ERR_SOCKS5_AUTH_METHOD') + } } - static [Symbol.hasInstance] (instance) { - return instance && instance[kResponseError] === true - } + /** + * Send username/password authentication request + */ + sendAuthRequest () { + const { username, password } = this.options - get [kResponseError] () { - return true - } -} + if (!username || !password) { + throw new InvalidArgumentError('Username and password required for authentication') + } -const kSecureProxyConnectionError = Symbol.for('undici.error.UND_ERR_PRX_TLS') -class SecureProxyConnectionError extends UndiciError { - constructor (cause, message, options = {}) { - super(message, { cause, ...options }) - this.name = 'SecureProxyConnectionError' - this.message = message || 'Secure Proxy Connection failed' - this.code = 'UND_ERR_PRX_TLS' - this.cause = cause - } + debug('sending username/password auth') - static [Symbol.hasInstance] (instance) { - return instance && instance[kSecureProxyConnectionError] === true - } + // Username/Password authentication request (RFC 1929) + // +----+------+----------+------+----------+ + // |VER | ULEN | UNAME | PLEN | PASSWD | + // +----+------+----------+------+----------+ + // | 1 | 1 | 1 to 255 | 1 | 1 to 255 | + // +----+------+----------+------+----------+ + const usernameBuffer = Buffer.from(username) + const passwordBuffer = Buffer.from(password) - get [kSecureProxyConnectionError] () { - return true - } -} + if (usernameBuffer.length > 255 || passwordBuffer.length > 255) { + throw new InvalidArgumentError('Username or password too long') + } -const kProxyConnectionError = Symbol.for('undici.error.UND_ERR_PRX_CONN') -class ProxyConnectionError extends UndiciError { - constructor (cause, message, options = {}) { - super(message, { cause, ...options }) - this.name = 'ProxyConnectionError' - this.message = message || 'Proxy Connection failed' - this.code = 'UND_ERR_PRX_CONN' - this.cause = cause - } + const request = Buffer.alloc(3 + usernameBuffer.length + passwordBuffer.length) + request[0] = 0x01 // Sub-negotiation version + request[1] = usernameBuffer.length + usernameBuffer.copy(request, 2) + request[2 + usernameBuffer.length] = passwordBuffer.length + passwordBuffer.copy(request, 3 + usernameBuffer.length) - static [Symbol.hasInstance] (instance) { - return instance && instance[kProxyConnectionError] === true + this.socket.write(request) } - get [kProxyConnectionError] () { - return true - } -} + /** + * Handle authentication response + */ + handleAuthResponse () { + if (this.buffer.length < 2) { + return // Not enough data yet + } -const kMaxOriginsReachedError = Symbol.for('undici.error.UND_ERR_MAX_ORIGINS_REACHED') -class MaxOriginsReachedError extends UndiciError { - constructor (message) { - super(message) - this.name = 'MaxOriginsReachedError' - this.message = message || 'Maximum allowed origins reached' - this.code = 'UND_ERR_MAX_ORIGINS_REACHED' - } + const version = this.buffer[0] + const status = this.buffer[1] - static [Symbol.hasInstance] (instance) { - return instance && instance[kMaxOriginsReachedError] === true - } + if (version !== 0x01) { + throw new Socks5ProxyError(`Invalid auth sub-negotiation version: ${version}`, 'UND_ERR_SOCKS5_AUTH_VERSION') + } - get [kMaxOriginsReachedError] () { - return true - } -} + if (status !== 0x00) { + throw new Socks5ProxyError('Authentication failed', 'UND_ERR_SOCKS5_AUTH_FAILED') + } -class Socks5ProxyError extends UndiciError { - constructor (message, code) { - super(message) - this.name = 'Socks5ProxyError' - this.message = message || 'SOCKS5 proxy error' - this.code = code || 'UND_ERR_SOCKS5' + this.buffer = this.buffer.subarray(2) + debug('authentication successful') + this.markAuthenticated() } -} -const kMessageSizeExceededError = Symbol.for('undici.error.UND_ERR_WS_MESSAGE_SIZE_EXCEEDED') -class MessageSizeExceededError extends UndiciError { - constructor (message) { - super(message) - this.name = 'MessageSizeExceededError' - this.message = message || 'Max decompressed message size exceeded' - this.code = 'UND_ERR_WS_MESSAGE_SIZE_EXCEEDED' - } + /** + * Send CONNECT command + * @param {string} address - Target address (IP or domain) + * @param {number} port - Target port + */ + connect (address, port) { + if (this.state === STATES.CONNECTING || this.state === STATES.CONNECTED) { + throw new InvalidArgumentError('Connection already in progress') + } - static [Symbol.hasInstance] (instance) { - return instance && instance[kMessageSizeExceededError] === true - } + if (this.state !== STATES.AUTHENTICATED) { + throw new InvalidArgumentError('Client must be authenticated before CONNECT') + } - get [kMessageSizeExceededError] () { - return true - } -} + debug('connecting to', address, port) + this.state = STATES.CONNECTING -module.exports = { - AbortError, - HTTPParserError, - UndiciError, - HeadersTimeoutError, - HeadersOverflowError, - BodyTimeoutError, - RequestContentLengthMismatchError, - ConnectTimeoutError, - InvalidArgumentError, - InvalidReturnValueError, - RequestAbortedError, - ClientDestroyedError, - ClientClosedError, - InformationalError, - SocketError, - NotSupportedError, - ResponseContentLengthMismatchError, - BalancedPoolMissingUpstreamError, - ResponseExceededMaxSizeError, - RequestRetryError, - ResponseError, - SecureProxyConnectionError, - ProxyConnectionError, - MaxOriginsReachedError, - Socks5ProxyError, - MessageSizeExceededError -} + const request = this.buildConnectRequest(COMMANDS.CONNECT, address, port) + this.socket.write(request) + } + /** + * Build a SOCKS5 request + */ + buildConnectRequest (command, address, port) { + // Parse address to determine type and buffer + const { type: addressType, buffer: addressBuffer } = parseAddress(address) -/***/ }), + // Build request + // +----+-----+-------+------+----------+----------+ + // |VER | CMD | RSV | ATYP | DST.ADDR | DST.PORT | + // +----+-----+-------+------+----------+----------+ + // | 1 | 1 | X'00' | 1 | Variable | 2 | + // +----+-----+-------+------+----------+----------+ + const request = Buffer.alloc(4 + addressBuffer.length + 2) + request[0] = SOCKS_VERSION + request[1] = command + request[2] = 0x00 // Reserved + request[3] = addressType + addressBuffer.copy(request, 4) + request.writeUInt16BE(port, 4 + addressBuffer.length) -/***/ 84: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return request + } -"use strict"; + /** + * Handle CONNECT response + */ + handleConnectResponse () { + if (this.buffer.length < 4) { + return // Not enough data for header + } + const version = this.buffer[0] + const reply = this.buffer[1] + const addressType = this.buffer[3] -const { - InvalidArgumentError, - NotSupportedError -} = __nccwpck_require__(7062) -const assert = __nccwpck_require__(4589) -const { - isValidHTTPToken, - isValidHeaderValue, - isStream, - destroy, - isBuffer, - isFormDataLike, - isIterable, - hasSafeIterator, - isBlobLike, - serializePathWithQuery, - parseHeaders, - assertRequestHandler, - getServerName, - normalizedMethodRecords, - getProtocolFromUrlString -} = __nccwpck_require__(9705) -const { channels } = __nccwpck_require__(4765) -const { headerNameLowerCasedRecord } = __nccwpck_require__(5368) + if (version !== SOCKS_VERSION) { + throw new Socks5ProxyError(`Invalid SOCKS version in reply: ${version}`, 'UND_ERR_SOCKS5_REPLY_VERSION') + } -// Verifies that a given path is valid does not contain control chars \x00 to \x20 -const invalidPathRegex = /[^\u0021-\u00ff]/ + // Calculate the expected response length + let responseLength = 4 // VER + REP + RSV + ATYP + if (addressType === ADDRESS_TYPES.IPV4) { + responseLength += 4 + 2 // IPv4 + port + } else if (addressType === ADDRESS_TYPES.DOMAIN) { + if (this.buffer.length < 5) { + return // Need domain length byte + } + responseLength += 1 + this.buffer[4] + 2 // length byte + domain + port + } else if (addressType === ADDRESS_TYPES.IPV6) { + responseLength += 16 + 2 // IPv6 + port + } else { + throw new Socks5ProxyError(`Invalid address type in reply: ${addressType}`, 'UND_ERR_SOCKS5_ADDR_TYPE') + } -function isValidContentLengthHeaderValue (val) { - if (typeof val !== 'string' || val.length === 0) { - return false - } + if (this.buffer.length < responseLength) { + return // Not enough data for full response + } - for (let i = 0; i < val.length; i++) { - const charCode = val.charCodeAt(i) - if (charCode < 48 || charCode > 57) { - return false + if (reply !== REPLY_CODES.SUCCEEDED) { + const errorMessage = this.getReplyErrorMessage(reply) + throw new Socks5ProxyError(`SOCKS5 connection failed: ${errorMessage}`, `UND_ERR_SOCKS5_REPLY_${reply}`) } - } - return true -} - -const kHandler = Symbol('handler') -const kController = Symbol('controller') -const kResume = Symbol('resume') - -class RequestController { - #paused = false - #reason = null - #aborted = false - #abort + // Parse bound address and port + let boundAddress + let offset = 4 - [kResume] = null + if (addressType === ADDRESS_TYPES.IPV4) { + boundAddress = Array.from(this.buffer.subarray(offset, offset + 4)).join('.') + offset += 4 + } else if (addressType === ADDRESS_TYPES.DOMAIN) { + const domainLength = this.buffer[offset] + offset += 1 + boundAddress = this.buffer.subarray(offset, offset + domainLength).toString() + offset += domainLength + } else if (addressType === ADDRESS_TYPES.IPV6) { + // Parse IPv6 address from 16-byte buffer + const parts = [] + for (let i = 0; i < 8; i++) { + const value = this.buffer.readUInt16BE(offset + i * 2) + parts.push(value.toString(16)) + } + boundAddress = parts.join(':') + offset += 16 + } - rawHeaders = null - rawTrailers = null + const boundPort = this.buffer.readUInt16BE(offset) - constructor (abort) { - this.#abort = abort - } + this.buffer = EMPTY_BUFFER + this.state = STATES.CONNECTED + this.socket.removeListener('data', this.onSocketData) - pause () { - this.#paused = true + debug('connected, bound address:', boundAddress, 'port:', boundPort) + this.emit('connected', { address: boundAddress, port: boundPort }) } - resume () { - if (this.#paused) { - this.#paused = false - this[kResume]?.() + /** + * Get human-readable error message for reply code + */ + getReplyErrorMessage (reply) { + switch (reply) { + case REPLY_CODES.GENERAL_FAILURE: + return 'General SOCKS server failure' + case REPLY_CODES.CONNECTION_NOT_ALLOWED: + return 'Connection not allowed by ruleset' + case REPLY_CODES.NETWORK_UNREACHABLE: + return 'Network unreachable' + case REPLY_CODES.HOST_UNREACHABLE: + return 'Host unreachable' + case REPLY_CODES.CONNECTION_REFUSED: + return 'Connection refused' + case REPLY_CODES.TTL_EXPIRED: + return 'TTL expired' + case REPLY_CODES.COMMAND_NOT_SUPPORTED: + return 'Command not supported' + case REPLY_CODES.ADDRESS_TYPE_NOT_SUPPORTED: + return 'Address type not supported' + default: + return `Unknown error code: ${reply}` } } +} - abort (reason) { - if (!this.#aborted) { - this.#aborted = true - this.#reason = reason - this.#abort(reason) - } - } +module.exports = { + Socks5Client, + AUTH_METHODS, + COMMANDS, + ADDRESS_TYPES, + REPLY_CODES, + STATES +} - get aborted () { - return this.#aborted - } - get reason () { - return this.#reason - } +/***/ }), - get paused () { - return this.#paused - } -} +/***/ 4933: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -class Request { - constructor (origin, { - path, - method, - body, - headers, - query, - idempotent, - blocking, - upgrade, - headersTimeout, - bodyTimeout, - reset, - expectContinue, - servername, - throwOnError, - maxRedirections, - typeOfService - }, handler) { - if (typeof path !== 'string') { - throw new InvalidArgumentError('path must be a string') - } else if ( - path[0] !== '/' && - !(path.startsWith('http://') || path.startsWith('https://')) && - method !== 'CONNECT' - ) { - throw new InvalidArgumentError('path must be an absolute URL or start with a slash') - } else if (invalidPathRegex.test(path)) { - throw new InvalidArgumentError('invalid request path') - } +"use strict"; - if (typeof method !== 'string') { - throw new InvalidArgumentError('method must be a string') - } else if (normalizedMethodRecords[method] === undefined && !isValidHTTPToken(method)) { - throw new InvalidArgumentError('invalid request method') - } - if (upgrade && typeof upgrade !== 'string') { - throw new InvalidArgumentError('upgrade must be a string') - } +const { Buffer } = __nccwpck_require__(4573) +const net = __nccwpck_require__(7030) +const { InvalidArgumentError } = __nccwpck_require__(4882) - if (upgrade && !isValidHeaderValue(upgrade)) { - throw new InvalidArgumentError('invalid upgrade header') +/** + * Parse an address and determine its type + * @param {string} address - The address to parse + * @returns {{type: number, buffer: Buffer}} Address type and buffer + */ +function parseAddress (address) { + // Check if it's an IPv4 address + if (net.isIPv4(address)) { + const parts = address.split('.').map(Number) + return { + type: 0x01, // IPv4 + buffer: Buffer.from(parts) } + } - if (headersTimeout != null && (!Number.isFinite(headersTimeout) || headersTimeout < 0)) { - throw new InvalidArgumentError('invalid headersTimeout') + // Check if it's an IPv6 address + if (net.isIPv6(address)) { + return { + type: 0x04, // IPv6 + buffer: parseIPv6(address) } + } - if (bodyTimeout != null && (!Number.isFinite(bodyTimeout) || bodyTimeout < 0)) { - throw new InvalidArgumentError('invalid bodyTimeout') - } + // Otherwise, treat as domain name + const domainBuffer = Buffer.from(address, 'utf8') + if (domainBuffer.length > 255) { + throw new InvalidArgumentError('Domain name too long (max 255 bytes)') + } - if (reset != null && typeof reset !== 'boolean') { - throw new InvalidArgumentError('invalid reset') - } + return { + type: 0x03, // Domain + buffer: Buffer.concat([Buffer.from([domainBuffer.length]), domainBuffer]) + } +} - if (expectContinue != null && typeof expectContinue !== 'boolean') { - throw new InvalidArgumentError('invalid expectContinue') - } +/** + * Parse IPv6 address to buffer + * @param {string} address - IPv6 address string + * @returns {Buffer} 16-byte buffer + */ +function parseIPv6 (address) { + const buffer = Buffer.alloc(16) + let normalizedAddress = address - if (throwOnError != null) { - throw new InvalidArgumentError('invalid throwOnError') - } + // Expand an embedded IPv4 tail into the last two IPv6 groups. + if (address.includes('.')) { + const lastColonIndex = address.lastIndexOf(':') + const ipv4Part = address.slice(lastColonIndex + 1) - if (maxRedirections != null && maxRedirections !== 0) { - throw new InvalidArgumentError('maxRedirections is not supported, use the redirect interceptor') + if (net.isIPv4(ipv4Part)) { + const octets = ipv4Part.split('.').map(Number) + const high = ((octets[0] << 8) | octets[1]).toString(16) + const low = ((octets[2] << 8) | octets[3]).toString(16) + normalizedAddress = `${address.slice(0, lastColonIndex)}:${high}:${low}` } + } - if (typeOfService != null && (!Number.isInteger(typeOfService) || typeOfService < 0 || typeOfService > 255)) { - throw new InvalidArgumentError('typeOfService must be an integer between 0 and 255') + // Handle compressed notation (::) + const doubleColonIndex = normalizedAddress.indexOf('::') + if (doubleColonIndex !== -1) { + const before = normalizedAddress.slice(0, doubleColonIndex) + const after = normalizedAddress.slice(doubleColonIndex + 2) + const beforeParts = before === '' ? [] : before.split(':') + const afterParts = after === '' ? [] : after.split(':') + + let bufferIndex = 0 + for (const part of beforeParts) { + buffer.writeUInt16BE(parseInt(part, 16), bufferIndex) + bufferIndex += 2 + } + bufferIndex = 16 - afterParts.length * 2 + for (const part of afterParts) { + buffer.writeUInt16BE(parseInt(part, 16), bufferIndex) + bufferIndex += 2 + } + } else { + const parts = normalizedAddress.split(':') + for (let i = 0; i < parts.length; i++) { + buffer.writeUInt16BE(parseInt(parts[i], 16), i * 2) } + } - this.headersTimeout = headersTimeout + return buffer +} - this.bodyTimeout = bodyTimeout +/** + * Build a SOCKS5 address buffer + * @param {number} type - Address type (1=IPv4, 3=Domain, 4=IPv6) + * @param {Buffer} addressBuffer - The address data + * @param {number} port - Port number + * @returns {Buffer} Complete address buffer including type, address, and port + */ +function buildAddressBuffer (type, addressBuffer, port) { + const portBuffer = Buffer.allocUnsafe(2) + portBuffer.writeUInt16BE(port, 0) - this.method = method + return Buffer.concat([ + Buffer.from([type]), + addressBuffer, + portBuffer + ]) +} - this.typeOfService = typeOfService +/** + * Parse address from SOCKS5 response + * @param {Buffer} buffer - Buffer containing the address + * @param {number} offset - Starting offset in buffer + * @returns {{address: string, port: number, bytesRead: number}} + */ +function parseResponseAddress (buffer, offset = 0) { + if (buffer.length < offset + 1) { + throw new InvalidArgumentError('Buffer too small to contain address type') + } - this.abort = null + const addressType = buffer[offset] + let address + let currentOffset = offset + 1 - if (body == null) { - this.body = null - } else if (isStream(body)) { - this.body = body + switch (addressType) { + case 0x01: { // IPv4 + if (buffer.length < currentOffset + 6) { + throw new InvalidArgumentError('Buffer too small for IPv4 address') + } + address = Array.from(buffer.subarray(currentOffset, currentOffset + 4)).join('.') + currentOffset += 4 + break + } - const rState = this.body._readableState - if (!rState || !rState.autoDestroy) { - this.endHandler = function autoDestroy () { - destroy(this) - } - this.body.on('end', this.endHandler) + case 0x03: { // Domain + if (buffer.length < currentOffset + 1) { + throw new InvalidArgumentError('Buffer too small for domain length') } + const domainLength = buffer[currentOffset] + currentOffset += 1 - this.errorHandler = err => { - if (this.abort) { - this.abort(err) - } else { - this.error = err - } + if (buffer.length < currentOffset + domainLength + 2) { + throw new InvalidArgumentError('Buffer too small for domain address') } - this.body.on('error', this.errorHandler) - } else if (isBuffer(body)) { - this.body = body.byteLength ? body : null - } else if (ArrayBuffer.isView(body)) { - this.body = body.buffer.byteLength ? Buffer.from(body.buffer, body.byteOffset, body.byteLength) : null - } else if (body instanceof ArrayBuffer) { - this.body = body.byteLength ? Buffer.from(body) : null - } else if (typeof body === 'string') { - this.body = body.length ? Buffer.from(body) : null - } else if (isFormDataLike(body) || isIterable(body) || isBlobLike(body)) { - this.body = body - } else { - throw new InvalidArgumentError('body must be a string, a Buffer, a Readable stream, an iterable, or an async iterable') + address = buffer.subarray(currentOffset, currentOffset + domainLength).toString('utf8') + currentOffset += domainLength + break } - this.completed = false - this.aborted = false - - this.upgrade = upgrade || null - - this.path = query ? serializePathWithQuery(path, query) : path - - // TODO: shall we maybe standardize it to an URL object? - this.origin = origin - - this.protocol = getProtocolFromUrlString(origin) - - this.idempotent = idempotent == null - ? method === 'HEAD' || method === 'GET' || method === 'QUERY' - : idempotent - - this.blocking = blocking ?? this.method !== 'HEAD' - - this.reset = reset == null ? null : reset - - this.host = null - - this.contentLength = null - - this.contentType = null - - this.headers = [] - - // Only for H2 - this.expectContinue = expectContinue != null ? expectContinue : false - - if (Array.isArray(headers)) { - if (headers.length % 2 !== 0) { - throw new InvalidArgumentError('headers array must be even') - } - for (let i = 0; i < headers.length; i += 2) { - processHeader(this, headers[i], headers[i + 1]) + case 0x04: { // IPv6 + if (buffer.length < currentOffset + 18) { + throw new InvalidArgumentError('Buffer too small for IPv6 address') } - } else if (headers && typeof headers === 'object') { - if (hasSafeIterator(headers)) { - for (const header of headers) { - if (!Array.isArray(header) || header.length !== 2) { - throw new InvalidArgumentError('headers must be in key-value pair format') - } - processHeader(this, header[0], header[1]) - } - } else { - const keys = Object.keys(headers) - for (let i = 0; i < keys.length; ++i) { - processHeader(this, keys[i], headers[keys[i]]) - } + // Convert buffer to IPv6 string + const parts = [] + for (let i = 0; i < 8; i++) { + const value = buffer.readUInt16BE(currentOffset + i * 2) + parts.push(value.toString(16)) } - } else if (headers != null) { - throw new InvalidArgumentError('headers must be an object or an array') - } - - assertRequestHandler(handler, method, upgrade) - - this.servername = servername || getServerName(this.host) || null - - this[kHandler] = handler - - if (channels.create.hasSubscribers) { - channels.create.publish({ request: this }) + address = parts.join(':') + currentOffset += 16 + break } - } - onBodySent (chunk) { - if (channels.bodyChunkSent.hasSubscribers) { - channels.bodyChunkSent.publish({ request: this, chunk }) - } - if (this[kHandler].onBodySent) { - try { - return this[kHandler].onBodySent(chunk) - } catch (err) { - this.abort(err) - } - } + default: + throw new InvalidArgumentError(`Invalid address type: ${addressType}`) } - onRequestSent () { - if (channels.bodySent.hasSubscribers) { - channels.bodySent.publish({ request: this }) - } - - if (this[kHandler].onRequestSent) { - try { - return this[kHandler].onRequestSent() - } catch (err) { - this.abort(err) - } - } + // Parse port + if (buffer.length < currentOffset + 2) { + throw new InvalidArgumentError('Buffer too small for port') } + const port = buffer.readUInt16BE(currentOffset) + currentOffset += 2 - onRequestStart (abort, context) { - assert(!this.aborted) - assert(!this.completed) - - this[kController] = new RequestController(abort) - - if (this.error) { - this[kController].abort(this.error) - return - } - - this.abort = abort - return this[kHandler].onRequestStart(this[kController], context) + return { + address, + port, + bytesRead: currentOffset - offset } +} - onResponseStarted () { - return this[kHandler].onResponseStarted?.() +/** + * Create error for SOCKS5 reply code + * @param {number} replyCode - SOCKS5 reply code + * @returns {Error} Appropriate error object + */ +function createReplyError (replyCode) { + const messages = { + 0x01: 'General SOCKS server failure', + 0x02: 'Connection not allowed by ruleset', + 0x03: 'Network unreachable', + 0x04: 'Host unreachable', + 0x05: 'Connection refused', + 0x06: 'TTL expired', + 0x07: 'Command not supported', + 0x08: 'Address type not supported' } - onResponseStart (statusCode, headers, resume, statusText) { - assert(!this.aborted) - assert(!this.completed) - - if (channels.headers.hasSubscribers) { - channels.headers.publish({ request: this, response: { statusCode, headers, statusText } }) - } + const message = messages[replyCode] || `Unknown SOCKS5 error code: ${replyCode}` + const error = new Error(message) + error.code = `SOCKS5_${replyCode}` + return error +} - const controller = this[kController] - if (controller) { - controller[kResume] = resume - controller.rawHeaders = headers - } +module.exports = { + parseAddress, + parseIPv6, + buildAddressBuffer, + parseResponseAddress, + createReplyError +} - const parsedHeaders = Array.isArray(headers) ? parseHeaders(headers) : headers - try { - this[kHandler].onResponseStart?.(controller, statusCode, parsedHeaders, statusText) - return !controller?.paused - } catch (err) { - this.abort(err) - return false - } - } +/***/ }), - onResponseData (chunk) { - assert(!this.aborted) - assert(!this.completed) +/***/ 228: +/***/ ((module) => { - if (channels.bodyChunkReceived.hasSubscribers) { - channels.bodyChunkReceived.publish({ request: this, chunk }) - } +"use strict"; - const controller = this[kController] - try { - this[kHandler].onResponseData?.(controller, chunk) - return !controller?.paused - } catch (err) { - this.abort(err) - return false - } - } - /** - * @param {number} statusCode - * @param {Buffer[]|string[]|import('../../types/header.d.ts').IncomingHttpHeaders} headers - * @param {import('node:stream').Duplex} socket - * @param {string} [statusText] - */ - onRequestUpgrade (statusCode, headers, socket, statusText = '') { - this.onFinally() - - assert(!this.aborted) - assert(!this.completed) - - if (channels.headers.hasSubscribers) { - channels.headers.publish({ request: this, response: { statusCode, headers, statusText } }) - } - - const controller = this[kController] - if (controller) { - controller.rawHeaders = headers - } +module.exports = { + kClose: Symbol('close'), + kDestroy: Symbol('destroy'), + kDispatch: Symbol('dispatch'), + kUrl: Symbol('url'), + kRequestOrigin: Symbol('request origin'), + kOriginless: Symbol('originless'), + kWriting: Symbol('writing'), + kResuming: Symbol('resuming'), + kQueue: Symbol('queue'), + kConnect: Symbol('connect'), + kConnecting: Symbol('connecting'), + kKeepAliveDefaultTimeout: Symbol('default keep alive timeout'), + kKeepAliveMaxTimeout: Symbol('max keep alive timeout'), + kKeepAliveTimeoutThreshold: Symbol('keep alive timeout threshold'), + kKeepAliveTimeoutValue: Symbol('keep alive timeout'), + kKeepAlive: Symbol('keep alive'), + kHeadersTimeout: Symbol('headers timeout'), + kBodyTimeout: Symbol('body timeout'), + kServerName: Symbol('server name'), + kLocalAddress: Symbol('local address'), + kHost: Symbol('host'), + kNoRef: Symbol('no ref'), + kBodyUsed: Symbol('used'), + kBody: Symbol('abstracted request body'), + kRunning: Symbol('running'), + kBlocking: Symbol('blocking'), + kPending: Symbol('pending'), + kSize: Symbol('size'), + kBusy: Symbol('busy'), + kQueued: Symbol('queued'), + kFree: Symbol('free'), + kConnected: Symbol('connected'), + kClosed: Symbol('closed'), + kNeedDrain: Symbol('need drain'), + kReset: Symbol('reset'), + kDestroyed: Symbol.for('nodejs.stream.destroyed'), + kResume: Symbol('resume'), + kOnError: Symbol('on error'), + kMaxHeadersSize: Symbol('max headers size'), + kRunningIdx: Symbol('running index'), + kPendingIdx: Symbol('pending index'), + kError: Symbol('error'), + kClients: Symbol('clients'), + kClient: Symbol('client'), + kParser: Symbol('parser'), + kOnDestroyed: Symbol('destroy callbacks'), + kPipelining: Symbol('pipelining'), + kSocket: Symbol('socket'), + kHostHeader: Symbol('host header'), + kConnector: Symbol('connector'), + kStrictContentLength: Symbol('strict content length'), + kMaxRedirections: Symbol('maxRedirections'), + kMaxRequests: Symbol('maxRequestsPerClient'), + kProxy: Symbol('proxy agent options'), + kCounter: Symbol('socket request counter'), + kMaxResponseSize: Symbol('max response size'), + kHTTP2Session: Symbol('http2Session'), + kHTTP2Options: Symbol('http2 options'), + kHTTP2SessionState: Symbol('http2Session state'), + kRetryHandlerDefaultRetry: Symbol('retry agent default retry'), + kConstruct: Symbol('constructable'), + kListeners: Symbol('listeners'), + kHTTPContext: Symbol('http context'), + kMaxConcurrentStreams: Symbol('max concurrent streams'), + kHostAuthority: Symbol('host authority'), + kHTTP2InitialWindowSize: Symbol('http2 initial window size'), + kHTTP2ConnectionWindowSize: Symbol('http2 connection window size'), + kEnableConnectProtocol: Symbol('http2session connect protocol'), + kRemoteSettings: Symbol('http2session remote settings'), + kHTTP2Stream: Symbol('http2session client stream'), + kPingInterval: Symbol('ping interval'), + kNoProxyAgent: Symbol('no proxy agent'), + kHttpProxyAgent: Symbol('http proxy agent'), + kHttpsProxyAgent: Symbol('https proxy agent'), + kSocks5ProxyAgent: Symbol('socks5 proxy agent') +} - const parsedHeaders = Array.isArray(headers) ? parseHeaders(headers) : headers - const result = this[kHandler].onRequestUpgrade?.(controller, statusCode, parsedHeaders, socket) +/***/ }), - if (!this.aborted) { - this.completed = true - if (channels.trailers.hasSubscribers) { - channels.trailers.publish({ request: this, trailers: [] }) - } - } +/***/ 3509: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return result - } +"use strict"; - onResponseEnd (trailers) { - this.onFinally() - assert(!this.aborted) - assert(!this.completed) +const { + wellknownHeaderNames, + headerNameLowerCasedRecord +} = __nccwpck_require__(5188) - this.completed = true - if (channels.trailers.hasSubscribers) { - channels.trailers.publish({ request: this, trailers }) +class TstNode { + /** @type {any} */ + value = null + /** @type {null | TstNode} */ + left = null + /** @type {null | TstNode} */ + middle = null + /** @type {null | TstNode} */ + right = null + /** @type {number} */ + code + /** + * @param {string} key + * @param {any} value + * @param {number} index + */ + constructor (key, value, index) { + if (index === undefined || index >= key.length) { + throw new TypeError('Unreachable') } - - const controller = this[kController] - if (controller) { - controller.rawTrailers = trailers + const code = this.code = key.charCodeAt(index) + // check code is ascii string + if (code > 0x7F) { + throw new TypeError('key must be ascii string') } - - const parsedTrailers = Array.isArray(trailers) ? parseHeaders(trailers) : trailers - - try { - return this[kHandler].onResponseEnd?.(controller, parsedTrailers) - } catch (err) { - // TODO (fix): This might be a bad idea? - this.onResponseError(err) + if (key.length !== ++index) { + this.middle = new TstNode(key, value, index) + } else { + this.value = value } } - onResponseError (error) { - this.onFinally() - - if (channels.error.hasSubscribers) { - channels.error.publish({ request: this, error }) + /** + * @param {string} key + * @param {any} value + * @returns {void} + */ + add (key, value) { + const length = key.length + if (length === 0) { + throw new TypeError('Unreachable') } - - if (this.aborted) { - return + let index = 0 + /** + * @type {TstNode} + */ + let node = this + while (true) { + const code = key.charCodeAt(index) + // check code is ascii string + if (code > 0x7F) { + throw new TypeError('key must be ascii string') + } + if (node.code === code) { + if (length === ++index) { + node.value = value + break + } else if (node.middle !== null) { + node = node.middle + } else { + node.middle = new TstNode(key, value, index) + break + } + } else if (node.code < code) { + if (node.left !== null) { + node = node.left + } else { + node.left = new TstNode(key, value, index) + break + } + } else if (node.right !== null) { + node = node.right + } else { + node.right = new TstNode(key, value, index) + break + } } - this.aborted = true - - const controller = this[kController] - - return this[kHandler].onResponseError?.(controller, error) } - onFinally () { - if (this.errorHandler) { - this.body.off('error', this.errorHandler) - this.errorHandler = null - } - - if (this.endHandler) { - this.body.off('end', this.endHandler) - this.endHandler = null + /** + * @param {Uint8Array} key + * @returns {TstNode | null} + */ + search (key) { + const keylength = key.length + let index = 0 + /** + * @type {TstNode|null} + */ + let node = this + while (node !== null && index < keylength) { + let code = key[index] + // A-Z + // First check if it is bigger than 0x5a. + // Lowercase letters have higher char codes than uppercase ones. + // Also we assume that headers will mostly contain lowercase characters. + if (code <= 0x5a && code >= 0x41) { + // Lowercase for uppercase. + code |= 32 + } + while (node !== null) { + if (code === node.code) { + if (keylength === ++index) { + // Returns Node since it is the last key. + return node + } + node = node.middle + break + } + node = node.code < code ? node.left : node.right + } } - } - - addHeader (key, value) { - processHeader(this, key, value) - return this + return null } } -function processHeader (request, key, val) { - if (val && (typeof val === 'object' && !Array.isArray(val))) { - throw new InvalidArgumentError(`invalid ${key} header`) - } else if (val === undefined) { - return - } - - let headerName = headerNameLowerCasedRecord[key] +class TernarySearchTree { + /** @type {TstNode | null} */ + node = null - if (headerName === undefined) { - headerName = key.toLowerCase() - if (headerNameLowerCasedRecord[headerName] === undefined && !isValidHTTPToken(headerName)) { - throw new InvalidArgumentError('invalid header key') + /** + * @param {string} key + * @param {any} value + * @returns {void} + * */ + insert (key, value) { + if (this.node === null) { + this.node = new TstNode(key, value, 0) + } else { + this.node.add(key, value) } } - if (Array.isArray(val)) { - const arr = [] - for (let i = 0; i < val.length; i++) { - if (typeof val[i] === 'string') { - if (!isValidHeaderValue(val[i])) { - throw new InvalidArgumentError(`invalid ${key} header`) - } - arr.push(val[i]) - } else if (val[i] === null) { - arr.push('') - } else if (typeof val[i] === 'object') { - throw new InvalidArgumentError(`invalid ${key} header`) - } else { - // Coerce primitives (and reject unsafe coercions such as functions - // with a crafted toString/Symbol.toPrimitive). - const str = `${val[i]}` - if (!isValidHeaderValue(str)) { - throw new InvalidArgumentError(`invalid ${key} header`) - } - arr.push(str) - } - } - val = arr - } else if (typeof val === 'string') { - if (!isValidHeaderValue(val)) { - throw new InvalidArgumentError(`invalid ${key} header`) - } - } else if (val === null) { - val = '' - } else { - // Coerce primitives (and reject unsafe coercions such as functions - // with a crafted toString/Symbol.toPrimitive). - val = `${val}` - if (!isValidHeaderValue(val)) { - throw new InvalidArgumentError(`invalid ${key} header`) - } + /** + * @param {Uint8Array} key + * @returns {any} + */ + lookup (key) { + return this.node?.search(key)?.value ?? null } +} - if (headerName === 'host') { - if (request.host !== null) { - throw new InvalidArgumentError('duplicate host header') - } - if (typeof val !== 'string') { - throw new InvalidArgumentError('invalid host header') - } - // Consumed by Client - request.host = val - } else if (headerName === 'content-length') { - if (request.contentLength !== null) { - throw new InvalidArgumentError('duplicate content-length header') - } - if (!isValidContentLengthHeaderValue(val)) { - throw new InvalidArgumentError('invalid content-length header') - } - request.contentLength = parseInt(val, 10) - } else if (request.contentType === null && headerName === 'content-type') { - request.contentType = val - request.headers.push(key, val) - } else if (headerName === 'transfer-encoding' || headerName === 'keep-alive' || headerName === 'upgrade') { - throw new InvalidArgumentError(`invalid ${headerName} header`) - } else if (headerName === 'connection') { - // Per RFC 7230 Section 6.1, Connection header can contain - // a comma-separated list of connection option tokens (header names) - const value = typeof val === 'string' ? val : null - if (value === null) { - throw new InvalidArgumentError('invalid connection header') - } +const tree = new TernarySearchTree() - for (const token of value.toLowerCase().split(',')) { - const trimmed = token.trim() - if (!isValidHTTPToken(trimmed)) { - throw new InvalidArgumentError('invalid connection header') - } - if (trimmed === 'close') { - request.reset = true - } - } - } else if (headerName === 'expect') { - throw new NotSupportedError('expect header not supported') - } else { - request.headers.push(key, val) - } +for (let i = 0; i < wellknownHeaderNames.length; ++i) { + const key = headerNameLowerCasedRecord[wellknownHeaderNames[i]] + tree.insert(key, key) } -module.exports = Request +module.exports = { + TernarySearchTree, + tree +} /***/ }), -/***/ 6089: +/***/ 9277: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const { EventEmitter } = __nccwpck_require__(8474) -const { Buffer } = __nccwpck_require__(4573) -const { InvalidArgumentError, Socks5ProxyError } = __nccwpck_require__(7062) -const { debuglog } = __nccwpck_require__(7975) -const { parseAddress } = __nccwpck_require__(3145) - -const debug = debuglog('undici:socks5') -const EMPTY_BUFFER = Buffer.alloc(0) +const assert = __nccwpck_require__(4589) +const { kDestroyed, kBodyUsed, kListeners, kBody } = __nccwpck_require__(228) +const { IncomingMessage } = __nccwpck_require__(7067) +const stream = __nccwpck_require__(7075) +const net = __nccwpck_require__(7030) +const { stringify } = __nccwpck_require__(1792) +const { EventEmitter: EE, addAbortListener: addAbortListenerNative } = __nccwpck_require__(8474) +const timers = __nccwpck_require__(3562) +const { InvalidArgumentError, ConnectTimeoutError } = __nccwpck_require__(4882) +const { headerNameLowerCasedRecord } = __nccwpck_require__(5188) +const { tree } = __nccwpck_require__(3509) -// SOCKS5 constants -const SOCKS_VERSION = 0x05 +class BodyAsyncIterable { + constructor (body) { + this[kBody] = body + this[kBodyUsed] = false + } -// Authentication methods -const AUTH_METHODS = { - NO_AUTH: 0x00, - GSSAPI: 0x01, - USERNAME_PASSWORD: 0x02, - NO_ACCEPTABLE: 0xFF + async * [Symbol.asyncIterator] () { + assert(!this[kBodyUsed], 'disturbed') + this[kBodyUsed] = true + yield * this[kBody] + } } -// SOCKS5 commands -const COMMANDS = { - CONNECT: 0x01, - BIND: 0x02, - UDP_ASSOCIATE: 0x03 -} +function noop () {} -// Address types -const ADDRESS_TYPES = { - IPV4: 0x01, - DOMAIN: 0x03, - IPV6: 0x04 -} +/** + * @param {*} body + * @returns {*} + */ +function wrapRequestBody (body) { + if (isStream(body)) { + // TODO (fix): Provide some way for the user to cache the file to e.g. /tmp + // so that it can be dispatched again? + // TODO (fix): Do we need 100-expect support to provide a way to do this properly? + if (bodyLength(body) === 0) { + body + .on('data', function () { + assert(false) + }) + } -// Reply codes -const REPLY_CODES = { - SUCCEEDED: 0x00, - GENERAL_FAILURE: 0x01, - CONNECTION_NOT_ALLOWED: 0x02, - NETWORK_UNREACHABLE: 0x03, - HOST_UNREACHABLE: 0x04, - CONNECTION_REFUSED: 0x05, - TTL_EXPIRED: 0x06, - COMMAND_NOT_SUPPORTED: 0x07, - ADDRESS_TYPE_NOT_SUPPORTED: 0x08 + if (typeof body.readableDidRead !== 'boolean') { + body[kBodyUsed] = false + EE.prototype.on.call(body, 'data', function () { + this[kBodyUsed] = true + }) + } + + return body + } else if (body && typeof body.pipeTo === 'function') { + // TODO (fix): We can't access ReadableStream internal state + // to determine whether or not it has been disturbed. This is just + // a workaround. + return new BodyAsyncIterable(body) + } else if (body && isFormDataLike(body)) { + return body + } else if ( + body && + typeof body !== 'string' && + !ArrayBuffer.isView(body) && + isIterable(body) + ) { + // TODO: Should we allow re-using iterable if !this.opts.idempotent + // or through some other flag? + return new BodyAsyncIterable(body) + } else { + return body + } } -// State machine states -const STATES = { - INITIAL: 'initial', - HANDSHAKING: 'handshaking', - AUTHENTICATING: 'authenticating', - AUTHENTICATED: 'authenticated', - CONNECTING: 'connecting', - CONNECTED: 'connected', - ERROR: 'error', - CLOSED: 'closed' +/** + * @param {*} obj + * @returns {obj is import('node:stream').Stream} + */ +function isStream (obj) { + return obj && typeof obj === 'object' && typeof obj.pipe === 'function' && typeof obj.on === 'function' } /** - * SOCKS5 client implementation - * Handles SOCKS5 protocol negotiation and connection establishment + * @param {*} object + * @returns {object is Blob} */ -class Socks5Client extends EventEmitter { - constructor (socket, options = {}) { - super() +function isBlobLike (object) { + return object instanceof Blob +} - if (!socket) { - throw new InvalidArgumentError('socket is required') - } +/** + * @param {string} url The path to check for query strings or fragments. + * @returns {boolean} Returns true if the path contains a query string or fragment. + */ +function pathHasQueryOrFragment (url) { + return ( + url.includes('?') || + url.includes('#') + ) +} - this.socket = socket - this.options = options - this.state = STATES.INITIAL - this.buffer = EMPTY_BUFFER - this.onSocketData = this.onData.bind(this) - this.onSocketError = this.onError.bind(this) - this.onSocketClose = this.onClose.bind(this) - - // Authentication settings - this.authMethods = [] - if (options.username && options.password) { - this.authMethods.push(AUTH_METHODS.USERNAME_PASSWORD) - } - this.authMethods.push(AUTH_METHODS.NO_AUTH) - - // Socket event handlers - this.socket.on('data', this.onSocketData) - this.socket.on('error', this.onSocketError) - this.socket.on('close', this.onSocketClose) +/** + * @param {string} url The URL to add the query params to + * @param {import('node:querystring').ParsedUrlQueryInput} queryParams The object to serialize into a URL query string + * @returns {string} The URL with the query params added + */ +function serializePathWithQuery (url, queryParams) { + if (pathHasQueryOrFragment(url)) { + throw new Error('Query params cannot be passed when url already contains "?" or "#".') } - /** - * Handle incoming data from the socket - */ - onData (data) { - debug('received data', data.length, 'bytes in state', this.state) - this.buffer = Buffer.concat([this.buffer, data]) + const stringified = stringify(queryParams) - try { - switch (this.state) { - case STATES.HANDSHAKING: - this.handleHandshakeResponse() - break - case STATES.AUTHENTICATING: - this.handleAuthResponse() - break - case STATES.CONNECTING: - this.handleConnectResponse() - break - } - } catch (err) { - this.onError(err) - } + if (stringified) { + url += '?' + stringified } - /** - * Handle socket errors - */ - onError (err) { - debug('socket error', err) - this.state = STATES.ERROR - this.emit('error', err) - this.destroy() - } + return url +} - /** - * Handle socket close - */ - onClose () { - debug('socket closed') - this.state = STATES.CLOSED - this.emit('close') - } +/** + * @param {number|string|undefined} port + * @returns {boolean} + */ +function isValidPort (port) { + const value = parseInt(port, 10) + return ( + value === Number(port) && + value >= 0 && + value <= 65535 + ) +} - /** - * Destroy the client and underlying socket - */ - destroy () { - if (this.socket && !this.socket.destroyed) { - this.socket.destroy() - } - } +/** + * Check if the value is a valid http or https prefixed string. + * + * @param {string} value + * @returns {boolean} + */ +function isHttpOrHttpsPrefixed (value) { + return ( + value != null && + value[0] === 'h' && + value[1] === 't' && + value[2] === 't' && + value[3] === 'p' && + ( + value[4] === ':' || + ( + value[4] === 's' && + value[5] === ':' + ) + ) + ) +} - markAuthenticated () { - this.state = STATES.AUTHENTICATED - this.emit('authenticated') - } +/** + * @param {string|URL|Record} url + * @returns {URL} + */ +function parseURL (url) { + if (typeof url === 'string') { + /** + * @type {URL} + */ + url = new URL(url) - /** - * Start the SOCKS5 handshake - */ - handshake () { - if (this.state !== STATES.INITIAL) { - throw new InvalidArgumentError('Handshake already started') + if (!isHttpOrHttpsPrefixed(url.origin || url.protocol)) { + throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.') } - debug('starting handshake with', this.authMethods.length, 'auth methods') - this.state = STATES.HANDSHAKING - - // Build handshake request - // +----+----------+----------+ - // |VER | NMETHODS | METHODS | - // +----+----------+----------+ - // | 1 | 1 | 1 to 255 | - // +----+----------+----------+ - const request = Buffer.alloc(2 + this.authMethods.length) - request[0] = SOCKS_VERSION - request[1] = this.authMethods.length - this.authMethods.forEach((method, i) => { - request[2 + i] = method - }) - - this.socket.write(request) + return url } - /** - * Handle handshake response from server - */ - handleHandshakeResponse () { - if (this.buffer.length < 2) { - return // Not enough data yet - } - - const version = this.buffer[0] - const method = this.buffer[1] + if (!url || typeof url !== 'object') { + throw new InvalidArgumentError('Invalid URL: The URL argument must be a non-null object.') + } - if (version !== SOCKS_VERSION) { - throw new Socks5ProxyError(`Invalid SOCKS version: ${version}`, 'UND_ERR_SOCKS5_VERSION') + if (!(url instanceof URL)) { + if (url.port != null && url.port !== '' && isValidPort(url.port) === false) { + throw new InvalidArgumentError('Invalid URL: port must be a valid integer or a string representation of an integer.') } - if (method === AUTH_METHODS.NO_ACCEPTABLE) { - throw new Socks5ProxyError('No acceptable authentication method', 'UND_ERR_SOCKS5_AUTH_REJECTED') + if (url.path != null && typeof url.path !== 'string') { + throw new InvalidArgumentError('Invalid URL path: the path must be a string or null/undefined.') } - this.buffer = this.buffer.subarray(2) - debug('server selected auth method', method) - - if (method === AUTH_METHODS.NO_AUTH) { - this.markAuthenticated() - } else if (method === AUTH_METHODS.USERNAME_PASSWORD) { - this.state = STATES.AUTHENTICATING - this.sendAuthRequest() - } else { - throw new Socks5ProxyError(`Unsupported authentication method: ${method}`, 'UND_ERR_SOCKS5_AUTH_METHOD') + if (url.pathname != null && typeof url.pathname !== 'string') { + throw new InvalidArgumentError('Invalid URL pathname: the pathname must be a string or null/undefined.') } - } - - /** - * Send username/password authentication request - */ - sendAuthRequest () { - const { username, password } = this.options - if (!username || !password) { - throw new InvalidArgumentError('Username and password required for authentication') + if (url.hostname != null && typeof url.hostname !== 'string') { + throw new InvalidArgumentError('Invalid URL hostname: the hostname must be a string or null/undefined.') } - debug('sending username/password auth') - - // Username/Password authentication request (RFC 1929) - // +----+------+----------+------+----------+ - // |VER | ULEN | UNAME | PLEN | PASSWD | - // +----+------+----------+------+----------+ - // | 1 | 1 | 1 to 255 | 1 | 1 to 255 | - // +----+------+----------+------+----------+ - const usernameBuffer = Buffer.from(username) - const passwordBuffer = Buffer.from(password) - - if (usernameBuffer.length > 255 || passwordBuffer.length > 255) { - throw new InvalidArgumentError('Username or password too long') + if (url.origin != null && typeof url.origin !== 'string') { + throw new InvalidArgumentError('Invalid URL origin: the origin must be a string or null/undefined.') } - const request = Buffer.alloc(3 + usernameBuffer.length + passwordBuffer.length) - request[0] = 0x01 // Sub-negotiation version - request[1] = usernameBuffer.length - usernameBuffer.copy(request, 2) - request[2 + usernameBuffer.length] = passwordBuffer.length - passwordBuffer.copy(request, 3 + usernameBuffer.length) - - this.socket.write(request) - } - - /** - * Handle authentication response - */ - handleAuthResponse () { - if (this.buffer.length < 2) { - return // Not enough data yet + if (!isHttpOrHttpsPrefixed(url.origin || url.protocol)) { + throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.') } - const version = this.buffer[0] - const status = this.buffer[1] + const port = url.port != null + ? url.port + : (url.protocol === 'https:' ? 443 : 80) + let origin = url.origin != null + ? url.origin + : `${url.protocol || ''}//${url.hostname || ''}:${port}` + let path = url.path != null + ? url.path + : `${url.pathname || ''}${url.search || ''}` - if (version !== 0x01) { - throw new Socks5ProxyError(`Invalid auth sub-negotiation version: ${version}`, 'UND_ERR_SOCKS5_AUTH_VERSION') + if (origin[origin.length - 1] === '/') { + origin = origin.slice(0, origin.length - 1) } - if (status !== 0x00) { - throw new Socks5ProxyError('Authentication failed', 'UND_ERR_SOCKS5_AUTH_FAILED') + if (path && path[0] !== '/') { + path = `/${path}` } - - this.buffer = this.buffer.subarray(2) - debug('authentication successful') - this.markAuthenticated() + // new URL(path, origin) is unsafe when `path` contains an absolute URL + // From https://developer.mozilla.org/en-US/docs/Web/API/URL/URL: + // If first parameter is a relative URL, second param is required, and will be used as the base URL. + // If first parameter is an absolute URL, a given second param will be ignored. + return new URL(`${origin}${path}`) } - /** - * Send CONNECT command - * @param {string} address - Target address (IP or domain) - * @param {number} port - Target port - */ - connect (address, port) { - if (this.state === STATES.CONNECTING || this.state === STATES.CONNECTED) { - throw new InvalidArgumentError('Connection already in progress') - } - - if (this.state !== STATES.AUTHENTICATED) { - throw new InvalidArgumentError('Client must be authenticated before CONNECT') - } - - debug('connecting to', address, port) - this.state = STATES.CONNECTING - - const request = this.buildConnectRequest(COMMANDS.CONNECT, address, port) - this.socket.write(request) + if (!isHttpOrHttpsPrefixed(url.origin || url.protocol)) { + throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.') } - /** - * Build a SOCKS5 request - */ - buildConnectRequest (command, address, port) { - // Parse address to determine type and buffer - const { type: addressType, buffer: addressBuffer } = parseAddress(address) + return url +} - // Build request - // +----+-----+-------+------+----------+----------+ - // |VER | CMD | RSV | ATYP | DST.ADDR | DST.PORT | - // +----+-----+-------+------+----------+----------+ - // | 1 | 1 | X'00' | 1 | Variable | 2 | - // +----+-----+-------+------+----------+----------+ - const request = Buffer.alloc(4 + addressBuffer.length + 2) - request[0] = SOCKS_VERSION - request[1] = command - request[2] = 0x00 // Reserved - request[3] = addressType - addressBuffer.copy(request, 4) - request.writeUInt16BE(port, 4 + addressBuffer.length) +/** + * @param {string|URL|Record} url + * @returns {URL} + */ +function parseOrigin (url) { + url = parseURL(url) - return request + if (url.pathname !== '/' || url.search || url.hash) { + throw new InvalidArgumentError('invalid url') } - /** - * Handle CONNECT response - */ - handleConnectResponse () { - if (this.buffer.length < 4) { - return // Not enough data for header - } - - const version = this.buffer[0] - const reply = this.buffer[1] - const addressType = this.buffer[3] - - if (version !== SOCKS_VERSION) { - throw new Socks5ProxyError(`Invalid SOCKS version in reply: ${version}`, 'UND_ERR_SOCKS5_REPLY_VERSION') - } - - // Calculate the expected response length - let responseLength = 4 // VER + REP + RSV + ATYP - if (addressType === ADDRESS_TYPES.IPV4) { - responseLength += 4 + 2 // IPv4 + port - } else if (addressType === ADDRESS_TYPES.DOMAIN) { - if (this.buffer.length < 5) { - return // Need domain length byte - } - responseLength += 1 + this.buffer[4] + 2 // length byte + domain + port - } else if (addressType === ADDRESS_TYPES.IPV6) { - responseLength += 16 + 2 // IPv6 + port - } else { - throw new Socks5ProxyError(`Invalid address type in reply: ${addressType}`, 'UND_ERR_SOCKS5_ADDR_TYPE') - } - - if (this.buffer.length < responseLength) { - return // Not enough data for full response - } - - if (reply !== REPLY_CODES.SUCCEEDED) { - const errorMessage = this.getReplyErrorMessage(reply) - throw new Socks5ProxyError(`SOCKS5 connection failed: ${errorMessage}`, `UND_ERR_SOCKS5_REPLY_${reply}`) - } - - // Parse bound address and port - let boundAddress - let offset = 4 - - if (addressType === ADDRESS_TYPES.IPV4) { - boundAddress = Array.from(this.buffer.subarray(offset, offset + 4)).join('.') - offset += 4 - } else if (addressType === ADDRESS_TYPES.DOMAIN) { - const domainLength = this.buffer[offset] - offset += 1 - boundAddress = this.buffer.subarray(offset, offset + domainLength).toString() - offset += domainLength - } else if (addressType === ADDRESS_TYPES.IPV6) { - // Parse IPv6 address from 16-byte buffer - const parts = [] - for (let i = 0; i < 8; i++) { - const value = this.buffer.readUInt16BE(offset + i * 2) - parts.push(value.toString(16)) - } - boundAddress = parts.join(':') - offset += 16 - } - - const boundPort = this.buffer.readUInt16BE(offset) + return url +} - this.buffer = EMPTY_BUFFER - this.state = STATES.CONNECTED - this.socket.removeListener('data', this.onSocketData) +/** + * @param {string} host + * @returns {string} + */ +function getHostname (host) { + if (host[0] === '[') { + const idx = host.indexOf(']') - debug('connected, bound address:', boundAddress, 'port:', boundPort) - this.emit('connected', { address: boundAddress, port: boundPort }) + assert(idx !== -1) + return host.substring(1, idx) } - /** - * Get human-readable error message for reply code - */ - getReplyErrorMessage (reply) { - switch (reply) { - case REPLY_CODES.GENERAL_FAILURE: - return 'General SOCKS server failure' - case REPLY_CODES.CONNECTION_NOT_ALLOWED: - return 'Connection not allowed by ruleset' - case REPLY_CODES.NETWORK_UNREACHABLE: - return 'Network unreachable' - case REPLY_CODES.HOST_UNREACHABLE: - return 'Host unreachable' - case REPLY_CODES.CONNECTION_REFUSED: - return 'Connection refused' - case REPLY_CODES.TTL_EXPIRED: - return 'TTL expired' - case REPLY_CODES.COMMAND_NOT_SUPPORTED: - return 'Command not supported' - case REPLY_CODES.ADDRESS_TYPE_NOT_SUPPORTED: - return 'Address type not supported' - default: - return `Unknown error code: ${reply}` - } - } -} + const idx = host.indexOf(':') + if (idx === -1) return host -module.exports = { - Socks5Client, - AUTH_METHODS, - COMMANDS, - ADDRESS_TYPES, - REPLY_CODES, - STATES + return host.substring(0, idx) } - -/***/ }), - -/***/ 3145: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const { Buffer } = __nccwpck_require__(4573) -const net = __nccwpck_require__(7030) -const { InvalidArgumentError } = __nccwpck_require__(7062) - /** - * Parse an address and determine its type - * @param {string} address - The address to parse - * @returns {{type: number, buffer: Buffer}} Address type and buffer + * IP addresses are not valid server names per RFC6066 + * Currently, the only server names supported are DNS hostnames + * @param {string|null} host + * @returns {string|null} */ -function parseAddress (address) { - // Check if it's an IPv4 address - if (net.isIPv4(address)) { - const parts = address.split('.').map(Number) - return { - type: 0x01, // IPv4 - buffer: Buffer.from(parts) - } +function getServerName (host) { + if (!host) { + return null } - // Check if it's an IPv6 address - if (net.isIPv6(address)) { - return { - type: 0x04, // IPv6 - buffer: parseIPv6(address) - } - } + assert(typeof host === 'string') - // Otherwise, treat as domain name - const domainBuffer = Buffer.from(address, 'utf8') - if (domainBuffer.length > 255) { - throw new InvalidArgumentError('Domain name too long (max 255 bytes)') + const servername = getHostname(host) + if (net.isIP(servername)) { + return '' } - return { - type: 0x03, // Domain - buffer: Buffer.concat([Buffer.from([domainBuffer.length]), domainBuffer]) - } + return servername } /** - * Parse IPv6 address to buffer - * @param {string} address - IPv6 address string - * @returns {Buffer} 16-byte buffer + * @function + * @template T + * @param {T} obj + * @returns {T} */ -function parseIPv6 (address) { - const buffer = Buffer.alloc(16) - let normalizedAddress = address +function deepClone (obj) { + return JSON.parse(JSON.stringify(obj)) +} - // Expand an embedded IPv4 tail into the last two IPv6 groups. - if (address.includes('.')) { - const lastColonIndex = address.lastIndexOf(':') - const ipv4Part = address.slice(lastColonIndex + 1) +/** + * @param {*} obj + * @returns {obj is AsyncIterable} + */ +function isAsyncIterable (obj) { + return !!(obj != null && typeof obj[Symbol.asyncIterator] === 'function') +} - if (net.isIPv4(ipv4Part)) { - const octets = ipv4Part.split('.').map(Number) - const high = ((octets[0] << 8) | octets[1]).toString(16) - const low = ((octets[2] << 8) | octets[3]).toString(16) - normalizedAddress = `${address.slice(0, lastColonIndex)}:${high}:${low}` - } - } +/** + * @param {*} obj + * @returns {obj is Iterable} + */ +function isIterable (obj) { + return !!(obj != null && (typeof obj[Symbol.iterator] === 'function' || typeof obj[Symbol.asyncIterator] === 'function')) +} - // Handle compressed notation (::) - const doubleColonIndex = normalizedAddress.indexOf('::') - if (doubleColonIndex !== -1) { - const before = normalizedAddress.slice(0, doubleColonIndex) - const after = normalizedAddress.slice(doubleColonIndex + 2) - const beforeParts = before === '' ? [] : before.split(':') - const afterParts = after === '' ? [] : after.split(':') +/** + * Checks whether an object has a safe Symbol.iterator — i.e. one that is + * either own or inherited from a non-Object.prototype chain. This prevents + * prototype-pollution attacks from injecting a fake iterator on + * Object.prototype. + * @param {object} obj + * @returns {boolean} + */ +function hasSafeIterator (obj) { + const prototype = Object.getPrototypeOf(obj) + const ownIterator = Object.hasOwn(obj, Symbol.iterator) + return ownIterator || (prototype != null && prototype !== Object.prototype && typeof obj[Symbol.iterator] === 'function') +} - let bufferIndex = 0 - for (const part of beforeParts) { - buffer.writeUInt16BE(parseInt(part, 16), bufferIndex) - bufferIndex += 2 - } - bufferIndex = 16 - afterParts.length * 2 - for (const part of afterParts) { - buffer.writeUInt16BE(parseInt(part, 16), bufferIndex) - bufferIndex += 2 - } - } else { - const parts = normalizedAddress.split(':') - for (let i = 0; i < parts.length; i++) { - buffer.writeUInt16BE(parseInt(parts[i], 16), i * 2) - } +/** + * @param {Blob|Buffer|import ('stream').Stream} body + * @returns {number|null} + */ +function bodyLength (body) { + if (body == null) { + return 0 + } else if (isStream(body)) { + const state = body._readableState + return state && state.objectMode === false && state.ended === true && Number.isFinite(state.length) + ? state.length + : null + } else if (isBlobLike(body)) { + return body.size != null ? body.size : null + } else if (isBuffer(body)) { + return body.byteLength } - return buffer + return null } /** - * Build a SOCKS5 address buffer - * @param {number} type - Address type (1=IPv4, 3=Domain, 4=IPv6) - * @param {Buffer} addressBuffer - The address data - * @param {number} port - Port number - * @returns {Buffer} Complete address buffer including type, address, and port + * @param {import ('stream').Stream} body + * @returns {boolean} */ -function buildAddressBuffer (type, addressBuffer, port) { - const portBuffer = Buffer.allocUnsafe(2) - portBuffer.writeUInt16BE(port, 0) - - return Buffer.concat([ - Buffer.from([type]), - addressBuffer, - portBuffer - ]) +function isDestroyed (body) { + return body && !!(body.destroyed || body[kDestroyed] || (stream.isDestroyed?.(body))) } /** - * Parse address from SOCKS5 response - * @param {Buffer} buffer - Buffer containing the address - * @param {number} offset - Starting offset in buffer - * @returns {{address: string, port: number, bytesRead: number}} + * @param {import ('stream').Stream} stream + * @param {Error} [err] + * @returns {void} */ -function parseResponseAddress (buffer, offset = 0) { - if (buffer.length < offset + 1) { - throw new InvalidArgumentError('Buffer too small to contain address type') +function destroy (stream, err) { + if (stream == null || !isStream(stream) || isDestroyed(stream)) { + return } - const addressType = buffer[offset] - let address - let currentOffset = offset + 1 - - switch (addressType) { - case 0x01: { // IPv4 - if (buffer.length < currentOffset + 6) { - throw new InvalidArgumentError('Buffer too small for IPv4 address') - } - address = Array.from(buffer.subarray(currentOffset, currentOffset + 4)).join('.') - currentOffset += 4 - break - } - - case 0x03: { // Domain - if (buffer.length < currentOffset + 1) { - throw new InvalidArgumentError('Buffer too small for domain length') - } - const domainLength = buffer[currentOffset] - currentOffset += 1 - - if (buffer.length < currentOffset + domainLength + 2) { - throw new InvalidArgumentError('Buffer too small for domain address') - } - address = buffer.subarray(currentOffset, currentOffset + domainLength).toString('utf8') - currentOffset += domainLength - break + if (typeof stream.destroy === 'function') { + if (Object.getPrototypeOf(stream).constructor === IncomingMessage) { + // See: https://github.com/nodejs/node/pull/38505/files + stream.socket = null } - case 0x04: { // IPv6 - if (buffer.length < currentOffset + 18) { - throw new InvalidArgumentError('Buffer too small for IPv6 address') - } - // Convert buffer to IPv6 string - const parts = [] - for (let i = 0; i < 8; i++) { - const value = buffer.readUInt16BE(currentOffset + i * 2) - parts.push(value.toString(16)) - } - address = parts.join(':') - currentOffset += 16 - break + try { + stream.destroy(err) + } catch { + // stream.destroy may throw on managed sockets (e.g., http2). + // Silently ignore — the socket lifecycle is handled by the subsystem. } - - default: - throw new InvalidArgumentError(`Invalid address type: ${addressType}`) - } - - // Parse port - if (buffer.length < currentOffset + 2) { - throw new InvalidArgumentError('Buffer too small for port') + } else if (err) { + queueMicrotask(() => { + stream.emit('error', err) + }) } - const port = buffer.readUInt16BE(currentOffset) - currentOffset += 2 - return { - address, - port, - bytesRead: currentOffset - offset + if (stream.destroyed !== true) { + stream[kDestroyed] = true } } +const KEEPALIVE_TIMEOUT_EXPR = /timeout=(\d+)/ /** - * Create error for SOCKS5 reply code - * @param {number} replyCode - SOCKS5 reply code - * @returns {Error} Appropriate error object + * @param {string} val + * @returns {number | null} */ -function createReplyError (replyCode) { - const messages = { - 0x01: 'General SOCKS server failure', - 0x02: 'Connection not allowed by ruleset', - 0x03: 'Network unreachable', - 0x04: 'Host unreachable', - 0x05: 'Connection refused', - 0x06: 'TTL expired', - 0x07: 'Command not supported', - 0x08: 'Address type not supported' - } - - const message = messages[replyCode] || `Unknown SOCKS5 error code: ${replyCode}` - const error = new Error(message) - error.code = `SOCKS5_${replyCode}` - return error +function parseKeepAliveTimeout (val) { + const m = val.match(KEEPALIVE_TIMEOUT_EXPR) + return m ? parseInt(m[1], 10) * 1000 : null } -module.exports = { - parseAddress, - parseIPv6, - buildAddressBuffer, - parseResponseAddress, - createReplyError +/** + * Retrieves a header name and returns its lowercase value. + * @param {string | Buffer} value Header name + * @returns {string} + */ +function headerNameToString (value) { + return typeof value === 'string' + ? headerNameLowerCasedRecord[value] ?? value.toLowerCase() + : tree.lookup(value) ?? value.toString('latin1').toLowerCase() } - -/***/ }), - -/***/ 7480: -/***/ ((module) => { - -"use strict"; - - -module.exports = { - kClose: Symbol('close'), - kDestroy: Symbol('destroy'), - kDispatch: Symbol('dispatch'), - kUrl: Symbol('url'), - kRequestOrigin: Symbol('request origin'), - kOriginless: Symbol('originless'), - kWriting: Symbol('writing'), - kResuming: Symbol('resuming'), - kQueue: Symbol('queue'), - kConnect: Symbol('connect'), - kConnecting: Symbol('connecting'), - kKeepAliveDefaultTimeout: Symbol('default keep alive timeout'), - kKeepAliveMaxTimeout: Symbol('max keep alive timeout'), - kKeepAliveTimeoutThreshold: Symbol('keep alive timeout threshold'), - kKeepAliveTimeoutValue: Symbol('keep alive timeout'), - kKeepAlive: Symbol('keep alive'), - kHeadersTimeout: Symbol('headers timeout'), - kBodyTimeout: Symbol('body timeout'), - kServerName: Symbol('server name'), - kLocalAddress: Symbol('local address'), - kHost: Symbol('host'), - kNoRef: Symbol('no ref'), - kBodyUsed: Symbol('used'), - kBody: Symbol('abstracted request body'), - kRunning: Symbol('running'), - kBlocking: Symbol('blocking'), - kPending: Symbol('pending'), - kSize: Symbol('size'), - kBusy: Symbol('busy'), - kQueued: Symbol('queued'), - kFree: Symbol('free'), - kConnected: Symbol('connected'), - kClosed: Symbol('closed'), - kNeedDrain: Symbol('need drain'), - kReset: Symbol('reset'), - kDestroyed: Symbol.for('nodejs.stream.destroyed'), - kResume: Symbol('resume'), - kOnError: Symbol('on error'), - kMaxHeadersSize: Symbol('max headers size'), - kRunningIdx: Symbol('running index'), - kPendingIdx: Symbol('pending index'), - kError: Symbol('error'), - kClients: Symbol('clients'), - kClient: Symbol('client'), - kParser: Symbol('parser'), - kOnDestroyed: Symbol('destroy callbacks'), - kPipelining: Symbol('pipelining'), - kSocket: Symbol('socket'), - kHostHeader: Symbol('host header'), - kConnector: Symbol('connector'), - kStrictContentLength: Symbol('strict content length'), - kMaxRedirections: Symbol('maxRedirections'), - kMaxRequests: Symbol('maxRequestsPerClient'), - kProxy: Symbol('proxy agent options'), - kCounter: Symbol('socket request counter'), - kMaxResponseSize: Symbol('max response size'), - kHTTP2Session: Symbol('http2Session'), - kHTTP2Options: Symbol('http2 options'), - kHTTP2SessionState: Symbol('http2Session state'), - kRetryHandlerDefaultRetry: Symbol('retry agent default retry'), - kConstruct: Symbol('constructable'), - kListeners: Symbol('listeners'), - kHTTPContext: Symbol('http context'), - kMaxConcurrentStreams: Symbol('max concurrent streams'), - kHostAuthority: Symbol('host authority'), - kHTTP2InitialWindowSize: Symbol('http2 initial window size'), - kHTTP2ConnectionWindowSize: Symbol('http2 connection window size'), - kEnableConnectProtocol: Symbol('http2session connect protocol'), - kRemoteSettings: Symbol('http2session remote settings'), - kHTTP2Stream: Symbol('http2session client stream'), - kPingInterval: Symbol('ping interval'), - kNoProxyAgent: Symbol('no proxy agent'), - kHttpProxyAgent: Symbol('http proxy agent'), - kHttpsProxyAgent: Symbol('https proxy agent'), - kSocks5ProxyAgent: Symbol('socks5 proxy agent') +/** + * Receive the buffer as a string and return its lowercase value. + * @param {Buffer} value Header name + * @returns {string} + */ +function bufferToLowerCasedHeaderName (value) { + return tree.lookup(value) ?? value.toString('latin1').toLowerCase() } +/** + * @param {(Buffer | string)[]} headers + * @param {Record} [obj] + * @returns {Record} + */ +function parseHeaders (headers, obj) { + if (obj === undefined) obj = {} -/***/ }), + for (let i = 0; i < headers.length; i += 2) { + const key = headerNameToString(headers[i]) + let val = obj[key] -/***/ 4273: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (val !== undefined) { + if (!Object.hasOwn(obj, key)) { + const headersValue = typeof headers[i + 1] === 'string' + ? headers[i + 1] + : Array.isArray(headers[i + 1]) + ? headers[i + 1].map(x => x.toString('latin1')) + : headers[i + 1].toString('latin1') -"use strict"; + if (key === '__proto__') { + Object.defineProperty(obj, key, { + value: headersValue, + enumerable: true, + configurable: true, + writable: true + }) + } else { + obj[key] = headersValue + } + } else { + if (typeof val === 'string') { + val = [val] + obj[key] = val + } + val.push(headers[i + 1].toString('latin1')) + } + } else { + const headersValue = typeof headers[i + 1] === 'string' + ? headers[i + 1] + : Array.isArray(headers[i + 1]) + ? headers[i + 1].map(x => x.toString('latin1')) + : headers[i + 1].toString('latin1') + obj[key] = headersValue + } + } -const { - wellknownHeaderNames, - headerNameLowerCasedRecord -} = __nccwpck_require__(5368) + return obj +} -class TstNode { - /** @type {any} */ - value = null - /** @type {null | TstNode} */ - left = null - /** @type {null | TstNode} */ - middle = null - /** @type {null | TstNode} */ - right = null - /** @type {number} */ - code - /** - * @param {string} key - * @param {any} value - * @param {number} index - */ - constructor (key, value, index) { - if (index === undefined || index >= key.length) { - throw new TypeError('Unreachable') - } - const code = this.code = key.charCodeAt(index) - // check code is ascii string - if (code > 0x7F) { - throw new TypeError('key must be ascii string') - } - if (key.length !== ++index) { - this.middle = new TstNode(key, value, index) - } else { - this.value = value - } +/** + * @param {Buffer[] | string[] | Record | null | undefined} headers + * @returns {string[]} + */ +function parseRawHeaders (headers) { + if (headers == null) { + return [] } - /** - * @param {string} key - * @param {any} value - * @returns {void} - */ - add (key, value) { - const length = key.length - if (length === 0) { - throw new TypeError('Unreachable') - } - let index = 0 - /** - * @type {TstNode} - */ - let node = this - while (true) { - const code = key.charCodeAt(index) - // check code is ascii string - if (code > 0x7F) { - throw new TypeError('key must be ascii string') - } - if (node.code === code) { - if (length === ++index) { - node.value = value - break - } else if (node.middle !== null) { - node = node.middle - } else { - node.middle = new TstNode(key, value, index) - break - } - } else if (node.code < code) { - if (node.left !== null) { - node = node.left - } else { - node.left = new TstNode(key, value, index) - break + if (!Array.isArray(headers)) { + const rawHeaders = [] + + for (const [name, value] of Object.entries(headers)) { + if (Array.isArray(value)) { + for (const entry of value) { + rawHeaders.push(name, `${entry}`) } - } else if (node.right !== null) { - node = node.right } else { - node.right = new TstNode(key, value, index) - break + rawHeaders.push(name, `${value}`) } } + + return rawHeaders } + const headersLength = headers.length /** - * @param {Uint8Array} key - * @returns {TstNode | null} + * @type {string[]} */ - search (key) { - const keylength = key.length - let index = 0 - /** - * @type {TstNode|null} - */ - let node = this - while (node !== null && index < keylength) { - let code = key[index] - // A-Z - // First check if it is bigger than 0x5a. - // Lowercase letters have higher char codes than uppercase ones. - // Also we assume that headers will mostly contain lowercase characters. - if (code <= 0x5a && code >= 0x41) { - // Lowercase for uppercase. - code |= 32 - } - while (node !== null) { - if (code === node.code) { - if (keylength === ++index) { - // Returns Node since it is the last key. - return node - } - node = node.middle - break - } - node = node.code < code ? node.left : node.right - } - } - return null + const ret = new Array(headersLength) + + let key + let val + + for (let n = 0; n < headersLength; n += 2) { + key = headers[n] + val = headers[n + 1] + + typeof key !== 'string' && (key = key.toString()) + typeof val !== 'string' && (val = val.toString('latin1')) + + ret[n] = key + ret[n + 1] = val } + + return ret } -class TernarySearchTree { - /** @type {TstNode | null} */ - node = null +/** + * @param {Record} headers + * @returns {Buffer[]} + */ +function toRawHeaders (headers) { + const rawHeaders = [] - /** - * @param {string} key - * @param {any} value - * @returns {void} - * */ - insert (key, value) { - if (this.node === null) { - this.node = new TstNode(key, value, 0) + for (const [name, value] of Object.entries(headers)) { + if (Array.isArray(value)) { + for (const entry of value) { + rawHeaders.push(Buffer.from(name, 'latin1'), Buffer.from(`${entry}`, 'latin1')) + } } else { - this.node.add(key, value) + rawHeaders.push(Buffer.from(name, 'latin1'), Buffer.from(`${value}`, 'latin1')) } } - /** - * @param {Uint8Array} key - * @returns {any} - */ - lookup (key) { - return this.node?.search(key)?.value ?? null - } -} - -const tree = new TernarySearchTree() - -for (let i = 0; i < wellknownHeaderNames.length; ++i) { - const key = headerNameLowerCasedRecord[wellknownHeaderNames[i]] - tree.insert(key, key) + return rawHeaders } -module.exports = { - TernarySearchTree, - tree +/** + * @param {string[]} headers + * @param {Buffer[]} headers + */ +function encodeRawHeaders (headers) { + if (!Array.isArray(headers)) { + throw new TypeError('expected headers to be an array') + } + return headers.map(x => Buffer.from(x)) } +/** + * @param {*} buffer + * @returns {buffer is Buffer} + */ +function isBuffer (buffer) { + // See, https://github.com/mcollina/undici/pull/319 + return buffer instanceof Uint8Array || Buffer.isBuffer(buffer) +} -/***/ }), - -/***/ 9705: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - +/** + * Asserts that the handler object is a request handler. + * + * @param {object} handler + * @param {string} method + * @param {string} [upgrade] + * @returns {asserts handler is import('../api/api-request').RequestHandler} + */ +function assertRequestHandler (handler, method, upgrade) { + if (!handler || typeof handler !== 'object') { + throw new InvalidArgumentError('handler must be an object') + } -const assert = __nccwpck_require__(4589) -const { kDestroyed, kBodyUsed, kListeners, kBody } = __nccwpck_require__(7480) -const { IncomingMessage } = __nccwpck_require__(7067) -const stream = __nccwpck_require__(7075) -const net = __nccwpck_require__(7030) -const { stringify } = __nccwpck_require__(1792) -const { EventEmitter: EE, addAbortListener: addAbortListenerNative } = __nccwpck_require__(8474) -const timers = __nccwpck_require__(4542) -const { InvalidArgumentError, ConnectTimeoutError } = __nccwpck_require__(7062) -const { headerNameLowerCasedRecord } = __nccwpck_require__(5368) -const { tree } = __nccwpck_require__(4273) + if (typeof handler.onRequestStart !== 'function') { + throw new InvalidArgumentError('invalid onRequestStart method') + } -class BodyAsyncIterable { - constructor (body) { - this[kBody] = body - this[kBodyUsed] = false + if (typeof handler.onResponseError !== 'function') { + throw new InvalidArgumentError('invalid onResponseError method') } - async * [Symbol.asyncIterator] () { - assert(!this[kBodyUsed], 'disturbed') - this[kBodyUsed] = true - yield * this[kBody] + if (typeof handler.onBodySent !== 'function' && handler.onBodySent !== undefined) { + throw new InvalidArgumentError('invalid onBodySent method') } -} -function noop () {} + if (typeof handler.onRequestSent !== 'function' && handler.onRequestSent !== undefined) { + throw new InvalidArgumentError('invalid onRequestSent method') + } -/** - * @param {*} body - * @returns {*} - */ -function wrapRequestBody (body) { - if (isStream(body)) { - // TODO (fix): Provide some way for the user to cache the file to e.g. /tmp - // so that it can be dispatched again? - // TODO (fix): Do we need 100-expect support to provide a way to do this properly? - if (bodyLength(body) === 0) { - body - .on('data', function () { - assert(false) - }) + if (upgrade || method === 'CONNECT') { + if (typeof handler.onRequestUpgrade !== 'function') { + throw new InvalidArgumentError('invalid onRequestUpgrade method') + } + } else { + if (typeof handler.onResponseStart !== 'function') { + throw new InvalidArgumentError('invalid onResponseStart method') } - if (typeof body.readableDidRead !== 'boolean') { - body[kBodyUsed] = false - EE.prototype.on.call(body, 'data', function () { - this[kBodyUsed] = true - }) + if (typeof handler.onResponseData !== 'function') { + throw new InvalidArgumentError('invalid onResponseData method') } - return body - } else if (body && typeof body.pipeTo === 'function') { - // TODO (fix): We can't access ReadableStream internal state - // to determine whether or not it has been disturbed. This is just - // a workaround. - return new BodyAsyncIterable(body) - } else if (body && isFormDataLike(body)) { - return body - } else if ( - body && - typeof body !== 'string' && - !ArrayBuffer.isView(body) && - isIterable(body) - ) { - // TODO: Should we allow re-using iterable if !this.opts.idempotent - // or through some other flag? - return new BodyAsyncIterable(body) - } else { - return body + if (typeof handler.onResponseEnd !== 'function') { + throw new InvalidArgumentError('invalid onResponseEnd method') + } } } /** - * @param {*} obj - * @returns {obj is import('node:stream').Stream} + * A body is disturbed if it has been read from and it cannot be re-used without + * losing state or data. + * @param {import('node:stream').Readable} body + * @returns {boolean} */ -function isStream (obj) { - return obj && typeof obj === 'object' && typeof obj.pipe === 'function' && typeof obj.on === 'function' +function isDisturbed (body) { + // TODO (fix): Why is body[kBodyUsed] needed? + return !!(body && (stream.isDisturbed(body) || body[kBodyUsed])) } /** - * @param {*} object - * @returns {object is Blob} + * @typedef {object} SocketInfo + * @property {string} [localAddress] + * @property {number} [localPort] + * @property {string} [remoteAddress] + * @property {number} [remotePort] + * @property {string} [remoteFamily] + * @property {number} [timeout] + * @property {number} bytesWritten + * @property {number} bytesRead */ -function isBlobLike (object) { - return object instanceof Blob + +/** + * @param {import('net').Socket} socket + * @returns {SocketInfo} + */ +function getSocketInfo (socket) { + return { + localAddress: socket.localAddress, + localPort: socket.localPort, + remoteAddress: socket.remoteAddress, + remotePort: socket.remotePort, + remoteFamily: socket.remoteFamily, + timeout: socket.timeout, + bytesWritten: socket.bytesWritten, + bytesRead: socket.bytesRead + } } /** - * @param {string} url The path to check for query strings or fragments. - * @returns {boolean} Returns true if the path contains a query string or fragment. + * The object should be a FormData instance and contains all the required + * methods. + * @param {*} object + * @returns {object is FormData} */ -function pathHasQueryOrFragment (url) { +function isFormDataLike (object) { return ( - url.includes('?') || - url.includes('#') + object && + typeof object === 'object' && + typeof object.append === 'function' && + typeof object.delete === 'function' && + typeof object.get === 'function' && + typeof object.getAll === 'function' && + typeof object.has === 'function' && + typeof object.set === 'function' && + object[Symbol.toStringTag] === 'FormData' ) } -/** - * @param {string} url The URL to add the query params to - * @param {import('node:querystring').ParsedUrlQueryInput} queryParams The object to serialize into a URL query string - * @returns {string} The URL with the query params added - */ -function serializePathWithQuery (url, queryParams) { - if (pathHasQueryOrFragment(url)) { - throw new Error('Query params cannot be passed when url already contains "?" or "#".') +function addAbortListener (signal, listener) { + if (!signal || 'aborted' in signal) { + return addAbortListenerNative(signal, listener)[Symbol.dispose] } - const stringified = stringify(queryParams) - - if (stringified) { - url += '?' + stringified + if (typeof signal.addEventListener === 'function') { + signal.addEventListener('abort', listener, { once: true }) + return () => signal.removeEventListener('abort', listener) } - - return url + signal.once('abort', listener) + return () => signal.removeListener('abort', listener) } -/** - * @param {number|string|undefined} port - * @returns {boolean} - */ -function isValidPort (port) { - const value = parseInt(port, 10) - return ( - value === Number(port) && - value >= 0 && - value <= 65535 - ) -} +const validTokenChars = new Uint8Array([ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0-15 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16-31 + 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, // 32-47 (!"#$%&'()*+,-./) + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 48-63 (0-9:;<=>?) + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64-79 (@A-O) + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, // 80-95 (P-Z[\]^_) + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96-111 (`a-o) + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, // 112-127 (p-z{|}~) + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 128-143 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 144-159 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 160-175 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 176-191 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 192-207 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 208-223 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 224-239 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 // 240-255 +]) /** - * Check if the value is a valid http or https prefixed string. - * - * @param {string} value + * @see https://tools.ietf.org/html/rfc7230#section-3.2.6 + * @param {number} c * @returns {boolean} */ -function isHttpOrHttpsPrefixed (value) { - return ( - value != null && - value[0] === 'h' && - value[1] === 't' && - value[2] === 't' && - value[3] === 'p' && - ( - value[4] === ':' || - ( - value[4] === 's' && - value[5] === ':' - ) - ) - ) +function isTokenCharCode (c) { + return (validTokenChars[c] === 1) } +const tokenRegExp = /^[\^_`a-zA-Z\-0-9!#$%&'*+.|~]+$/ + /** - * @param {string|URL|Record} url - * @returns {URL} + * @param {string} characters + * @returns {boolean} */ -function parseURL (url) { - if (typeof url === 'string') { - /** - * @type {URL} - */ - url = new URL(url) +function isValidHTTPToken (characters) { + if (characters.length >= 12) return tokenRegExp.test(characters) + if (characters.length === 0) return false - if (!isHttpOrHttpsPrefixed(url.origin || url.protocol)) { - throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.') + for (let i = 0; i < characters.length; i++) { + if (validTokenChars[characters.charCodeAt(i)] !== 1) { + return false } - - return url - } - - if (!url || typeof url !== 'object') { - throw new InvalidArgumentError('Invalid URL: The URL argument must be a non-null object.') } + return true +} - if (!(url instanceof URL)) { - if (url.port != null && url.port !== '' && isValidPort(url.port) === false) { - throw new InvalidArgumentError('Invalid URL: port must be a valid integer or a string representation of an integer.') - } +// headerCharRegex have been lifted from +// https://github.com/nodejs/node/blob/main/lib/_http_common.js - if (url.path != null && typeof url.path !== 'string') { - throw new InvalidArgumentError('Invalid URL path: the path must be a string or null/undefined.') - } +/** + * Matches if val contains an invalid field-vchar + * field-value = *( field-content / obs-fold ) + * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] + * field-vchar = VCHAR / obs-text + */ +const headerCharRegex = /[^\t\x20-\x7e\x80-\xff]/ - if (url.pathname != null && typeof url.pathname !== 'string') { - throw new InvalidArgumentError('Invalid URL pathname: the pathname must be a string or null/undefined.') - } +/** + * @param {string} characters + * @returns {boolean} + */ +function isValidHeaderValue (characters) { + return !headerCharRegex.test(characters) +} - if (url.hostname != null && typeof url.hostname !== 'string') { - throw new InvalidArgumentError('Invalid URL hostname: the hostname must be a string or null/undefined.') - } +const rangeHeaderRegex = /^bytes (\d+)-(\d+)\/(\d+|\*)?$/ - if (url.origin != null && typeof url.origin !== 'string') { - throw new InvalidArgumentError('Invalid URL origin: the origin must be a string or null/undefined.') - } +/** + * @typedef {object} RangeHeader + * @property {number} start + * @property {number | null} end + * @property {number | null} size + */ - if (!isHttpOrHttpsPrefixed(url.origin || url.protocol)) { - throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.') - } +/** + * Parse accordingly to RFC 9110 + * @see https://www.rfc-editor.org/rfc/rfc9110#field.content-range + * @param {string} [range] + * @returns {RangeHeader|null} + */ +function parseRangeHeader (range) { + if (range == null || range === '') return { start: 0, end: null, size: null } + if (!range) return null - const port = url.port != null - ? url.port - : (url.protocol === 'https:' ? 443 : 80) - let origin = url.origin != null - ? url.origin - : `${url.protocol || ''}//${url.hostname || ''}:${port}` - let path = url.path != null - ? url.path - : `${url.pathname || ''}${url.search || ''}` + const m = rangeHeaderRegex.exec(range) + return m + ? { + start: parseInt(m[1]), + end: m[2] ? parseInt(m[2]) : null, + size: m[3] && m[3] !== '*' ? parseInt(m[3]) : null + } + : null +} - if (origin[origin.length - 1] === '/') { - origin = origin.slice(0, origin.length - 1) - } +/** + * @template {import("events").EventEmitter} T + * @param {T} obj + * @param {string} name + * @param {(...args: any[]) => void} listener + * @returns {T} + */ +function addListener (obj, name, listener) { + const listeners = (obj[kListeners] ??= []) + listeners.push([name, listener]) + obj.on(name, listener) + return obj +} - if (path && path[0] !== '/') { - path = `/${path}` +/** + * @template {import("events").EventEmitter} T + * @param {T} obj + * @returns {T} + */ +function removeAllListeners (obj) { + if (obj[kListeners] != null) { + for (const [name, listener] of obj[kListeners]) { + obj.removeListener(name, listener) } - // new URL(path, origin) is unsafe when `path` contains an absolute URL - // From https://developer.mozilla.org/en-US/docs/Web/API/URL/URL: - // If first parameter is a relative URL, second param is required, and will be used as the base URL. - // If first parameter is an absolute URL, a given second param will be ignored. - return new URL(`${origin}${path}`) + obj[kListeners] = null } + return obj +} - if (!isHttpOrHttpsPrefixed(url.origin || url.protocol)) { - throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.') +/** + * @param {import ('../dispatcher/client')} client + * @param {import ('../core/request')} request + * @param {Error} err + */ +function errorRequest (client, request, err) { + try { + request.onResponseError(err) + assert(request.aborted) + } catch (err) { + client.emit('error', err) } - - return url } /** - * @param {string|URL|Record} url - * @returns {URL} + * @param {WeakRef} socketWeakRef + * @param {object} opts + * @param {number} opts.timeout + * @param {string} opts.hostname + * @param {number} opts.port + * @returns {() => void} */ -function parseOrigin (url) { - url = parseURL(url) +const setupConnectTimeout = process.platform === 'win32' + ? (socketWeakRef, opts) => { + if (!opts.timeout) { + return noop + } - if (url.pathname !== '/' || url.search || url.hash) { - throw new InvalidArgumentError('invalid url') - } + let s1 = null + let s2 = null + const fastTimer = timers.setFastTimeout(() => { + // setImmediate is added to make sure that we prioritize socket error events over timeouts + s1 = setImmediate(() => { + // Windows needs an extra setImmediate probably due to implementation differences in the socket logic + s2 = setImmediate(() => onConnectTimeout(socketWeakRef.deref(), opts)) + }) + }, opts.timeout) + return () => { + timers.clearFastTimeout(fastTimer) + clearImmediate(s1) + clearImmediate(s2) + } + } + : (socketWeakRef, opts) => { + if (!opts.timeout) { + return noop + } - return url -} + let s1 = null + const fastTimer = timers.setFastTimeout(() => { + // setImmediate is added to make sure that we prioritize socket error events over timeouts + s1 = setImmediate(() => { + onConnectTimeout(socketWeakRef.deref(), opts) + }) + }, opts.timeout) + return () => { + timers.clearFastTimeout(fastTimer) + clearImmediate(s1) + } + } /** - * @param {string} host - * @returns {string} + * @param {net.Socket} socket + * @param {object} opts + * @param {number} opts.timeout + * @param {string} opts.hostname + * @param {number} opts.port */ -function getHostname (host) { - if (host[0] === '[') { - const idx = host.indexOf(']') +function onConnectTimeout (socket, opts) { + // The socket could be already garbage collected + if (socket == null) { + return + } - assert(idx !== -1) - return host.substring(1, idx) + let message = 'Connect Timeout Error' + if (Array.isArray(socket.autoSelectFamilyAttemptedAddresses)) { + message += ` (attempted addresses: ${socket.autoSelectFamilyAttemptedAddresses.join(', ')},` + } else { + message += ` (attempted address: ${opts.hostname}:${opts.port},` } - const idx = host.indexOf(':') - if (idx === -1) return host + message += ` timeout: ${opts.timeout}ms)` - return host.substring(0, idx) + destroy(socket, new ConnectTimeoutError(message)) } +let lastUrlString = null +let lastProtocol = null + /** - * IP addresses are not valid server names per RFC6066 - * Currently, the only server names supported are DNS hostnames - * @param {string|null} host - * @returns {string|null} + * @param {string} urlString + * @returns {string} */ -function getServerName (host) { - if (!host) { - return null +function getProtocolFromUrlString (urlString) { + // Requests are typically dispatched against the same origin over and over, + // so cache the last (urlString, protocol) pair to skip re-parsing. + if (urlString === lastUrlString) { + return lastProtocol } - assert(typeof host === 'string') - - const servername = getHostname(host) - if (net.isIP(servername)) { - return '' - } + const protocol = getProtocolFromUrlStringSlow(urlString) + lastUrlString = urlString + lastProtocol = protocol - return servername + return protocol } /** - * @function - * @template T - * @param {T} obj - * @returns {T} + * @param {string} urlString + * @returns {string} */ -function deepClone (obj) { - return JSON.parse(JSON.stringify(obj)) -} - -/** - * @param {*} obj - * @returns {obj is AsyncIterable} - */ -function isAsyncIterable (obj) { - return !!(obj != null && typeof obj[Symbol.asyncIterator] === 'function') +function getProtocolFromUrlStringSlow (urlString) { + if ( + urlString[0] === 'h' && + urlString[1] === 't' && + urlString[2] === 't' && + urlString[3] === 'p' + ) { + switch (urlString[4]) { + case ':': + return 'http:' + case 's': + if (urlString[5] === ':') { + return 'https:' + } + } + } + // fallback if none of the usual suspects + return urlString.slice(0, urlString.indexOf(':') + 1) } -/** - * @param {*} obj - * @returns {obj is Iterable} - */ -function isIterable (obj) { - return !!(obj != null && (typeof obj[Symbol.iterator] === 'function' || typeof obj[Symbol.asyncIterator] === 'function')) +const kEnumerableProperty = { + __proto__: null, + enumerable: true } -/** - * Checks whether an object has a safe Symbol.iterator — i.e. one that is - * either own or inherited from a non-Object.prototype chain. This prevents - * prototype-pollution attacks from injecting a fake iterator on - * Object.prototype. - * @param {object} obj - * @returns {boolean} - */ -function hasSafeIterator (obj) { - const prototype = Object.getPrototypeOf(obj) - const ownIterator = Object.hasOwn(obj, Symbol.iterator) - return ownIterator || (prototype != null && prototype !== Object.prototype && typeof obj[Symbol.iterator] === 'function') +const normalizedMethodRecordsBase = { + delete: 'DELETE', + DELETE: 'DELETE', + get: 'GET', + GET: 'GET', + head: 'HEAD', + HEAD: 'HEAD', + options: 'OPTIONS', + OPTIONS: 'OPTIONS', + post: 'POST', + POST: 'POST', + put: 'PUT', + PUT: 'PUT', + query: 'QUERY', + QUERY: 'QUERY' } -/** - * @param {Blob|Buffer|import ('stream').Stream} body - * @returns {number|null} - */ -function bodyLength (body) { - if (body == null) { - return 0 - } else if (isStream(body)) { - const state = body._readableState - return state && state.objectMode === false && state.ended === true && Number.isFinite(state.length) - ? state.length - : null - } else if (isBlobLike(body)) { - return body.size != null ? body.size : null - } else if (isBuffer(body)) { - return body.byteLength - } +const normalizedMethodRecords = { + ...normalizedMethodRecordsBase, + patch: 'patch', + PATCH: 'PATCH' +} - return null +// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`. +Object.setPrototypeOf(normalizedMethodRecordsBase, null) +Object.setPrototypeOf(normalizedMethodRecords, null) + +module.exports = { + kEnumerableProperty, + isDisturbed, + isBlobLike, + parseOrigin, + parseURL, + getServerName, + isStream, + isIterable, + hasSafeIterator, + isAsyncIterable, + isDestroyed, + headerNameToString, + bufferToLowerCasedHeaderName, + addListener, + removeAllListeners, + errorRequest, + parseRawHeaders, + toRawHeaders, + encodeRawHeaders, + parseHeaders, + parseKeepAliveTimeout, + destroy, + bodyLength, + deepClone, + isBuffer, + assertRequestHandler, + getSocketInfo, + isFormDataLike, + pathHasQueryOrFragment, + serializePathWithQuery, + addAbortListener, + isValidHTTPToken, + isValidHeaderValue, + isTokenCharCode, + parseRangeHeader, + normalizedMethodRecordsBase, + normalizedMethodRecords, + isValidPort, + isHttpOrHttpsPrefixed, + safeHTTPMethods: Object.freeze(['GET', 'HEAD', 'OPTIONS', 'TRACE']), + wrapRequestBody, + setupConnectTimeout, + getProtocolFromUrlString } -/** - * @param {import ('stream').Stream} body - * @returns {boolean} - */ -function isDestroyed (body) { - return body && !!(body.destroyed || body[kDestroyed] || (stream.isDestroyed?.(body))) + +/***/ }), + +/***/ 1470: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const { InvalidArgumentError, MaxOriginsReachedError } = __nccwpck_require__(4882) +const { kBusy, kClients, kConnected, kRunning, kPending, kClose, kDestroy, kDispatch, kUrl } = __nccwpck_require__(228) +const DispatcherBase = __nccwpck_require__(1538) +const Pool = __nccwpck_require__(3469) +const Client = __nccwpck_require__(1696) +const util = __nccwpck_require__(9277) + +const kOnConnect = Symbol('onConnect') +const kOnDisconnect = Symbol('onDisconnect') +const kOnConnectionError = Symbol('onConnectionError') +const kOnDrain = Symbol('onDrain') +const kFactory = Symbol('factory') +const kOptions = Symbol('options') +const kOrigins = Symbol('origins') + +function defaultFactory (origin, opts) { + return opts && opts.connections === 1 + ? new Client(origin, opts) + : new Pool(origin, opts) } -/** - * @param {import ('stream').Stream} stream - * @param {Error} [err] - * @returns {void} - */ -function destroy (stream, err) { - if (stream == null || !isStream(stream) || isDestroyed(stream)) { - return - } +class Agent extends DispatcherBase { + constructor ({ factory = defaultFactory, maxOrigins = Infinity, connect, ...options } = {}) { + if (typeof factory !== 'function') { + throw new InvalidArgumentError('factory must be a function.') + } - if (typeof stream.destroy === 'function') { - if (Object.getPrototypeOf(stream).constructor === IncomingMessage) { - // See: https://github.com/nodejs/node/pull/38505/files - stream.socket = null + if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { + throw new InvalidArgumentError('connect must be a function or an object') } - try { - stream.destroy(err) - } catch { - // stream.destroy may throw on managed sockets (e.g., http2). - // Silently ignore — the socket lifecycle is handled by the subsystem. + if (typeof maxOrigins !== 'number' || Number.isNaN(maxOrigins) || maxOrigins <= 0) { + throw new InvalidArgumentError('maxOrigins must be a number greater than 0') + } + + super(options) + + if (connect && typeof connect !== 'function') { + connect = { ...connect } + } + + this[kOptions] = { ...util.deepClone(options), maxOrigins, connect } + this[kFactory] = factory + this[kClients] = new Map() + this[kOrigins] = new Set() + + this[kOnDrain] = (origin, targets) => { + this.emit('drain', origin, [this, ...targets]) + } + + this[kOnConnect] = (origin, targets) => { + this.emit('connect', origin, [this, ...targets]) + } + + this[kOnDisconnect] = (origin, targets, err) => { + this.emit('disconnect', origin, [this, ...targets], err) + } + + this[kOnConnectionError] = (origin, targets, err) => { + this.emit('connectionError', origin, [this, ...targets], err) } - } else if (err) { - queueMicrotask(() => { - stream.emit('error', err) - }) } - if (stream.destroyed !== true) { - stream[kDestroyed] = true + get [kRunning] () { + let ret = 0 + for (const dispatcher of this[kClients].values()) { + ret += dispatcher[kRunning] + } + return ret } -} -const KEEPALIVE_TIMEOUT_EXPR = /timeout=(\d+)/ -/** - * @param {string} val - * @returns {number | null} - */ -function parseKeepAliveTimeout (val) { - const m = val.match(KEEPALIVE_TIMEOUT_EXPR) - return m ? parseInt(m[1], 10) * 1000 : null -} + [kDispatch] (opts, handler) { + let origin + if (opts.origin && (typeof opts.origin === 'string' || opts.origin instanceof URL)) { + origin = String(opts.origin) + } else { + throw new InvalidArgumentError('opts.origin must be a non-empty string or URL.') + } -/** - * Retrieves a header name and returns its lowercase value. - * @param {string | Buffer} value Header name - * @returns {string} - */ -function headerNameToString (value) { - return typeof value === 'string' - ? headerNameLowerCasedRecord[value] ?? value.toLowerCase() - : tree.lookup(value) ?? value.toString('latin1').toLowerCase() -} + const allowH2 = opts.allowH2 ?? this[kOptions].allowH2 + const key = allowH2 === false ? `${origin}#http1-only` : origin -/** - * Receive the buffer as a string and return its lowercase value. - * @param {Buffer} value Header name - * @returns {string} - */ -function bufferToLowerCasedHeaderName (value) { - return tree.lookup(value) ?? value.toString('latin1').toLowerCase() -} + if (this[kOrigins].size >= this[kOptions].maxOrigins && !this[kOrigins].has(origin)) { + throw new MaxOriginsReachedError() + } -/** - * @param {(Buffer | string)[]} headers - * @param {Record} [obj] - * @returns {Record} - */ -function parseHeaders (headers, obj) { - if (obj === undefined) obj = {} + let dispatcher = this[kClients].get(key) + if (!dispatcher) { + dispatcher = this[kFactory](opts.origin, allowH2 === false + ? { ...this[kOptions], allowH2: false } + : this[kOptions]) - for (let i = 0; i < headers.length; i += 2) { - const key = headerNameToString(headers[i]) - let val = obj[key] + const closeClientIfUnused = () => { + if (this[kClients].get(key) !== dispatcher) { + return + } - if (val !== undefined) { - if (!Object.hasOwn(obj, key)) { - const headersValue = typeof headers[i + 1] === 'string' - ? headers[i + 1] - : Array.isArray(headers[i + 1]) - ? headers[i + 1].map(x => x.toString('latin1')) - : headers[i + 1].toString('latin1') + // A GOAWAY detaches the HTTP/2 session before requeued requests are + // dispatched on a replacement connection. At that point the pool has + // no connected clients and is not busy, but it still has pending work. + // Closing it here lets the replacement Client finish those requests + // and then destroys that new connection with ClientDestroyedError. + if (dispatcher[kConnected] > 0 || dispatcher[kBusy] || dispatcher[kPending] > 0) { + return + } - if (key === '__proto__') { - Object.defineProperty(obj, key, { - value: headersValue, - enumerable: true, - configurable: true, - writable: true - }) - } else { - obj[key] = headersValue + this[kClients].delete(key) + if (!dispatcher.destroyed) { + dispatcher.close() } - } else { - if (typeof val === 'string') { - val = [val] - obj[key] = val + + let hasOrigin = false + for (const k of this[kClients].keys()) { + if (k === origin || k === `${origin}#http1-only`) { + hasOrigin = true + break + } + } + + if (!hasOrigin) { + this[kOrigins].delete(origin) } - val.push(headers[i + 1].toString('latin1')) } - } else { - const headersValue = typeof headers[i + 1] === 'string' - ? headers[i + 1] - : Array.isArray(headers[i + 1]) - ? headers[i + 1].map(x => x.toString('latin1')) - : headers[i + 1].toString('latin1') - obj[key] = headersValue + dispatcher + .on('drain', this[kOnDrain]) + .on('connect', this[kOnConnect]) + .on('disconnect', (origin, targets, err) => { + closeClientIfUnused() + this[kOnDisconnect](origin, targets, err) + }) + .on('connectionError', (origin, targets, err) => { + closeClientIfUnused() + this[kOnConnectionError](origin, targets, err) + }) + + this[kClients].set(key, dispatcher) + this[kOrigins].add(origin) } + + return dispatcher.dispatch(opts, handler) } - return obj -} + [kClose] () { + const closePromises = [] + for (const dispatcher of this[kClients].values()) { + closePromises.push(dispatcher.close()) + } + this[kClients].clear() -/** - * @param {Buffer[] | string[] | Record | null | undefined} headers - * @returns {string[]} - */ -function parseRawHeaders (headers) { - if (headers == null) { - return [] + return Promise.all(closePromises) } - if (!Array.isArray(headers)) { - const rawHeaders = [] - - for (const [name, value] of Object.entries(headers)) { - if (Array.isArray(value)) { - for (const entry of value) { - rawHeaders.push(name, `${entry}`) - } - } else { - rawHeaders.push(name, `${value}`) - } + [kDestroy] (err) { + const destroyPromises = [] + for (const dispatcher of this[kClients].values()) { + destroyPromises.push(dispatcher.destroy(err)) } + this[kClients].clear() - return rawHeaders + return Promise.all(destroyPromises) } - const headersLength = headers.length - /** - * @type {string[]} - */ - const ret = new Array(headersLength) + get stats () { + const allClientStats = {} + for (const dispatcher of this[kClients].values()) { + if (dispatcher.stats) { + allClientStats[dispatcher[kUrl].origin] = dispatcher.stats + } + } + return allClientStats + } +} - let key - let val +module.exports = Agent - for (let n = 0; n < headersLength; n += 2) { - key = headers[n] - val = headers[n + 1] - typeof key !== 'string' && (key = key.toString()) - typeof val !== 'string' && (val = val.toString('latin1')) +/***/ }), - ret[n] = key - ret[n + 1] = val - } +/***/ 9586: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return ret -} +"use strict"; -/** - * @param {Record} headers - * @returns {Buffer[]} - */ -function toRawHeaders (headers) { - const rawHeaders = [] - for (const [name, value] of Object.entries(headers)) { - if (Array.isArray(value)) { - for (const entry of value) { - rawHeaders.push(Buffer.from(name, 'latin1'), Buffer.from(`${entry}`, 'latin1')) - } - } else { - rawHeaders.push(Buffer.from(name, 'latin1'), Buffer.from(`${value}`, 'latin1')) - } - } +const { + BalancedPoolMissingUpstreamError, + InvalidArgumentError +} = __nccwpck_require__(4882) +const { + PoolBase, + kClients, + kNeedDrain, + kAddClient, + kRemoveClient, + kGetDispatcher +} = __nccwpck_require__(63) +const Pool = __nccwpck_require__(3469) +const { kOriginless, kUrl } = __nccwpck_require__(228) +const util = __nccwpck_require__(9277) +const kFactory = Symbol('factory') - return rawHeaders -} +const kOptions = Symbol('options') +const kGreatestCommonDivisor = Symbol('kGreatestCommonDivisor') +const kCurrentWeight = Symbol('kCurrentWeight') +const kIndex = Symbol('kIndex') +const kWeight = Symbol('kWeight') +const kMaxWeightPerServer = Symbol('kMaxWeightPerServer') +const kErrorPenalty = Symbol('kErrorPenalty') /** - * @param {string[]} headers - * @param {Buffer[]} headers + * Calculate the greatest common divisor of two numbers by + * using the Euclidean algorithm. + * + * @param {number} a + * @param {number} b + * @returns {number} */ -function encodeRawHeaders (headers) { - if (!Array.isArray(headers)) { - throw new TypeError('expected headers to be an array') +function getGreatestCommonDivisor (a, b) { + if (a === 0) return b + + while (b !== 0) { + const t = b + b = a % b + a = t } - return headers.map(x => Buffer.from(x)) + return a } -/** - * @param {*} buffer - * @returns {buffer is Buffer} - */ -function isBuffer (buffer) { - // See, https://github.com/mcollina/undici/pull/319 - return buffer instanceof Uint8Array || Buffer.isBuffer(buffer) +function defaultFactory (origin, opts) { + return new Pool(origin, opts) } -/** - * Asserts that the handler object is a request handler. - * - * @param {object} handler - * @param {string} method - * @param {string} [upgrade] - * @returns {asserts handler is import('../api/api-request').RequestHandler} - */ -function assertRequestHandler (handler, method, upgrade) { - if (!handler || typeof handler !== 'object') { - throw new InvalidArgumentError('handler must be an object') - } +class BalancedPool extends PoolBase { + constructor (upstreams = [], { factory = defaultFactory, connect, tls, ...opts } = {}) { + if (typeof factory !== 'function') { + throw new InvalidArgumentError('factory must be a function.') + } - if (typeof handler.onRequestStart !== 'function') { - throw new InvalidArgumentError('invalid onRequestStart method') - } + super(opts) - if (typeof handler.onResponseError !== 'function') { - throw new InvalidArgumentError('invalid onResponseError method') - } + this[kOriginless] = true + if (connect && typeof connect !== 'function') connect = { ...connect } + if (tls && typeof tls !== 'function') tls = { ...tls } + this[kOptions] = { ...util.deepClone(opts), connect, tls } + this[kIndex] = -1 + this[kCurrentWeight] = 0 - if (typeof handler.onBodySent !== 'function' && handler.onBodySent !== undefined) { - throw new InvalidArgumentError('invalid onBodySent method') - } + this[kMaxWeightPerServer] = this[kOptions].maxWeightPerServer || 100 + this[kErrorPenalty] = this[kOptions].errorPenalty || 15 - if (typeof handler.onRequestSent !== 'function' && handler.onRequestSent !== undefined) { - throw new InvalidArgumentError('invalid onRequestSent method') - } - - if (upgrade || method === 'CONNECT') { - if (typeof handler.onRequestUpgrade !== 'function') { - throw new InvalidArgumentError('invalid onRequestUpgrade method') - } - } else { - if (typeof handler.onResponseStart !== 'function') { - throw new InvalidArgumentError('invalid onResponseStart method') + if (!Array.isArray(upstreams)) { + upstreams = [upstreams] } - if (typeof handler.onResponseData !== 'function') { - throw new InvalidArgumentError('invalid onResponseData method') - } + this[kFactory] = factory - if (typeof handler.onResponseEnd !== 'function') { - throw new InvalidArgumentError('invalid onResponseEnd method') + for (const upstream of upstreams) { + this.addUpstream(upstream) } + this._updateBalancedPoolStats() } -} -/** - * A body is disturbed if it has been read from and it cannot be re-used without - * losing state or data. - * @param {import('node:stream').Readable} body - * @returns {boolean} - */ -function isDisturbed (body) { - // TODO (fix): Why is body[kBodyUsed] needed? - return !!(body && (stream.isDisturbed(body) || body[kBodyUsed])) -} + addUpstream (upstream) { + const upstreamOrigin = util.parseOrigin(upstream).origin -/** - * @typedef {object} SocketInfo - * @property {string} [localAddress] - * @property {number} [localPort] - * @property {string} [remoteAddress] - * @property {number} [remotePort] - * @property {string} [remoteFamily] - * @property {number} [timeout] - * @property {number} bytesWritten - * @property {number} bytesRead - */ + if (this[kClients].find((pool) => ( + pool[kUrl].origin === upstreamOrigin && + pool.closed !== true && + pool.destroyed !== true + ))) { + return this + } + const pool = this[kFactory](upstreamOrigin, this[kOptions]) -/** - * @param {import('net').Socket} socket - * @returns {SocketInfo} - */ -function getSocketInfo (socket) { - return { - localAddress: socket.localAddress, - localPort: socket.localPort, - remoteAddress: socket.remoteAddress, - remotePort: socket.remotePort, - remoteFamily: socket.remoteFamily, - timeout: socket.timeout, - bytesWritten: socket.bytesWritten, - bytesRead: socket.bytesRead - } -} + this[kAddClient](pool) + pool.on('connect', () => { + pool[kWeight] = Math.min(this[kMaxWeightPerServer], pool[kWeight] + this[kErrorPenalty]) + }) -/** - * The object should be a FormData instance and contains all the required - * methods. - * @param {*} object - * @returns {object is FormData} - */ -function isFormDataLike (object) { - return ( - object && - typeof object === 'object' && - typeof object.append === 'function' && - typeof object.delete === 'function' && - typeof object.get === 'function' && - typeof object.getAll === 'function' && - typeof object.has === 'function' && - typeof object.set === 'function' && - object[Symbol.toStringTag] === 'FormData' - ) -} + pool.on('connectionError', () => { + pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty]) + this._updateBalancedPoolStats() + }) -function addAbortListener (signal, listener) { - if (!signal || 'aborted' in signal) { - return addAbortListenerNative(signal, listener)[Symbol.dispose] - } + pool.on('disconnect', (...args) => { + const err = args[2] + if (err && err.code === 'UND_ERR_SOCKET') { + // decrease the weight of the pool. + pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty]) + this._updateBalancedPoolStats() + } + }) - if (typeof signal.addEventListener === 'function') { - signal.addEventListener('abort', listener, { once: true }) - return () => signal.removeEventListener('abort', listener) + for (const client of this[kClients]) { + client[kWeight] = this[kMaxWeightPerServer] + } + + this._updateBalancedPoolStats() + + return this } - signal.once('abort', listener) - return () => signal.removeListener('abort', listener) -} -const validTokenChars = new Uint8Array([ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0-15 - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16-31 - 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, // 32-47 (!"#$%&'()*+,-./) - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 48-63 (0-9:;<=>?) - 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64-79 (@A-O) - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, // 80-95 (P-Z[\]^_) - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96-111 (`a-o) - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, // 112-127 (p-z{|}~) - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 128-143 - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 144-159 - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 160-175 - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 176-191 - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 192-207 - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 208-223 - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 224-239 - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 // 240-255 -]) + _updateBalancedPoolStats () { + let result = 0 + for (let i = 0; i < this[kClients].length; i++) { + result = getGreatestCommonDivisor(this[kClients][i][kWeight], result) + } -/** - * @see https://tools.ietf.org/html/rfc7230#section-3.2.6 - * @param {number} c - * @returns {boolean} - */ -function isTokenCharCode (c) { - return (validTokenChars[c] === 1) -} + this[kGreatestCommonDivisor] = result + } -const tokenRegExp = /^[\^_`a-zA-Z\-0-9!#$%&'*+.|~]+$/ + removeUpstream (upstream) { + const upstreamOrigin = util.parseOrigin(upstream).origin -/** - * @param {string} characters - * @returns {boolean} - */ -function isValidHTTPToken (characters) { - if (characters.length >= 12) return tokenRegExp.test(characters) - if (characters.length === 0) return false + const pool = this[kClients].find((pool) => ( + pool[kUrl].origin === upstreamOrigin && + pool.closed !== true && + pool.destroyed !== true + )) - for (let i = 0; i < characters.length; i++) { - if (validTokenChars[characters.charCodeAt(i)] !== 1) { - return false + if (pool) { + this[kRemoveClient](pool) } + + return this } - return true -} -// headerCharRegex have been lifted from -// https://github.com/nodejs/node/blob/main/lib/_http_common.js + getUpstream (upstream) { + const upstreamOrigin = util.parseOrigin(upstream).origin -/** - * Matches if val contains an invalid field-vchar - * field-value = *( field-content / obs-fold ) - * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] - * field-vchar = VCHAR / obs-text - */ -const headerCharRegex = /[^\t\x20-\x7e\x80-\xff]/ + return this[kClients].find((pool) => ( + pool[kUrl].origin === upstreamOrigin && + pool.closed !== true && + pool.destroyed !== true + )) + } -/** - * @param {string} characters - * @returns {boolean} - */ -function isValidHeaderValue (characters) { - return !headerCharRegex.test(characters) -} + get upstreams () { + return this[kClients] + .filter(dispatcher => dispatcher.closed !== true && dispatcher.destroyed !== true) + .map((p) => p[kUrl].origin) + } -const rangeHeaderRegex = /^bytes (\d+)-(\d+)\/(\d+|\*)?$/ + [kGetDispatcher] () { + // We validate that pools is greater than 0, + // otherwise we would have to wait until an upstream + // is added, which might never happen. + if (this[kClients].length === 0) { + throw new BalancedPoolMissingUpstreamError() + } -/** - * @typedef {object} RangeHeader - * @property {number} start - * @property {number | null} end - * @property {number | null} size - */ + let counter = 0 -/** - * Parse accordingly to RFC 9110 - * @see https://www.rfc-editor.org/rfc/rfc9110#field.content-range - * @param {string} [range] - * @returns {RangeHeader|null} - */ -function parseRangeHeader (range) { - if (range == null || range === '') return { start: 0, end: null, size: null } - if (!range) return null + let maxWeightIndex = -1 - const m = rangeHeaderRegex.exec(range) - return m - ? { - start: parseInt(m[1]), - end: m[2] ? parseInt(m[2]) : null, - size: m[3] && m[3] !== '*' ? parseInt(m[3]) : null - } - : null -} + while (counter++ < this[kClients].length) { + this[kIndex] = (this[kIndex] + 1) % this[kClients].length + const pool = this[kClients][this[kIndex]] -/** - * @template {import("events").EventEmitter} T - * @param {T} obj - * @param {string} name - * @param {(...args: any[]) => void} listener - * @returns {T} - */ -function addListener (obj, name, listener) { - const listeners = (obj[kListeners] ??= []) - listeners.push([name, listener]) - obj.on(name, listener) - return obj -} + // decrease the current weight every `this[kClients].length`. + if (this[kIndex] === 0) { + // Set the current weight to the next lower weight. + this[kCurrentWeight] = this[kCurrentWeight] - this[kGreatestCommonDivisor] -/** - * @template {import("events").EventEmitter} T - * @param {T} obj - * @returns {T} - */ -function removeAllListeners (obj) { - if (obj[kListeners] != null) { - for (const [name, listener] of obj[kListeners]) { - obj.removeListener(name, listener) - } - obj[kListeners] = null - } - return obj -} + if (this[kCurrentWeight] <= 0) { + this[kCurrentWeight] = this[kMaxWeightPerServer] + } + } -/** - * @param {import ('../dispatcher/client')} client - * @param {import ('../core/request')} request - * @param {Error} err - */ -function errorRequest (client, request, err) { - try { - request.onResponseError(err) - assert(request.aborted) - } catch (err) { - client.emit('error', err) - } -} + // Skip unavailable pools after updating the current weight for this cycle. + if ( + pool[kNeedDrain] || + pool.closed === true || + pool.destroyed === true + ) { + continue + } -/** - * @param {WeakRef} socketWeakRef - * @param {object} opts - * @param {number} opts.timeout - * @param {string} opts.hostname - * @param {number} opts.port - * @returns {() => void} - */ -const setupConnectTimeout = process.platform === 'win32' - ? (socketWeakRef, opts) => { - if (!opts.timeout) { - return noop + // Track the best fallback if no pool matches the current weight. + if (maxWeightIndex === -1 || pool[kWeight] > this[kClients][maxWeightIndex][kWeight]) { + maxWeightIndex = this[kIndex] } - let s1 = null - let s2 = null - const fastTimer = timers.setFastTimeout(() => { - // setImmediate is added to make sure that we prioritize socket error events over timeouts - s1 = setImmediate(() => { - // Windows needs an extra setImmediate probably due to implementation differences in the socket logic - s2 = setImmediate(() => onConnectTimeout(socketWeakRef.deref(), opts)) - }) - }, opts.timeout) - return () => { - timers.clearFastTimeout(fastTimer) - clearImmediate(s1) - clearImmediate(s2) + if (pool[kWeight] >= this[kCurrentWeight]) { + return pool } } - : (socketWeakRef, opts) => { - if (!opts.timeout) { - return noop - } - let s1 = null - const fastTimer = timers.setFastTimeout(() => { - // setImmediate is added to make sure that we prioritize socket error events over timeouts - s1 = setImmediate(() => { - onConnectTimeout(socketWeakRef.deref(), opts) - }) - }, opts.timeout) - return () => { - timers.clearFastTimeout(fastTimer) - clearImmediate(s1) - } + if (maxWeightIndex === -1) { + return } -/** - * @param {net.Socket} socket - * @param {object} opts - * @param {number} opts.timeout - * @param {string} opts.hostname - * @param {number} opts.port - */ -function onConnectTimeout (socket, opts) { - // The socket could be already garbage collected - if (socket == null) { - return + this[kCurrentWeight] = this[kClients][maxWeightIndex][kWeight] + this[kIndex] = maxWeightIndex + return this[kClients][maxWeightIndex] } +} - let message = 'Connect Timeout Error' - if (Array.isArray(socket.autoSelectFamilyAttemptedAddresses)) { - message += ` (attempted addresses: ${socket.autoSelectFamilyAttemptedAddresses.join(', ')},` - } else { - message += ` (attempted address: ${opts.hostname}:${opts.port},` - } +module.exports = BalancedPool - message += ` timeout: ${opts.timeout}ms)` - destroy(socket, new ConnectTimeoutError(message)) -} +/***/ }), -let lastUrlString = null -let lastProtocol = null +/***/ 9742: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * @param {string} urlString - * @returns {string} - */ -function getProtocolFromUrlString (urlString) { - // Requests are typically dispatched against the same origin over and over, - // so cache the last (urlString, protocol) pair to skip re-parsing. - if (urlString === lastUrlString) { - return lastProtocol - } +"use strict"; - const protocol = getProtocolFromUrlStringSlow(urlString) - lastUrlString = urlString - lastProtocol = protocol - return protocol -} +/* global WebAssembly */ -/** - * @param {string} urlString - * @returns {string} - */ -function getProtocolFromUrlStringSlow (urlString) { - if ( - urlString[0] === 'h' && - urlString[1] === 't' && - urlString[2] === 't' && - urlString[3] === 'p' - ) { - switch (urlString[4]) { - case ':': - return 'http:' - case 's': - if (urlString[5] === ':') { - return 'https:' - } - } - } - // fallback if none of the usual suspects - return urlString.slice(0, urlString.indexOf(':') + 1) -} +const assert = __nccwpck_require__(4589) +const util = __nccwpck_require__(9277) +const { channels } = __nccwpck_require__(185) +const timers = __nccwpck_require__(3562) +const { + RequestContentLengthMismatchError, + ResponseContentLengthMismatchError, + RequestAbortedError, + InvalidArgumentError, + HeadersTimeoutError, + HeadersOverflowError, + SocketError, + InformationalError, + BodyTimeoutError, + HTTPParserError, + ResponseExceededMaxSizeError +} = __nccwpck_require__(4882) +const { + kUrl, + kReset, + kClient, + kParser, + kBlocking, + kRunning, + kPending, + kSize, + kWriting, + kQueue, + kNoRef, + kKeepAliveDefaultTimeout, + kHostHeader, + kPendingIdx, + kRunningIdx, + kError, + kPipelining, + kSocket, + kKeepAliveTimeoutValue, + kMaxHeadersSize, + kKeepAliveMaxTimeout, + kKeepAliveTimeoutThreshold, + kHeadersTimeout, + kBodyTimeout, + kStrictContentLength, + kMaxRequests, + kCounter, + kMaxResponseSize, + kOnError, + kResume, + kHTTPContext, + kClosed +} = __nccwpck_require__(228) -const kEnumerableProperty = { - __proto__: null, - enumerable: true -} +const constants = __nccwpck_require__(8383) +const EMPTY_BUF = Buffer.alloc(0) +const FastBuffer = Buffer[Symbol.species] +const removeAllListeners = util.removeAllListeners +const kIdleSocketValidation = Symbol('kIdleSocketValidation') +const kIdleSocketValidationTimeout = Symbol('kIdleSocketValidationTimeout') +const kSocketUsed = Symbol('kSocketUsed') +const kTypeOfService = Symbol('kTypeOfService') -const normalizedMethodRecordsBase = { - delete: 'DELETE', - DELETE: 'DELETE', - get: 'GET', - GET: 'GET', - head: 'HEAD', - HEAD: 'HEAD', - options: 'OPTIONS', - OPTIONS: 'OPTIONS', - post: 'POST', - POST: 'POST', - put: 'PUT', - PUT: 'PUT', - query: 'QUERY', - QUERY: 'QUERY' -} +let extractBody -const normalizedMethodRecords = { - ...normalizedMethodRecordsBase, - patch: 'patch', - PATCH: 'PATCH' -} +function lazyllhttp () { + const llhttpWasmData = process.env.JEST_WORKER_ID ? __nccwpck_require__(8425) : undefined -// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`. -Object.setPrototypeOf(normalizedMethodRecordsBase, null) -Object.setPrototypeOf(normalizedMethodRecords, null) - -module.exports = { - kEnumerableProperty, - isDisturbed, - isBlobLike, - parseOrigin, - parseURL, - getServerName, - isStream, - isIterable, - hasSafeIterator, - isAsyncIterable, - isDestroyed, - headerNameToString, - bufferToLowerCasedHeaderName, - addListener, - removeAllListeners, - errorRequest, - parseRawHeaders, - toRawHeaders, - encodeRawHeaders, - parseHeaders, - parseKeepAliveTimeout, - destroy, - bodyLength, - deepClone, - isBuffer, - assertRequestHandler, - getSocketInfo, - isFormDataLike, - pathHasQueryOrFragment, - serializePathWithQuery, - addAbortListener, - isValidHTTPToken, - isValidHeaderValue, - isTokenCharCode, - parseRangeHeader, - normalizedMethodRecordsBase, - normalizedMethodRecords, - isValidPort, - isHttpOrHttpsPrefixed, - safeHTTPMethods: Object.freeze(['GET', 'HEAD', 'OPTIONS', 'TRACE']), - wrapRequestBody, - setupConnectTimeout, - getProtocolFromUrlString -} - - -/***/ }), - -/***/ 4722: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const { InvalidArgumentError, MaxOriginsReachedError } = __nccwpck_require__(7062) -const { kBusy, kClients, kConnected, kRunning, kPending, kClose, kDestroy, kDispatch, kUrl } = __nccwpck_require__(7480) -const DispatcherBase = __nccwpck_require__(8782) -const Pool = __nccwpck_require__(737) -const Client = __nccwpck_require__(940) -const util = __nccwpck_require__(9705) - -const kOnConnect = Symbol('onConnect') -const kOnDisconnect = Symbol('onDisconnect') -const kOnConnectionError = Symbol('onConnectionError') -const kOnDrain = Symbol('onDrain') -const kFactory = Symbol('factory') -const kOptions = Symbol('options') -const kOrigins = Symbol('origins') - -function defaultFactory (origin, opts) { - return opts && opts.connections === 1 - ? new Client(origin, opts) - : new Pool(origin, opts) -} - -class Agent extends DispatcherBase { - constructor ({ factory = defaultFactory, maxOrigins = Infinity, connect, ...options } = {}) { - if (typeof factory !== 'function') { - throw new InvalidArgumentError('factory must be a function.') - } - - if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { - throw new InvalidArgumentError('connect must be a function or an object') - } - - if (typeof maxOrigins !== 'number' || Number.isNaN(maxOrigins) || maxOrigins <= 0) { - throw new InvalidArgumentError('maxOrigins must be a number greater than 0') - } - - super(options) - - if (connect && typeof connect !== 'function') { - connect = { ...connect } - } - - this[kOptions] = { ...util.deepClone(options), maxOrigins, connect } - this[kFactory] = factory - this[kClients] = new Map() - this[kOrigins] = new Set() - - this[kOnDrain] = (origin, targets) => { - this.emit('drain', origin, [this, ...targets]) - } - - this[kOnConnect] = (origin, targets) => { - this.emit('connect', origin, [this, ...targets]) - } - - this[kOnDisconnect] = (origin, targets, err) => { - this.emit('disconnect', origin, [this, ...targets], err) - } - - this[kOnConnectionError] = (origin, targets, err) => { - this.emit('connectionError', origin, [this, ...targets], err) - } - } - - get [kRunning] () { - let ret = 0 - for (const dispatcher of this[kClients].values()) { - ret += dispatcher[kRunning] - } - return ret - } - - [kDispatch] (opts, handler) { - let origin - if (opts.origin && (typeof opts.origin === 'string' || opts.origin instanceof URL)) { - origin = String(opts.origin) - } else { - throw new InvalidArgumentError('opts.origin must be a non-empty string or URL.') - } - - const allowH2 = opts.allowH2 ?? this[kOptions].allowH2 - const key = allowH2 === false ? `${origin}#http1-only` : origin - - if (this[kOrigins].size >= this[kOptions].maxOrigins && !this[kOrigins].has(origin)) { - throw new MaxOriginsReachedError() - } - - let dispatcher = this[kClients].get(key) - if (!dispatcher) { - dispatcher = this[kFactory](opts.origin, allowH2 === false - ? { ...this[kOptions], allowH2: false } - : this[kOptions]) - - const closeClientIfUnused = () => { - if (this[kClients].get(key) !== dispatcher) { - return - } - - // A GOAWAY detaches the HTTP/2 session before requeued requests are - // dispatched on a replacement connection. At that point the pool has - // no connected clients and is not busy, but it still has pending work. - // Closing it here lets the replacement Client finish those requests - // and then destroys that new connection with ClientDestroyedError. - if (dispatcher[kConnected] > 0 || dispatcher[kBusy] || dispatcher[kPending] > 0) { - return - } - - this[kClients].delete(key) - if (!dispatcher.destroyed) { - dispatcher.close() - } - - let hasOrigin = false - for (const k of this[kClients].keys()) { - if (k === origin || k === `${origin}#http1-only`) { - hasOrigin = true - break - } - } - - if (!hasOrigin) { - this[kOrigins].delete(origin) - } - } - - dispatcher - .on('drain', this[kOnDrain]) - .on('connect', this[kOnConnect]) - .on('disconnect', (origin, targets, err) => { - closeClientIfUnused() - this[kOnDisconnect](origin, targets, err) - }) - .on('connectionError', (origin, targets, err) => { - closeClientIfUnused() - this[kOnConnectionError](origin, targets, err) - }) - - this[kClients].set(key, dispatcher) - this[kOrigins].add(origin) - } - - return dispatcher.dispatch(opts, handler) - } - - [kClose] () { - const closePromises = [] - for (const dispatcher of this[kClients].values()) { - closePromises.push(dispatcher.close()) - } - this[kClients].clear() - - return Promise.all(closePromises) - } - - [kDestroy] (err) { - const destroyPromises = [] - for (const dispatcher of this[kClients].values()) { - destroyPromises.push(dispatcher.destroy(err)) - } - this[kClients].clear() - - return Promise.all(destroyPromises) - } - - get stats () { - const allClientStats = {} - for (const dispatcher of this[kClients].values()) { - if (dispatcher.stats) { - allClientStats[dispatcher[kUrl].origin] = dispatcher.stats - } - } - return allClientStats - } -} - -module.exports = Agent - - -/***/ }), - -/***/ 6022: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const { - BalancedPoolMissingUpstreamError, - InvalidArgumentError -} = __nccwpck_require__(7062) -const { - PoolBase, - kClients, - kNeedDrain, - kAddClient, - kRemoveClient, - kGetDispatcher -} = __nccwpck_require__(8747) -const Pool = __nccwpck_require__(737) -const { kOriginless, kUrl } = __nccwpck_require__(7480) -const util = __nccwpck_require__(9705) -const kFactory = Symbol('factory') - -const kOptions = Symbol('options') -const kGreatestCommonDivisor = Symbol('kGreatestCommonDivisor') -const kCurrentWeight = Symbol('kCurrentWeight') -const kIndex = Symbol('kIndex') -const kWeight = Symbol('kWeight') -const kMaxWeightPerServer = Symbol('kMaxWeightPerServer') -const kErrorPenalty = Symbol('kErrorPenalty') - -/** - * Calculate the greatest common divisor of two numbers by - * using the Euclidean algorithm. - * - * @param {number} a - * @param {number} b - * @returns {number} - */ -function getGreatestCommonDivisor (a, b) { - if (a === 0) return b - - while (b !== 0) { - const t = b - b = a % b - a = t - } - return a -} - -function defaultFactory (origin, opts) { - return new Pool(origin, opts) -} - -class BalancedPool extends PoolBase { - constructor (upstreams = [], { factory = defaultFactory, connect, tls, ...opts } = {}) { - if (typeof factory !== 'function') { - throw new InvalidArgumentError('factory must be a function.') - } - - super(opts) - - this[kOriginless] = true - if (connect && typeof connect !== 'function') connect = { ...connect } - if (tls && typeof tls !== 'function') tls = { ...tls } - this[kOptions] = { ...util.deepClone(opts), connect, tls } - this[kIndex] = -1 - this[kCurrentWeight] = 0 - - this[kMaxWeightPerServer] = this[kOptions].maxWeightPerServer || 100 - this[kErrorPenalty] = this[kOptions].errorPenalty || 15 - - if (!Array.isArray(upstreams)) { - upstreams = [upstreams] - } - - this[kFactory] = factory - - for (const upstream of upstreams) { - this.addUpstream(upstream) - } - this._updateBalancedPoolStats() - } - - addUpstream (upstream) { - const upstreamOrigin = util.parseOrigin(upstream).origin - - if (this[kClients].find((pool) => ( - pool[kUrl].origin === upstreamOrigin && - pool.closed !== true && - pool.destroyed !== true - ))) { - return this - } - const pool = this[kFactory](upstreamOrigin, this[kOptions]) - - this[kAddClient](pool) - pool.on('connect', () => { - pool[kWeight] = Math.min(this[kMaxWeightPerServer], pool[kWeight] + this[kErrorPenalty]) - }) - - pool.on('connectionError', () => { - pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty]) - this._updateBalancedPoolStats() - }) - - pool.on('disconnect', (...args) => { - const err = args[2] - if (err && err.code === 'UND_ERR_SOCKET') { - // decrease the weight of the pool. - pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty]) - this._updateBalancedPoolStats() - } - }) - - for (const client of this[kClients]) { - client[kWeight] = this[kMaxWeightPerServer] - } - - this._updateBalancedPoolStats() - - return this - } - - _updateBalancedPoolStats () { - let result = 0 - for (let i = 0; i < this[kClients].length; i++) { - result = getGreatestCommonDivisor(this[kClients][i][kWeight], result) - } - - this[kGreatestCommonDivisor] = result - } - - removeUpstream (upstream) { - const upstreamOrigin = util.parseOrigin(upstream).origin - - const pool = this[kClients].find((pool) => ( - pool[kUrl].origin === upstreamOrigin && - pool.closed !== true && - pool.destroyed !== true - )) - - if (pool) { - this[kRemoveClient](pool) - } - - return this - } - - getUpstream (upstream) { - const upstreamOrigin = util.parseOrigin(upstream).origin - - return this[kClients].find((pool) => ( - pool[kUrl].origin === upstreamOrigin && - pool.closed !== true && - pool.destroyed !== true - )) - } - - get upstreams () { - return this[kClients] - .filter(dispatcher => dispatcher.closed !== true && dispatcher.destroyed !== true) - .map((p) => p[kUrl].origin) - } - - [kGetDispatcher] () { - // We validate that pools is greater than 0, - // otherwise we would have to wait until an upstream - // is added, which might never happen. - if (this[kClients].length === 0) { - throw new BalancedPoolMissingUpstreamError() - } - - let counter = 0 - - let maxWeightIndex = -1 - - while (counter++ < this[kClients].length) { - this[kIndex] = (this[kIndex] + 1) % this[kClients].length - const pool = this[kClients][this[kIndex]] - - // decrease the current weight every `this[kClients].length`. - if (this[kIndex] === 0) { - // Set the current weight to the next lower weight. - this[kCurrentWeight] = this[kCurrentWeight] - this[kGreatestCommonDivisor] - - if (this[kCurrentWeight] <= 0) { - this[kCurrentWeight] = this[kMaxWeightPerServer] - } - } - - // Skip unavailable pools after updating the current weight for this cycle. - if ( - pool[kNeedDrain] || - pool.closed === true || - pool.destroyed === true - ) { - continue - } - - // Track the best fallback if no pool matches the current weight. - if (maxWeightIndex === -1 || pool[kWeight] > this[kClients][maxWeightIndex][kWeight]) { - maxWeightIndex = this[kIndex] - } - - if (pool[kWeight] >= this[kCurrentWeight]) { - return pool - } - } - - if (maxWeightIndex === -1) { - return - } - - this[kCurrentWeight] = this[kClients][maxWeightIndex][kWeight] - this[kIndex] = maxWeightIndex - return this[kClients][maxWeightIndex] - } -} - -module.exports = BalancedPool - - -/***/ }), - -/***/ 2634: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -/* global WebAssembly */ - -const assert = __nccwpck_require__(4589) -const util = __nccwpck_require__(9705) -const { channels } = __nccwpck_require__(4765) -const timers = __nccwpck_require__(4542) -const { - RequestContentLengthMismatchError, - ResponseContentLengthMismatchError, - RequestAbortedError, - InvalidArgumentError, - HeadersTimeoutError, - HeadersOverflowError, - SocketError, - InformationalError, - BodyTimeoutError, - HTTPParserError, - ResponseExceededMaxSizeError -} = __nccwpck_require__(7062) -const { - kUrl, - kReset, - kClient, - kParser, - kBlocking, - kRunning, - kPending, - kSize, - kWriting, - kQueue, - kNoRef, - kKeepAliveDefaultTimeout, - kHostHeader, - kPendingIdx, - kRunningIdx, - kError, - kPipelining, - kSocket, - kKeepAliveTimeoutValue, - kMaxHeadersSize, - kKeepAliveMaxTimeout, - kKeepAliveTimeoutThreshold, - kHeadersTimeout, - kBodyTimeout, - kStrictContentLength, - kMaxRequests, - kCounter, - kMaxResponseSize, - kOnError, - kResume, - kHTTPContext, - kClosed -} = __nccwpck_require__(7480) - -const constants = __nccwpck_require__(9843) -const EMPTY_BUF = Buffer.alloc(0) -const FastBuffer = Buffer[Symbol.species] -const removeAllListeners = util.removeAllListeners -const kIdleSocketValidation = Symbol('kIdleSocketValidation') -const kIdleSocketValidationTimeout = Symbol('kIdleSocketValidationTimeout') -const kSocketUsed = Symbol('kSocketUsed') -const kTypeOfService = Symbol('kTypeOfService') - -let extractBody - -function lazyllhttp () { - const llhttpWasmData = process.env.JEST_WORKER_ID ? __nccwpck_require__(1421) : undefined - - let mod + let mod // We disable wasm SIMD on older versions of Node.js on ppc64 that are broken on Power >=9 architectures. let useWasmSIMD = true @@ -10844,7 +7960,7 @@ function lazyllhttp () { if (useWasmSIMD) { try { - mod = new WebAssembly.Module(__nccwpck_require__(1727)) + mod = new WebAssembly.Module(__nccwpck_require__(1707)) } catch { } } @@ -10854,7 +7970,7 @@ function lazyllhttp () { // being enabled, but the occurring of this other error // * https://github.com/emscripten-core/emscripten/issues/11495 // got me to remove that check to avoid breaking Node 12. - mod = new WebAssembly.Module(llhttpWasmData || __nccwpck_require__(1421)) + mod = new WebAssembly.Module(llhttpWasmData || __nccwpck_require__(8425)) } return new WebAssembly.Instance(mod, { @@ -11964,7 +9080,7 @@ function writeH1 (client, request) { if (util.isFormDataLike(body)) { if (!extractBody) { - extractBody = (__nccwpck_require__(463).extractBody) + extractBody = (__nccwpck_require__(4051).extractBody) } const [bodyStream, contentType] = extractBody(body) @@ -12567,7 +9683,7 @@ module.exports = connectH1 /***/ }), -/***/ 7735: +/***/ 5755: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -12575,7 +9691,7 @@ module.exports = connectH1 const assert = __nccwpck_require__(4589) const { pipeline } = __nccwpck_require__(7075) -const util = __nccwpck_require__(9705) +const util = __nccwpck_require__(9277) const { RequestContentLengthMismatchError, ResponseContentLengthMismatchError, @@ -12586,7 +9702,7 @@ const { HeadersTimeoutError, BodyTimeoutError, ResponseExceededMaxSizeError -} = __nccwpck_require__(7062) +} = __nccwpck_require__(4882) const { kUrl, kReset, @@ -12616,8 +9732,8 @@ const { kHTTP2SessionState, kHTTP2Options, kMaxResponseSize -} = __nccwpck_require__(7480) -const { channels } = __nccwpck_require__(4765) +} = __nccwpck_require__(228) +const { channels } = __nccwpck_require__(185) const kOpenStreams = Symbol('open streams') const kRequestStreamId = Symbol('request stream id') @@ -13769,7 +10885,7 @@ function writeH2 (client, request) { let contentLength = util.bodyLength(body) if (util.isFormDataLike(body)) { - extractBody ??= (__nccwpck_require__(463).extractBody) + extractBody ??= (__nccwpck_require__(4051).extractBody) const [bodyStream, contentType] = extractBody(body) headers['content-type'] = contentType @@ -14400,7 +11516,7 @@ module.exports = connectH2 /***/ }), -/***/ 940: +/***/ 1696: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -14409,17 +11525,17 @@ module.exports = connectH2 const assert = __nccwpck_require__(4589) const net = __nccwpck_require__(7030) const http = __nccwpck_require__(7067) -const util = __nccwpck_require__(9705) -const { ClientStats } = __nccwpck_require__(5901) -const { channels } = __nccwpck_require__(4765) -const Request = __nccwpck_require__(84) -const DispatcherBase = __nccwpck_require__(8782) +const util = __nccwpck_require__(9277) +const { ClientStats } = __nccwpck_require__(6553) +const { channels } = __nccwpck_require__(185) +const Request = __nccwpck_require__(5960) +const DispatcherBase = __nccwpck_require__(1538) const { InvalidArgumentError, InformationalError, ClientDestroyedError -} = __nccwpck_require__(7062) -const buildConnector = __nccwpck_require__(4463) +} = __nccwpck_require__(4882) +const buildConnector = __nccwpck_require__(8203) const { kUrl, kServerName, @@ -14461,9 +11577,9 @@ const { kHostAuthority, kResume, kHTTP2Options -} = __nccwpck_require__(7480) -const connectH1 = __nccwpck_require__(2634) -const connectH2 = __nccwpck_require__(7735) +} = __nccwpck_require__(228) +const connectH1 = __nccwpck_require__(9742) +const connectH2 = __nccwpck_require__(5755) const kClosedResolve = Symbol('kClosedResolve') @@ -15154,20 +12270,20 @@ module.exports = Client /***/ }), -/***/ 8782: +/***/ 1538: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const buffer = __nccwpck_require__(4573) -const Dispatcher = __nccwpck_require__(9342) +const Dispatcher = __nccwpck_require__(1178) const { ClientDestroyedError, ClientClosedError, InvalidArgumentError -} = __nccwpck_require__(7062) -const { kDestroy, kClose, kClosed, kDestroyed, kDispatch } = __nccwpck_require__(7480) +} = __nccwpck_require__(4882) +const { kDestroy, kClose, kClosed, kDestroyed, kDispatch } = __nccwpck_require__(228) const kOnDestroyed = Symbol('onDestroyed') const kOnClosed = Symbol('onClosed') @@ -15359,13 +12475,13 @@ module.exports = DispatcherBase /***/ }), -/***/ 9342: +/***/ 1178: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const EventEmitter = __nccwpck_require__(8474) -const { kOriginless, kUrl } = __nccwpck_require__(7480) +const { kOriginless, kUrl } = __nccwpck_require__(228) class Dispatcher extends EventEmitter { dispatch () { @@ -15425,16 +12541,16 @@ module.exports = Dispatcher /***/ }), -/***/ 4925: +/***/ 5241: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const Dispatcher = __nccwpck_require__(9342) -const { InvalidArgumentError } = __nccwpck_require__(7062) -const { toRawHeaders } = __nccwpck_require__(9705) -const { kOriginless, kUrl } = __nccwpck_require__(7480) +const Dispatcher = __nccwpck_require__(1178) +const { InvalidArgumentError } = __nccwpck_require__(4882) +const { toRawHeaders } = __nccwpck_require__(9277) +const { kOriginless, kUrl } = __nccwpck_require__(228) class LegacyHandlerWrapper { #handler @@ -15543,16 +12659,16 @@ module.exports = Dispatcher1Wrapper /***/ }), -/***/ 7968: +/***/ 6956: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const DispatcherBase = __nccwpck_require__(8782) -const { kClose, kDestroy, kClosed, kDestroyed, kDispatch, kNoProxyAgent, kHttpProxyAgent, kHttpsProxyAgent } = __nccwpck_require__(7480) -const ProxyAgent = __nccwpck_require__(8251) -const Agent = __nccwpck_require__(4722) +const DispatcherBase = __nccwpck_require__(1538) +const { kClose, kDestroy, kClosed, kDestroyed, kDispatch, kNoProxyAgent, kHttpProxyAgent, kHttpsProxyAgent } = __nccwpck_require__(228) +const ProxyAgent = __nccwpck_require__(6983) +const Agent = __nccwpck_require__(1470) const DEFAULT_PORTS = { 'http:': 80, @@ -15741,7 +12857,7 @@ module.exports = EnvHttpProxyAgent /***/ }), -/***/ 975: +/***/ 7627: /***/ ((module) => { "use strict"; @@ -15884,14 +13000,14 @@ module.exports = class FixedQueue { /***/ }), -/***/ 1334: +/***/ 5506: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const { InvalidArgumentError } = __nccwpck_require__(7062) -const Client = __nccwpck_require__(940) +const { InvalidArgumentError } = __nccwpck_require__(4882) +const Client = __nccwpck_require__(1696) class H2CClient extends Client { constructor (origin, clientOpts) { @@ -15943,16 +13059,16 @@ module.exports = H2CClient /***/ }), -/***/ 8747: +/***/ 63: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const { PoolStats } = __nccwpck_require__(5901) -const DispatcherBase = __nccwpck_require__(8782) -const FixedQueue = __nccwpck_require__(975) -const { kConnected, kSize, kRunning, kPending, kQueued, kBusy, kFree, kUrl, kClose, kDestroy, kDispatch } = __nccwpck_require__(7480) +const { PoolStats } = __nccwpck_require__(6553) +const DispatcherBase = __nccwpck_require__(1538) +const FixedQueue = __nccwpck_require__(7627) +const { kConnected, kSize, kRunning, kPending, kQueued, kBusy, kFree, kUrl, kClose, kDestroy, kDispatch } = __nccwpck_require__(228) const kClients = Symbol('clients') const kNeedDrain = Symbol('needDrain') @@ -16244,7 +13360,7 @@ module.exports = { /***/ }), -/***/ 737: +/***/ 3469: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -16261,14 +13377,14 @@ const { kGetDispatcher, kHasDispatcher, kRemoveClient -} = __nccwpck_require__(8747) -const Client = __nccwpck_require__(940) +} = __nccwpck_require__(63) +const Client = __nccwpck_require__(1696) const { InvalidArgumentError -} = __nccwpck_require__(7062) -const util = __nccwpck_require__(9705) -const { kConnecting, kHTTPContext, kUrl } = __nccwpck_require__(7480) -const buildConnector = __nccwpck_require__(4463) +} = __nccwpck_require__(4882) +const util = __nccwpck_require__(9277) +const { kConnecting, kHTTPContext, kUrl } = __nccwpck_require__(228) +const buildConnector = __nccwpck_require__(8203) const kOptions = Symbol('options') const kConnections = Symbol('connections') @@ -16478,22 +13594,22 @@ module.exports = Pool /***/ }), -/***/ 8251: +/***/ 6983: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const { kProxy, kClose, kDestroy, kDispatch } = __nccwpck_require__(7480) -const Agent = __nccwpck_require__(4722) -const Pool = __nccwpck_require__(737) -const DispatcherBase = __nccwpck_require__(8782) -const { InvalidArgumentError, RequestAbortedError, SecureProxyConnectionError, ProxyConnectionError } = __nccwpck_require__(7062) -const buildConnector = __nccwpck_require__(4463) -const Client = __nccwpck_require__(940) -const { channels } = __nccwpck_require__(4765) -const Socks5ProxyAgent = __nccwpck_require__(4258) -const { hasSafeIterator } = __nccwpck_require__(9705) +const { kProxy, kClose, kDestroy, kDispatch } = __nccwpck_require__(228) +const Agent = __nccwpck_require__(1470) +const Pool = __nccwpck_require__(3469) +const DispatcherBase = __nccwpck_require__(1538) +const { InvalidArgumentError, RequestAbortedError, SecureProxyConnectionError, ProxyConnectionError } = __nccwpck_require__(4882) +const buildConnector = __nccwpck_require__(8203) +const Client = __nccwpck_require__(1696) +const { channels } = __nccwpck_require__(185) +const Socks5ProxyAgent = __nccwpck_require__(958) +const { hasSafeIterator } = __nccwpck_require__(9277) const kAgent = Symbol('proxy agent') const kClient = Symbol('proxy client') @@ -16894,15 +14010,15 @@ module.exports = ProxyAgent /***/ }), -/***/ 7273: +/***/ 525: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const Dispatcher = __nccwpck_require__(9342) -const RetryHandler = __nccwpck_require__(8077) -const { kOriginless, kUrl } = __nccwpck_require__(7480) +const Dispatcher = __nccwpck_require__(1178) +const RetryHandler = __nccwpck_require__(9217) +const { kOriginless, kUrl } = __nccwpck_require__(228) class RetryAgent extends Dispatcher { #agent = null @@ -16940,7 +14056,7 @@ module.exports = RetryAgent /***/ }), -/***/ 5877: +/***/ 5905: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -16954,14 +14070,14 @@ const { kGetDispatcher, kHasDispatcher, kRemoveClient -} = __nccwpck_require__(8747) -const Client = __nccwpck_require__(940) +} = __nccwpck_require__(63) +const Client = __nccwpck_require__(1696) const { InvalidArgumentError -} = __nccwpck_require__(7062) -const util = __nccwpck_require__(9705) -const { kUrl } = __nccwpck_require__(7480) -const buildConnector = __nccwpck_require__(4463) +} = __nccwpck_require__(4882) +const util = __nccwpck_require__(9277) +const { kUrl } = __nccwpck_require__(228) +const buildConnector = __nccwpck_require__(8203) const kOptions = Symbol('options') const kConnections = Symbol('connections') @@ -17107,7 +14223,7 @@ module.exports = RoundRobinPool /***/ }), -/***/ 4258: +/***/ 958: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -17116,13 +14232,13 @@ module.exports = RoundRobinPool const { URL } = __nccwpck_require__(3136) let tls // include tls conditionally since it is not always available -const DispatcherBase = __nccwpck_require__(8782) -const { ConnectTimeoutError, InvalidArgumentError } = __nccwpck_require__(7062) -const { Socks5Client, STATES } = __nccwpck_require__(6089) -const { kBusy, kConnected, kDispatch, kClose, kDestroy } = __nccwpck_require__(7480) -const Pool = __nccwpck_require__(737) -const buildConnector = __nccwpck_require__(4463) -const { setupConnectTimeout } = __nccwpck_require__(9705) +const DispatcherBase = __nccwpck_require__(1538) +const { ConnectTimeoutError, InvalidArgumentError } = __nccwpck_require__(4882) +const { Socks5Client, STATES } = __nccwpck_require__(4037) +const { kBusy, kConnected, kDispatch, kClose, kDestroy } = __nccwpck_require__(228) +const Pool = __nccwpck_require__(3469) +const buildConnector = __nccwpck_require__(8203) +const { setupConnectTimeout } = __nccwpck_require__(9277) const { debuglog } = __nccwpck_require__(7975) const debug = debuglog('undici:socks5-proxy') @@ -17465,7 +14581,7 @@ module.exports = Socks5ProxyAgent /***/ }), -/***/ 9115: +/***/ 3495: /***/ ((module) => { "use strict"; @@ -17506,7 +14622,7 @@ module.exports = { /***/ }), -/***/ 3034: +/***/ 7078: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -17516,9 +14632,9 @@ module.exports = { // this version number must be increased to avoid conflicts. const globalDispatcher = Symbol.for('undici.globalDispatcher.2') const legacyGlobalDispatcher = Symbol.for('undici.globalDispatcher.1') -const { InvalidArgumentError } = __nccwpck_require__(7062) -const Agent = __nccwpck_require__(4722) -const Dispatcher1Wrapper = __nccwpck_require__(4925) +const { InvalidArgumentError } = __nccwpck_require__(4882) +const Agent = __nccwpck_require__(1470) +const Dispatcher1Wrapper = __nccwpck_require__(5241) // Fallback storage for when globalThis is not extensible (e.g. frozen) let fallbackDispatcher @@ -17596,13 +14712,13 @@ module.exports = { /***/ }), -/***/ 4817: +/***/ 5357: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const util = __nccwpck_require__(9705) +const util = __nccwpck_require__(9277) const { parseCacheControlHeader, hasInvalidCacheControlDirective, @@ -17610,8 +14726,8 @@ const { hasVaryStar, isInvalidOrWildcardVaryHeader, isEtagUsable -} = __nccwpck_require__(3816) -const { parseHttpDate } = __nccwpck_require__(6872) +} = __nccwpck_require__(1164) +const { parseHttpDate } = __nccwpck_require__(7684) function noop () {} @@ -18422,7 +15538,7 @@ module.exports = CacheHandler /***/ }), -/***/ 126: +/***/ 6994: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -18564,7 +15680,7 @@ module.exports = CacheRevalidationHandler /***/ }), -/***/ 6150: +/***/ 6834: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -18644,13 +15760,13 @@ module.exports = class DecoratorHandler { /***/ }), -/***/ 554: +/***/ 9790: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const { RequestAbortedError } = __nccwpck_require__(7062) +const { RequestAbortedError } = __nccwpck_require__(4882) /** * @typedef {import('../../types/dispatcher.d.ts').default.DispatchHandler} DispatchHandler @@ -19131,16 +16247,16 @@ module.exports = DeduplicationHandler /***/ }), -/***/ 1789: +/***/ 8201: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const util = __nccwpck_require__(9705) +const util = __nccwpck_require__(9277) const assert = __nccwpck_require__(4589) -const { InvalidArgumentError } = __nccwpck_require__(7062) -const { kRequestOrigin } = __nccwpck_require__(7480) +const { InvalidArgumentError } = __nccwpck_require__(4882) +const { kRequestOrigin } = __nccwpck_require__(228) const redirectableStatusCodes = [300, 301, 302, 303, 307, 308] @@ -19382,20 +16498,20 @@ module.exports = RedirectHandler /***/ }), -/***/ 8077: +/***/ 9217: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const assert = __nccwpck_require__(4589) -const { kRetryHandlerDefaultRetry } = __nccwpck_require__(7480) -const { RequestRetryError, RequestAbortedError } = __nccwpck_require__(7062) +const { kRetryHandlerDefaultRetry } = __nccwpck_require__(228) +const { RequestRetryError, RequestAbortedError } = __nccwpck_require__(4882) const { isDisturbed, parseRangeHeader, wrapRequestBody -} = __nccwpck_require__(9705) +} = __nccwpck_require__(9277) function calculateRetryAfterHeader (retryAfter) { const retryTime = new Date(retryAfter).getTime() @@ -20043,7 +17159,7 @@ module.exports = RetryHandler /***/ }), -/***/ 3191: +/***/ 2395: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -20051,10 +17167,10 @@ module.exports = RetryHandler const assert = __nccwpck_require__(4589) const { Readable } = __nccwpck_require__(7075) -const util = __nccwpck_require__(9705) -const CacheHandler = __nccwpck_require__(4817) -const MemoryCacheStore = __nccwpck_require__(3330) -const CacheRevalidationHandler = __nccwpck_require__(126) +const util = __nccwpck_require__(9277) +const CacheHandler = __nccwpck_require__(5357) +const MemoryCacheStore = __nccwpck_require__(750) +const CacheRevalidationHandler = __nccwpck_require__(6994) const { assertCacheStore, assertCacheMethods, @@ -20064,9 +17180,9 @@ const { parseCacheControlHeader, isInvalidOrWildcardVaryHeader, parseVaryHeader -} = __nccwpck_require__(3816) -const { AbortError } = __nccwpck_require__(7062) -const { parseHttpDate } = __nccwpck_require__(6872) +} = __nccwpck_require__(1164) +const { AbortError } = __nccwpck_require__(4882) +const { parseHttpDate } = __nccwpck_require__(7684) /** * @param {(string | RegExp)[] | undefined} origins @@ -20725,7 +17841,7 @@ module.exports = (opts = {}) => { /***/ }), -/***/ 1790: +/***/ 6170: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -20733,8 +17849,8 @@ module.exports = (opts = {}) => { const { createInflate, createGunzip, createBrotliDecompress, createZstdDecompress } = __nccwpck_require__(8522) const { pipeline, Transform: TransformStream } = __nccwpck_require__(7075) -const { InvalidArgumentError, ResponseExceededMaxSizeError } = __nccwpck_require__(7062) -const DecoratorHandler = __nccwpck_require__(6150) +const { InvalidArgumentError, ResponseExceededMaxSizeError } = __nccwpck_require__(4882) +const DecoratorHandler = __nccwpck_require__(6834) /** @typedef {import('node:stream').Transform} Transform */ /** @typedef {import('node:stream').Transform} Controller */ @@ -21294,16 +18410,16 @@ module.exports = createDecompressInterceptor /***/ }), -/***/ 7305: +/***/ 4221: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const diagnosticsChannel = __nccwpck_require__(3053) -const util = __nccwpck_require__(9705) -const DeduplicationHandler = __nccwpck_require__(554) -const { getInterceptorOrigin, normalizeHeaders, makeCacheKey, makeDeduplicationKey } = __nccwpck_require__(3816) +const util = __nccwpck_require__(9277) +const DeduplicationHandler = __nccwpck_require__(9790) +const { getInterceptorOrigin, normalizeHeaders, makeCacheKey, makeDeduplicationKey } = __nccwpck_require__(1164) const pendingRequestsChannel = diagnosticsChannel.channel('undici:request:pending-requests') @@ -21420,16 +18536,16 @@ module.exports = (opts = {}) => { /***/ }), -/***/ 4230: +/***/ 9410: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { isIP } = __nccwpck_require__(7030) const { lookup } = __nccwpck_require__(610) -const DecoratorHandler = __nccwpck_require__(6150) -const { InvalidArgumentError, InformationalError } = __nccwpck_require__(7062) -const { kRequestOrigin } = __nccwpck_require__(7480) +const DecoratorHandler = __nccwpck_require__(6834) +const { InvalidArgumentError, InformationalError } = __nccwpck_require__(4882) +const { kRequestOrigin } = __nccwpck_require__(228) const maxInt = Math.pow(2, 31) - 1 function hasSafeIterator (headers) { @@ -22010,14 +19126,14 @@ module.exports = interceptorOpts => { /***/ }), -/***/ 951: +/***/ 8355: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const { InvalidArgumentError, RequestAbortedError } = __nccwpck_require__(7062) -const DecoratorHandler = __nccwpck_require__(6150) +const { InvalidArgumentError, RequestAbortedError } = __nccwpck_require__(4882) +const DecoratorHandler = __nccwpck_require__(6834) class DumpHandler extends DecoratorHandler { #maxSize = 1024 * 1024 @@ -22117,13 +19233,13 @@ module.exports = createDumpInterceptor /***/ }), -/***/ 3721: +/***/ 3853: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const RedirectHandler = __nccwpck_require__(1789) +const RedirectHandler = __nccwpck_require__(8201) function createRedirectInterceptor ({ maxRedirections: defaultMaxRedirections, throwOnMaxRedirect: defaultThrowOnMaxRedirect, stripHeadersOnRedirect: defaultStripHeadersOnRedirect, stripHeadersOnCrossOriginRedirect: defaultStripHeadersOnCrossOriginRedirect } = {}) { return (dispatch) => { @@ -22146,15 +19262,15 @@ module.exports = createRedirectInterceptor /***/ }), -/***/ 1257: +/***/ 4325: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // const { parseHeaders } = require('../core/util') -const DecoratorHandler = __nccwpck_require__(6150) -const { ResponseError } = __nccwpck_require__(7062) +const DecoratorHandler = __nccwpck_require__(6834) +const { ResponseError } = __nccwpck_require__(4882) class ResponseErrorHandler extends DecoratorHandler { #statusCode @@ -22249,12 +19365,12 @@ module.exports = () => { /***/ }), -/***/ 6207: +/***/ 4987: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const RetryHandler = __nccwpck_require__(8077) +const RetryHandler = __nccwpck_require__(9217) module.exports = globalOpts => { return dispatch => { @@ -22276,14 +19392,14 @@ module.exports = globalOpts => { /***/ }), -/***/ 9843: +/***/ 8383: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SPECIAL_HEADERS = exports.MINOR = exports.MAJOR = exports.HTAB_SP_VCHAR_OBS_TEXT = exports.QUOTED_STRING = exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS = exports.TOKEN = exports.HEX = exports.URL_CHAR = exports.USERINFO_CHARS = exports.MARK = exports.ALPHANUM = exports.NUM = exports.HEX_MAP = exports.NUM_MAP = exports.ALPHA = exports.STATUSES_HTTP = exports.H_METHOD_MAP = exports.METHOD_MAP = exports.METHODS_RTSP = exports.METHODS_ICE = exports.METHODS_HTTP = exports.HEADER_STATE = exports.FINISH = exports.STATUSES = exports.METHODS = exports.LENIENT_FLAGS = exports.FLAGS = exports.TYPE = exports.ERROR = void 0; -const utils_1 = __nccwpck_require__(9027); +const utils_1 = __nccwpck_require__(4639); // Emums exports.ERROR = { OK: 0, @@ -22815,7 +19931,7 @@ exports["default"] = { /***/ }), -/***/ 1421: +/***/ 8425: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -22839,7 +19955,7 @@ Object.defineProperty(module, 'exports', { /***/ }), -/***/ 1727: +/***/ 1707: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -22863,7 +19979,7 @@ Object.defineProperty(module, 'exports', { /***/ }), -/***/ 9027: +/***/ 4639: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -22883,14 +19999,14 @@ function enumToMap(obj, filter = [], exceptions = []) { /***/ }), -/***/ 676: +/***/ 9096: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const { kClients } = __nccwpck_require__(7480) -const Agent = __nccwpck_require__(4722) +const { kClients } = __nccwpck_require__(228) +const Agent = __nccwpck_require__(1470) const { kAgent, kMockAgentSet, @@ -22908,14 +20024,14 @@ const { kMockAgentAcceptsNonStandardSearchParameters, kMockCallHistoryAddLog, kIgnoreTrailingSlash -} = __nccwpck_require__(5184) -const MockClient = __nccwpck_require__(4882) -const MockPool = __nccwpck_require__(2719) -const { matchValue, normalizeSearchParams, buildAndValidateMockOptions, normalizeOrigin } = __nccwpck_require__(340) -const { InvalidArgumentError, UndiciError } = __nccwpck_require__(7062) -const Dispatcher = __nccwpck_require__(9342) -const PendingInterceptorsFormatter = __nccwpck_require__(6563) -const { MockCallHistory } = __nccwpck_require__(1112) +} = __nccwpck_require__(780) +const MockClient = __nccwpck_require__(3950) +const MockPool = __nccwpck_require__(7763) +const { matchValue, normalizeSearchParams, buildAndValidateMockOptions, normalizeOrigin } = __nccwpck_require__(4416) +const { InvalidArgumentError, UndiciError } = __nccwpck_require__(4882) +const Dispatcher = __nccwpck_require__(1178) +const PendingInterceptorsFormatter = __nccwpck_require__(5431) +const { MockCallHistory } = __nccwpck_require__(5980) class MockAgent extends Dispatcher { constructor (opts = {}) { @@ -23135,14 +20251,14 @@ module.exports = MockAgent /***/ }), -/***/ 1112: +/***/ 5980: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const { kMockCallHistoryAddLog } = __nccwpck_require__(5184) -const { InvalidArgumentError } = __nccwpck_require__(7062) +const { kMockCallHistoryAddLog } = __nccwpck_require__(780) +const { InvalidArgumentError } = __nccwpck_require__(4882) function handleFilterCallsWithOptions (criteria, options, handler, store, allLogs) { switch (options.operator) { @@ -23391,15 +20507,15 @@ module.exports.MockCallHistoryLog = MockCallHistoryLog /***/ }), -/***/ 4882: +/***/ 3950: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { promisify } = __nccwpck_require__(7975) -const Client = __nccwpck_require__(940) -const { buildMockDispatch } = __nccwpck_require__(340) +const Client = __nccwpck_require__(1696) +const { buildMockDispatch } = __nccwpck_require__(4416) const { kDispatches, kMockAgent, @@ -23409,10 +20525,10 @@ const { kOriginalDispatch, kConnected, kIgnoreTrailingSlash -} = __nccwpck_require__(5184) -const { MockInterceptor } = __nccwpck_require__(6926) -const Symbols = __nccwpck_require__(7480) -const { InvalidArgumentError } = __nccwpck_require__(7062) +} = __nccwpck_require__(780) +const { MockInterceptor } = __nccwpck_require__(7042) +const Symbols = __nccwpck_require__(228) +const { InvalidArgumentError } = __nccwpck_require__(4882) /** * MockClient provides an API that extends the Client to influence the mockDispatches. @@ -23467,13 +20583,13 @@ module.exports = MockClient /***/ }), -/***/ 7102: +/***/ 170: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const { UndiciError } = __nccwpck_require__(7062) +const { UndiciError } = __nccwpck_require__(4882) const kMockNotMatchedError = Symbol.for('undici.error.UND_MOCK_ERR_MOCK_NOT_MATCHED') @@ -23504,13 +20620,13 @@ module.exports = { /***/ }), -/***/ 6926: +/***/ 7042: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const { getResponseData, buildKey, addMockDispatch } = __nccwpck_require__(340) +const { getResponseData, buildKey, addMockDispatch } = __nccwpck_require__(4416) const { kDispatches, kDispatchKey, @@ -23519,9 +20635,9 @@ const { kContentLength, kMockDispatch, kIgnoreTrailingSlash -} = __nccwpck_require__(5184) -const { InvalidArgumentError } = __nccwpck_require__(7062) -const { serializePathWithQuery } = __nccwpck_require__(9705) +} = __nccwpck_require__(780) +const { InvalidArgumentError } = __nccwpck_require__(4882) +const { serializePathWithQuery } = __nccwpck_require__(9277) const { types: { isPromise @@ -23739,15 +20855,15 @@ module.exports.MockScope = MockScope /***/ }), -/***/ 2719: +/***/ 7763: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { promisify } = __nccwpck_require__(7975) -const Pool = __nccwpck_require__(737) -const { buildMockDispatch } = __nccwpck_require__(340) +const Pool = __nccwpck_require__(3469) +const { buildMockDispatch } = __nccwpck_require__(4416) const { kDispatches, kMockAgent, @@ -23757,10 +20873,10 @@ const { kOriginalDispatch, kConnected, kIgnoreTrailingSlash -} = __nccwpck_require__(5184) -const { MockInterceptor } = __nccwpck_require__(6926) -const Symbols = __nccwpck_require__(7480) -const { InvalidArgumentError } = __nccwpck_require__(7062) +} = __nccwpck_require__(780) +const { MockInterceptor } = __nccwpck_require__(7042) +const Symbols = __nccwpck_require__(228) +const { InvalidArgumentError } = __nccwpck_require__(4882) /** * MockPool provides an API that extends the Pool to influence the mockDispatches. @@ -23815,7 +20931,7 @@ module.exports = MockPool /***/ }), -/***/ 5184: +/***/ 780: /***/ ((module) => { "use strict"; @@ -23855,13 +20971,13 @@ module.exports = { /***/ }), -/***/ 340: +/***/ 4416: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const { MockNotMatchedError } = __nccwpck_require__(7102) +const { MockNotMatchedError } = __nccwpck_require__(170) const { kDispatches, kMockAgent, @@ -23869,15 +20985,15 @@ const { kOrigin, kGetNetConnect, kTotalDispatchCount -} = __nccwpck_require__(5184) -const { serializePathWithQuery, parseHeaders } = __nccwpck_require__(9705) +} = __nccwpck_require__(780) +const { serializePathWithQuery, parseHeaders } = __nccwpck_require__(9277) const { STATUS_CODES } = __nccwpck_require__(7067) const { types: { isPromise } } = __nccwpck_require__(7975) -const { InvalidArgumentError } = __nccwpck_require__(7062) +const { InvalidArgumentError } = __nccwpck_require__(4882) const requestAborted = Symbol('request aborted') function matchValue (match, value) { @@ -24583,7 +21699,7 @@ module.exports = { /***/ }), -/***/ 6563: +/***/ 5431: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -24634,18 +21750,18 @@ module.exports = class PendingInterceptorsFormatter { /***/ }), -/***/ 818: +/***/ 5790: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const Agent = __nccwpck_require__(4722) -const MockAgent = __nccwpck_require__(676) -const { SnapshotRecorder } = __nccwpck_require__(6689) -const { InvalidArgumentError, UndiciError } = __nccwpck_require__(7062) -const util = __nccwpck_require__(9705) -const { validateSnapshotMode } = __nccwpck_require__(7726) +const Agent = __nccwpck_require__(1470) +const MockAgent = __nccwpck_require__(9096) +const { SnapshotRecorder } = __nccwpck_require__(1525) +const { InvalidArgumentError, UndiciError } = __nccwpck_require__(4882) +const util = __nccwpck_require__(9277) +const { validateSnapshotMode } = __nccwpck_require__(6482) const kSnapshotRecorder = Symbol('kSnapshotRecorder') const kSnapshotMode = Symbol('kSnapshotMode') @@ -25013,7 +22129,7 @@ module.exports = SnapshotAgent /***/ }), -/***/ 6689: +/***/ 1525: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -25022,8 +22138,8 @@ module.exports = SnapshotAgent const { writeFile, readFile, mkdir } = __nccwpck_require__(1455) const { dirname, resolve } = __nccwpck_require__(6760) const { setTimeout, clearTimeout } = __nccwpck_require__(7997) -const { InvalidArgumentError, UndiciError } = __nccwpck_require__(7062) -const { hashId, isUrlExcludedFactory, normalizeHeaders, createHeaderFilters } = __nccwpck_require__(7726) +const { InvalidArgumentError, UndiciError } = __nccwpck_require__(4882) +const { hashId, isUrlExcludedFactory, normalizeHeaders, createHeaderFilters } = __nccwpck_require__(6482) /** * @typedef {Object} SnapshotRequestOptions @@ -25644,14 +22760,14 @@ module.exports = { SnapshotRecorder, formatRequestKey, createRequestHash, filter /***/ }), -/***/ 7726: +/***/ 6482: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const { InvalidArgumentError } = __nccwpck_require__(7062) -const { runtimeFeatures } = __nccwpck_require__(5504) +const { InvalidArgumentError } = __nccwpck_require__(4882) +const { runtimeFeatures } = __nccwpck_require__(8332) /** * @typedef {Object} HeaderFilters @@ -25810,7 +22926,7 @@ module.exports = { /***/ }), -/***/ 3816: +/***/ 1164: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -25821,10 +22937,10 @@ const { pathHasQueryOrFragment, hasSafeIterator, isValidHTTPToken -} = __nccwpck_require__(9705) +} = __nccwpck_require__(9277) -const { serializePathWithQuery } = __nccwpck_require__(9705) -const { kRequestOrigin } = __nccwpck_require__(7480) +const { serializePathWithQuery } = __nccwpck_require__(9277) +const { kRequestOrigin } = __nccwpck_require__(228) const MAX_DELTA_SECONDS = 2147483647 const RESTRICTIVE_DIRECTIVE_NAMES = ['no-store', 'private', 'no-cache'] @@ -26576,7 +23692,7 @@ module.exports = { /***/ }), -/***/ 6872: +/***/ 7684: /***/ ((module) => { "use strict"; @@ -27254,7 +24370,7 @@ module.exports = { /***/ }), -/***/ 5504: +/***/ 8332: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -27355,7 +24471,7 @@ module.exports["default"] = instance /***/ }), -/***/ 5901: +/***/ 6553: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -27368,7 +24484,7 @@ const { kSize, kFree, kQueued -} = __nccwpck_require__(7480) +} = __nccwpck_require__(228) class ClientStats { constructor (client) { @@ -27395,7 +24511,7 @@ module.exports = { ClientStats, PoolStats } /***/ }), -/***/ 4542: +/***/ 3562: /***/ ((module) => { "use strict"; @@ -27828,7 +24944,7 @@ module.exports = { /***/ }), -/***/ 1408: +/***/ 2199: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -27836,14 +24952,14 @@ module.exports = { const assert = __nccwpck_require__(4589) -const { kConstruct } = __nccwpck_require__(7480) -const { urlEquals, getFieldValues } = __nccwpck_require__(789) -const { kEnumerableProperty, isDisturbed } = __nccwpck_require__(9705) -const { webidl } = __nccwpck_require__(2240) -const { cloneResponse, fromInnerResponse, getResponseState } = __nccwpck_require__(3976) -const { Request, fromInnerRequest, getRequestState } = __nccwpck_require__(518) -const { fetching } = __nccwpck_require__(7343) -const { urlIsHttpHttpsScheme, readAllBytes } = __nccwpck_require__(3855) +const { kConstruct } = __nccwpck_require__(228) +const { urlEquals, getFieldValues } = __nccwpck_require__(8993) +const { kEnumerableProperty, isDisturbed } = __nccwpck_require__(9277) +const { webidl } = __nccwpck_require__(7908) +const { cloneResponse, fromInnerResponse, getResponseState } = __nccwpck_require__(7148) +const { Request, fromInnerRequest, getRequestState } = __nccwpck_require__(7442) +const { fetching } = __nccwpck_require__(7683) +const { urlIsHttpHttpsScheme, readAllBytes } = __nccwpck_require__(2875) /** * @see https://w3c.github.io/ServiceWorker/#dfn-cache-batch-operation * @typedef {Object} CacheBatchOperation @@ -28707,16 +25823,16 @@ module.exports = { /***/ }), -/***/ 8574: +/***/ 9722: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const { Cache } = __nccwpck_require__(1408) -const { webidl } = __nccwpck_require__(2240) -const { kEnumerableProperty } = __nccwpck_require__(9705) -const { kConstruct } = __nccwpck_require__(7480) +const { Cache } = __nccwpck_require__(2199) +const { webidl } = __nccwpck_require__(7908) +const { kEnumerableProperty } = __nccwpck_require__(9277) +const { kConstruct } = __nccwpck_require__(228) class CacheStorage { /** @@ -28873,15 +25989,15 @@ module.exports = { /***/ }), -/***/ 789: +/***/ 8993: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const assert = __nccwpck_require__(4589) -const { URLSerializer } = __nccwpck_require__(2403) -const { isValidHeaderName } = __nccwpck_require__(3855) +const { URLSerializer } = __nccwpck_require__(9199) +const { isValidHeaderName } = __nccwpck_require__(2875) /** * @see https://url.spec.whatwg.org/#concept-url-equals @@ -28926,7 +26042,7 @@ module.exports = { /***/ }), -/***/ 2409: +/***/ 6077: /***/ ((module) => { "use strict"; @@ -28946,15 +26062,15 @@ module.exports = { /***/ }), -/***/ 9876: +/***/ 4360: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const { parseSetCookie } = __nccwpck_require__(8503) -const { stringify } = __nccwpck_require__(3542) -const { webidl } = __nccwpck_require__(2240) +const { parseSetCookie } = __nccwpck_require__(8731) +const { stringify } = __nccwpck_require__(4498) +const { webidl } = __nccwpck_require__(7908) const globalHeadersBrandCheck = (arg) => webidl.brandCheck(arg, webidl.util.MakeTypeAssertion(globalThis.Headers)) const undiciHeadersBrandCheck = (arg) => webidl.brandCheck(arg, webidl.is.Headers) @@ -29165,15 +26281,15 @@ module.exports = { /***/ }), -/***/ 8503: +/***/ 8731: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const { collectASequenceOfCodePointsFast } = __nccwpck_require__(517) -const { maxNameValuePairSize, maxAttributeValueSize } = __nccwpck_require__(2409) -const { isCTLExcludingHtab } = __nccwpck_require__(3542) +const { collectASequenceOfCodePointsFast } = __nccwpck_require__(4897) +const { maxNameValuePairSize, maxAttributeValueSize } = __nccwpck_require__(6077) +const { isCTLExcludingHtab } = __nccwpck_require__(4498) const assert = __nccwpck_require__(4589) /** @@ -29491,7 +26607,7 @@ module.exports = { /***/ }), -/***/ 3542: +/***/ 4498: /***/ ((module) => { "use strict"; @@ -29853,14 +26969,14 @@ module.exports = { /***/ }), -/***/ 3964: +/***/ 3448: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const buffer = __nccwpck_require__(4573) const { Transform } = __nccwpck_require__(7075) -const { isASCIINumber, isValidLastEventId } = __nccwpck_require__(2272) +const { isASCIINumber, isValidLastEventId } = __nccwpck_require__(436) /** * @type {number[]} BOM @@ -30382,24 +27498,24 @@ module.exports = { /***/ }), -/***/ 5663: +/***/ 3715: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { pipeline } = __nccwpck_require__(7075) -const { fetching } = __nccwpck_require__(7343) -const { webidl } = __nccwpck_require__(2240) -const { EventSourceStream } = __nccwpck_require__(3964) -const { parseMIMEType } = __nccwpck_require__(2403) -const { createFastMessageEvent } = __nccwpck_require__(1003) -const { isNetworkError } = __nccwpck_require__(3976) -const { isValidHeaderValue, kEnumerableProperty } = __nccwpck_require__(9705) -const { environmentSettingsObject } = __nccwpck_require__(3855) -const { createPotentialCORSRequest } = __nccwpck_require__(2272) -const { getGlobalDispatcher } = __nccwpck_require__(3034) -const { isomorphicDecode } = __nccwpck_require__(517) +const { fetching } = __nccwpck_require__(7683) +const { webidl } = __nccwpck_require__(7908) +const { EventSourceStream } = __nccwpck_require__(3448) +const { parseMIMEType } = __nccwpck_require__(9199) +const { createFastMessageEvent } = __nccwpck_require__(8935) +const { isNetworkError } = __nccwpck_require__(7148) +const { isValidHeaderValue, kEnumerableProperty } = __nccwpck_require__(9277) +const { environmentSettingsObject } = __nccwpck_require__(2875) +const { createPotentialCORSRequest } = __nccwpck_require__(436) +const { getGlobalDispatcher } = __nccwpck_require__(7078) +const { isomorphicDecode } = __nccwpck_require__(4897) const textEncoder = new TextEncoder() @@ -30914,13 +28030,13 @@ module.exports = { /***/ }), -/***/ 2272: +/***/ 436: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const { makeRequest } = __nccwpck_require__(518) +const { makeRequest } = __nccwpck_require__(7442) /** * Checks if the given value is a valid LastEventId. @@ -30982,27 +28098,27 @@ module.exports = { /***/ }), -/***/ 463: +/***/ 4051: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const util = __nccwpck_require__(9705) +const util = __nccwpck_require__(9277) const { readableStreamClose, fullyReadBody, extractMimeType -} = __nccwpck_require__(3855) -const { FormData, setFormDataState, getFormDataBoundary } = __nccwpck_require__(4333) -const { webidl } = __nccwpck_require__(2240) +} = __nccwpck_require__(2875) +const { FormData, setFormDataState, getFormDataBoundary } = __nccwpck_require__(5801) +const { webidl } = __nccwpck_require__(7908) const assert = __nccwpck_require__(4589) const { isErrored, isDisturbed } = __nccwpck_require__(7075) const { isUint8Array } = __nccwpck_require__(3429) -const { serializeAMimeType } = __nccwpck_require__(2403) -const { multipartFormDataParser } = __nccwpck_require__(5589) -const { parseJSONFromBytes } = __nccwpck_require__(517) -const { utf8DecodeBytes } = __nccwpck_require__(9115) +const { serializeAMimeType } = __nccwpck_require__(9199) +const { multipartFormDataParser } = __nccwpck_require__(5497) +const { parseJSONFromBytes } = __nccwpck_require__(4897) +const { utf8DecodeBytes } = __nccwpck_require__(3495) const { ReadableStreamTee } = __nccwpck_require__(7830) const textEncoder = new TextEncoder() @@ -31544,7 +28660,7 @@ module.exports = { /***/ }), -/***/ 4818: +/***/ 3734: /***/ ((module) => { "use strict"; @@ -31683,14 +28799,14 @@ module.exports = { /***/ }), -/***/ 2403: +/***/ 9199: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const assert = __nccwpck_require__(4589) -const { asciiLowercase, forgivingBase64, collectASequenceOfCodePoints, collectASequenceOfCodePointsFast, isomorphicDecode, removeASCIIWhitespace, removeChars } = __nccwpck_require__(517) +const { asciiLowercase, forgivingBase64, collectASequenceOfCodePoints, collectASequenceOfCodePointsFast, isomorphicDecode, removeASCIIWhitespace, removeChars } = __nccwpck_require__(4897) const encoder = new TextEncoder() @@ -32287,18 +29403,18 @@ module.exports = { /***/ }), -/***/ 5589: +/***/ 5497: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const { bufferToLowerCasedHeaderName } = __nccwpck_require__(9705) -const { HTTP_TOKEN_CODEPOINTS } = __nccwpck_require__(2403) -const { makeEntry } = __nccwpck_require__(4333) -const { webidl } = __nccwpck_require__(2240) +const { bufferToLowerCasedHeaderName } = __nccwpck_require__(9277) +const { HTTP_TOKEN_CODEPOINTS } = __nccwpck_require__(9199) +const { makeEntry } = __nccwpck_require__(5801) +const { webidl } = __nccwpck_require__(7908) const assert = __nccwpck_require__(4589) -const { isomorphicDecode } = __nccwpck_require__(517) +const { isomorphicDecode } = __nccwpck_require__(4897) const dd = Buffer.from('--') const decoder = new TextDecoder() @@ -32881,17 +29997,17 @@ module.exports = { /***/ }), -/***/ 4333: +/***/ 5801: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const { iteratorMixin } = __nccwpck_require__(3855) -const { kEnumerableProperty } = __nccwpck_require__(9705) -const { webidl } = __nccwpck_require__(2240) +const { iteratorMixin } = __nccwpck_require__(2875) +const { kEnumerableProperty } = __nccwpck_require__(9277) +const { webidl } = __nccwpck_require__(7908) const nodeUtil = __nccwpck_require__(7975) -const { runtimeFeatures } = __nccwpck_require__(5504) +const { runtimeFeatures } = __nccwpck_require__(8332) const random = runtimeFeatures.has('crypto') ? (__nccwpck_require__(7598).randomInt) @@ -33161,7 +30277,7 @@ module.exports = { FormData, makeEntry, setFormDataState, getFormDataBoundary } /***/ }), -/***/ 2912: +/***/ 1684: /***/ ((module) => { "use strict"; @@ -33209,7 +30325,7 @@ module.exports = { /***/ }), -/***/ 5825: +/***/ 2133: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -33217,14 +30333,14 @@ module.exports = { -const { kConstruct } = __nccwpck_require__(7480) -const { kEnumerableProperty } = __nccwpck_require__(9705) +const { kConstruct } = __nccwpck_require__(228) +const { kEnumerableProperty } = __nccwpck_require__(9277) const { iteratorMixin, isValidHeaderName, isValidHeaderValue -} = __nccwpck_require__(3855) -const { webidl } = __nccwpck_require__(2240) +} = __nccwpck_require__(2875) +const { webidl } = __nccwpck_require__(7908) const assert = __nccwpck_require__(4589) const util = __nccwpck_require__(7975) @@ -33939,7 +31055,7 @@ module.exports = { /***/ }), -/***/ 7343: +/***/ 7683: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -33954,9 +31070,9 @@ const { makeResponse, fromInnerResponse, getResponseState -} = __nccwpck_require__(3976) -const { HeadersList } = __nccwpck_require__(5825) -const { Request, cloneRequest, getRequestDispatcher, getRequestState, removeRequestAbortListener } = __nccwpck_require__(518) +} = __nccwpck_require__(7148) +const { HeadersList } = __nccwpck_require__(2133) +const { Request, cloneRequest, getRequestDispatcher, getRequestState, removeRequestAbortListener } = __nccwpck_require__(7442) const zlib = __nccwpck_require__(8522) const { makePolicyContainer, @@ -33991,26 +31107,26 @@ const { hasAuthenticationEntry, includesCredentials, isTraversableNavigable -} = __nccwpck_require__(3855) +} = __nccwpck_require__(2875) const assert = __nccwpck_require__(4589) -const { safelyExtractBody, extractBody } = __nccwpck_require__(463) +const { safelyExtractBody, extractBody } = __nccwpck_require__(4051) const { redirectStatusSet, nullBodyStatus, safeMethodsSet, requestBodyHeader, subresourceSet -} = __nccwpck_require__(4818) +} = __nccwpck_require__(3734) const EE = __nccwpck_require__(8474) const { Readable, pipeline, finished, isErrored, isReadable } = __nccwpck_require__(7075) -const { addAbortListener, bufferToLowerCasedHeaderName } = __nccwpck_require__(9705) -const { SocketError } = __nccwpck_require__(7062) -const { dataURLProcessor, serializeAMimeType, minimizeSupportedMimeType } = __nccwpck_require__(2403) -const { getGlobalDispatcher } = __nccwpck_require__(3034) -const { webidl } = __nccwpck_require__(2240) +const { addAbortListener, bufferToLowerCasedHeaderName } = __nccwpck_require__(9277) +const { SocketError } = __nccwpck_require__(4882) +const { dataURLProcessor, serializeAMimeType, minimizeSupportedMimeType } = __nccwpck_require__(9199) +const { getGlobalDispatcher } = __nccwpck_require__(7078) +const { webidl } = __nccwpck_require__(7908) const { STATUS_CODES } = __nccwpck_require__(7067) -const { bytesMatch } = __nccwpck_require__(7435) -const { isomorphicEncode } = __nccwpck_require__(517) +const { bytesMatch } = __nccwpck_require__(9471) +const { isomorphicEncode } = __nccwpck_require__(4897) const GET_OR_HEAD = ['GET', 'HEAD'] @@ -36400,7 +33516,7 @@ module.exports = { /***/ }), -/***/ 518: +/***/ 7442: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -36408,15 +33524,15 @@ module.exports = { -const { extractBody, mixinBody, cloneBody, bodyUnusable } = __nccwpck_require__(463) -const { Headers, fill: fillHeaders, HeadersList, setHeadersGuard, getHeadersGuard, setHeadersList, getHeadersList } = __nccwpck_require__(5825) -const util = __nccwpck_require__(9705) +const { extractBody, mixinBody, cloneBody, bodyUnusable } = __nccwpck_require__(4051) +const { Headers, fill: fillHeaders, HeadersList, setHeadersGuard, getHeadersGuard, setHeadersList, getHeadersList } = __nccwpck_require__(2133) +const util = __nccwpck_require__(9277) const nodeUtil = __nccwpck_require__(7975) const { isValidHTTPToken, sameOrigin, environmentSettingsObject -} = __nccwpck_require__(3855) +} = __nccwpck_require__(2875) const { forbiddenMethodsSet, corsSafeListedMethodsSet, @@ -36426,11 +33542,11 @@ const { requestCredentials, requestCache, requestDuplex -} = __nccwpck_require__(4818) +} = __nccwpck_require__(3734) const { kEnumerableProperty, normalizedMethodRecordsBase, normalizedMethodRecords } = util -const { webidl } = __nccwpck_require__(2240) -const { URLSerializer } = __nccwpck_require__(2403) -const { kConstruct } = __nccwpck_require__(7480) +const { webidl } = __nccwpck_require__(7908) +const { URLSerializer } = __nccwpck_require__(9199) +const { kConstruct } = __nccwpck_require__(228) const assert = __nccwpck_require__(4589) const { getMaxListeners, setMaxListeners, defaultMaxListeners } = __nccwpck_require__(8474) @@ -37547,15 +34663,15 @@ module.exports = { /***/ }), -/***/ 3976: +/***/ 7148: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const { Headers, HeadersList, fill, getHeadersGuard, setHeadersGuard, setHeadersList } = __nccwpck_require__(5825) -const { extractBody, cloneBody, mixinBody, streamRegistry, bodyUnusable } = __nccwpck_require__(463) -const util = __nccwpck_require__(9705) +const { Headers, HeadersList, fill, getHeadersGuard, setHeadersGuard, setHeadersList } = __nccwpck_require__(2133) +const { extractBody, cloneBody, mixinBody, streamRegistry, bodyUnusable } = __nccwpck_require__(4051) +const util = __nccwpck_require__(9277) const nodeUtil = __nccwpck_require__(7975) const { kEnumerableProperty } = util const { @@ -37564,16 +34680,16 @@ const { isAborted, isErrorLike, environmentSettingsObject: relevantRealm -} = __nccwpck_require__(3855) +} = __nccwpck_require__(2875) const { redirectStatusSet, nullBodyStatus -} = __nccwpck_require__(4818) -const { webidl } = __nccwpck_require__(2240) -const { URLSerializer } = __nccwpck_require__(2403) -const { kConstruct } = __nccwpck_require__(7480) +} = __nccwpck_require__(3734) +const { webidl } = __nccwpck_require__(7908) +const { URLSerializer } = __nccwpck_require__(9199) +const { kConstruct } = __nccwpck_require__(228) const assert = __nccwpck_require__(4589) -const { isomorphicEncode, serializeJavascriptValueToJSONString } = __nccwpck_require__(517) +const { isomorphicEncode, serializeJavascriptValueToJSONString } = __nccwpck_require__(4897) const textEncoder = new TextEncoder('utf-8') let getResponseHeaders, setResponseHeaders, getResponseState, setResponseState @@ -38193,7 +35309,7 @@ module.exports = { /***/ }), -/***/ 3855: +/***/ 2875: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -38201,15 +35317,15 @@ module.exports = { const { Transform } = __nccwpck_require__(7075) const zlib = __nccwpck_require__(8522) -const { redirectStatusSet, referrerPolicyTokens, badPortsSet } = __nccwpck_require__(4818) -const { getGlobalOrigin } = __nccwpck_require__(2912) -const { collectAnHTTPQuotedString, parseMIMEType } = __nccwpck_require__(2403) +const { redirectStatusSet, referrerPolicyTokens, badPortsSet } = __nccwpck_require__(3734) +const { getGlobalOrigin } = __nccwpck_require__(1684) +const { collectAnHTTPQuotedString, parseMIMEType } = __nccwpck_require__(9199) const { performance } = __nccwpck_require__(643) -const { isValidHTTPToken, normalizedMethodRecordsBase } = __nccwpck_require__(9705) +const { isValidHTTPToken, normalizedMethodRecordsBase } = __nccwpck_require__(9277) const assert = __nccwpck_require__(4589) const { isUint8Array } = __nccwpck_require__(3429) -const { webidl } = __nccwpck_require__(2240) -const { isomorphicEncode, collectASequenceOfCodePoints, removeChars } = __nccwpck_require__(517) +const { webidl } = __nccwpck_require__(7908) +const { isomorphicEncode, collectASequenceOfCodePoints, removeChars } = __nccwpck_require__(4897) function responseURL (response) { // https://fetch.spec.whatwg.org/#responses @@ -39731,14 +36847,14 @@ module.exports = { /***/ }), -/***/ 517: +/***/ 4897: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const assert = __nccwpck_require__(4589) -const { utf8DecodeBytes } = __nccwpck_require__(9115) +const { utf8DecodeBytes } = __nccwpck_require__(3495) /** * @param {(char: string) => boolean} condition @@ -39983,14 +37099,14 @@ module.exports = { /***/ }), -/***/ 7435: +/***/ 9471: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const assert = __nccwpck_require__(4589) -const { runtimeFeatures } = __nccwpck_require__(5504) +const { runtimeFeatures } = __nccwpck_require__(8332) /** * @typedef {object} Metadata @@ -40298,7 +37414,7 @@ module.exports = { /***/ }), -/***/ 2240: +/***/ 7908: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -41298,21 +38414,21 @@ module.exports = { /***/ }), -/***/ 4402: +/***/ 526: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const { uid, states, sentCloseFrameState, emptyBuffer, opcodes } = __nccwpck_require__(7453) -const { parseExtensions, isClosed, isClosing, isEstablished, isConnecting, validateCloseCodeAndReason } = __nccwpck_require__(8738) -const { makeRequest } = __nccwpck_require__(518) -const { fetching } = __nccwpck_require__(7343) -const { Headers, getHeadersList } = __nccwpck_require__(5825) -const { getDecodeSplit } = __nccwpck_require__(3855) -const { WebsocketFrameSend } = __nccwpck_require__(7257) +const { uid, states, sentCloseFrameState, emptyBuffer, opcodes } = __nccwpck_require__(353) +const { parseExtensions, isClosed, isClosing, isEstablished, isConnecting, validateCloseCodeAndReason } = __nccwpck_require__(1518) +const { makeRequest } = __nccwpck_require__(7442) +const { fetching } = __nccwpck_require__(7683) +const { Headers, getHeadersList } = __nccwpck_require__(2133) +const { getDecodeSplit } = __nccwpck_require__(2875) +const { WebsocketFrameSend } = __nccwpck_require__(5981) const assert = __nccwpck_require__(4589) -const { runtimeFeatures } = __nccwpck_require__(5504) +const { runtimeFeatures } = __nccwpck_require__(8332) const crypto = runtimeFeatures.has('crypto') ? __nccwpck_require__(7598) @@ -41656,7 +38772,7 @@ module.exports = { /***/ }), -/***/ 7453: +/***/ 353: /***/ ((module) => { "use strict"; @@ -41790,15 +38906,15 @@ module.exports = { /***/ }), -/***/ 1003: +/***/ 8935: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const { webidl } = __nccwpck_require__(2240) -const { kEnumerableProperty } = __nccwpck_require__(9705) -const { kConstruct } = __nccwpck_require__(7480) +const { webidl } = __nccwpck_require__(7908) +const { kEnumerableProperty } = __nccwpck_require__(9277) +const { kConstruct } = __nccwpck_require__(228) let createFastMessageEvent @@ -42146,14 +39262,14 @@ module.exports = { /***/ }), -/***/ 7257: +/***/ 5981: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const { runtimeFeatures } = __nccwpck_require__(5504) -const { maxUnsigned16Bit, opcodes } = __nccwpck_require__(7453) +const { runtimeFeatures } = __nccwpck_require__(8332) +const { maxUnsigned16Bit, opcodes } = __nccwpck_require__(353) const BUFFER_SIZE = 8 * 1024 @@ -42281,15 +39397,15 @@ module.exports = { /***/ }), -/***/ 4974: +/***/ 2: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { createInflateRaw, Z_DEFAULT_WINDOWBITS } = __nccwpck_require__(8522) -const { isValidClientWindowBits } = __nccwpck_require__(8738) -const { MessageSizeExceededError } = __nccwpck_require__(7062) +const { isValidClientWindowBits } = __nccwpck_require__(1518) +const { MessageSizeExceededError } = __nccwpck_require__(4882) const tail = Buffer.from([0x00, 0x00, 0xff, 0xff]) const kBuffer = Symbol('kBuffer') @@ -42394,7 +39510,7 @@ module.exports = { PerMessageDeflate } /***/ }), -/***/ 7287: +/***/ 2955: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -42402,7 +39518,7 @@ module.exports = { PerMessageDeflate } const { Writable } = __nccwpck_require__(7075) const assert = __nccwpck_require__(4589) -const { parserStates, opcodes, states, emptyBuffer, sentCloseFrameState } = __nccwpck_require__(7453) +const { parserStates, opcodes, states, emptyBuffer, sentCloseFrameState } = __nccwpck_require__(353) const { isValidStatusCode, isValidOpcode, @@ -42411,11 +39527,11 @@ const { isControlFrame, isTextBinaryFrame, isContinuationFrame -} = __nccwpck_require__(8738) -const { failWebsocketConnection } = __nccwpck_require__(4402) -const { WebsocketFrameSend } = __nccwpck_require__(7257) -const { PerMessageDeflate } = __nccwpck_require__(4974) -const { MessageSizeExceededError } = __nccwpck_require__(7062) +} = __nccwpck_require__(1518) +const { failWebsocketConnection } = __nccwpck_require__(526) +const { WebsocketFrameSend } = __nccwpck_require__(5981) +const { PerMessageDeflate } = __nccwpck_require__(2) +const { MessageSizeExceededError } = __nccwpck_require__(4882) // This code was influenced by ws released under the MIT license. // Copyright (c) 2011 Einar Otto Stangvik @@ -42911,15 +40027,15 @@ module.exports = { /***/ }), -/***/ 4019: +/***/ 1495: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const { WebsocketFrameSend } = __nccwpck_require__(7257) -const { opcodes, sendHints } = __nccwpck_require__(7453) -const FixedQueue = __nccwpck_require__(975) +const { WebsocketFrameSend } = __nccwpck_require__(5981) +const { opcodes, sendHints } = __nccwpck_require__(353) +const FixedQueue = __nccwpck_require__(7627) /** * @typedef {object} SendQueueNode @@ -43028,16 +40144,16 @@ module.exports = { SendQueue } /***/ }), -/***/ 174: +/***/ 1506: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const { webidl } = __nccwpck_require__(2240) -const { validateCloseCodeAndReason } = __nccwpck_require__(8738) -const { kConstruct } = __nccwpck_require__(7480) -const { kEnumerableProperty } = __nccwpck_require__(9705) +const { webidl } = __nccwpck_require__(7908) +const { validateCloseCodeAndReason } = __nccwpck_require__(1518) +const { kConstruct } = __nccwpck_require__(228) +const { kEnumerableProperty } = __nccwpck_require__(9277) function createInheritableDOMException () { // https://github.com/nodejs/node/issues/59677 @@ -43143,24 +40259,24 @@ module.exports = { WebSocketError, createUnvalidatedWebSocketError } /***/ }), -/***/ 5818: +/***/ 3134: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { addAbortListener } = __nccwpck_require__(8474) -const { environmentSettingsObject, readableStreamClose } = __nccwpck_require__(3855) -const { states, opcodes, sentCloseFrameState } = __nccwpck_require__(7453) -const { webidl } = __nccwpck_require__(2240) -const { getURLRecord, isValidSubprotocol, isEstablished, utf8Decode } = __nccwpck_require__(8738) -const { establishWebSocketConnection, failWebsocketConnection, closeWebSocketConnection } = __nccwpck_require__(4402) -const { channels } = __nccwpck_require__(4765) -const { WebsocketFrameSend } = __nccwpck_require__(7257) -const { ByteParser } = __nccwpck_require__(7287) -const { WebSocketError, createUnvalidatedWebSocketError } = __nccwpck_require__(174) -const { kEnumerableProperty } = __nccwpck_require__(9705) -const { utf8DecodeBytes } = __nccwpck_require__(9115) +const { environmentSettingsObject, readableStreamClose } = __nccwpck_require__(2875) +const { states, opcodes, sentCloseFrameState } = __nccwpck_require__(353) +const { webidl } = __nccwpck_require__(7908) +const { getURLRecord, isValidSubprotocol, isEstablished, utf8Decode } = __nccwpck_require__(1518) +const { establishWebSocketConnection, failWebsocketConnection, closeWebSocketConnection } = __nccwpck_require__(526) +const { channels } = __nccwpck_require__(185) +const { WebsocketFrameSend } = __nccwpck_require__(5981) +const { ByteParser } = __nccwpck_require__(2955) +const { WebSocketError, createUnvalidatedWebSocketError } = __nccwpck_require__(1506) +const { kEnumerableProperty } = __nccwpck_require__(9277) +const { utf8DecodeBytes } = __nccwpck_require__(3495) let emittedExperimentalWarning = false @@ -43662,16 +40778,16 @@ module.exports = { WebSocketStream } /***/ }), -/***/ 8738: +/***/ 1518: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const { states, opcodes } = __nccwpck_require__(7453) +const { states, opcodes } = __nccwpck_require__(353) const { isUtf8 } = __nccwpck_require__(4573) -const { removeHTTPWhitespace } = __nccwpck_require__(2403) -const { collectASequenceOfCodePointsFast } = __nccwpck_require__(517) +const { removeHTTPWhitespace } = __nccwpck_require__(9199) +const { collectASequenceOfCodePointsFast } = __nccwpck_require__(4897) /** * @param {number} readyState @@ -44017,17 +41133,17 @@ module.exports = { /***/ }), -/***/ 9127: +/***/ 9723: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { isArrayBuffer } = __nccwpck_require__(3429) -const { webidl } = __nccwpck_require__(2240) -const { URLSerializer } = __nccwpck_require__(2403) -const { environmentSettingsObject } = __nccwpck_require__(3855) -const { staticPropertyDescriptors, states, sentCloseFrameState, sendHints, opcodes } = __nccwpck_require__(7453) +const { webidl } = __nccwpck_require__(7908) +const { URLSerializer } = __nccwpck_require__(9199) +const { environmentSettingsObject } = __nccwpck_require__(2875) +const { staticPropertyDescriptors, states, sentCloseFrameState, sendHints, opcodes } = __nccwpck_require__(353) const { isConnecting, isEstablished, @@ -44038,15 +41154,15 @@ const { utf8Decode, toArrayBuffer, getURLRecord -} = __nccwpck_require__(8738) -const { establishWebSocketConnection, closeWebSocketConnection, failWebsocketConnection } = __nccwpck_require__(4402) -const { ByteParser } = __nccwpck_require__(7287) -const { kEnumerableProperty } = __nccwpck_require__(9705) -const { getGlobalDispatcher } = __nccwpck_require__(3034) -const { ErrorEvent, CloseEvent, createFastMessageEvent } = __nccwpck_require__(1003) -const { SendQueue } = __nccwpck_require__(4019) -const { WebsocketFrameSend } = __nccwpck_require__(7257) -const { channels } = __nccwpck_require__(4765) +} = __nccwpck_require__(1518) +const { establishWebSocketConnection, closeWebSocketConnection, failWebsocketConnection } = __nccwpck_require__(526) +const { ByteParser } = __nccwpck_require__(2955) +const { kEnumerableProperty } = __nccwpck_require__(9277) +const { getGlobalDispatcher } = __nccwpck_require__(7078) +const { ErrorEvent, CloseEvent, createFastMessageEvent } = __nccwpck_require__(8935) +const { SendQueue } = __nccwpck_require__(1495) +const { WebsocketFrameSend } = __nccwpck_require__(5981) +const { channels } = __nccwpck_require__(185) const kRef = Symbol.for('nodejs.ref') const kUnref = Symbol.for('nodejs.unref') @@ -44808,850 +41924,43 @@ module.exports = { /***/ }), -/***/ 6866: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 2613: +/***/ ((module) => { "use strict"; +module.exports = require("assert"); -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 })); -const core_1 = __nccwpck_require__(7153); -const params_1 = __nccwpck_require__(5745); -const status_1 = __nccwpck_require__(1933); -const wrapper_version_1 = __nccwpck_require__(5397); -const child_process_1 = __nccwpck_require__(5317); -const dcdPackageName = '@devicecloud.dev/dcd'; -const escapeShellValue = (value) => { - // Escape special characters that could cause shell interpretation issues - return value.replace(/(["\\'$`!\s\[\]{}()&|;<>*?#^~])/g, '\\$1'); -}; -const executeCommand = (command, log = true) => { - return new Promise((resolve, reject) => { - let output = ''; - const process = (0, child_process_1.spawn)(command, { shell: true }); - process.stdout.on('data', (data) => { - const chunk = data.toString(); - output += chunk; - if (log) { - console.info(chunk); - } - }); - process.stderr.on('data', (data) => { - const chunk = data.toString(); - output += chunk; - if (log) { - console.error(chunk); - } - }); - process.on('close', (code) => { - resolve({ output, exitCode: code !== null && code !== void 0 ? code : 0 }); - }); - process.on('error', (err) => { - reject(err); - }); - }); -}; -const getTestStatus = (uploadId, apiKey, dcdVersionString, apiUrl) => __awaiter(void 0, void 0, void 0, function* () { - try { - let command = `npx --yes "${dcdVersionString}" status --json --upload-id ${uploadId} --api-key ${escapeShellValue(apiKey)}`; - if (apiUrl) { - command += ` --api-url ${escapeShellValue(apiUrl)}`; - } - const { output } = yield executeCommand(command, false); - // Filter out non-JSON lines (e.g., npm warnings) - // Find the first line that starts with '{' or '[' (JSON start) - const lines = output.split('\n'); - const jsonStartIndex = lines.findIndex(line => { - const trimmed = line.trim(); - return trimmed.startsWith('{') || trimmed.startsWith('['); - }); - if (jsonStartIndex === -1) { - throw new Error('No JSON found in output'); - } - // Log any warnings that appeared before the JSON output - if (jsonStartIndex > 0) { - const warnings = lines.slice(0, jsonStartIndex).join('\n').trim(); - if (warnings) { - console.warn('npm warnings during status check:\n', warnings); - } - } - // Join from the JSON start to the end - const jsonOutput = lines.slice(jsonStartIndex).join('\n'); - return JSON.parse(jsonOutput); - } - catch (error) { - console.warn('Failed to get test status:', error); - return null; - } -}); -const getLatestDcdVersion = (...args_1) => __awaiter(void 0, [...args_1], void 0, function* (useBeta = false) { - try { - if (useBeta) { - console.info(`Using beta version of DCD CLI`); - return `${dcdPackageName}@beta`; - } - const { output } = yield executeCommand(`npm view ${dcdPackageName} version`, false); - const version = output.trim(); - console.info(`Latest DCD version from npm: ${version}`); - return `${dcdPackageName}@${version}`; - } - catch (error) { - console.warn('Failed to fetch latest DCD version, falling back to >=4.0.3:', error); - return `${dcdPackageName}@>=4.0.3`; - } -}); -const run = () => __awaiter(void 0, void 0, void 0, function* () { - var _a, _b; - try { - const { androidApiLevel, androidDevice, apiKey, apiUrl, appBinaryId, appFilePath, async, cancelPrevious, config, deviceLocale, downloadArtifacts, env, excludeFlows, excludeTags, googlePlay, ignoreShaCheck, includeTags, iOSVersion, iosDevice, jsonFile, maestroVersion, name, orientation, report, retry, workspaceFolder, runnerType, renderEngine, debug, moropoV1ApiKey, useBeta, maestroChromeOnboarding, androidNoSnapshot, disableAnimations, githubContext, quiet, } = yield (0, params_1.getParameters)(); - const REMOVED_MAESTRO_VERSIONS = ['1.39.2', '1.39.7', '2.0.3']; - if (maestroVersion && REMOVED_MAESTRO_VERSIONS.includes(maestroVersion)) { - (0, core_1.setFailed)(`Maestro version ${maestroVersion} is no longer supported. ` + - `Please upgrade to a newer version. See: https://docs.devicecloud.dev/reference/maestro-versions`); - return; - } - const dcdVersionString = yield getLatestDcdVersion(useBeta); - const params = { - 'android-api-level': androidApiLevel, - 'android-device': androidDevice, - 'api-key': apiKey, - 'api-url': apiUrl, - 'app-binary-id': appBinaryId, - 'app-file': appFilePath, - async, - 'cancel-previous': cancelPrevious, - config, - 'device-locale': deviceLocale, - 'download-artifacts': downloadArtifacts, - 'exclude-flows': excludeFlows, - 'exclude-tags': excludeTags, - flows: workspaceFolder, - 'google-play': googlePlay, - 'ignore-sha-check': ignoreShaCheck, - 'include-tags': includeTags, - 'ios-device': iosDevice, - 'ios-version': iOSVersion, - 'maestro-version': maestroVersion, - name, - orientation, - report, - retry, - 'runner-type': runnerType, - 'render-engine': renderEngine, - 'json-file': jsonFile, - debug, - 'moropo-v1-api-key': moropoV1ApiKey, - 'maestro-chrome-onboarding': maestroChromeOnboarding, - 'android-no-snapshot': androidNoSnapshot, - 'disable-animations': disableAnimations, - }; - let paramsString = Object.keys(params).reduce((acc, key) => { - if (!params[key]) - return acc; - const value = typeof params[key] === 'string' - ? escapeShellValue(params[key]) - : params[key]; - return `${acc} --${key} ${value}`; - }, ''); - if (env && env.length > 0) { - env.forEach((e) => { - let [key, ...rest] = e.split('='); - let value = rest.join('='); - if (value.startsWith('"') && value.endsWith('"')) { - // remove quotes so they dont get escaped - value = value.slice(1, -1); - } - paramsString += ` --env ${key}=${escapeShellValue(value)}`; - }); - } - if (githubContext && githubContext.length > 0) { - githubContext.forEach((pair) => { - paramsString += ` --metadata ${escapeShellValue(pair)}`; - }); - } - // Forward CI identity so DCD notices can target this GitHub Action (e.g. - // "GitHub Action < X"). The CLI reads these env vars; the spawned child - // inherits process.env. Provider alone still enables CI-surface notices. - process.env.DCD_CI_PROVIDER = 'github'; - // Read at runtime, never bundled: see readWrapperVersion. Best-effort, as - // the version is optional. - const wrapperVersion = (0, wrapper_version_1.readWrapperVersion)(__dirname); - if (wrapperVersion) { - process.env.DCD_CI_WRAPPER_VERSION = wrapperVersion; - } - // Execute the test command and capture the upload ID - let uploadId = null; - let testOutput = ''; - // The CLI's exit code is the primary verdict: it is computed by the process - // that actually watched the run. 0 = every test passed, 1 = CLI/infra error, - // 2 = the run itself failed (a failed test, or a cancelled one). This used to - // be discarded for anything but 1, leaving the separate `dcd status` call as - // the only gate — so one wrong branch in the API's status rollup turned - // cancelled runs green. - let cloudExitCode = 0; - try { - const { output, exitCode } = yield executeCommand(`npx --yes "${dcdVersionString}" cloud ${paramsString}${quiet ? ' --quiet' : ''}`); - testOutput = output; - cloudExitCode = exitCode; - if (exitCode === 1) { - throw new Error('DeviceCloud CLI failed to run - check your parameters or contact support'); - } - } - finally { - uploadId = - ((_a = testOutput === null || testOutput === void 0 ? void 0 : testOutput.match(/https:\/\/(?:dev\.)?console\.devicecloud\.dev\/results\?upload=([a-zA-Z0-9-]+)/)) === null || _a === void 0 ? void 0 : _a[1]) || null; - } - if (!uploadId) { - throw new Error('Failed to get upload ID from console URL'); - } - // Async mode: the CLI has already submitted the run and exited (saving CI - // minutes). Do NOT poll for results — the DeviceCloud GitHub App reports the - // outcome as a "DeviceCloud" check on the commit/PR when the run completes. - // Just surface the upload id/console URL and exit successfully. - if (async) { - const consoleUrl = ((_b = testOutput === null || testOutput === void 0 ? void 0 : testOutput.match(/https:\/\/(?:dev\.)?console\.devicecloud\.dev\/results\?upload=[a-zA-Z0-9-]+/)) === null || _b === void 0 ? void 0 : _b[0]) || ''; - (0, core_1.setOutput)('DEVICE_CLOUD_CONSOLE_URL', consoleUrl); - (0, core_1.setOutput)('DEVICE_CLOUD_UPLOAD_STATUS', 'PENDING'); - (0, core_1.setOutput)('DEVICE_CLOUD_FLOW_RESULTS', '[]'); - console.info('Async run submitted; not waiting for results.' + - (consoleUrl ? ` Track progress: ${consoleUrl}` : '')); - console.info('Install the DeviceCloud GitHub App to get a pass/fail check on this ' + - 'commit/PR when the run completes: https://docs.devicecloud.dev/ci-cd/github-actions'); - return; - } - // Get the test status and results - const result = yield getTestStatus(uploadId, apiKey, dcdVersionString, apiUrl); - if (result) { - // Superseded (cancel-previous), passed, failed or indeterminate: see - // evaluateRun for how the status and the exit code combine. - const verdict = (0, status_1.evaluateRun)(result, cloudExitCode); - // Set outputs based on the status results - (0, core_1.setOutput)('DEVICE_CLOUD_CONSOLE_URL', result.consoleUrl || ''); - (0, core_1.setOutput)('DEVICE_CLOUD_APP_BINARY_ID', result.appBinaryId || ''); - (0, core_1.setOutput)('DEVICE_CLOUD_UPLOAD_STATUS', verdict.uploadStatus); - // Format flow results to match expected structure - const flowResults = (result.tests || []).map((test) => ({ - name: test.name, - status: test.status, - })); - (0, core_1.setOutput)('DEVICE_CLOUD_FLOW_RESULTS', JSON.stringify(flowResults, null, 2)); - if (verdict.outcome === 'fail') { - (0, core_1.setFailed)(verdict.message); - } - else if (verdict.outcome === 'warn') { - (0, core_1.warning)(verdict.message); - } - else { - console.info(verdict.message); - } - } - else { - (0, core_1.setOutput)('DEVICE_CLOUD_UPLOAD_STATUS', 'ERROR'); - (0, core_1.setOutput)('DEVICE_CLOUD_FLOW_RESULTS', '[]'); - throw new Error('Failed to get test status'); - } - } - catch (error) { - if (typeof error === 'string') { - (0, core_1.setFailed)(error); - } - else { - (0, core_1.setFailed)(error.message); - } - } -}); -run(); +/***/ }), +/***/ 4434: +/***/ ((module) => { + +"use strict"; +module.exports = require("events"); /***/ }), -/***/ 8619: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 8611: +/***/ ((module) => { "use strict"; +module.exports = require("http"); -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 () { - 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); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - 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; - }; -})(); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.resolveAppFile = resolveAppFile; -const fs = __importStar(__nccwpck_require__(9896)); -const path = __importStar(__nccwpck_require__(6928)); -/** Characters that make an app-file value a glob pattern. */ -const GLOB_CHARS = /[*?[\]{}]/; -/** - * Resolve the app-file input, so it can be a glob as it can with Maestro - * Cloud's action (e.g. `app/build/outputs/apk/release/*.apk`). - * - * A value without glob characters is returned unchanged, and so is one that - * exists as written, so a path that happens to contain `[` or `{` keeps - * working. Anything else is expanded relative to `cwd` and the first match in - * sorted order wins: sorting makes the pick the same on every runner, which - * the order the filesystem lists entries in is not. Directories match too, - * since an iOS simulator build is a `.app` directory. - * - * Uses Node's built-in fs.globSync (Node 22+; the action runs on node24), so - * no glob library is bundled. - */ -function resolveAppFile(appFile, cwd = process.cwd()) { - if (!appFile || - !GLOB_CHARS.test(appFile) || - fs.existsSync(path.resolve(cwd, appFile))) { - return { path: appFile, matches: [] }; - } - const matches = fs.globSync(appFile, { cwd }).sort(); - if (matches.length === 0) { - throw new Error(`No file matches the app-file pattern "${appFile}"`); - } - return { path: matches[0], matches }; -} +/***/ }), + +/***/ 5692: +/***/ ((module) => { +"use strict"; +module.exports = require("https"); /***/ }), -/***/ 5745: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 9278: +/***/ ((module) => { "use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || (function () { - 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); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - 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; - }; -})(); -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.getParameters = getParameters; -const github = __importStar(__nccwpck_require__(6137)); -const core = __importStar(__nccwpck_require__(7153)); -const app_file_1 = __nccwpck_require__(8619); -function getAndroidApiLevel(apiLevel) { - return apiLevel ? +apiLevel : undefined; -} -function getIOSVersion(iosVersion) { - return iosVersion ? +iosVersion : undefined; -} -function parseTags(tags) { - if (tags === undefined || tags === '' || tags === null || tags.length === 0) - return null; - if (tags.includes(',')) { - const arrayTags = tags.split(',').map((it) => it.trim()); - if (!Array.isArray(arrayTags)) - throw new Error('tags must be an Array.'); - return arrayTags; - } - return [tags]; -} -function parseAndroidDevice(device) { - if (device === undefined || device === '') - return null; - return device; -} -function parseIOSDevice(device) { - if (device === undefined || device === '') - return null; - return device; -} -function getPullRequestTitle() { - var _a; - const pullRequestTitle = (_a = github.context.payload.pull_request) === null || _a === void 0 ? void 0 : _a.title; - if (pullRequestTitle === undefined) - return undefined; - return `${pullRequestTitle}`; -} -function getInferredName() { - var _a; - const pullRequestTitle = getPullRequestTitle(); - if (pullRequestTitle) - return pullRequestTitle; - if (github.context.eventName === 'push') { - const pushPayload = github.context.payload; - const commitMessage = (_a = pushPayload.head_commit) === null || _a === void 0 ? void 0 : _a.message; - if (commitMessage) - return commitMessage; - } - return github.context.sha; -} -/** - * `checkName` names the GitHub check this run posts. It is appended to the - * backend's base name ("DeviceCloud / iOS"), which is what lets a PR that runs - * iOS and Android as two submissions carry two checks that branch protection - * can require separately — GitHub matches required checks by name, so two runs - * sharing one name collapse into a single gate that follows whichever finished - * last. Keep it constant for a given job; a value that varies per commit can - * never be a required check. - */ -function getGithubContextMetadata(checkName) { - var _a, _b, _c, _d, _e; - const ctx = github.context; - const pr = ctx.payload.pull_request; - const rawRef = (_b = (_a = pr === null || pr === void 0 ? void 0 : pr.head) === null || _a === void 0 ? void 0 : _a.ref) !== null && _b !== void 0 ? _b : ctx.ref; - const branch = (_c = rawRef === null || rawRef === void 0 ? void 0 : rawRef.replace(/^refs\/heads\//, '')) !== null && _c !== void 0 ? _c : ''; - // On pull_request events ctx.sha is a throwaway *merge* commit; a GitHub - // check (and the developer-visible commit) must use the PR's head sha. - const headSha = (_e = (_d = pr === null || pr === void 0 ? void 0 : pr.head) === null || _d === void 0 ? void 0 : _d.sha) !== null && _e !== void 0 ? _e : ctx.sha; - const pairs = [ - `gh_sha=${headSha}`, - `gh_run_id=${ctx.runId}`, - `gh_repo=${ctx.repo.owner}/${ctx.repo.repo}`, - ]; - if (branch) - pairs.push(`gh_branch=${branch}`); - if (checkName) - pairs.push(`gh_check_name=${checkName}`); - if (pr) { - pairs.push(`gh_pr_number=${pr.number}`); - if (pr.html_url) - pairs.push(`gh_pr_url=${pr.html_url}`); - } - return pairs; -} -// The CLI accepts 0 and 90 only; fail here with a clear message rather than -// letting 180/270 through to a CLI error. -function parseOrientation(orientation) { - if (!orientation) - return undefined; - const value = parseInt(orientation); - if (value === 0 || value === 90) { - return value; - } - throw new Error(`Invalid orientation: ${orientation}. Must be 0 or 90`); -} -const REPORT_FORMATS = ['junit', 'html', 'html-detailed']; -function parseDownloadArtifacts(value) { - if (!value) - return undefined; - if (value !== 'ALL' && value !== 'FAILED') { - throw new Error(`Invalid download-artifacts value: ${value}. Must be ALL or FAILED`); - } - return value; -} -/** - * app-file as the CLI should get it: a glob is resolved to its first match - * (see resolveAppFile), and the pick is logged so it's visible in the run. - */ -function getAppFilePath(appFile) { - const { path, matches } = (0, app_file_1.resolveAppFile)(appFile); - if (matches.length > 1) { - const shown = matches.slice(0, 5).join(', '); - const more = matches.length > 5 ? `, and ${matches.length - 5} more` : ''; - core.warning(`app-file "${appFile}" matched ${matches.length} paths (${shown}${more}); ` + - `using the first: ${path}`); - } - else if (matches.length === 1) { - core.info(`app-file "${appFile}" matched ${path}`); - } - return path; -} -function getParameters() { - return __awaiter(this, void 0, void 0, function* () { - const apiUrl = core.getInput('api-url', { required: false }) || - 'https://api.devicecloud.dev'; - const apiKey = core.getInput('api-key', { required: true }); - const name = core.getInput('name', { required: false }) || getInferredName(); - // Support both 'flows' and 'workspace' inputs (flows takes precedence if both are provided) - const flowsInput = core.getInput('flows', { required: false }); - const workspaceInput = core.getInput('workspace', { required: false }); - const workspaceFolder = flowsInput || workspaceInput; - const async = core.getInput('async', { required: false }) === 'true'; - const androidApiLevelString = core.getInput('android-api-level', { - required: false, - }); - const iOSVersionString = core.getInput('ios-version', { required: false }); - const includeTags = parseTags(core.getInput('include-tags', { required: false })); - const excludeTags = parseTags(core.getInput('exclude-tags', { required: false })); - const appFileInput = core.getInput('app-file', { required: false }); - const appBinaryId = core.getInput('app-binary-id', { required: false }); - const androidDevice = parseAndroidDevice(core.getInput('android-device', { required: false })); - const iosDevice = parseIOSDevice(core.getInput('ios-device', { required: false })); - const excludeFlows = core.getInput('exclude-flows', { required: false }); - const googlePlay = core.getInput('google-play', { required: false }) === 'true'; - const cancelPrevious = core.getInput('cancel-previous', { required: false }) === 'true'; - const deviceLocale = core.getInput('device-locale', { required: false }); - const downloadArtifacts = parseDownloadArtifacts(core.getInput('download-artifacts', { required: false })); - const maestroVersion = core.getInput('maestro-version', { required: false }); - const orientation = parseOrientation(core.getInput('orientation', { required: false })); - const ignoreShaCheck = core.getInput('ignore-sha-check', { required: false }) === 'true'; - const reportInput = core.getInput('report', { required: false }); - if (reportInput && - !REPORT_FORMATS.includes(reportInput)) { - throw new Error('Report format must be one of "junit", "html" or "html-detailed"'); - } - const report = (reportInput || undefined); - const config = core.getInput('config', { required: false }); - const runnerType = core.getInput('runner-type', { required: false }); - const renderEngine = core.getInput('render-engine', { required: false }); - const jsonFile = core.getInput('json-file', { required: false }) === 'true'; - const debug = core.getInput('debug', { required: false }) === 'true'; - const moropoV1ApiKey = core.getInput('moropo-v1-api-key', { - required: false, - }); - const useBeta = core.getInput('use-beta', { required: false }) === 'true'; - const checkName = core.getInput('check-name', { required: false }).trim(); - const includeGithubContext = core.getInput('include-github-context', { required: false }) !== 'false'; - const githubContext = includeGithubContext - ? getGithubContextMetadata(checkName) - : undefined; - if (checkName && !includeGithubContext) { - // Without the context there is no sha to post against, so no check at all — - // say so rather than letting the input look like it did something. - core.warning('check-name is ignored because include-github-context is false: with no ' + - 'commit context attached, DeviceCloud posts no check on this run.'); - } - const maestroChromeOnboarding = core.getInput('maestro-chrome-onboarding', { required: false }) === 'true'; - const androidNoSnapshot = core.getInput('android-no-snapshot', { required: false }) === 'true'; - const disableAnimations = core.getInput('disable-animations', { required: false }) === 'true'; - if (!(appFileInput !== '') !== (appBinaryId !== '')) { - throw new Error('Either app-file or app-binary-id must be used'); - } - const appFilePath = getAppFilePath(appFileInput); - const env = core.getMultilineInput('env', { required: false }); - // --quiet was always passed before this input was read, so anything but an - // explicit "false" keeps it on. - const quiet = core.getInput('quiet', { required: false }) !== 'false'; - const androidApiLevel = getAndroidApiLevel(androidApiLevelString); - const iOSVersion = getIOSVersion(iOSVersionString); - const retry = parseInt(core.getInput('retry', { required: false })) || undefined; - return { - apiUrl, - apiKey, - appFilePath, - workspaceFolder, - env, - async, - androidApiLevel, - iOSVersion, - includeTags, - excludeTags, - appBinaryId, - name, - androidDevice, - iosDevice, - excludeFlows, - googlePlay, - cancelPrevious, - deviceLocale, - downloadArtifacts, - maestroVersion, - orientation, - retry, - ignoreShaCheck, - report, - config, - runnerType, - renderEngine, - jsonFile, - debug, - moropoV1ApiKey, - useBeta, - maestroChromeOnboarding, - androidNoSnapshot, - disableAnimations, - githubContext, - quiet, - }; - }); -} - - -/***/ }), - -/***/ 1933: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.supersedingConsoleUrl = supersedingConsoleUrl; -exports.evaluateRun = evaluateRun; -/** - * The console link for the run that superseded this one. The status call's - * consoleUrl deep-links one of THIS run's results, which the newer run does - * not contain, so swap the upload and drop the result (as the CLI does). - */ -function supersedingConsoleUrl(consoleUrl, supersededBy) { - if (!consoleUrl) - return undefined; - try { - const url = new URL(consoleUrl); - url.searchParams.set('upload', supersededBy); - url.searchParams.delete('result'); - return url.toString(); - } - catch (_a) { - return undefined; - } -} -/** - * Decide the job's outcome from the status call and the `dcd cloud` exit code. - * - * A superseded run passes, whatever else is true of it. A newer run from the - * same CI context cancelled its queued tests (cancel-previous), and the API - * rolls those up to FAILED, but the run no longer speaks for the commit. - * Failing the job for it would fail it for work nobody is waiting on. - * `dcd cloud` 5.6.0 exits 0 for such a run; an older CLI exits 2. - * - * Otherwise, fail on either signal. The exit code is authoritative for a run - * that finished badly; the status call can only add failures the CLI could not - * see. A non-terminal status (PENDING/RUNNING) alongside a clean exit is a racy - * or degraded status call, not a failure: the CLI watched the run to - * completion, so warn rather than turn the build red. - */ -function evaluateRun(result, cloudExitCode) { - const supersededBy = typeof result.supersededBy === 'string' ? result.supersededBy : ''; - if (supersededBy) { - const newer = supersedingConsoleUrl(result.consoleUrl, supersededBy); - return { - outcome: 'pass', - uploadStatus: 'SUPERSEDED', - message: `Superseded by ${supersededBy}: a newer run from the same CI context ` + - `replaced this one, so this job does not fail.` + - (newer ? ` Newer run: ${newer}` : ''), - }; - } - const uploadStatus = result.status || 'PENDING'; - if (cloudExitCode !== 0) { - return { - outcome: 'fail', - uploadStatus, - message: `Test run failed (dcd exited ${cloudExitCode}, status ${result.status}). ` + - `Check flow results for details: ${result.consoleUrl}`, - }; - } - if (result.status === 'PASSED') { - return { - outcome: 'pass', - uploadStatus, - message: 'Successfully completed test run.', - }; - } - if (result.status === 'FAILED' || result.status === 'CANCELLED') { - return { - outcome: 'fail', - uploadStatus, - message: `Test run ${result.status}. Check flow results for details: ${result.consoleUrl}`, - }; - } - return { - outcome: 'warn', - uploadStatus, - message: `dcd reported success but the upload status is ${result.status}. ` + - `Treating the run as passed: ${result.consoleUrl}`, - }; -} - - -/***/ }), - -/***/ 5397: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || (function () { - 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); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - 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; - }; -})(); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.readWrapperVersion = readWrapperVersion; -const fs = __importStar(__nccwpck_require__(9896)); -const path = __importStar(__nccwpck_require__(6928)); -/** - * The action's own version, read from package.json at RUNTIME. - * - * `entryDir` is the directory of the running entry file: `dist/` in the - * published action and `src/` from source. Both sit one level below - * package.json, so `/../package.json` is the repo root's either way. - * - * This is deliberately not `require('../package.json')` or a JSON import. ncc - * inlines those into dist/index.js, so dist then carried whatever version was - * current when it was last built. v2.5.0 shipped reporting 2.4.0 that way, and - * a release-please release PR (which bumps only package.json) would either tag - * a dist holding the previous version or force a dist rebuild into the release - * commit. The path is built from a parameter so ncc's asset relocator can't - * resolve it at build time and copy package.json into dist/. - * - * Best-effort: returns undefined rather than throwing. - */ -function readWrapperVersion(entryDir) { - try { - const manifest = JSON.parse(fs.readFileSync(path.join(entryDir, '..', 'package.json'), 'utf8')); - return typeof manifest.version === 'string' && manifest.version - ? manifest.version - : undefined; - } - catch (_a) { - return undefined; - } -} - - -/***/ }), - -/***/ 2613: -/***/ ((module) => { - -"use strict"; -module.exports = require("assert"); - -/***/ }), - -/***/ 5317: -/***/ ((module) => { - -"use strict"; -module.exports = require("child_process"); - -/***/ }), - -/***/ 6982: -/***/ ((module) => { - -"use strict"; -module.exports = require("crypto"); - -/***/ }), - -/***/ 4434: -/***/ ((module) => { - -"use strict"; -module.exports = require("events"); - -/***/ }), - -/***/ 9896: -/***/ ((module) => { - -"use strict"; -module.exports = require("fs"); - -/***/ }), - -/***/ 8611: -/***/ ((module) => { - -"use strict"; -module.exports = require("http"); - -/***/ }), - -/***/ 5692: -/***/ ((module) => { - -"use strict"; -module.exports = require("https"); - -/***/ }), - -/***/ 9278: -/***/ ((module) => { - -"use strict"; -module.exports = require("net"); +module.exports = require("net"); /***/ }), @@ -45855,38 +42164,6 @@ module.exports = require("node:zlib"); /***/ }), -/***/ 857: -/***/ ((module) => { - -"use strict"; -module.exports = require("os"); - -/***/ }), - -/***/ 6928: -/***/ ((module) => { - -"use strict"; -module.exports = require("path"); - -/***/ }), - -/***/ 3193: -/***/ ((module) => { - -"use strict"; -module.exports = require("string_decoder"); - -/***/ }), - -/***/ 3557: -/***/ ((module) => { - -"use strict"; -module.exports = require("timers"); - -/***/ }), - /***/ 4756: /***/ ((module) => { @@ -45901,1931 +42178,5150 @@ module.exports = require("tls"); "use strict"; module.exports = require("util"); -/***/ }), - -/***/ 3356: -/***/ ((module) => { +/***/ }) +/******/ }); +/************************************************************************/ +/******/ // 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] = { +/******/ id: moduleId, +/******/ loaded: false, +/******/ 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]; +/******/ } +/******/ +/******/ // Flag the module as loaded +/******/ module.loaded = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/************************************************************************/ +/******/ /* webpack/runtime/asset-relocator-loader */ +/******/ if (typeof __nccwpck_require__ !== 'undefined') __nccwpck_require__.ab = __dirname + "/"; +/******/ +/******/ /* webpack/runtime/node module decorator */ +/******/ (() => { +/******/ __nccwpck_require__.nmd = (module) => { +/******/ module.paths = []; +/******/ if (!module.children) module.children = []; +/******/ return module; +/******/ }; +/******/ })(); +/******/ +/************************************************************************/ +var __webpack_exports__ = {}; +// This entry need to be wrapped in an IIFE because it need to be in strict mode. +(() => { "use strict"; -var __webpack_unused_export__; - - -const NullObject = function NullObject () { } -NullObject.prototype = Object.create(null) - -/** - * RegExp to match *( ";" parameter ) in RFC 7231 sec 3.1.1.1 - * - * parameter = token "=" ( token / quoted-string ) - * token = 1*tchar - * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" - * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" - * / DIGIT / ALPHA - * ; any VCHAR, except delimiters - * quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE - * qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text - * obs-text = %x80-FF - * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) - */ -const paramRE = /; *([!#$%&'*+.^\w`|~-]+)=("(?:[\v\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\v\u0020-\u00ff])*"|[!#$%&'*+.^\w`|~-]+) */gu +;// CONCATENATED MODULE: external "os" +const external_os_namespaceObject = require("os"); +;// CONCATENATED MODULE: ./node_modules/.pnpm/@actions+core@3.0.1/node_modules/@actions/core/lib/utils.js +// We use any as a valid input type +/* eslint-disable @typescript-eslint/no-explicit-any */ /** - * RegExp to match quoted-pair in RFC 7230 sec 3.2.6 - * - * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) - * obs-text = %x80-FF + * Sanitizes an input into a string so it can be passed into issueCommand safely + * @param input input to sanitize into a string */ -const quotedPairRE = /\\([\v\u0020-\u00ff])/gu - +function utils_toCommandValue(input) { + if (input === null || input === undefined) { + return ''; + } + else if (typeof input === 'string' || input instanceof String) { + return input; + } + return JSON.stringify(input); +} /** - * RegExp to match type in RFC 7231 sec 3.1.1.1 * - * media-type = type "/" subtype - * type = token - * subtype = token + * @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 */ -const mediaTypeRE = /^[!#$%&'*+.^\w|~-]+\/[!#$%&'*+.^\w|~-]+$/u +function utils_toCommandProperties(annotationProperties) { + if (!Object.keys(annotationProperties).length) { + return {}; + } + return { + title: annotationProperties.title, + file: annotationProperties.file, + line: annotationProperties.startLine, + endLine: annotationProperties.endLine, + col: annotationProperties.startColumn, + endColumn: annotationProperties.endColumn + }; +} +//# sourceMappingURL=utils.js.map +;// CONCATENATED MODULE: ./node_modules/.pnpm/@actions+core@3.0.1/node_modules/@actions/core/lib/command.js -// default ContentType to prevent repeated object creation -const defaultContentType = { type: '', parameters: new NullObject() } -Object.freeze(defaultContentType.parameters) -Object.freeze(defaultContentType) /** - * Parse media type to object. + * Issues a command to the GitHub Actions runner + * + * @param command - The command name to issue + * @param properties - Additional properties for the command (key-value pairs) + * @param message - The message to include with the command + * @remarks + * This function outputs a specially formatted string to stdout that the Actions + * runner interprets as a command. These commands can control workflow behavior, + * set outputs, create annotations, mask values, and more. + * + * Command Format: + * ::name key=value,key=value::message + * + * @example + * ```typescript + * // Issue a warning annotation + * issueCommand('warning', {}, 'This is a warning message'); + * // Output: ::warning::This is a warning message * - * @param {string|object} header - * @return {Object} - * @public + * // Set an environment variable + * issueCommand('set-env', { name: 'MY_VAR' }, 'some value'); + * // Output: ::set-env name=MY_VAR::some value + * + * // Add a secret mask + * issueCommand('add-mask', {}, 'secretValue123'); + * // Output: ::add-mask::secretValue123 + * ``` + * + * @internal + * This is an internal utility function that powers the public API functions + * such as setSecret, warning, error, and exportVariable. */ - -function parse (header) { - if (typeof header !== 'string') { - throw new TypeError('argument header is required and must be a string') - } - - let index = header.indexOf(';') - const type = index !== -1 - ? header.slice(0, index).trim() - : header.trim() - - if (mediaTypeRE.test(type) === false) { - throw new TypeError('invalid media type') - } - - const result = { - type: type.toLowerCase(), - parameters: new NullObject() - } - - // parse parameters - if (index === -1) { - return result - } - - let key - let match - let value - - paramRE.lastIndex = index - - while ((match = paramRE.exec(header))) { - if (match.index !== index) { - throw new TypeError('invalid parameter format') +function command_issueCommand(command, properties, message) { + const cmd = new Command(command, properties, message); + process.stdout.write(cmd.toString() + external_os_namespaceObject.EOL); +} +function command_issue(name, message = '') { + command_issueCommand(name, {}, message); +} +const CMD_STRING = '::'; +class Command { + constructor(command, properties, message) { + if (!command) { + command = 'missing.command'; + } + this.command = command; + this.properties = properties; + this.message = message; } - - index += match[0].length - key = match[1].toLowerCase() - value = match[2] - - if (value[0] === '"') { - // remove quotes and escapes - value = value - .slice(1, value.length - 1) - - quotedPairRE.test(value) && (value = value.replace(quotedPairRE, '$1')) + 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; } - - result.parameters[key] = value - } - - if (index !== header.length) { - throw new TypeError('invalid parameter format') - } - - return result } +function escapeData(s) { + return utils_toCommandValue(s) + .replace(/%/g, '%25') + .replace(/\r/g, '%0D') + .replace(/\n/g, '%0A'); +} +function escapeProperty(s) { + return utils_toCommandValue(s) + .replace(/%/g, '%25') + .replace(/\r/g, '%0D') + .replace(/\n/g, '%0A') + .replace(/:/g, '%3A') + .replace(/,/g, '%2C'); +} +//# sourceMappingURL=command.js.map +;// CONCATENATED MODULE: external "crypto" +const external_crypto_namespaceObject = require("crypto"); +;// CONCATENATED MODULE: external "fs" +const external_fs_namespaceObject = require("fs"); +;// CONCATENATED MODULE: ./node_modules/.pnpm/@actions+core@3.0.1/node_modules/@actions/core/lib/file-command.js +// For internal use, subject to change. +// We use any as a valid input type +/* eslint-disable @typescript-eslint/no-explicit-any */ -function safeParse (header) { - if (typeof header !== 'string') { - return defaultContentType - } - - let index = header.indexOf(';') - const type = index !== -1 - ? header.slice(0, index).trim() - : header.trim() - - if (mediaTypeRE.test(type) === false) { - return defaultContentType - } - - const result = { - type: type.toLowerCase(), - parameters: new NullObject() - } - - // parse parameters - if (index === -1) { - return result - } - let key - let match - let value - paramRE.lastIndex = index - while ((match = paramRE.exec(header))) { - if (match.index !== index) { - return defaultContentType +function file_command_issueFileCommand(command, message) { + const filePath = process.env[`GITHUB_${command}`]; + if (!filePath) { + throw new Error(`Unable to find environment variable for file command ${command}`); } - - index += match[0].length - key = match[1].toLowerCase() - value = match[2] - - if (value[0] === '"') { - // remove quotes and escapes - value = value - .slice(1, value.length - 1) - - quotedPairRE.test(value) && (value = value.replace(quotedPairRE, '$1')) + if (!external_fs_namespaceObject.existsSync(filePath)) { + throw new Error(`Missing file at path: ${filePath}`); } - - result.parameters[key] = value - } - - if (index !== header.length) { - return defaultContentType - } - - return result -} - -__webpack_unused_export__ = { parse, safeParse } -__webpack_unused_export__ = parse -module.exports.xL = safeParse -__webpack_unused_export__ = defaultContentType - - -/***/ }), - -/***/ 6895: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { - -"use strict"; -// ESM COMPAT FLAG -__nccwpck_require__.r(__webpack_exports__); - -// EXPORTS -__nccwpck_require__.d(__webpack_exports__, { - Octokit: () => (/* binding */ Octokit) -}); - -;// CONCATENATED MODULE: ./node_modules/.pnpm/universal-user-agent@7.0.3/node_modules/universal-user-agent/index.js -function getUserAgent() { - if (typeof navigator === "object" && "userAgent" in navigator) { - return navigator.userAgent; - } - - if (typeof process === "object" && process.version !== undefined) { - return `Node.js/${process.version.substr(1)} (${process.platform}; ${ - process.arch - })`; - } - - return ""; + external_fs_namespaceObject.appendFileSync(filePath, `${utils_toCommandValue(message)}${external_os_namespaceObject.EOL}`, { + encoding: 'utf8' + }); } - -;// CONCATENATED MODULE: ./node_modules/.pnpm/before-after-hook@4.0.0/node_modules/before-after-hook/lib/register.js -// @ts-check - -function register(state, name, method, options) { - if (typeof method !== "function") { - throw new Error("method for before hook must be a function"); - } - - if (!options) { - options = {}; - } - - if (Array.isArray(name)) { - return name.reverse().reduce((callback, name) => { - return register.bind(null, state, name, callback, options); - }, method)(); - } - - return Promise.resolve().then(() => { - if (!state.registry[name]) { - return method(options); +function file_command_prepareKeyValueMessage(key, value) { + const delimiter = `ghadelimiter_${external_crypto_namespaceObject.randomUUID()}`; + const convertedValue = utils_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}"`); } - - return state.registry[name].reduce((method, registered) => { - return registered.hook.bind(null, method, options); - }, method)(); - }); -} - -;// CONCATENATED MODULE: ./node_modules/.pnpm/before-after-hook@4.0.0/node_modules/before-after-hook/lib/add.js -// @ts-check - -function addHook(state, kind, name, hook) { - const orig = hook; - if (!state.registry[name]) { - state.registry[name] = []; - } - - if (kind === "before") { - hook = (method, options) => { - return Promise.resolve() - .then(orig.bind(null, options)) - .then(method.bind(null, options)); - }; - } - - if (kind === "after") { - hook = (method, options) => { - let result; - return Promise.resolve() - .then(method.bind(null, options)) - .then((result_) => { - result = result_; - return orig(result, options); - }) - .then(() => { - return result; - }); - }; - } - - if (kind === "error") { - hook = (method, options) => { - return Promise.resolve() - .then(method.bind(null, options)) - .catch((error) => { - return orig(error, options); - }); - }; - } - - state.registry[name].push({ - hook: hook, - orig: orig, - }); + if (convertedValue.includes(delimiter)) { + throw new Error(`Unexpected input: value should not contain the delimiter "${delimiter}"`); + } + return `${key}<<${delimiter}${external_os_namespaceObject.EOL}${convertedValue}${external_os_namespaceObject.EOL}${delimiter}`; } - -;// CONCATENATED MODULE: ./node_modules/.pnpm/before-after-hook@4.0.0/node_modules/before-after-hook/lib/remove.js -// @ts-check - -function removeHook(state, name, method) { - if (!state.registry[name]) { - return; - } - - const index = state.registry[name] - .map((registered) => { - return registered.orig; - }) - .indexOf(method); - - if (index === -1) { - return; - } - - state.registry[name].splice(index, 1); +//# sourceMappingURL=file-command.js.map +;// CONCATENATED MODULE: external "path" +const external_path_namespaceObject = require("path"); +// EXTERNAL MODULE: external "http" +var external_http_ = __nccwpck_require__(8611); +// EXTERNAL MODULE: external "https" +var external_https_ = __nccwpck_require__(5692); +;// CONCATENATED MODULE: ./node_modules/.pnpm/@actions+http-client@4.0.1/node_modules/@actions/http-client/lib/proxy.js +function getProxyUrl(reqUrl) { + const usingSsl = reqUrl.protocol === 'https:'; + if (checkBypass(reqUrl)) { + return undefined; + } + 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; + } } - -;// CONCATENATED MODULE: ./node_modules/.pnpm/before-after-hook@4.0.0/node_modules/before-after-hook/index.js -// @ts-check - - - - - -// bind with array of arguments: https://stackoverflow.com/a/21792913 -const bind = Function.bind; -const bindable = bind.bind(bind); - -function bindApi(hook, state, name) { - const removeHookRef = bindable(removeHook, null).apply( - null, - name ? [state, name] : [state] - ); - hook.api = { remove: removeHookRef }; - hook.remove = removeHookRef; - ["before", "error", "after", "wrap"].forEach((kind) => { - const args = name ? [state, kind, name] : [state, kind]; - hook[kind] = hook.api[kind] = bindable(addHook, null).apply(null, args); - }); +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; + } + } + return false; } - -function Singular() { - const singularHookName = Symbol("Singular"); - const singularHookState = { - registry: {}, - }; - const singularHook = register.bind(null, singularHookState, singularHookName); - bindApi(singularHook, singularHookState, singularHookName); - return singularHook; +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]')); } - -function Collection() { - const state = { - registry: {}, - }; - - const hook = register.bind(null, state); - bindApi(hook, state); - - return hook; +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; + } } - -/* harmony default export */ const before_after_hook = ({ Singular, Collection }); - -;// CONCATENATED MODULE: ./node_modules/.pnpm/@octokit+endpoint@11.0.3/node_modules/@octokit/endpoint/dist-bundle/index.js -// pkg/dist-src/defaults.js +//# sourceMappingURL=proxy.js.map +// EXTERNAL MODULE: ./node_modules/.pnpm/tunnel@0.0.6/node_modules/tunnel/index.js +var node_modules_tunnel = __nccwpck_require__(7013); +// EXTERNAL MODULE: ./node_modules/.pnpm/undici@8.11.2/node_modules/undici/index.js +var undici = __nccwpck_require__(1889); +;// CONCATENATED MODULE: ./node_modules/.pnpm/@actions+http-client@4.0.1/node_modules/@actions/http-client/lib/index.js +/* eslint-disable @typescript-eslint/no-explicit-any */ +var __awaiter = (undefined && undefined.__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()); + }); +}; -// pkg/dist-src/version.js -var VERSION = "0.0.0-development"; -// pkg/dist-src/defaults.js -var userAgent = `octokit-endpoint.js/${VERSION} ${getUserAgent()}`; -var DEFAULTS = { - method: "GET", - baseUrl: "https://api.github.com", - headers: { - accept: "application/vnd.github.v3+json", - "user-agent": userAgent - }, - mediaType: { - format: "" - } -}; -// pkg/dist-src/util/lowercase-keys.js -function lowercaseKeys(object) { - if (!object) { - return {}; - } - return Object.keys(object).reduce((newObj, key) => { - newObj[key.toLowerCase()] = object[key]; - return newObj; - }, {}); -} -// pkg/dist-src/util/is-plain-object.js -function isPlainObject(value) { - if (typeof value !== "object" || value === null) return false; - if (Object.prototype.toString.call(value) !== "[object Object]") return false; - const proto = Object.getPrototypeOf(value); - if (proto === null) return true; - const Ctor = Object.prototype.hasOwnProperty.call(proto, "constructor") && proto.constructor; - return typeof Ctor === "function" && Ctor instanceof Ctor && Function.prototype.call(Ctor) === Function.prototype.call(value); +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 || (HttpCodes = {})); +var Headers; +(function (Headers) { + Headers["Accept"] = "accept"; + Headers["ContentType"] = "content-type"; +})(Headers || (Headers = {})); +var MediaTypes; +(function (MediaTypes) { + MediaTypes["ApplicationJson"] = "application/json"; +})(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 lib_getProxyUrl(serverUrl) { + const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ''; } - -// pkg/dist-src/util/merge-deep.js -function mergeDeep(defaults, options) { - const result = Object.assign({}, defaults); - Object.keys(options).forEach((key) => { - if (isPlainObject(options[key])) { - if (!(key in defaults)) Object.assign(result, { [key]: options[key] }); - else result[key] = mergeDeep(defaults[key], options[key]); - } else { - Object.assign(result, { [key]: options[key] }); +const HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect +]; +const HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout +]; +const RetryableHttpVerbs = (/* unused pure expression or super */ null && (['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); } - }); - return result; } - -// pkg/dist-src/util/remove-undefined-properties.js -function removeUndefinedProperties(obj) { - for (const key in obj) { - if (obj[key] === void 0) { - delete obj[key]; +class HttpClientResponse { + constructor(message) { + this.message = message; } - } - return obj; -} - -// pkg/dist-src/merge.js -function merge(defaults, route, options) { - if (typeof route === "string") { - let [method, url] = route.split(" "); - options = Object.assign(url ? { method, url } : { url: method }, options); - } else { - options = Object.assign({}, route); - } - options.headers = lowercaseKeys(options.headers); - removeUndefinedProperties(options); - removeUndefinedProperties(options.headers); - const mergedOptions = mergeDeep(defaults || {}, options); - if (options.url === "/graphql") { - if (defaults && defaults.mediaType.previews?.length) { - mergedOptions.mediaType.previews = defaults.mediaType.previews.filter( - (preview) => !mergedOptions.mediaType.previews.includes(preview) - ).concat(mergedOptions.mediaType.previews); + 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()); + }); + })); + }); } - mergedOptions.mediaType.previews = (mergedOptions.mediaType.previews || []).map((preview) => preview.replace(/-preview/, "")); - } - return mergedOptions; -} - -// pkg/dist-src/util/add-query-parameters.js -function addQueryParameters(url, parameters) { - const separator = /\?/.test(url) ? "&" : "?"; - const names = Object.keys(parameters); - if (names.length === 0) { - return url; - } - return url + separator + names.map((name) => { - if (name === "q") { - return "q=" + parameters.q.split("+").map(encodeURIComponent).join("+"); + 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)); + }); + })); + }); } - return `${name}=${encodeURIComponent(parameters[name])}`; - }).join("&"); -} - -// pkg/dist-src/util/extract-url-variable-names.js -var urlVariableRegex = /\{[^{}}]+\}/g; -function removeNonChars(variableName) { - return variableName.replace(/(?:^\W+)|(?:(? a.concat(b), []); +function isHttps(requestUrl) { + const parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === 'https:'; } - -// pkg/dist-src/util/omit.js -function omit(object, keysToOmit) { - const result = { __proto__: null }; - for (const key of Object.keys(object)) { - if (keysToOmit.indexOf(key) === -1) { - result[key] = object[key]; +class lib_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 = this._getUserAgentWithOrchestrationId(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; + } + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + } + 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 result; -} - -// pkg/dist-src/util/url-template.js -function encodeReserved(str) { - return str.split(/(%[0-9A-Fa-f]{2})/g).map(function(part) { - if (!/%[0-9A-Fa-f]/.test(part)) { - part = encodeURI(part).replace(/%5B/g, "[").replace(/%5D/g, "]"); + options(requestUrl, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('OPTIONS', requestUrl, null, additionalHeaders || {}); + }); } - return part; - }).join(""); -} -function encodeUnreserved(str) { - return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { - return "%" + c.charCodeAt(0).toString(16).toUpperCase(); - }); -} -function encodeValue(operator, value, key) { - value = operator === "+" || operator === "#" ? encodeReserved(value) : encodeUnreserved(value); - if (key) { - return encodeUnreserved(key) + "=" + value; - } else { - return value; - } -} -function isDefined(value) { - return value !== void 0 && value !== null; -} -function isKeyOperator(operator) { - return operator === ";" || operator === "&" || operator === "?"; -} -function getValues(context, operator, key, modifier) { - var value = context[key], result = []; - if (isDefined(value) && value !== "") { - if (typeof value === "string" || typeof value === "number" || typeof value === "bigint" || typeof value === "boolean") { - value = value.toString(); - if (modifier && modifier !== "*") { - value = value.substring(0, parseInt(modifier, 10)); - } - result.push( - encodeValue(operator, value, isKeyOperator(operator) ? key : "") - ); - } else { - if (modifier === "*") { - if (Array.isArray(value)) { - value.filter(isDefined).forEach(function(value2) { - result.push( - encodeValue(operator, value2, isKeyOperator(operator) ? key : "") - ); - }); - } else { - Object.keys(value).forEach(function(k) { - if (isDefined(value[k])) { - result.push(encodeValue(operator, value[k], k)); + 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 + */ + getJson(requestUrl_1) { + return __awaiter(this, arguments, void 0, function* (requestUrl, additionalHeaders = {}) { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + const res = yield this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + postJson(requestUrl_1, obj_1) { + return __awaiter(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = + this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson); + const res = yield this.post(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + putJson(requestUrl_1, obj_1) { + return __awaiter(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = + this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson); + const res = yield this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + patchJson(requestUrl_1, obj_1) { + return __awaiter(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = + this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson); + const res = yield this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + /** + * 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; + }); + } + /** + * Needs to be called if keepAlive is set to true in request options. + */ + dispose() { + if (this._agent) { + this._agent.destroy(); } - } else { - const tmp = []; - if (Array.isArray(value)) { - value.filter(isDefined).forEach(function(value2) { - tmp.push(encodeValue(operator, value2)); - }); - } else { - Object.keys(value).forEach(function(k) { - if (isDefined(value[k])) { - tmp.push(encodeUnreserved(k)); - tmp.push(encodeValue(operator, value[k].toString())); + 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); + }); + }); + } + /** + * Raw request with callback. + * @param info + * @param data + * @param onResult + */ + requestRawWithCallback(info, data, onResult) { + if (typeof data === 'string') { + if (!info.options.headers) { + info.options.headers = {}; } - }); + info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8'); } - if (isKeyOperator(operator)) { - result.push(encodeUnreserved(key) + "=" + tmp.join(",")); - } else if (tmp.length !== 0) { - result.push(tmp.join(",")); + 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); + }); + 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(); } - } } - } else { - if (operator === ";") { - if (isDefined(value)) { - result.push(encodeUnreserved(key)); - } - } else if (value === "" && (operator === "&" || operator === "?")) { - result.push(encodeUnreserved(key) + "="); - } else if (value === "") { - result.push(""); + /** + * 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 + */ + getAgent(serverUrl) { + const parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); } - } - return result; -} -function parseUrl(template) { - return { - expand: expand.bind(null, template) - }; -} -function expand(template, context) { - var operators = ["+", "#", ".", "/", ";", "?", "&"]; - template = template.replace( - /\{([^\{\}]+)\}|([^\{\}]+)/g, - function(_, expression, literal) { - if (expression) { - let operator = ""; - const values = []; - if (operators.indexOf(expression.charAt(0)) !== -1) { - operator = expression.charAt(0); - expression = expression.substr(1); + getAgentDispatcher(serverUrl) { + const parsedUrl = new URL(serverUrl); + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (!useProxy) { + return; } - expression.split(/,/g).forEach(function(variable) { - var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable); - values.push(getValues(context, operator, tmp[1], tmp[2] || tmp[3])); - }); - if (operator && operator !== "+") { - var separator = ","; - if (operator === "?") { - separator = "&"; - } else if (operator !== "#") { - separator = operator; - } - return (values.length !== 0 ? operator : "") + values.join(separator); - } else { - return values.join(","); + 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; } - } else { - return encodeReserved(literal); - } + 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; } - ); - if (template === "/") { - return template; - } else { - return template.replace(/\/$/, ""); - } -} - -// pkg/dist-src/parse.js -function parse(options) { - let method = options.method.toUpperCase(); - let url = (options.url || "/").replace(/:([a-z]\w+)/g, "{$1}"); - let headers = Object.assign({}, options.headers); - let body; - let parameters = omit(options, [ - "method", - "baseUrl", - "url", - "headers", - "request", - "mediaType" - ]); - const urlVariableNames = extractUrlVariableNames(url); - url = parseUrl(url).expand(parameters); - if (!/^http/.test(url)) { - url = options.baseUrl + url; - } - const omittedParameters = Object.keys(options).filter((option) => urlVariableNames.includes(option)).concat("baseUrl"); - const remainingParameters = omit(parameters, omittedParameters); - const isBinaryRequest = /application\/octet-stream/i.test(headers.accept); - if (!isBinaryRequest) { - if (options.mediaType.format) { - headers.accept = headers.accept.split(/,/).map( - (format) => format.replace( - /application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/, - `application/vnd$1$2.${options.mediaType.format}` - ) - ).join(","); + _mergeHeaders(headers) { + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); + } + return lowercaseKeys(headers || {}); } - if (url.endsWith("/graphql")) { - if (options.mediaType.previews?.length) { - const previewsFromAcceptHeader = headers.accept.match(/(? { - const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json"; - return `application/vnd.github.${preview}-preview${format}`; - }).join(","); - } + /** + * Gets an existing header value or returns a default. + * Handles converting number header values to strings since HTTP headers must be strings. + * Note: This returns string | string[] since some headers can have multiple values. + * For headers that must always be a single string (like Content-Type), use the + * specialized _getExistingOrDefaultContentTypeHeader method instead. + */ + _getExistingOrDefaultHeader(additionalHeaders, header, _default) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + const headerValue = lowercaseKeys(this.requestOptions.headers)[header]; + if (headerValue) { + clientHeader = + typeof headerValue === 'number' ? headerValue.toString() : headerValue; + } + } + const additionalValue = additionalHeaders[header]; + if (additionalValue !== undefined) { + return typeof additionalValue === 'number' + ? additionalValue.toString() + : additionalValue; + } + if (clientHeader !== undefined) { + return clientHeader; + } + return _default; } - } - if (["GET", "HEAD"].includes(method)) { - url = addQueryParameters(url, remainingParameters); - } else { - if ("data" in remainingParameters) { - body = remainingParameters.data; - } else { - if (Object.keys(remainingParameters).length) { - body = remainingParameters; - } + /** + * Specialized version of _getExistingOrDefaultHeader for Content-Type header. + * Always returns a single string (not an array) since Content-Type should be a single value. + * Converts arrays to comma-separated strings and numbers to strings to ensure type safety. + * This was split from _getExistingOrDefaultHeader to provide stricter typing for callers + * that assign the result to places expecting a string (e.g., additionalHeaders[Headers.ContentType]). + */ + _getExistingOrDefaultContentTypeHeader(additionalHeaders, _default) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + const headerValue = lowercaseKeys(this.requestOptions.headers)[Headers.ContentType]; + if (headerValue) { + if (typeof headerValue === 'number') { + clientHeader = String(headerValue); + } + else if (Array.isArray(headerValue)) { + clientHeader = headerValue.join(', '); + } + else { + clientHeader = headerValue; + } + } + } + const additionalValue = additionalHeaders[Headers.ContentType]; + // Return the first non-undefined value, converting numbers or arrays to strings if necessary + if (additionalValue !== undefined) { + if (typeof additionalValue === 'number') { + return String(additionalValue); + } + else if (Array.isArray(additionalValue)) { + return additionalValue.join(', '); + } + else { + return additionalValue; + } + } + if (clientHeader !== undefined) { + return clientHeader; + } + return _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 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; + } + _getUserAgentWithOrchestrationId(userAgent) { + const baseUserAgent = userAgent || 'actions/http-client'; + const orchId = process.env['ACTIONS_ORCHESTRATION_ID']; + if (orchId) { + // Sanitize the orchestration ID to ensure it contains only valid characters + // Valid characters: 0-9, a-z, _, -, . + const sanitizedId = orchId.replace(/[^a-z0-9_.-]/gi, '_'); + return `${baseUserAgent} actions_orchestration_id/${sanitizedId}`; + } + return baseUserAgent; + } + _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); + } + })); + }); } - } - if (!headers["content-type"] && typeof body !== "undefined") { - headers["content-type"] = "application/json; charset=utf-8"; - } - if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") { - body = ""; - } - return Object.assign( - { method, url, headers }, - typeof body !== "undefined" ? { body } : null, - options.request ? { request: options.request } : null - ); -} - -// pkg/dist-src/endpoint-with-defaults.js -function endpointWithDefaults(defaults, route, options) { - return parse(merge(defaults, route, options)); -} - -// pkg/dist-src/with-defaults.js -function withDefaults(oldDefaults, newDefaults) { - const DEFAULTS2 = merge(oldDefaults, newDefaults); - const endpoint2 = endpointWithDefaults.bind(null, DEFAULTS2); - return Object.assign(endpoint2, { - DEFAULTS: DEFAULTS2, - defaults: withDefaults.bind(null, DEFAULTS2), - merge: merge.bind(null, DEFAULTS2), - parse - }); } - -// pkg/dist-src/index.js -var endpoint = withDefaults(null, DEFAULTS); - - -// EXTERNAL MODULE: ./node_modules/.pnpm/fast-content-type-parse@3.0.0/node_modules/fast-content-type-parse/index.js -var fast_content_type_parse = __nccwpck_require__(3356); -;// CONCATENATED MODULE: ./node_modules/.pnpm/json-with-bigint@3.5.7/node_modules/json-with-bigint/json-with-bigint.js -const intRegex = /^-?\d+$/; -const noiseValue = /^-?\d+n+$/; // Noise - strings that match the custom format before being converted to it -const originalStringify = JSON.stringify; -const originalParse = JSON.parse; -const customFormat = /^-?\d+n$/; - -const bigIntsStringify = /([\[:])?"(-?\d+)n"($|([\\n]|\s)*(\s|[\\n])*[,\}\]])/g; -const noiseStringify = - /([\[:])?("-?\d+n+)n("$|"([\\n]|\s)*(\s|[\\n])*[,\}\]])/g; - -/** @typedef {(key: string, value: any, context?: { source: string }) => any} Reviver */ - -/** - * Function to serialize value to a JSON string. - * Converts BigInt values to a custom format (strings with digits and "n" at the end) and then converts them to proper big integers in a JSON string. - * @param {*} value - The value to convert to a JSON string. - * @param {(Function|Array|null)} [replacer] - A function that alters the behavior of the stringification process, or an array of strings to indicate properties to exclude. - * @param {(string|number)} [space] - A string or number to specify indentation or pretty-printing. - * @returns {string} The JSON string representation. - */ -const JSONStringify = (value, replacer, space) => { - if ("rawJSON" in JSON) { - return originalStringify( - value, - (key, value) => { - if (typeof value === "bigint") return JSON.rawJSON(value.toString()); - - if (typeof replacer === "function") return replacer(key, value); - - if (Array.isArray(replacer) && replacer.includes(key)) return value; - - return value; - }, - space, - ); - } - - if (!value) return originalStringify(value, replacer, space); - - const convertedToCustomJSON = originalStringify( - value, - (key, value) => { - const isNoise = - typeof value === "string" && Boolean(value.match(noiseValue)); - - if (isNoise) return value.toString() + "n"; // Mark noise values with additional "n" to offset the deletion of one "n" during the processing - - if (typeof value === "bigint") return value.toString() + "n"; - - if (typeof replacer === "function") return replacer(key, value); - - if (Array.isArray(replacer) && replacer.includes(key)) return value; - - return value; - }, - space, - ); - const processedJSON = convertedToCustomJSON.replace( - bigIntsStringify, - "$1$2$3", - ); // Delete one "n" off the end of every BigInt value - const denoisedJSON = processedJSON.replace(noiseStringify, "$1$2$3"); // Remove one "n" off the end of every noisy string - - return denoisedJSON; -}; - -/** - * Support for JSON.parse's context.source feature detection. - * @type {boolean} - */ -const isContextSourceSupported = () => - JSON.parse("1", (_, __, context) => !!context && context.source === "1"); - -/** - * Convert marked big numbers to BigInt - * @type {Reviver} - */ -const convertMarkedBigIntsReviver = (key, value, context, userReviver) => { - const isCustomFormatBigInt = - typeof value === "string" && value.match(customFormat); - if (isCustomFormatBigInt) return BigInt(value.slice(0, -1)); - - const isNoiseValue = typeof value === "string" && value.match(noiseValue); - if (isNoiseValue) return value.slice(0, -1); - - if (typeof userReviver !== "function") return value; - return userReviver(key, value, context); -}; - -/** - * Faster (2x) and simpler function to parse JSON. - * Based on JSON.parse's context.source feature, which is not universally available now. - * Does not support the legacy custom format, used in the first version of this library. - */ -const JSONParseV2 = (text, reviver) => { - return JSON.parse(text, (key, value, context) => { - const isBigNumber = - typeof value === "number" && - (value > Number.MAX_SAFE_INTEGER || value < Number.MIN_SAFE_INTEGER); - const isInt = context && intRegex.test(context.source); - const isBigInt = isBigNumber && isInt; - - if (isBigInt) return BigInt(context.source); - - if (typeof reviver !== "function") return value; - - return reviver(key, value, context); - }); -}; - -const MAX_INT = Number.MAX_SAFE_INTEGER.toString(); -const MAX_DIGITS = MAX_INT.length; -const stringsOrLargeNumbers = - /"(?:\\.|[^"])*"|-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?/g; -const noiseValueWithQuotes = /^"-?\d+n+"$/; // Noise - strings that match the custom format before being converted to it - -/** - * Function to parse JSON. - * If JSON has number values greater than Number.MAX_SAFE_INTEGER, we convert those values to a custom format, then parse them to BigInt values. - * Other types of values are not affected and parsed as native JSON.parse() would parse them. - */ -const JSONParse = (text, reviver) => { - if (!text) return originalParse(text, reviver); - - if (isContextSourceSupported()) return JSONParseV2(text, reviver); // Shortcut to a faster (2x) and simpler version - - // Find and mark big numbers with "n" - const serializedData = text.replace( - stringsOrLargeNumbers, - (text, digits, fractional, exponential) => { - const isString = text[0] === '"'; - const isNoise = isString && Boolean(text.match(noiseValueWithQuotes)); - - if (isNoise) return text.substring(0, text.length - 1) + 'n"'; // Mark noise values with additional "n" to offset the deletion of one "n" during the processing - - const isFractionalOrExponential = fractional || exponential; - const isLessThanMaxSafeInt = - digits && - (digits.length < MAX_DIGITS || - (digits.length === MAX_DIGITS && digits <= MAX_INT)); // With a fixed number of digits, we can correctly use lexicographical comparison to do a numeric comparison - - if (isString || isFractionalOrExponential || isLessThanMaxSafeInt) - return text; - - return '"' + text + 'n"'; - }, - ); - - return originalParse(serializedData, (key, value, context) => - convertMarkedBigIntsReviver(key, value, context, reviver), - ); +const lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); +//# sourceMappingURL=index.js.map +;// CONCATENATED MODULE: ./node_modules/.pnpm/@actions+http-client@4.0.1/node_modules/@actions/http-client/lib/auth.js +var auth_awaiter = (undefined && undefined.__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()); + }); }; - - - -;// CONCATENATED MODULE: ./node_modules/.pnpm/@octokit+request-error@7.1.0/node_modules/@octokit/request-error/dist-src/index.js -class RequestError extends Error { - name; - /** - * http status code - */ - status; - /** - * Request options that lead to the error. - */ - request; - /** - * Response object if a response was received - */ - response; - constructor(message, statusCode, options) { - super(message, { cause: options.cause }); - this.name = "HttpError"; - this.status = Number.parseInt(statusCode); - if (Number.isNaN(this.status)) { - this.status = 0; +class BasicCredentialHandler { + constructor(username, password) { + this.username = username; + this.password = password; } - /* v8 ignore else -- @preserve -- Bug with vitest coverage where it sees an else branch that doesn't exist */ - if ("response" in options) { - this.response = options.response; + prepareRequest(options) { + if (!options.headers) { + throw Error('The request has no headers'); + } + options.headers['Authorization'] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString('base64')}`; } - const requestCopy = Object.assign({}, options.request); - if (options.request.headers.authorization) { - requestCopy.headers = Object.assign({}, options.request.headers, { - authorization: options.request.headers.authorization.replace( - /(? { + 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 id_token; + }); + } + static getIDToken(audience) { + return oidc_utils_awaiter(this, void 0, void 0, function* () { + try { + // New ID Token is requested from action service + let id_token_url = oidc_utils_OidcClient.getIDTokenUrl(); + if (audience) { + const encodedAudience = encodeURIComponent(audience); + id_token_url = `${id_token_url}&audience=${encodedAudience}`; + } + debug(`ID token url is ${id_token_url}`); + const id_token = yield oidc_utils_OidcClient.getCall(id_token_url); + setSecret(id_token); + return id_token; + } + catch (error) { + throw new Error(`Error message: ${error.message}`); + } + }); + } } +//# sourceMappingURL=oidc-utils.js.map +;// CONCATENATED MODULE: ./node_modules/.pnpm/@actions+core@3.0.1/node_modules/@actions/core/lib/summary.js +var summary_awaiter = (undefined && undefined.__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()); + }); +}; -// pkg/dist-src/fetch-wrapper.js -var noop = () => ""; -async function fetchWrapper(requestOptions) { - const fetch = requestOptions.request?.fetch || globalThis.fetch; - if (!fetch) { - throw new Error( - "fetch is not set. Please pass a fetch implementation as new Octokit({ request: { fetch }}). Learn more at https://github.com/octokit/octokit.js/#fetch-missing" - ); - } - const log = requestOptions.request?.log || console; - const parseSuccessResponseBody = requestOptions.request?.parseSuccessResponseBody !== false; - const body = dist_bundle_isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body) ? JSONStringify(requestOptions.body) : requestOptions.body; - const requestHeaders = Object.fromEntries( - Object.entries(requestOptions.headers).map(([name, value]) => [ - name, - String(value) - ]) - ); - let fetchResponse; - try { - fetchResponse = await fetch(requestOptions.url, { - method: requestOptions.method, - body, - redirect: requestOptions.request?.redirect, - headers: requestHeaders, - signal: requestOptions.request?.signal, - // duplex must be set if request.body is ReadableStream or Async Iterables. - // See https://fetch.spec.whatwg.org/#dom-requestinit-duplex. - ...requestOptions.body && { duplex: "half" } - }); - } catch (error) { - let message = "Unknown Error"; - if (error instanceof Error) { - if (error.name === "AbortError") { - error.status = 500; - throw error; - } - message = error.message; - if (error.name === "TypeError" && "cause" in error) { - if (error.cause instanceof Error) { - message = error.cause.message; - } else if (typeof error.cause === "string") { - message = error.cause; - } - } +const { access, appendFile, writeFile } = external_fs_namespaceObject.promises; +const SUMMARY_ENV_VAR = 'GITHUB_STEP_SUMMARY'; +const SUMMARY_DOCS_URL = 'https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#adding-a-job-summary'; +class Summary { + constructor() { + this._buffer = ''; } - const requestError = new RequestError(message, 500, { - request: requestOptions - }); - requestError.cause = error; - throw requestError; - } - const status = fetchResponse.status; - const url = fetchResponse.url; - const responseHeaders = {}; - for (const [key, value] of fetchResponse.headers) { - responseHeaders[key] = value; - } - const octokitResponse = { - url, - status, - headers: responseHeaders, - data: "" - }; - if ("deprecation" in responseHeaders) { - const matches = responseHeaders.link && responseHeaders.link.match(/<([^<>]+)>; rel="deprecation"/); - const deprecationLink = matches && matches.pop(); - log.warn( - `[@octokit/request] "${requestOptions.method} ${requestOptions.url}" is deprecated. It is scheduled to be removed on ${responseHeaders.sunset}${deprecationLink ? `. See ${deprecationLink}` : ""}` - ); - } - if (status === 204 || status === 205) { - return octokitResponse; - } - if (requestOptions.method === "HEAD") { - if (status < 400) { - return octokitResponse; + /** + * 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 summary_awaiter(this, void 0, void 0, function* () { + if (this._filePath) { + return this._filePath; + } + const pathFromEnv = process.env[SUMMARY_ENV_VAR]; + if (!pathFromEnv) { + throw new Error(`Unable to find environment variable for $${SUMMARY_ENV_VAR}. Check if your runtime environment supports job summaries.`); + } + try { + yield access(pathFromEnv, external_fs_namespaceObject.constants.R_OK | external_fs_namespaceObject.constants.W_OK); + } + catch (_a) { + throw new Error(`Unable to access summary file: '${pathFromEnv}'. Check if the file has correct read/write permissions.`); + } + this._filePath = pathFromEnv; + return this._filePath; + }); } - throw new RequestError(fetchResponse.statusText, status, { - response: octokitResponse, - request: requestOptions - }); - } - if (status === 304) { - octokitResponse.data = await getResponseData(fetchResponse); - throw new RequestError("Not modified", status, { - response: octokitResponse, - request: requestOptions - }); - } - if (status >= 400) { - octokitResponse.data = await getResponseData(fetchResponse); - throw new RequestError(toErrorMessage(octokitResponse.data), status, { - response: octokitResponse, - request: requestOptions - }); - } - octokitResponse.data = parseSuccessResponseBody ? await getResponseData(fetchResponse) : fetchResponse.body; - return octokitResponse; -} -async function getResponseData(response) { - const contentType = response.headers.get("content-type"); - if (!contentType) { - return response.text().catch(noop); - } - const mimetype = (0,fast_content_type_parse/* safeParse */.xL)(contentType); - if (isJSONResponse(mimetype)) { - let text = ""; - try { - text = await response.text(); - return JSONParse(text); - } catch (err) { - return text; + /** + * 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}>`; + } + return `<${tag}${htmlAttrs}>${content}`; } - } else if (mimetype.type.startsWith("text/") || mimetype.parameters.charset?.toLowerCase() === "utf-8") { - return response.text().catch(noop); - } else { - return response.arrayBuffer().catch( - /* v8 ignore next -- @preserve */ - () => new ArrayBuffer(0) - ); - } -} -function isJSONResponse(mimetype) { - return mimetype.type === "application/json" || mimetype.type === "application/scim+json"; -} -function toErrorMessage(data) { - if (typeof data === "string") { - return data; - } - if (data instanceof ArrayBuffer) { - return "Unknown error"; - } - if ("message" in data) { - const suffix = "documentation_url" in data ? ` - ${data.documentation_url}` : ""; - return Array.isArray(data.errors) ? `${data.message}: ${data.errors.map((v) => JSON.stringify(v)).join(", ")}${suffix}` : `${data.message}${suffix}`; - } - return `Unknown error: ${JSON.stringify(data)}`; -} - -// pkg/dist-src/with-defaults.js -function dist_bundle_withDefaults(oldEndpoint, newDefaults) { - const endpoint2 = oldEndpoint.defaults(newDefaults); - const newApi = function(route, parameters) { - const endpointOptions = endpoint2.merge(route, parameters); - if (!endpointOptions.request || !endpointOptions.request.hook) { - return fetchWrapper(endpoint2.parse(endpointOptions)); + /** + * 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 summary_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(); + }); } - const request2 = (route2, parameters2) => { - return fetchWrapper( - endpoint2.parse(endpoint2.merge(route2, parameters2)) - ); - }; - Object.assign(request2, { - endpoint: endpoint2, - defaults: dist_bundle_withDefaults.bind(null, endpoint2) - }); - return endpointOptions.request.hook(request2, endpointOptions); - }; - return Object.assign(newApi, { - endpoint: endpoint2, - defaults: dist_bundle_withDefaults.bind(null, endpoint2) - }); -} - -// pkg/dist-src/index.js -var request = dist_bundle_withDefaults(endpoint, defaults_default); - -/* v8 ignore next -- @preserve */ -/* v8 ignore else -- @preserve */ - -;// CONCATENATED MODULE: ./node_modules/.pnpm/@octokit+graphql@9.0.3/node_modules/@octokit/graphql/dist-bundle/index.js -// pkg/dist-src/index.js - - - -// pkg/dist-src/version.js -var graphql_dist_bundle_VERSION = "0.0.0-development"; - -// pkg/dist-src/with-defaults.js - - -// pkg/dist-src/graphql.js - - -// pkg/dist-src/error.js -function _buildMessageForResponseErrors(data) { - return `Request failed due to following response errors: -` + data.errors.map((e) => ` - ${e.message}`).join("\n"); -} -var GraphqlResponseError = class extends Error { - constructor(request2, headers, response) { - super(_buildMessageForResponseErrors(response)); - this.request = request2; - this.headers = headers; - this.response = response; - this.errors = response.errors; - this.data = response.data; - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); + /** + * Clears the summary buffer and wipes the summary file + * + * @returns {Summary} summary instance + */ + clear() { + return summary_awaiter(this, void 0, void 0, function* () { + return this.emptyBuffer().write({ overwrite: true }); + }); } - } - name = "GraphqlResponseError"; - errors; - data; -}; - -// pkg/dist-src/graphql.js -var NON_VARIABLE_OPTIONS = [ - "method", - "baseUrl", - "url", - "headers", - "request", - "query", - "mediaType", - "operationName" -]; -var FORBIDDEN_VARIABLE_OPTIONS = ["query", "method", "url"]; -var GHES_V3_SUFFIX_REGEX = /\/api\/v3\/?$/; -function graphql(request2, query, options) { - if (options) { - if (typeof query === "string" && "query" in options) { - return Promise.reject( - new Error(`[@octokit/graphql] "query" cannot be used as variable name`) - ); + /** + * Returns the current summary buffer as a string + * + * @returns {string} string of summary buffer + */ + stringify() { + return this._buffer; } - for (const key in options) { - if (!FORBIDDEN_VARIABLE_OPTIONS.includes(key)) continue; - return Promise.reject( - new Error( - `[@octokit/graphql] "${key}" cannot be used as variable name` - ) - ); + /** + * If the summary buffer is empty + * + * @returns {boolen} true if the buffer is empty + */ + isEmptyBuffer() { + return this._buffer.length === 0; } - } - const parsedOptions = typeof query === "string" ? Object.assign({ query }, options) : query; - const requestOptions = Object.keys( - parsedOptions - ).reduce((result, key) => { - if (NON_VARIABLE_OPTIONS.includes(key)) { - result[key] = parsedOptions[key]; - return result; + /** + * Resets the summary buffer without writing to summary file + * + * @returns {Summary} summary instance + */ + emptyBuffer() { + this._buffer = ''; + return this; } - if (!result.variables) { - result.variables = {}; + /** + * 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; } - result.variables[key] = parsedOptions[key]; - return result; - }, {}); - const baseUrl = parsedOptions.baseUrl || request2.endpoint.DEFAULTS.baseUrl; - if (GHES_V3_SUFFIX_REGEX.test(baseUrl)) { - requestOptions.url = baseUrl.replace(GHES_V3_SUFFIX_REGEX, "/api/graphql"); - } - return request2(requestOptions).then((response) => { - if (response.data.errors) { - const headers = {}; - for (const key of Object.keys(response.headers)) { - headers[key] = response.headers[key]; - } - throw new GraphqlResponseError( - requestOptions, - headers, - response.data - ); + /** + * Adds the operating system-specific end-of-line marker to the buffer + * + * @returns {Summary} summary instance + */ + addEOL() { + return this.addRaw(external_os_namespaceObject.EOL); + } + /** + * 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(); + } + /** + * 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(); + } + /** + * 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(); } - return response.data.data; - }); } +const _summary = new Summary(); +/** + * @deprecated use `core.summary` + */ +const markdownSummary = (/* unused pure expression or super */ null && (_summary)); +const summary = (/* unused pure expression or super */ null && (_summary)); +//# sourceMappingURL=summary.js.map +;// CONCATENATED MODULE: ./node_modules/.pnpm/@actions+core@3.0.1/node_modules/@actions/core/lib/path-utils.js -// pkg/dist-src/with-defaults.js -function graphql_dist_bundle_withDefaults(request2, newDefaults) { - const newRequest = request2.defaults(newDefaults); - const newApi = (query, options) => { - return graphql(newRequest, query, options); - }; - return Object.assign(newApi, { - defaults: graphql_dist_bundle_withDefaults.bind(null, newRequest), - endpoint: newRequest.endpoint - }); +/** + * 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, '/'); } - -// pkg/dist-src/index.js -var graphql2 = graphql_dist_bundle_withDefaults(request, { - headers: { - "user-agent": `octokit-graphql.js/${graphql_dist_bundle_VERSION} ${getUserAgent()}` - }, - method: "POST", - url: "/graphql" -}); -function withCustomRequest(customRequest) { - return graphql_dist_bundle_withDefaults(customRequest, { - method: "POST", - url: "/graphql" - }); +/** + * 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, '\\'); } +/** + * 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); +} +//# sourceMappingURL=path-utils.js.map +;// CONCATENATED MODULE: external "string_decoder" +const external_string_decoder_namespaceObject = require("string_decoder"); +// EXTERNAL MODULE: external "events" +var external_events_ = __nccwpck_require__(4434); +;// CONCATENATED MODULE: external "child_process" +const external_child_process_namespaceObject = require("child_process"); +// EXTERNAL MODULE: external "assert" +var external_assert_ = __nccwpck_require__(2613); +;// CONCATENATED MODULE: ./node_modules/.pnpm/@actions+io@3.0.2/node_modules/@actions/io/lib/io-util.js +var io_util_awaiter = (undefined && undefined.__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()); + }); +}; -;// CONCATENATED MODULE: ./node_modules/.pnpm/@octokit+auth-token@6.0.0/node_modules/@octokit/auth-token/dist-bundle/index.js -// pkg/dist-src/is-jwt.js -var b64url = "(?:[a-zA-Z0-9_-]+)"; -var sep = "\\."; -var jwtRE = new RegExp(`^${b64url}${sep}${b64url}${sep}${b64url}$`); -var isJWT = jwtRE.test.bind(jwtRE); - -// pkg/dist-src/auth.js -async function auth(token) { - const isApp = isJWT(token); - const isInstallation = token.startsWith("v1.") || token.startsWith("ghs_"); - const isUserToServer = token.startsWith("ghu_"); - const tokenType = isApp ? "app" : isInstallation ? "installation" : isUserToServer ? "user-to-server" : "oauth"; - return { - type: "token", - token, - tokenType - }; -} - -// pkg/dist-src/with-authorization-prefix.js -function withAuthorizationPrefix(token) { - if (token.split(/\./).length === 3) { - return `bearer ${token}`; - } - return `token ${token}`; +const { chmod, copyFile, lstat, mkdir, open: io_util_open, readdir, rename, rm, rmdir, stat, symlink, unlink } = external_fs_namespaceObject.promises; +// export const {open} = 'fs' +const IS_WINDOWS = process.platform === 'win32'; +/** + * Custom implementation of readlink to ensure Windows junctions + * maintain trailing backslash for backward compatibility with Node.js < 24 + * + * In Node.js 20, Windows junctions (directory symlinks) always returned paths + * with trailing backslashes. Node.js 24 removed this behavior, which breaks + * code that relied on this format for path operations. + * + * This implementation restores the Node 20 behavior by adding a trailing + * backslash to all junction results on Windows. + */ +function readlink(fsPath) { + return io_util_awaiter(this, void 0, void 0, function* () { + const result = yield fs.promises.readlink(fsPath); + // On Windows, restore Node 20 behavior: add trailing backslash to all results + // since junctions on Windows are always directory links + if (IS_WINDOWS && !result.endsWith('\\')) { + return `${result}\\`; + } + return result; + }); } - -// pkg/dist-src/hook.js -async function hook(token, request, route, parameters) { - const endpoint = request.endpoint.merge( - route, - parameters - ); - endpoint.headers.authorization = withAuthorizationPrefix(token); - return request(endpoint); +// See https://github.com/nodejs/node/blob/d0153aee367422d0858105abec186da4dff0a0c5/deps/uv/include/uv/win.h#L691 +const UV_FS_O_EXLOCK = 0x10000000; +const READONLY = external_fs_namespaceObject.constants.O_RDONLY; +function exists(fsPath) { + return io_util_awaiter(this, void 0, void 0, function* () { + try { + yield stat(fsPath); + } + catch (err) { + if (err.code === 'ENOENT') { + return false; + } + throw err; + } + return true; + }); } - -// pkg/dist-src/index.js -var createTokenAuth = function createTokenAuth2(token) { - if (!token) { - throw new Error("[@octokit/auth-token] No token passed to createTokenAuth"); - } - if (typeof token !== "string") { - throw new Error( - "[@octokit/auth-token] Token passed to createTokenAuth is not a string" - ); - } - token = token.replace(/^(token|bearer) +/i, ""); - return Object.assign(auth.bind(null, token), { - hook: hook.bind(null, token) - }); -}; - - -;// CONCATENATED MODULE: ./node_modules/.pnpm/@octokit+core@7.0.6/node_modules/@octokit/core/dist-src/version.js -const version_VERSION = "7.0.6"; - - -;// CONCATENATED MODULE: ./node_modules/.pnpm/@octokit+core@7.0.6/node_modules/@octokit/core/dist-src/index.js - - - - - - -const dist_src_noop = () => { -}; -const consoleWarn = console.warn.bind(console); -const consoleError = console.error.bind(console); -function createLogger(logger = {}) { - if (typeof logger.debug !== "function") { - logger.debug = dist_src_noop; - } - if (typeof logger.info !== "function") { - logger.info = dist_src_noop; - } - if (typeof logger.warn !== "function") { - logger.warn = consoleWarn; - } - if (typeof logger.error !== "function") { - logger.error = consoleError; - } - return logger; +function isDirectory(fsPath_1) { + return io_util_awaiter(this, arguments, void 0, function* (fsPath, useStat = false) { + const stats = useStat ? yield stat(fsPath) : yield lstat(fsPath); + return stats.isDirectory(); + }); } -const userAgentTrail = `octokit-core.js/${version_VERSION} ${getUserAgent()}`; -class Octokit { - static VERSION = version_VERSION; - static defaults(defaults) { - const OctokitWithDefaults = class extends this { - constructor(...args) { - const options = args[0] || {}; - if (typeof defaults === "function") { - super(defaults(options)); - return; - } - super( - Object.assign( - {}, - defaults, - options, - options.userAgent && defaults.userAgent ? { - userAgent: `${options.userAgent} ${defaults.userAgent}` - } : null - ) - ); - } - }; - return OctokitWithDefaults; - } - static plugins = []; - /** - * Attach a plugin (or many) to your Octokit instance. - * - * @example - * const API = Octokit.plugin(plugin1, plugin2, plugin3, ...) - */ - static plugin(...newPlugins) { - const currentPlugins = this.plugins; - const NewOctokit = class extends this { - static plugins = currentPlugins.concat( - newPlugins.filter((plugin) => !currentPlugins.includes(plugin)) - ); - }; - return NewOctokit; - } - constructor(options = {}) { - const hook = new before_after_hook.Collection(); - const requestDefaults = { - baseUrl: request.endpoint.DEFAULTS.baseUrl, - headers: {}, - request: Object.assign({}, options.request, { - // @ts-ignore internal usage only, no need to type - hook: hook.bind(null, "request") - }), - mediaType: { - previews: [], - format: "" - } - }; - requestDefaults.headers["user-agent"] = options.userAgent ? `${options.userAgent} ${userAgentTrail}` : userAgentTrail; - if (options.baseUrl) { - requestDefaults.baseUrl = options.baseUrl; - } - if (options.previews) { - requestDefaults.mediaType.previews = options.previews; - } - if (options.timeZone) { - requestDefaults.headers["time-zone"] = options.timeZone; +/** + * 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'); } - this.request = request.defaults(requestDefaults); - this.graphql = withCustomRequest(this.request).defaults(requestDefaults); - this.log = createLogger(options.log); - this.hook = hook; - if (!options.authStrategy) { - if (!options.auth) { - this.auth = async () => ({ - type: "unauthenticated" - }); - } else { - const auth = createTokenAuth(options.auth); - hook.wrap("request", auth.hook); - this.auth = auth; - } - } else { - const { authStrategy, ...otherOptions } = options; - const auth = authStrategy( - Object.assign( - { - request: this.request, - log: this.log, - // we pass the current octokit instance as well as its constructor options - // to allow for authentication strategies that return a new octokit instance - // that shares the same internal state as the current one. The original - // requirement for this was the "event-octokit" authentication strategy - // of https://github.com/probot/octokit-auth-probot. - octokit: this, - octokitOptions: otherOptions - }, - options.auth - ) - ); - hook.wrap("request", auth.hook); - this.auth = auth; + if (IS_WINDOWS) { + return (p.startsWith('\\') || /^[A-Z]:/i.test(p) // e.g. \ or \hello or \\hello + ); // e.g. C: or C:\hello } - const classConstructor = this.constructor; - for (let i = 0; i < classConstructor.plugins.length; ++i) { - Object.assign(this, classConstructor.plugins[i](this, options)); + return p.startsWith('/'); +} +/** + * 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 io_util_awaiter(this, void 0, void 0, function* () { + let stats = undefined; + try { + // test file exists + stats = yield 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 (IS_WINDOWS) { + // on Windows, test for valid extension + const upperExt = external_path_namespaceObject.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 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 (IS_WINDOWS) { + // preserve the case of the actual file (since an extension was appended) + try { + const directory = external_path_namespaceObject.dirname(filePath); + const upperName = external_path_namespaceObject.basename(filePath).toUpperCase(); + for (const actualName of yield readdir(directory)) { + if (upperName === actualName.toUpperCase()) { + filePath = external_path_namespaceObject.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; + } + } + } + } + return ''; + }); +} +function normalizeSeparators(p) { + p = p || ''; + if (IS_WINDOWS) { + // convert slashes on Windows + p = p.replace(/\//g, '\\'); + // remove redundant slashes + return p.replace(/\\\\+/g, '\\'); } - } - // assigned during constructor - request; - graphql; - log; - hook; - // TODO: type `octokit.auth` based on passed options.authStrategy - auth; + // 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 && + process.getgid !== undefined && + stats.gid === process.getgid()) || + ((stats.mode & 64) > 0 && + process.getuid !== undefined && + 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`; +} +//# sourceMappingURL=io-util.js.map +;// CONCATENATED MODULE: ./node_modules/.pnpm/@actions+io@3.0.2/node_modules/@actions/io/lib/io.js +var io_awaiter = (undefined && undefined.__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()); + }); +}; -/***/ }), - -/***/ 6212: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { - -"use strict"; -__nccwpck_require__.r(__webpack_exports__); -/* harmony export */ __nccwpck_require__.d(__webpack_exports__, { -/* harmony export */ composePaginateRest: () => (/* binding */ composePaginateRest), -/* harmony export */ isPaginatingEndpoint: () => (/* binding */ isPaginatingEndpoint), -/* harmony export */ paginateRest: () => (/* binding */ paginateRest), -/* harmony export */ paginatingEndpoints: () => (/* binding */ paginatingEndpoints) -/* harmony export */ }); -// pkg/dist-src/version.js -var VERSION = "0.0.0-development"; - -// pkg/dist-src/normalize-paginated-list-response.js -function normalizePaginatedListResponse(response) { - if (!response.data) { - return { - ...response, - data: [] - }; - } - const responseNeedsNormalization = ("total_count" in response.data || "total_commits" in response.data) && !("url" in response.data); - if (!responseNeedsNormalization) return response; - const incompleteResults = response.data.incomplete_results; - const repositorySelection = response.data.repository_selection; - const totalCount = response.data.total_count; - const totalCommits = response.data.total_commits; - delete response.data.incomplete_results; - delete response.data.repository_selection; - delete response.data.total_count; - delete response.data.total_commits; - const namespaceKey = Object.keys(response.data)[0]; - const data = response.data[namespaceKey]; - response.data = data; - if (typeof incompleteResults !== "undefined") { - response.data.incomplete_results = incompleteResults; - } - if (typeof repositorySelection !== "undefined") { - response.data.repository_selection = repositorySelection; - } - response.data.total_count = totalCount; - response.data.total_commits = totalCommits; - return response; +/** + * 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 cp(source_1, dest_1) { + return io_awaiter(this, arguments, void 0, function* (source, dest, options = {}) { + 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 io_copyFile(source, newDest, force); + } + }); } - -// pkg/dist-src/iterator.js -function iterator(octokit, route, parameters) { - const options = typeof route === "function" ? route.endpoint(parameters) : octokit.request.endpoint(route, parameters); - const requestMethod = typeof route === "function" ? route : octokit.request; - const method = options.method; - const headers = options.headers; - let url = options.url; - return { - [Symbol.asyncIterator]: () => ({ - async next() { - if (!url) return { done: true }; - try { - const response = await requestMethod({ method, url, headers }); - const normalizedResponse = normalizePaginatedListResponse(response); - url = ((normalizedResponse.headers.link || "").match( - /<([^<>]+)>;\s*rel="next"/ - ) || [])[1]; - if (!url && "total_commits" in normalizedResponse.data) { - const parsedUrl = new URL(normalizedResponse.url); - const params = parsedUrl.searchParams; - const page = parseInt(params.get("page") || "1", 10); - const per_page = parseInt(params.get("per_page") || "250", 10); - if (page * per_page < normalizedResponse.data.total_commits) { - params.set("page", String(page + 1)); - url = parsedUrl.toString(); +/** + * Moves a path. + * + * @param source source path + * @param dest destination path + * @param options optional. See MoveOptions. + */ +function mv(source_1, dest_1) { + return io_awaiter(this, arguments, void 0, function* (source, dest, options = {}) { + 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); } - } - return { value: normalizedResponse }; - } catch (error) { - if (error.status !== 409) throw error; - url = ""; - return { - value: { - status: 200, - headers: {}, - data: [] + 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); + }); } - -// pkg/dist-src/paginate.js -function paginate(octokit, route, parameters, mapFn) { - if (typeof parameters === "function") { - mapFn = parameters; - parameters = void 0; - } - return gather( - octokit, - [], - iterator(octokit, route, parameters)[Symbol.asyncIterator](), - mapFn - ); +/** + * Remove a path recursively with force + * + * @param inputPath path to remove + */ +function rmRF(inputPath) { + return io_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}`); + } + }); } -function gather(octokit, results, iterator2, mapFn) { - return iterator2.next().then((result) => { - if (result.done) { - return results; - } - let earlyExit = false; - function done() { - earlyExit = true; - } - results = results.concat( - mapFn ? mapFn(result.value, done) : result.value.data - ); - if (earlyExit) { - return results; - } - return gather(octokit, results, iterator2, mapFn); - }); +/** + * 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 io_awaiter(this, void 0, void 0, function* () { + ok(fsPath, 'a path argument must be provided'); + yield ioUtil.mkdir(fsPath, { recursive: true }); + }); } - -// pkg/dist-src/compose-paginate.js -var composePaginateRest = Object.assign(paginate, { - iterator -}); - -// pkg/dist-src/generated/paginating-endpoints.js -var paginatingEndpoints = [ - "GET /advisories", - "GET /app/hook/deliveries", - "GET /app/installation-requests", - "GET /app/installations", - "GET /assignments/{assignment_id}/accepted_assignments", - "GET /classrooms", - "GET /classrooms/{classroom_id}/assignments", - "GET /enterprises/{enterprise}/code-security/configurations", - "GET /enterprises/{enterprise}/code-security/configurations/{configuration_id}/repositories", - "GET /enterprises/{enterprise}/dependabot/alerts", - "GET /enterprises/{enterprise}/teams", - "GET /enterprises/{enterprise}/teams/{enterprise-team}/memberships", - "GET /enterprises/{enterprise}/teams/{enterprise-team}/organizations", - "GET /events", - "GET /gists", - "GET /gists/public", - "GET /gists/starred", - "GET /gists/{gist_id}/comments", - "GET /gists/{gist_id}/commits", - "GET /gists/{gist_id}/forks", - "GET /installation/repositories", - "GET /issues", - "GET /licenses", - "GET /marketplace_listing/plans", - "GET /marketplace_listing/plans/{plan_id}/accounts", - "GET /marketplace_listing/stubbed/plans", - "GET /marketplace_listing/stubbed/plans/{plan_id}/accounts", - "GET /networks/{owner}/{repo}/events", - "GET /notifications", - "GET /organizations", - "GET /organizations/{org}/dependabot/repository-access", - "GET /orgs/{org}/actions/cache/usage-by-repository", - "GET /orgs/{org}/actions/hosted-runners", - "GET /orgs/{org}/actions/permissions/repositories", - "GET /orgs/{org}/actions/permissions/self-hosted-runners/repositories", - "GET /orgs/{org}/actions/runner-groups", - "GET /orgs/{org}/actions/runner-groups/{runner_group_id}/hosted-runners", - "GET /orgs/{org}/actions/runner-groups/{runner_group_id}/repositories", - "GET /orgs/{org}/actions/runner-groups/{runner_group_id}/runners", - "GET /orgs/{org}/actions/runners", - "GET /orgs/{org}/actions/secrets", - "GET /orgs/{org}/actions/secrets/{secret_name}/repositories", - "GET /orgs/{org}/actions/variables", - "GET /orgs/{org}/actions/variables/{name}/repositories", - "GET /orgs/{org}/attestations/repositories", - "GET /orgs/{org}/attestations/{subject_digest}", - "GET /orgs/{org}/blocks", - "GET /orgs/{org}/campaigns", - "GET /orgs/{org}/code-scanning/alerts", - "GET /orgs/{org}/code-security/configurations", - "GET /orgs/{org}/code-security/configurations/{configuration_id}/repositories", - "GET /orgs/{org}/codespaces", - "GET /orgs/{org}/codespaces/secrets", - "GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories", - "GET /orgs/{org}/copilot/billing/seats", - "GET /orgs/{org}/copilot/metrics", - "GET /orgs/{org}/dependabot/alerts", - "GET /orgs/{org}/dependabot/secrets", - "GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories", - "GET /orgs/{org}/events", - "GET /orgs/{org}/failed_invitations", - "GET /orgs/{org}/hooks", - "GET /orgs/{org}/hooks/{hook_id}/deliveries", - "GET /orgs/{org}/insights/api/route-stats/{actor_type}/{actor_id}", - "GET /orgs/{org}/insights/api/subject-stats", - "GET /orgs/{org}/insights/api/user-stats/{user_id}", - "GET /orgs/{org}/installations", - "GET /orgs/{org}/invitations", - "GET /orgs/{org}/invitations/{invitation_id}/teams", - "GET /orgs/{org}/issues", - "GET /orgs/{org}/members", - "GET /orgs/{org}/members/{username}/codespaces", - "GET /orgs/{org}/migrations", - "GET /orgs/{org}/migrations/{migration_id}/repositories", - "GET /orgs/{org}/organization-roles/{role_id}/teams", - "GET /orgs/{org}/organization-roles/{role_id}/users", - "GET /orgs/{org}/outside_collaborators", - "GET /orgs/{org}/packages", - "GET /orgs/{org}/packages/{package_type}/{package_name}/versions", - "GET /orgs/{org}/personal-access-token-requests", - "GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories", - "GET /orgs/{org}/personal-access-tokens", - "GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories", - "GET /orgs/{org}/private-registries", - "GET /orgs/{org}/projects", - "GET /orgs/{org}/projectsV2", - "GET /orgs/{org}/projectsV2/{project_number}/fields", - "GET /orgs/{org}/projectsV2/{project_number}/items", - "GET /orgs/{org}/properties/values", - "GET /orgs/{org}/public_members", - "GET /orgs/{org}/repos", - "GET /orgs/{org}/rulesets", - "GET /orgs/{org}/rulesets/rule-suites", - "GET /orgs/{org}/rulesets/{ruleset_id}/history", - "GET /orgs/{org}/secret-scanning/alerts", - "GET /orgs/{org}/security-advisories", - "GET /orgs/{org}/settings/immutable-releases/repositories", - "GET /orgs/{org}/settings/network-configurations", - "GET /orgs/{org}/team/{team_slug}/copilot/metrics", - "GET /orgs/{org}/teams", - "GET /orgs/{org}/teams/{team_slug}/discussions", - "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments", - "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions", - "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions", - "GET /orgs/{org}/teams/{team_slug}/invitations", - "GET /orgs/{org}/teams/{team_slug}/members", - "GET /orgs/{org}/teams/{team_slug}/projects", - "GET /orgs/{org}/teams/{team_slug}/repos", - "GET /orgs/{org}/teams/{team_slug}/teams", - "GET /projects/{project_id}/collaborators", - "GET /repos/{owner}/{repo}/actions/artifacts", - "GET /repos/{owner}/{repo}/actions/caches", - "GET /repos/{owner}/{repo}/actions/organization-secrets", - "GET /repos/{owner}/{repo}/actions/organization-variables", - "GET /repos/{owner}/{repo}/actions/runners", - "GET /repos/{owner}/{repo}/actions/runs", - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts", - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs", - "GET /repos/{owner}/{repo}/actions/secrets", - "GET /repos/{owner}/{repo}/actions/variables", - "GET /repos/{owner}/{repo}/actions/workflows", - "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs", - "GET /repos/{owner}/{repo}/activity", - "GET /repos/{owner}/{repo}/assignees", - "GET /repos/{owner}/{repo}/attestations/{subject_digest}", - "GET /repos/{owner}/{repo}/branches", - "GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations", - "GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs", - "GET /repos/{owner}/{repo}/code-scanning/alerts", - "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances", - "GET /repos/{owner}/{repo}/code-scanning/analyses", - "GET /repos/{owner}/{repo}/codespaces", - "GET /repos/{owner}/{repo}/codespaces/devcontainers", - "GET /repos/{owner}/{repo}/codespaces/secrets", - "GET /repos/{owner}/{repo}/collaborators", - "GET /repos/{owner}/{repo}/comments", - "GET /repos/{owner}/{repo}/comments/{comment_id}/reactions", - "GET /repos/{owner}/{repo}/commits", - "GET /repos/{owner}/{repo}/commits/{commit_sha}/comments", - "GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls", - "GET /repos/{owner}/{repo}/commits/{ref}/check-runs", - "GET /repos/{owner}/{repo}/commits/{ref}/check-suites", - "GET /repos/{owner}/{repo}/commits/{ref}/status", - "GET /repos/{owner}/{repo}/commits/{ref}/statuses", - "GET /repos/{owner}/{repo}/compare/{basehead}", - "GET /repos/{owner}/{repo}/compare/{base}...{head}", - "GET /repos/{owner}/{repo}/contributors", - "GET /repos/{owner}/{repo}/dependabot/alerts", - "GET /repos/{owner}/{repo}/dependabot/secrets", - "GET /repos/{owner}/{repo}/deployments", - "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses", - "GET /repos/{owner}/{repo}/environments", - "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies", - "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps", - "GET /repos/{owner}/{repo}/environments/{environment_name}/secrets", - "GET /repos/{owner}/{repo}/environments/{environment_name}/variables", - "GET /repos/{owner}/{repo}/events", - "GET /repos/{owner}/{repo}/forks", - "GET /repos/{owner}/{repo}/hooks", - "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries", - "GET /repos/{owner}/{repo}/invitations", - "GET /repos/{owner}/{repo}/issues", - "GET /repos/{owner}/{repo}/issues/comments", - "GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions", - "GET /repos/{owner}/{repo}/issues/events", - "GET /repos/{owner}/{repo}/issues/{issue_number}/comments", - "GET /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by", - "GET /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocking", - "GET /repos/{owner}/{repo}/issues/{issue_number}/events", - "GET /repos/{owner}/{repo}/issues/{issue_number}/labels", - "GET /repos/{owner}/{repo}/issues/{issue_number}/reactions", - "GET /repos/{owner}/{repo}/issues/{issue_number}/sub_issues", - "GET /repos/{owner}/{repo}/issues/{issue_number}/timeline", - "GET /repos/{owner}/{repo}/keys", - "GET /repos/{owner}/{repo}/labels", - "GET /repos/{owner}/{repo}/milestones", - "GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels", - "GET /repos/{owner}/{repo}/notifications", - "GET /repos/{owner}/{repo}/pages/builds", - "GET /repos/{owner}/{repo}/projects", - "GET /repos/{owner}/{repo}/pulls", - "GET /repos/{owner}/{repo}/pulls/comments", - "GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions", - "GET /repos/{owner}/{repo}/pulls/{pull_number}/comments", - "GET /repos/{owner}/{repo}/pulls/{pull_number}/commits", - "GET /repos/{owner}/{repo}/pulls/{pull_number}/files", - "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews", - "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments", - "GET /repos/{owner}/{repo}/releases", - "GET /repos/{owner}/{repo}/releases/{release_id}/assets", - "GET /repos/{owner}/{repo}/releases/{release_id}/reactions", - "GET /repos/{owner}/{repo}/rules/branches/{branch}", - "GET /repos/{owner}/{repo}/rulesets", - "GET /repos/{owner}/{repo}/rulesets/rule-suites", - "GET /repos/{owner}/{repo}/rulesets/{ruleset_id}/history", - "GET /repos/{owner}/{repo}/secret-scanning/alerts", - "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations", - "GET /repos/{owner}/{repo}/security-advisories", - "GET /repos/{owner}/{repo}/stargazers", - "GET /repos/{owner}/{repo}/subscribers", - "GET /repos/{owner}/{repo}/tags", - "GET /repos/{owner}/{repo}/teams", - "GET /repos/{owner}/{repo}/topics", - "GET /repositories", - "GET /search/code", - "GET /search/commits", - "GET /search/issues", - "GET /search/labels", - "GET /search/repositories", - "GET /search/topics", - "GET /search/users", - "GET /teams/{team_id}/discussions", - "GET /teams/{team_id}/discussions/{discussion_number}/comments", - "GET /teams/{team_id}/discussions/{discussion_number}/comments/{comment_number}/reactions", - "GET /teams/{team_id}/discussions/{discussion_number}/reactions", - "GET /teams/{team_id}/invitations", - "GET /teams/{team_id}/members", - "GET /teams/{team_id}/projects", - "GET /teams/{team_id}/repos", - "GET /teams/{team_id}/teams", - "GET /user/blocks", - "GET /user/codespaces", - "GET /user/codespaces/secrets", - "GET /user/emails", - "GET /user/followers", - "GET /user/following", - "GET /user/gpg_keys", - "GET /user/installations", - "GET /user/installations/{installation_id}/repositories", - "GET /user/issues", - "GET /user/keys", - "GET /user/marketplace_purchases", - "GET /user/marketplace_purchases/stubbed", - "GET /user/memberships/orgs", - "GET /user/migrations", - "GET /user/migrations/{migration_id}/repositories", - "GET /user/orgs", - "GET /user/packages", - "GET /user/packages/{package_type}/{package_name}/versions", - "GET /user/public_emails", - "GET /user/repos", - "GET /user/repository_invitations", - "GET /user/social_accounts", - "GET /user/ssh_signing_keys", - "GET /user/starred", - "GET /user/subscriptions", - "GET /user/teams", - "GET /users", - "GET /users/{username}/attestations/{subject_digest}", - "GET /users/{username}/events", - "GET /users/{username}/events/orgs/{org}", - "GET /users/{username}/events/public", - "GET /users/{username}/followers", - "GET /users/{username}/following", - "GET /users/{username}/gists", - "GET /users/{username}/gpg_keys", - "GET /users/{username}/keys", - "GET /users/{username}/orgs", - "GET /users/{username}/packages", - "GET /users/{username}/projects", - "GET /users/{username}/projectsV2", - "GET /users/{username}/projectsV2/{project_number}/fields", - "GET /users/{username}/projectsV2/{project_number}/items", - "GET /users/{username}/received_events", - "GET /users/{username}/received_events/public", - "GET /users/{username}/repos", - "GET /users/{username}/social_accounts", - "GET /users/{username}/ssh_signing_keys", - "GET /users/{username}/starred", - "GET /users/{username}/subscriptions" -]; - -// pkg/dist-src/paginating-endpoints.js -function isPaginatingEndpoint(arg) { - if (typeof arg === "string") { - return paginatingEndpoints.includes(arg); - } else { - return false; - } +/** + * 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 io_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 (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; + } + const matches = yield findInPath(tool); + if (matches && matches.length > 0) { + return matches[0]; + } + return ''; + }); } - -// pkg/dist-src/index.js -function paginateRest(octokit) { - return { - paginate: Object.assign(paginate.bind(null, octokit), { - iterator: iterator.bind(null, octokit) - }) - }; +/** + * 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 io_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 (IS_WINDOWS && process.env['PATHEXT']) { + for (const extension of process.env['PATHEXT'].split(external_path_namespaceObject.delimiter)) { + if (extension) { + extensions.push(extension); + } + } + } + // if it's rooted, return it if exists. otherwise return empty. + if (isRooted(tool)) { + const filePath = yield tryGetExecutablePath(tool, extensions); + if (filePath) { + return [filePath]; + } + return []; + } + // if any path separators, return empty + if (tool.includes(external_path_namespaceObject.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(external_path_namespaceObject.delimiter)) { + if (p) { + directories.push(p); + } + } + } + // find all matches + const matches = []; + for (const directory of directories) { + const filePath = yield tryGetExecutablePath(external_path_namespaceObject.join(directory, tool), extensions); + if (filePath) { + matches.push(filePath); + } + } + return matches; + }); } -paginateRest.VERSION = VERSION; - - +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 io_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 io_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 io_copyFile(srcFile, destFile, force) { + return io_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 +;// CONCATENATED MODULE: external "timers" +const external_timers_namespaceObject = require("timers"); +;// CONCATENATED MODULE: ./node_modules/.pnpm/@actions+exec@3.0.0/node_modules/@actions/exec/lib/toolrunner.js +var toolrunner_awaiter = (undefined && undefined.__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()); + }); +}; -/***/ }), -/***/ 9289: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { -"use strict"; -// ESM COMPAT FLAG -__nccwpck_require__.r(__webpack_exports__); -// EXPORTS -__nccwpck_require__.d(__webpack_exports__, { - legacyRestEndpointMethods: () => (/* binding */ legacyRestEndpointMethods), - restEndpointMethods: () => (/* binding */ restEndpointMethods) -}); -;// CONCATENATED MODULE: ./node_modules/.pnpm/@octokit+plugin-rest-endpoint-methods@17.0.0_@octokit+core@7.0.6/node_modules/@octokit/plugin-rest-endpoint-methods/dist-src/version.js -const VERSION = "17.0.0"; -//# sourceMappingURL=version.js.map -;// CONCATENATED MODULE: ./node_modules/.pnpm/@octokit+plugin-rest-endpoint-methods@17.0.0_@octokit+core@7.0.6/node_modules/@octokit/plugin-rest-endpoint-methods/dist-src/generated/endpoints.js -const Endpoints = { - actions: { - addCustomLabelsToSelfHostedRunnerForOrg: [ - "POST /orgs/{org}/actions/runners/{runner_id}/labels" - ], - addCustomLabelsToSelfHostedRunnerForRepo: [ - "POST /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" - ], - addRepoAccessToSelfHostedRunnerGroupInOrg: [ - "PUT /orgs/{org}/actions/runner-groups/{runner_group_id}/repositories/{repository_id}" - ], - addSelectedRepoToOrgSecret: [ - "PUT /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}" - ], - addSelectedRepoToOrgVariable: [ - "PUT /orgs/{org}/actions/variables/{name}/repositories/{repository_id}" - ], - approveWorkflowRun: [ - "POST /repos/{owner}/{repo}/actions/runs/{run_id}/approve" - ], - cancelWorkflowRun: [ - "POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel" - ], - createEnvironmentVariable: [ - "POST /repos/{owner}/{repo}/environments/{environment_name}/variables" - ], - createHostedRunnerForOrg: ["POST /orgs/{org}/actions/hosted-runners"], - createOrUpdateEnvironmentSecret: [ - "PUT /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}" - ], - createOrUpdateOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}"], - createOrUpdateRepoSecret: [ - "PUT /repos/{owner}/{repo}/actions/secrets/{secret_name}" - ], - createOrgVariable: ["POST /orgs/{org}/actions/variables"], - createRegistrationTokenForOrg: [ - "POST /orgs/{org}/actions/runners/registration-token" - ], - createRegistrationTokenForRepo: [ - "POST /repos/{owner}/{repo}/actions/runners/registration-token" - ], - createRemoveTokenForOrg: ["POST /orgs/{org}/actions/runners/remove-token"], - createRemoveTokenForRepo: [ - "POST /repos/{owner}/{repo}/actions/runners/remove-token" - ], - createRepoVariable: ["POST /repos/{owner}/{repo}/actions/variables"], - createWorkflowDispatch: [ - "POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches" - ], - deleteActionsCacheById: [ - "DELETE /repos/{owner}/{repo}/actions/caches/{cache_id}" +/* eslint-disable @typescript-eslint/unbound-method */ +const toolrunner_IS_WINDOWS = process.platform === 'win32'; +/* + * Class for running command line tools. Handles quoting and arg parsing in a platform agnostic way. + */ +class ToolRunner extends external_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); + } + } + _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 (toolrunner_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}`; + } + } + return cmd; + } + _processLineBuffer(data, strBuffer, onLine) { + try { + let s = strBuffer + data.toString(); + let n = s.indexOf(external_os_namespaceObject.EOL); + while (n > -1) { + const line = s.substring(0, n); + onLine(line); + // the rest of the string ... + s = s.substring(n + external_os_namespaceObject.EOL.length); + n = s.indexOf(external_os_namespaceObject.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 ''; + } + } + _getSpawnFileName() { + if (toolrunner_IS_WINDOWS) { + if (this._isCmdFile()) { + return process.env['COMSPEC'] || 'cmd.exe'; + } + } + return this.toolPath; + } + _getSpawnArgs(options) { + if (toolrunner_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]; + } + } + return this.args; + } + _endsWith(str, end) { + return str.endsWith(end); + } + _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); + } + // 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; + } + } + // 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(''); + } + _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}"`; + } + // 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; + } + _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; + } + /** + * 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 + */ + exec() { + return toolrunner_awaiter(this, void 0, void 0, function* () { + // root the tool path if it is unrooted and contains relative pathing + if (!isRooted(this.toolPath) && + (this.toolPath.includes('/') || + (toolrunner_IS_WINDOWS && this.toolPath.includes('\\')))) { + // prefer options.cwd if it is specified, however options.cwd may also need to be rooted + this.toolPath = external_path_namespaceObject.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 which(this.toolPath, true); + return new Promise((resolve, reject) => toolrunner_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) + external_os_namespaceObject.EOL); + } + const state = new ExecState(optionsNonNull, this.toolPath); + state.on('debug', (message) => { + this._debug(message); + }); + if (this.options.cwd && !(yield exists(this.options.cwd))) { + return reject(new Error(`The cwd: ${this.options.cwd} does not exist!`)); + } + const fileName = this._getSpawnFileName(); + const cp = external_child_process_namespaceObject.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); + } + })); + }); + } +} +/** + * 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; + } + 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 (arg.length > 0) { + args.push(arg.trim()); + } + return args; +} +class ExecState extends external_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; + } + } + CheckComplete() { + if (this.done) { + return; + } + if (this.processClosed) { + this._setResult(); + } + else if (this.processExited) { + this.timeout = (0,external_timers_namespaceObject.setTimeout)(ExecState.HandleTimeout, this.delay, this); + } + } + _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}`); + } + 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); + } + 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(); + } +} +//# sourceMappingURL=toolrunner.js.map +;// CONCATENATED MODULE: ./node_modules/.pnpm/@actions+exec@3.0.0/node_modules/@actions/exec/lib/exec.js +var exec_awaiter = (undefined && undefined.__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()); + }); +}; + + +/** + * 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_exec(commandLine, args, options) { + return exec_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(); + }); +} +/** + * 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 + */ +function getExecOutput(commandLine, args, options) { + return exec_awaiter(this, void 0, void 0, function* () { + var _a, _b; + let stdout = ''; + let stderr = ''; + //Using string decoder covers the case where a mult-byte character is split + const stdoutDecoder = new StringDecoder('utf8'); + const stderrDecoder = new 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_exec(commandLine, args, Object.assign(Object.assign({}, options), { listeners })); + //flush any remaining characters + stdout += stdoutDecoder.end(); + stderr += stderrDecoder.end(); + return { + exitCode, + stdout, + stderr + }; + }); +} +//# sourceMappingURL=exec.js.map +;// CONCATENATED MODULE: ./node_modules/.pnpm/@actions+core@3.0.1/node_modules/@actions/core/lib/platform.js +var platform_awaiter = (undefined && undefined.__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()); + }); +}; + + +const getWindowsInfo = () => platform_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 = () => platform_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 = () => platform_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 + }; +}); +const platform = external_os_namespaceObject.platform(); +const arch = external_os_namespaceObject.arch(); +const isWindows = platform === 'win32'; +const isMacOS = platform === 'darwin'; +const isLinux = platform === 'linux'; +function getDetails() { + return platform_awaiter(this, void 0, void 0, function* () { + return Object.assign(Object.assign({}, (yield (isWindows + ? getWindowsInfo() + : isMacOS + ? getMacOsInfo() + : getLinuxInfo()))), { platform, + arch, + isWindows, + isMacOS, + isLinux }); + }); +} +//# sourceMappingURL=platform.js.map +;// CONCATENATED MODULE: ./node_modules/.pnpm/@actions+core@3.0.1/node_modules/@actions/core/lib/core.js +var core_awaiter = (undefined && undefined.__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()); + }); +}; + + + + + + +/** + * 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 || (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 = toCommandValue(val); + process.env[name] = convertedVal; + const filePath = process.env['GITHUB_ENV'] || ''; + if (filePath) { + return issueFileCommand('ENV', prepareKeyValueMessage(name, val)); + } + issueCommand('set-env', { name }, convertedVal); +} +/** + * Registers a secret which will get masked from logs + * + * @param secret - Value of the secret to be masked + * @remarks + * This function instructs the Actions runner to mask the specified value in any + * logs produced during the workflow run. Once registered, the secret value will + * be replaced with asterisks (***) whenever it appears in console output, logs, + * or error messages. + * + * This is useful for protecting sensitive information such as: + * - API keys + * - Access tokens + * - Authentication credentials + * - URL parameters containing signatures (SAS tokens) + * + * Note that masking only affects future logs; any previous appearances of the + * secret in logs before calling this function will remain unmasked. + * + * @example + * ```typescript + * // Register an API token as a secret + * const apiToken = "abc123xyz456"; + * setSecret(apiToken); + * + * // Now any logs containing this value will show *** instead + * console.log(`Using token: ${apiToken}`); // Outputs: "Using token: ***" + * ``` + */ +function core_setSecret(secret) { + issueCommand('add-mask', {}, secret); +} +/** + * Prepends inputPath to the PATH (for this action and future actions) + * @param inputPath + */ +function addPath(inputPath) { + const filePath = process.env['GITHUB_PATH'] || ''; + if (filePath) { + issueFileCommand('PATH', inputPath); + } + else { + issueCommand('add-path', {}, inputPath); + } + process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`; +} +/** + * 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 name name of the input to get + * @param options optional. See InputOptions. + * @returns string + */ +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(); +} +/** + * 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()); +} +/** + * 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\``); +} +/** + * 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 file_command_issueFileCommand('OUTPUT', file_command_prepareKeyValueMessage(name, value)); + } + process.stdout.write(external_os_namespaceObject.EOL); + command_issueCommand('set-output', { name }, utils_toCommandValue(value)); +} +/** + * 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) { + issue('echo', enabled ? 'on' : 'off'); +} +//----------------------------------------------------------------------- +// 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); +} +//----------------------------------------------------------------------- +// Logging Commands +//----------------------------------------------------------------------- +/** + * Gets whether Actions Step Debug is on or not + */ +function isDebug() { + return process.env['RUNNER_DEBUG'] === '1'; +} +/** + * Writes debug message to user log + * @param message debug message + */ +function core_debug(message) { + issueCommand('debug', {}, message); +} +/** + * 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 = {}) { + command_issueCommand('error', utils_toCommandProperties(properties), message instanceof Error ? message.toString() : message); +} +/** + * 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 = {}) { + command_issueCommand('warning', utils_toCommandProperties(properties), message instanceof Error ? message.toString() : message); +} +/** + * 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 = {}) { + issueCommand('notice', toCommandProperties(properties), message instanceof Error ? message.toString() : message); +} +/** + * Writes info to log with console.log. + * @param message info message + */ +function info(message) { + process.stdout.write(message + external_os_namespaceObject.EOL); +} +/** + * 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) { + issue('group', name); +} +/** + * End an output group. + */ +function endGroup() { + issue('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 core_awaiter(this, void 0, void 0, function* () { + startGroup(name); + let result; + try { + result = yield fn(); + } + finally { + endGroup(); + } + return result; + }); +} +//----------------------------------------------------------------------- +// Wrapper action state +//----------------------------------------------------------------------- +/** + * Saves state for current action, the state can only be retrieved by this action's post job execution. + * + * @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 + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function saveState(name, value) { + const filePath = process.env['GITHUB_STATE'] || ''; + if (filePath) { + return issueFileCommand('STATE', prepareKeyValueMessage(name, value)); + } + issueCommand('save-state', { name }, toCommandValue(value)); +} +/** + * 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}`] || ''; +} +function getIDToken(aud) { + return core_awaiter(this, void 0, void 0, function* () { + return yield OidcClient.getIDToken(aud); + }); +} +/** + * Summary exports + */ + +/** + * @deprecated use core.summary + */ + +/** + * Path exports + */ + +/** + * Platform utilities exports + */ + +//# sourceMappingURL=core.js.map +;// CONCATENATED MODULE: ./node_modules/.pnpm/@actions+github@9.1.1/node_modules/@actions/github/lib/context.js + + +class Context { + /** + * Hydrate the context from the environment + */ + constructor() { + var _a, _b, _c; + this.payload = {}; + if (process.env.GITHUB_EVENT_PATH) { + if ((0,external_fs_namespaceObject.existsSync)(process.env.GITHUB_EVENT_PATH)) { + this.payload = JSON.parse((0,external_fs_namespaceObject.readFileSync)(process.env.GITHUB_EVENT_PATH, { encoding: 'utf8' })); + } + else { + const path = process.env.GITHUB_EVENT_PATH; + process.stdout.write(`GITHUB_EVENT_PATH ${path} does not exist${external_os_namespaceObject.EOL}`); + } + } + this.eventName = process.env.GITHUB_EVENT_NAME; + this.sha = process.env.GITHUB_SHA; + this.ref = process.env.GITHUB_REF; + this.workflow = process.env.GITHUB_WORKFLOW; + this.action = process.env.GITHUB_ACTION; + this.actor = process.env.GITHUB_ACTOR; + this.job = process.env.GITHUB_JOB; + this.runAttempt = parseInt(process.env.GITHUB_RUN_ATTEMPT, 10); + this.runNumber = parseInt(process.env.GITHUB_RUN_NUMBER, 10); + this.runId = parseInt(process.env.GITHUB_RUN_ID, 10); + this.apiUrl = (_a = process.env.GITHUB_API_URL) !== null && _a !== void 0 ? _a : `https://api.github.com`; + this.serverUrl = (_b = process.env.GITHUB_SERVER_URL) !== null && _b !== void 0 ? _b : `https://github.com`; + this.graphqlUrl = + (_c = process.env.GITHUB_GRAPHQL_URL) !== null && _c !== void 0 ? _c : `https://api.github.com/graphql`; + } + get issue() { + const payload = this.payload; + return Object.assign(Object.assign({}, this.repo), { number: (payload.issue || payload.pull_request || payload).number }); + } + get repo() { + if (process.env.GITHUB_REPOSITORY) { + const [owner, repo] = process.env.GITHUB_REPOSITORY.split('/'); + return { owner, repo }; + } + if (this.payload.repository) { + return { + owner: this.payload.repository.owner.login, + repo: this.payload.repository.name + }; + } + throw new Error("context.repo requires a GITHUB_REPOSITORY environment variable like 'owner/repo'"); + } +} +//# sourceMappingURL=context.js.map +// EXTERNAL MODULE: ./node_modules/.pnpm/@actions+http-client@3.0.2/node_modules/@actions/http-client/lib/index.js +var lib = __nccwpck_require__(2504); +;// CONCATENATED MODULE: ./node_modules/.pnpm/@actions+github@9.1.1/node_modules/@actions/github/lib/internal/utils.js +var utils_awaiter = (undefined && undefined.__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()); + }); +}; + + +function getAuthString(token, options) { + if (!token && !options.auth) { + throw new Error('Parameter token or opts.auth is required'); + } + else if (token && options.auth) { + throw new Error('Parameters token and opts.auth may not both be specified'); + } + return typeof options.auth === 'string' ? options.auth : `token ${token}`; +} +function getProxyAgent(destinationUrl) { + const hc = new lib.HttpClient(); + return hc.getAgent(destinationUrl); +} +function getProxyAgentDispatcher(destinationUrl) { + const hc = new lib.HttpClient(); + return hc.getAgentDispatcher(destinationUrl); +} +function getProxyFetch(destinationUrl) { + const httpDispatcher = getProxyAgentDispatcher(destinationUrl); + const proxyFetch = (url, opts) => utils_awaiter(this, void 0, void 0, function* () { + return (0,undici.fetch)(url, Object.assign(Object.assign({}, opts), { dispatcher: httpDispatcher })); + }); + return proxyFetch; +} +function getApiBaseUrl() { + return process.env['GITHUB_API_URL'] || 'https://api.github.com'; +} +function getUserAgentWithOrchestrationId(baseUserAgent) { + var _a; + const orchId = (_a = process.env['ACTIONS_ORCHESTRATION_ID']) === null || _a === void 0 ? void 0 : _a.trim(); + if (orchId) { + const sanitizedId = orchId.replace(/[^a-z0-9_.-]/gi, '_'); + const tag = `actions_orchestration_id/${sanitizedId}`; + if (baseUserAgent === null || baseUserAgent === void 0 ? void 0 : baseUserAgent.includes(tag)) + return baseUserAgent; + const ua = baseUserAgent ? `${baseUserAgent} ` : ''; + return `${ua}${tag}`; + } + return baseUserAgent; +} +//# sourceMappingURL=utils.js.map +;// CONCATENATED MODULE: ./node_modules/.pnpm/universal-user-agent@7.0.3/node_modules/universal-user-agent/index.js +function getUserAgent() { + if (typeof navigator === "object" && "userAgent" in navigator) { + return navigator.userAgent; + } + + if (typeof process === "object" && process.version !== undefined) { + return `Node.js/${process.version.substr(1)} (${process.platform}; ${ + process.arch + })`; + } + + return ""; +} + +;// CONCATENATED MODULE: ./node_modules/.pnpm/before-after-hook@4.0.0/node_modules/before-after-hook/lib/register.js +// @ts-check + +function register(state, name, method, options) { + if (typeof method !== "function") { + throw new Error("method for before hook must be a function"); + } + + if (!options) { + options = {}; + } + + if (Array.isArray(name)) { + return name.reverse().reduce((callback, name) => { + return register.bind(null, state, name, callback, options); + }, method)(); + } + + return Promise.resolve().then(() => { + if (!state.registry[name]) { + return method(options); + } + + return state.registry[name].reduce((method, registered) => { + return registered.hook.bind(null, method, options); + }, method)(); + }); +} + +;// CONCATENATED MODULE: ./node_modules/.pnpm/before-after-hook@4.0.0/node_modules/before-after-hook/lib/add.js +// @ts-check + +function addHook(state, kind, name, hook) { + const orig = hook; + if (!state.registry[name]) { + state.registry[name] = []; + } + + if (kind === "before") { + hook = (method, options) => { + return Promise.resolve() + .then(orig.bind(null, options)) + .then(method.bind(null, options)); + }; + } + + if (kind === "after") { + hook = (method, options) => { + let result; + return Promise.resolve() + .then(method.bind(null, options)) + .then((result_) => { + result = result_; + return orig(result, options); + }) + .then(() => { + return result; + }); + }; + } + + if (kind === "error") { + hook = (method, options) => { + return Promise.resolve() + .then(method.bind(null, options)) + .catch((error) => { + return orig(error, options); + }); + }; + } + + state.registry[name].push({ + hook: hook, + orig: orig, + }); +} + +;// CONCATENATED MODULE: ./node_modules/.pnpm/before-after-hook@4.0.0/node_modules/before-after-hook/lib/remove.js +// @ts-check + +function removeHook(state, name, method) { + if (!state.registry[name]) { + return; + } + + const index = state.registry[name] + .map((registered) => { + return registered.orig; + }) + .indexOf(method); + + if (index === -1) { + return; + } + + state.registry[name].splice(index, 1); +} + +;// CONCATENATED MODULE: ./node_modules/.pnpm/before-after-hook@4.0.0/node_modules/before-after-hook/index.js +// @ts-check + + + + + +// bind with array of arguments: https://stackoverflow.com/a/21792913 +const bind = Function.bind; +const bindable = bind.bind(bind); + +function bindApi(hook, state, name) { + const removeHookRef = bindable(removeHook, null).apply( + null, + name ? [state, name] : [state] + ); + hook.api = { remove: removeHookRef }; + hook.remove = removeHookRef; + ["before", "error", "after", "wrap"].forEach((kind) => { + const args = name ? [state, kind, name] : [state, kind]; + hook[kind] = hook.api[kind] = bindable(addHook, null).apply(null, args); + }); +} + +function Singular() { + const singularHookName = Symbol("Singular"); + const singularHookState = { + registry: {}, + }; + const singularHook = register.bind(null, singularHookState, singularHookName); + bindApi(singularHook, singularHookState, singularHookName); + return singularHook; +} + +function Collection() { + const state = { + registry: {}, + }; + + const hook = register.bind(null, state); + bindApi(hook, state); + + return hook; +} + +/* harmony default export */ const before_after_hook = ({ Singular, Collection }); + +;// CONCATENATED MODULE: ./node_modules/.pnpm/@octokit+endpoint@11.0.5/node_modules/@octokit/endpoint/dist-bundle/index.js +// pkg/dist-src/defaults.js + + +// pkg/dist-src/version.js +var VERSION = "0.0.0-development"; + +// pkg/dist-src/defaults.js +var userAgent = `octokit-endpoint.js/${VERSION} ${getUserAgent()}`; +var DEFAULTS = { + method: "GET", + baseUrl: "https://api.github.com", + headers: { + accept: "application/vnd.github.v3+json", + "user-agent": userAgent + }, + mediaType: { + format: "" + } +}; + +// pkg/dist-src/util/lowercase-keys.js +function dist_bundle_lowercaseKeys(object) { + if (!object) { + return {}; + } + return Object.keys(object).reduce((newObj, key) => { + newObj[key.toLowerCase()] = object[key]; + return newObj; + }, {}); +} + +// pkg/dist-src/util/is-plain-object.js +function isPlainObject(value) { + if (typeof value !== "object" || value === null) return false; + if (Object.prototype.toString.call(value) !== "[object Object]") return false; + const proto = Object.getPrototypeOf(value); + if (proto === null) return true; + const Ctor = Object.prototype.hasOwnProperty.call(proto, "constructor") && proto.constructor; + return typeof Ctor === "function" && Ctor instanceof Ctor && Function.prototype.call(Ctor) === Function.prototype.call(value); +} + +// pkg/dist-src/util/merge-deep.js +function mergeDeep(defaults, options) { + const result = Object.assign({}, defaults); + Object.keys(options).forEach((key) => { + if (isPlainObject(options[key])) { + if (!(key in defaults)) Object.assign(result, { [key]: options[key] }); + else result[key] = mergeDeep(defaults[key], options[key]); + } else { + Object.assign(result, { [key]: options[key] }); + } + }); + return result; +} + +// pkg/dist-src/util/remove-undefined-properties.js +function removeUndefinedProperties(obj) { + for (const key in obj) { + if (obj[key] === void 0) { + delete obj[key]; + } + } + return obj; +} + +// pkg/dist-src/merge.js +function merge(defaults, route, options) { + if (typeof route === "string") { + let [method, url] = route.split(" "); + options = Object.assign(url ? { method, url } : { url: method }, options); + } else { + options = Object.assign({}, route); + } + options.headers = dist_bundle_lowercaseKeys(options.headers); + removeUndefinedProperties(options); + removeUndefinedProperties(options.headers); + const mergedOptions = mergeDeep(defaults || {}, options); + if (options.url === "/graphql") { + if (defaults && defaults.mediaType.previews?.length) { + mergedOptions.mediaType.previews = defaults.mediaType.previews.filter( + (preview) => !mergedOptions.mediaType.previews.includes(preview) + ).concat(mergedOptions.mediaType.previews); + } + mergedOptions.mediaType.previews = (mergedOptions.mediaType.previews || []).map((preview) => preview.replace(/-preview/, "")); + } + return mergedOptions; +} + +// pkg/dist-src/util/add-query-parameters.js +function addQueryParameters(url, parameters) { + const separator = /\?/.test(url) ? "&" : "?"; + const names = Object.keys(parameters); + if (names.length === 0) { + return url; + } + return url + separator + names.map((name) => { + if (name === "q") { + return "q=" + parameters.q.split("+").map(encodeURIComponent).join("+"); + } + return `${name}=${encodeURIComponent(parameters[name])}`; + }).join("&"); +} + +// pkg/dist-src/util/extract-url-variable-names.js +var urlVariableRegex = /\{[^{}}]+\}/g; +function removeNonChars(variableName) { + return variableName.replace(/(?:^\W+)|(?:(? a.concat(b), []); +} + +// pkg/dist-src/util/omit.js +function omit(object, keysToOmit) { + const result = { __proto__: null }; + for (const key of Object.keys(object)) { + if (keysToOmit.indexOf(key) === -1) { + result[key] = object[key]; + } + } + return result; +} + +// pkg/dist-src/util/url-template.js +function encodeReserved(str) { + return str.split(/(%[0-9A-Fa-f]{2})/g).map(function(part) { + if (!/%[0-9A-Fa-f]/.test(part)) { + part = encodeURI(part).replace(/%5B/g, "[").replace(/%5D/g, "]"); + } + return part; + }).join(""); +} +function encodeUnreserved(str) { + return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { + return "%" + c.charCodeAt(0).toString(16).toUpperCase(); + }); +} +function encodeValue(operator, value, key) { + value = operator === "+" || operator === "#" ? encodeReserved(value) : encodeUnreserved(value); + if (key) { + return encodeUnreserved(key) + "=" + value; + } else { + return value; + } +} +function isDefined(value) { + return value !== void 0 && value !== null; +} +function isKeyOperator(operator) { + return operator === ";" || operator === "&" || operator === "?"; +} +function getValues(context, operator, key, modifier) { + var value = context[key], result = []; + if (isDefined(value) && value !== "") { + if (typeof value === "string" || typeof value === "number" || typeof value === "bigint" || typeof value === "boolean") { + value = value.toString(); + if (modifier && modifier !== "*") { + value = value.substring(0, parseInt(modifier, 10)); + } + result.push( + encodeValue(operator, value, isKeyOperator(operator) ? key : "") + ); + } else { + if (modifier === "*") { + if (Array.isArray(value)) { + value.filter(isDefined).forEach(function(value2) { + result.push( + encodeValue(operator, value2, isKeyOperator(operator) ? key : "") + ); + }); + } else { + Object.keys(value).forEach(function(k) { + if (isDefined(value[k])) { + result.push(encodeValue(operator, value[k], k)); + } + }); + } + } else { + const tmp = []; + if (Array.isArray(value)) { + value.filter(isDefined).forEach(function(value2) { + tmp.push(encodeValue(operator, value2)); + }); + } else { + Object.keys(value).forEach(function(k) { + if (isDefined(value[k])) { + tmp.push(encodeUnreserved(k)); + tmp.push(encodeValue(operator, value[k].toString())); + } + }); + } + if (isKeyOperator(operator)) { + result.push(encodeUnreserved(key) + "=" + tmp.join(",")); + } else if (tmp.length !== 0) { + result.push(tmp.join(",")); + } + } + } + } else { + if (operator === ";") { + if (isDefined(value)) { + result.push(encodeUnreserved(key)); + } + } else if (value === "" && (operator === "&" || operator === "?")) { + result.push(encodeUnreserved(key) + "="); + } else if (value === "") { + result.push(""); + } + } + return result; +} +function parseUrl(template) { + return { + expand: expand.bind(null, template) + }; +} +function expand(template, context) { + var operators = ["+", "#", ".", "/", ";", "?", "&"]; + template = template.replace( + /\{([^\{\}]+)\}|([^\{\}]+)/g, + function(_, expression, literal) { + if (expression) { + let operator = ""; + const values = []; + if (operators.indexOf(expression.charAt(0)) !== -1) { + operator = expression.charAt(0); + expression = expression.substr(1); + } + expression.split(/,/g).forEach(function(variable) { + var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable); + values.push(getValues(context, operator, tmp[1], tmp[2] || tmp[3])); + }); + if (operator && operator !== "+") { + var separator = ","; + if (operator === "?") { + separator = "&"; + } else if (operator !== "#") { + separator = operator; + } + return (values.length !== 0 ? operator : "") + values.join(separator); + } else { + return values.join(","); + } + } else { + return encodeReserved(literal); + } + } + ); + if (template === "/") { + return template; + } else { + return template.replace(/\/$/, ""); + } +} + +// pkg/dist-src/parse.js +function parse(options) { + let method = options.method.toUpperCase(); + let url = (options.url || "/").replace(/:([a-z]\w+)/g, "{$1}"); + let headers = Object.assign({}, options.headers); + let body; + let parameters = omit(options, [ + "method", + "baseUrl", + "url", + "headers", + "request", + "mediaType" + ]); + const urlVariableNames = extractUrlVariableNames(url); + url = parseUrl(url).expand(parameters); + if (!/^http/.test(url)) { + url = options.baseUrl + url; + } + const omittedParameters = Object.keys(options).filter((option) => urlVariableNames.includes(option)).concat("baseUrl"); + const remainingParameters = omit(parameters, omittedParameters); + const isBinaryRequest = /application\/octet-stream/i.test(headers.accept); + if (!isBinaryRequest) { + if (options.mediaType.format) { + headers.accept = headers.accept.split(/,/).map( + (format) => format.replace( + /application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/, + `application/vnd$1$2.${options.mediaType.format}` + ) + ).join(","); + } + if (url.endsWith("/graphql")) { + if (options.mediaType.previews?.length) { + const previewsFromAcceptHeader = headers.accept.match(/(? { + const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json"; + return `application/vnd.github.${preview}-preview${format}`; + }).join(","); + } + } + } + if (["GET", "HEAD"].includes(method)) { + url = addQueryParameters(url, remainingParameters); + } else { + if ("data" in remainingParameters) { + body = remainingParameters.data; + } else { + if (Object.keys(remainingParameters).length) { + body = remainingParameters; + } + } + } + if (!headers["content-type"] && typeof body !== "undefined") { + headers["content-type"] = "application/json; charset=utf-8"; + } + if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") { + body = ""; + } + return Object.assign( + { method, url, headers }, + typeof body !== "undefined" ? { body } : null, + options.request ? { request: options.request } : null + ); +} + +// pkg/dist-src/endpoint-with-defaults.js +function endpointWithDefaults(defaults, route, options) { + return parse(merge(defaults, route, options)); +} + +// pkg/dist-src/with-defaults.js +function withDefaults(oldDefaults, newDefaults) { + const DEFAULTS2 = merge(oldDefaults, newDefaults); + const endpoint2 = endpointWithDefaults.bind(null, DEFAULTS2); + return Object.assign(endpoint2, { + DEFAULTS: DEFAULTS2, + defaults: withDefaults.bind(null, DEFAULTS2), + merge: merge.bind(null, DEFAULTS2), + parse + }); +} + +// pkg/dist-src/index.js +var endpoint = withDefaults(null, DEFAULTS); + + +;// CONCATENATED MODULE: ./node_modules/.pnpm/content-type@3.1.1/node_modules/content-type/dist/index.js +/*! + * content-type + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ +const SP = 32; // " " +const HTAB = 9; // "\t" +const SEMI = 59; // ";" +const EQ = 61; // "=" +const DQUOTE = 34; // '"' +const BSLASH = 92; // "\\" +const COMMA = 44; // "," +const LOWER_CASE = 1; +const OWS = 2; +const SEMI_FLAG = 4; +const COMMA_FLAG = 8; +const TOKEN_FLAG = 16; +const NON_ASCII = 0xff00; +const CASE_FLAGS = LOWER_CASE | NON_ASCII; +/** + * Character flags used to normalize HTTP field values while scanning. + * Out-of-range reads intentionally coerce to zero in bitwise expressions. + */ +const CHAR_MAP = new Uint8Array(0x100); +CHAR_MAP[HTAB] |= OWS; +CHAR_MAP[SP] |= OWS; +CHAR_MAP[SEMI] |= SEMI_FLAG; +CHAR_MAP[COMMA] |= COMMA_FLAG; +for (let code = 0x80 /* non-ASCII */; code <= 0xff; code++) { + CHAR_MAP[code] |= LOWER_CASE; +} +for (const char of "!#$%&'*+-.^_`|~") { + CHAR_MAP[char.charCodeAt(0)] |= TOKEN_FLAG; +} +for (let code = 0x30 /* 0 */; code <= 0x39 /* 9 */; code++) { + CHAR_MAP[code] |= TOKEN_FLAG; +} +for (let code = 0x41 /* A */; code <= 0x5a /* Z */; code++) { + CHAR_MAP[code] |= LOWER_CASE | TOKEN_FLAG; +} +for (let code = 0x61 /* a */; code <= 0x7a /* z */; code++) { + CHAR_MAP[code] |= TOKEN_FLAG; +} +/** + * Null object perf optimization. Faster than `Object.create(null)` and `{ __proto__: null }`. + */ +const NullObject = /* @__PURE__ */ (() => { + const C = function () { }; + C.prototype = Object.create(null); + return C; +})(); +/** + * Validate a type string against RFC 9110. + */ +function isTypeValid(type, start = 0, end = type.length) { + let hasSlash = false; + for (let index = start; index < end; index++) { + const code = type.charCodeAt(index); + if (code === 47 /* / */) { + if (hasSlash || index === start || index >= end - 1) + return false; + hasSlash = true; + } + else if (!isTokenCode(code)) { + return false; + } + } + return hasSlash; +} +/** + * Validate a token against RFC 9110. + */ +function isTokenValid(token, start = 0, end = token.length) { + if (start >= end) + return false; + for (let index = start; index < end; index++) { + if (!isTokenCode(token.charCodeAt(index))) + return false; + } + return true; +} +/** + * Check whether a character code belongs to the token production in RFC 9110. + */ +function isTokenCode(code) { + return (CHAR_MAP[code] & TOKEN_FLAG) !== 0; +} +/** + * Serialize a parameter value. + */ +function parameterValue(str) { + const len = str.length; + if (len === 0) + return '""'; + let index = 0; + while (index < len && isTokenCode(str.charCodeAt(index))) + index++; + if (index === len) + return str; + let result = '"'; + let start = 0; + while (index < len) { + const code = str.charCodeAt(index); + if (code !== HTAB && (code < SP || code === 127 || code > 255)) { + throw new TypeError(`Invalid parameter value: ${str}`); + } + if (code === 34 /* " */ || code === 92 /* \\ */) { + result += `${str.slice(start, index)}\\`; + start = index; + } + index++; + } + return `${result}${str.slice(start)}"`; +} +/** + * Format an object into a `Content-Type` header. + */ +function format(obj) { + const { type, parameters } = obj; + if (!type || !isTypeValid(type)) { + throw new TypeError(`Invalid type: ${type}`); + } + let result = type; + if (parameters) { + for (const param of Object.keys(parameters)) { + if (!isTokenValid(param)) { + throw new TypeError(`Invalid parameter name: ${param}`); + } + result += `; ${param}=${parameterValue(parameters[param])}`; + } + } + return result; +} +/** + * Parse a `Content-Type` header. + */ +function dist_parse(header, options) { + const stopFlags = SEMI_FLAG | (options?.comma === true ? COMMA_FLAG : 0); + const len = header.length; + let valueStart = options?.start ?? 0; + while ((CHAR_MAP[header.charCodeAt(valueStart)] & OWS) !== 0) { + valueStart++; + } + let index = valueStart; + let typeFlags = 0; + let whitespace = -1; + let stop = options?.parameters === false ? COMMA_FLAG : 0; + while (index < len) { + const code = header.charCodeAt(index); + const flags = CHAR_MAP[code]; + if ((flags & stopFlags) !== 0) { + stop |= flags & COMMA_FLAG; + break; + } + if ((flags & OWS) !== 0) { + if (whitespace === -1) + whitespace = index; + } + else { + whitespace = -1; + } + typeFlags |= (code & NON_ASCII) | flags; + index++; + } + const valueEnd = whitespace === -1 ? index : whitespace; + const value = header.slice(valueStart, valueEnd); + const type = (typeFlags & CASE_FLAGS) === 0 ? value : value.toLowerCase(); + if (index === len || stop !== 0) { + return { type, index, parameters: new NullObject() }; + } + return parseParameters(header, type, index, len, stopFlags); +} +/** + * Parses the parameters of a `Content-Type` header starting at the given index. + */ +function parseParameters(header, type, index, len, stopFlags) { + const parameters = new NullObject(); + parameter: while (index < len) { + index++; // Skip over ; + while ((CHAR_MAP[header.charCodeAt(index)] & OWS) !== 0) { + index++; + } + const keyStart = index; + let keyFlags = 0; + let keyWhitespace = -1; + while (index < len) { + const code = header.charCodeAt(index); + const flags = CHAR_MAP[code]; + if ((flags & stopFlags) !== 0) { + if ((flags & COMMA_FLAG) !== 0) + break parameter; + continue parameter; + } + if (code === EQ) { + const keyEnd = keyWhitespace === -1 ? index : keyWhitespace; + const value = header.slice(keyStart, keyEnd); + const key = (keyFlags & CASE_FLAGS) === 0 ? value : value.toLowerCase(); + index++; + while ((CHAR_MAP[header.charCodeAt(index)] & OWS) !== 0) { + index++; + } + if (index < len && header.charCodeAt(index) === DQUOTE) { + const quotedStart = ++index; + let escaped = false; + while (index < len) { + const code = header.charCodeAt(index); + if (code === DQUOTE) { + if (parameters[key] === undefined) { + parameters[key] = escaped + ? unescapeQuotedPairs(header, quotedStart, index) + : header.slice(quotedStart, index); + } + index++; + let stop = 0; + // Discard characters between quote and delimiter. + while (index < len) { + const code = header.charCodeAt(index); + const flags = CHAR_MAP[code]; + if ((flags & stopFlags) !== 0) { + stop = flags & COMMA_FLAG; + break; + } + index++; + } + if (stop !== 0) + break parameter; + continue parameter; + } + if (code === BSLASH && index + 1 < len) { + escaped = true; + index += 2; + continue; + } + index++; + } + continue parameter; + } + const valueStart = index; + let stop = 0; + let valueWhitespace = -1; + while (index < len) { + const code = header.charCodeAt(index); + const flags = CHAR_MAP[code]; + if ((flags & stopFlags) !== 0) { + stop = flags & COMMA_FLAG; + break; + } + if ((flags & OWS) !== 0) { + if (valueWhitespace === -1) + valueWhitespace = index; + } + else { + valueWhitespace = -1; + } + index++; + } + if (parameters[key] === undefined) { + const valueEnd = valueWhitespace === -1 ? index : valueWhitespace; + parameters[key] = header.slice(valueStart, valueEnd); + } + if (stop !== 0) + break parameter; + continue parameter; + } + if ((flags & OWS) !== 0) { + if (keyWhitespace === -1) + keyWhitespace = index; + } + else { + keyWhitespace = -1; + } + keyFlags |= (code & NON_ASCII) | flags; + index++; + } + } + return { type, index, parameters }; +} +/** + * Remove backslashes from quoted pairs in a known-terminated quoted string body. + */ +function unescapeQuotedPairs(str, start, end) { + let result = ""; + for (let index = start; index < end; index++) { + if (str.charCodeAt(index) === BSLASH) { + result += str.slice(start, index); + start = ++index; + } + } + return result + str.slice(start, end); +} +//# sourceMappingURL=index.js.map +;// CONCATENATED MODULE: ./node_modules/.pnpm/json-with-bigint@3.5.12/node_modules/json-with-bigint/json-with-bigint.js +const intRegex = /^-?\d+$/; +const noiseValue = /^-?\d+n+$/; // Noise - strings that match the custom format before being converted to it +const originalStringify = JSON.stringify; +const originalParse = JSON.parse; +const customFormat = /^-?\d+n$/; + +const bigIntsStringify = /([\[:])?"(-?\d+)n"($|\s*[,\}\]])/g; +const noiseStringify = /([\[:])?("-?\d+n+)n("$|"\s*[,\}\]])/g; + +/** + * @typedef {(this: any, key: string | number | undefined, value: any) => any} Replacer + * @typedef {(key: string | number | undefined, value: any, context?: { source: string }) => any} Reviver + */ + +/** + * Checks if a value is unstringifiable according to native JSON.stringify rules. + * + * @param {any} val The value to check. + * @returns {boolean} True if the value is undefined, a function, or a symbol. + */ +const isUnstringifiable = (val) => + val === undefined || typeof val === "function" || typeof val === "symbol"; + +/** + * Checks if a value is a native JSON.rawJSON object (Node.js 22+). + * + * @param {any} val The value to check. + * @returns {boolean} True if the value is a RawJSON instance. + */ +const isRawJSON = (val) => + val !== null && + typeof val === "object" && + val.constructor && + val.constructor.name === "RawJSON"; + +/** + * Iteratively converts a JS value to a JSON string. + * Used as a fallback when the native JSON.stringify hits the Maximum Call Stack size. + * Fully compliant with JSON formatting (space), replacers, and toJSON behaviors. + * + * @param {any} rootValue The value to stringify. + * @param {Replacer | Array | null} [replacer] User's custom replacer function. + * @param {string | number} [spaceParam] Indentation for pretty-printing. + * @returns {string | undefined} The generated JSON string. + */ +const stringifyIteratively = (rootValue, replacer, spaceParam) => { + let space = ""; + + if (typeof spaceParam === "number") { + space = " ".repeat(Math.min(10, Math.max(0, Math.floor(spaceParam)))); + } else if (typeof spaceParam === "string") { + space = spaceParam.slice(0, 10); + } + + const isFunctionReplacer = typeof replacer === "function"; + const propertyList = Array.isArray(replacer) + ? new Set(replacer.map(String)) + : null; + + /** + * Prepares a value for stringification by resolving toJSON, handling BigInts, + * applying custom replacers, and unwrapping primitive objects. + * + * @param {object|Array} parent The parent object or array holding the value. + * @param {string} key The key associated with the value. + * @param {any} val The raw value to process. + * @returns {any} The processed value ready for stringification. + */ + const prepareVal = (parent, key, val) => { + const isObject = val !== null && typeof val === "object"; + const hasToJSON = isObject && typeof val.toJSON === "function"; + + if (hasToJSON) { + val = val.toJSON(key); + } + + const isNoise = typeof val === "string" && noiseValue.test(val); + + if (isNoise) return val + "n"; + + const isBigInt = typeof val === "bigint"; + + if (isBigInt) { + const supportsRawJSON = "rawJSON" in JSON; + + if (supportsRawJSON) return JSON.rawJSON(val.toString()); + + return val.toString() + "n"; + } + + if (isFunctionReplacer) { + val = replacer.call(parent, key, val); + } + + const isPostReplacerObject = val !== null && typeof val === "object"; + + if (isPostReplacerObject) { + const isPrimitiveWrapper = + val instanceof Number || + val instanceof String || + val instanceof Boolean; + + if (isPrimitiveWrapper) { + val = val.valueOf(); + } + } + + return val; + }; + + const rootProcessed = prepareVal({ "": rootValue }, "", rootValue); + + if (isUnstringifiable(rootProcessed)) { + return undefined; + } + + const isRootPrimitive = + rootProcessed === null || typeof rootProcessed !== "object"; + const isRootNativeRawJSON = isRawJSON(rootProcessed); + + if (isRootPrimitive || isRootNativeRawJSON) { + return originalStringify(rootProcessed); + } + + const chunks = []; + let level = 0; + + const stack = [ + { + parent: { "": rootProcessed }, + key: "", + val: rootProcessed, + isArray: Array.isArray(rootProcessed), + keys: Array.isArray(rootProcessed) ? null : Object.keys(rootProcessed), + index: 0, + first: true, + }, + ]; + + const visited = new WeakSet([rootProcessed]); + + while (stack.length > 0) { + const node = stack[stack.length - 1]; + + if (node.index === 0) { + chunks.push(node.isArray ? "[" : "{"); + level++; + } + + let isDone = false; + + if (node.isArray) { + if (node.index < node.val.length) { + if (!node.first) chunks.push(","); + + if (space) chunks.push("\n" + space.repeat(level)); + + const childRaw = node.val[node.index]; + const childVal = prepareVal(node.val, String(node.index), childRaw); + + if (isUnstringifiable(childVal)) { + chunks.push("null"); + node.first = false; + node.index++; + } else { + const isComplexObject = + childVal !== null && typeof childVal === "object"; + const isNativeRaw = isRawJSON(childVal); + + if (isComplexObject && !isNativeRaw) { + if (visited.has(childVal)) { + throw new TypeError("Converting circular structure to JSON"); + } + + visited.add(childVal); + + stack.push({ + parent: node.val, + key: String(node.index), + val: childVal, + isArray: Array.isArray(childVal), + keys: Array.isArray(childVal) ? null : Object.keys(childVal), + index: 0, + first: true, + }); + + node.first = false; + node.index++; + } else { + chunks.push(originalStringify(childVal)); + node.first = false; + node.index++; + } + } + } else { + isDone = true; + } + } else { + while (node.index < node.keys.length) { + const k = node.keys[node.index++]; + + const isFilteredOutByArray = propertyList && !propertyList.has(k); + + if (isFilteredOutByArray) continue; + + const childRaw = node.val[k]; + const childVal = prepareVal(node.val, k, childRaw); + + if (isUnstringifiable(childVal)) continue; + + if (!node.first) chunks.push(","); + + if (space) { + chunks.push("\n" + space.repeat(level) + originalStringify(k) + ": "); + } else { + chunks.push(originalStringify(k) + ":"); + } + + const isComplexObject = + childVal !== null && typeof childVal === "object"; + const isNativeRaw = isRawJSON(childVal); + + if (isComplexObject && !isNativeRaw) { + if (visited.has(childVal)) { + throw new TypeError("Converting circular structure to JSON"); + } + + visited.add(childVal); + + stack.push({ + parent: node.val, + key: k, + val: childVal, + isArray: Array.isArray(childVal), + keys: Array.isArray(childVal) ? null : Object.keys(childVal), + index: 0, + first: true, + }); + + node.first = false; + + break; // Stop current loop level to process the newly pushed stack node + } else { + chunks.push(originalStringify(childVal)); + node.first = false; + } + } + + const isNodeFullyProcessed = + node.index >= node.keys.length && stack[stack.length - 1] === node; + + if (isNodeFullyProcessed) { + isDone = true; + } + } + + if (isDone) { + level--; + + if (!node.first && space) chunks.push("\n" + space.repeat(level)); + + chunks.push(node.isArray ? "]" : "}"); + visited.delete(node.val); + stack.pop(); + } + } + + return chunks.join(""); +}; + +/** + * Converts a JavaScript value to a JSON string. + * + * Supports serialization of BigInt values using two strategies: + * 1. Custom format "123n" → "123" (universal fallback) + * 2. Native JSON.rawJSON() (Node.js 22+, fastest) when available + * + * All other values are serialized exactly like native JSON.stringify(). + * + * @param {*} value The value to convert to a JSON string. + * @param {Replacer | Array | null} [replacer] + * A function that alters the behavior of the stringification process, + * or an array of strings/numbers to indicate properties to exclude. + * @param {string | number} [space] + * A string or number to specify indentation or pretty-printing. + * @returns {string} The JSON string representation. + */ +const JSONStringify = (value, replacer, space) => { + try { + const supportsRawJSON = "rawJSON" in JSON; + + if (supportsRawJSON) { + return originalStringify( + value, + (key, val) => { + if (typeof val === "bigint") return JSON.rawJSON(val.toString()); + + const hasFunctionReplacer = typeof replacer === "function"; + + if (hasFunctionReplacer) return replacer(key, val); + + const isKeyInArrayReplacer = + Array.isArray(replacer) && replacer.includes(key); + + if (isKeyInArrayReplacer) return val; + + return val; + }, + space, + ); + } + + if (!value) return originalStringify(value, replacer, space); + + const convertedToCustomJSON = originalStringify( + value, + (key, val) => { + const isNoise = typeof val === "string" && noiseValue.test(val); + + if (isNoise) return val.toString() + "n"; // Mark noise values with additional "n" to offset the deletion of one "n" during the processing + + if (typeof val === "bigint") return val.toString() + "n"; + + const hasFunctionReplacer = typeof replacer === "function"; + + if (hasFunctionReplacer) return replacer(key, val); + + const isKeyInArrayReplacer = + Array.isArray(replacer) && replacer.includes(key); + + if (isKeyInArrayReplacer) return val; + + return val; + }, + space, + ); + + const processedJSON = convertedToCustomJSON.replace( + bigIntsStringify, + "$1$2$3", + ); // Delete one "n" off the end of every BigInt value + + const denoisedJSON = processedJSON.replace(noiseStringify, "$1$2$3"); // Remove one "n" off the end of every noisy string + + return denoisedJSON; + } catch (error) { + if (error instanceof RangeError) { + const convertedJSON = stringifyIteratively(value, replacer, space); + + if (convertedJSON === undefined) return undefined; + + const supportsRawJSON = "rawJSON" in JSON; + + if (supportsRawJSON) return convertedJSON; + + const processedJSON = convertedJSON.replace(bigIntsStringify, "$1$2$3"); + + return processedJSON.replace(noiseStringify, "$1$2$3"); + } + + throw error; + } +}; + +const featureCache = new Map(); + +/** + * Detects if the current JSON.parse implementation supports the context.source feature. + * + * Uses toString() fingerprinting to cache results and automatically detect runtime + * replacements of JSON.parse (polyfills, mocks, etc.). + * + * @returns {boolean} true if context.source is supported, false otherwise. + */ +const isContextSourceSupported = () => { + const parseFingerprint = JSON.parse.toString(); + + if (featureCache.has(parseFingerprint)) { + return featureCache.get(parseFingerprint); + } + + try { + const result = JSON.parse( + "1", + (_, __, context) => !!context?.source && context.source === "1", + ); + featureCache.set(parseFingerprint, result); + + return result; + } catch { + featureCache.set(parseFingerprint, false); + + return false; + } +}; + +/** + * Reviver function that converts custom-format BigInt strings back to BigInt values. + * Also handles "noise" strings that accidentally match the BigInt format. + * + * @param {string | number | undefined} key The object key. + * @param {*} value The value being parsed. + * @param {object} [context] Parse context (if supported by JSON.parse). + * @param {Reviver} [userReviver] User's custom reviver function. + * @returns {any} The transformed value. + */ +const convertMarkedBigIntsReviver = (key, value, context, userReviver) => { + const isCustomFormatBigInt = + typeof value === "string" && customFormat.test(value); + + if (isCustomFormatBigInt) return BigInt(value.slice(0, -1)); + + const isNoiseValue = typeof value === "string" && noiseValue.test(value); + if (isNoiseValue) return value.slice(0, -1); + + const hasUserReviver = typeof userReviver === "function"; + + if (!hasUserReviver) return value; + + return userReviver(key, value, context); +}; + +/** + * Fast JSON.parse implementation (~2x faster than classic fallback). + * Uses JSON.parse's context.source feature to detect integers and convert + * large numbers directly to BigInt without string manipulation. + * + * Does not support legacy custom format from v1 of this library. + * + * @param {string} text JSON string to parse. + * @param {Reviver} [reviver] Transform function to apply to each value. + * @returns {any} Parsed JavaScript value. + */ +const JSONParseV2 = (text, reviver) => { + return JSON.parse(text, (key, value, context) => { + const isNumber = typeof value === "number"; + const isOutOfBounds = + value > Number.MAX_SAFE_INTEGER || value < Number.MIN_SAFE_INTEGER; + const isBigNumber = isNumber && isOutOfBounds; + const isInt = context && intRegex.test(context.source); + const isBigInt = isBigNumber && isInt; + + if (isBigInt) return BigInt(context.source); + + const hasCustomReviver = typeof reviver === "function"; + + if (!hasCustomReviver) return value; + + return reviver(key, value, context); + }); +}; + +const MAX_INT = Number.MAX_SAFE_INTEGER.toString(); +const MAX_DIGITS = MAX_INT.length; +const stringsOrLargeNumbers = + /"(?:[^"\\]|\\.)*"|-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?/g; +const noiseValueWithQuotes = /^"-?\d+n+"$/; // Noise - strings that match the custom format before being converted to it + +/** + * Iteratively traverses the parsed object bottom-up (post-order), + * emulating the native JSON.parse reviver behavior. + * This avoids Call Stack overflows (RangeError) on deeply nested structures. + * + * @param {any} parsed The natively parsed JSON object. + * @param {Reviver} [userReviver] User's custom reviver function. + * @returns {any} The fully processed object. + */ +const applyReviverIteratively = (parsed, userReviver) => { + const rootHolder = { "": parsed }; + const stack = [{ parent: rootHolder, key: "", visited: false }]; + + while (stack.length > 0) { + const node = stack[stack.length - 1]; + + if (!node.visited) { + node.visited = true; + + const value = node.parent[node.key]; + const isComplexObject = value !== null && typeof value === "object"; + + if (isComplexObject) { + const keys = Object.keys(value); + + for (let i = keys.length - 1; i >= 0; i--) { + stack.push({ parent: value, key: keys[i], visited: false }); + } + } + } else { + const { parent, key } = node; + let value = parent[key]; + + if (typeof value === "string") { + const isCustomFormatBigInt = customFormat.test(value); + + if (isCustomFormatBigInt) { + value = BigInt(value.slice(0, -1)); + } else { + const isNoise = noiseValue.test(value); + + if (isNoise) value = value.slice(0, -1); + } + } + + const hasUserReviver = typeof userReviver === "function"; + + if (hasUserReviver) { + value = userReviver.call(parent, key, value); + } + + const isDeleted = value === undefined; + + if (isDeleted) { + delete parent[key]; + } else { + parent[key] = value; + } + + stack.pop(); + } + } + + return rootHolder[""]; +}; + +/** + * Pre-processes the JSON string to mark large numbers with an 'n' suffix. + * + * @param {string} text The raw JSON string. + * @returns {string} The serialized string with marked BigInts. + */ +const serializeBigInts = (text) => { + return text.replace( + stringsOrLargeNumbers, + (match, digits, fractional, exponential) => { + const isString = match[0] === '"'; + const isNoise = isString && noiseValueWithQuotes.test(match); + + if (isNoise) return match.substring(0, match.length - 1) + 'n"'; // Mark noise values with additional "n" to offset the deletion of one "n" during the processing + + const hasFractionalOrExponential = fractional || exponential; + + // With a fixed number of digits, we can correctly use lexicographical comparison to do a numeric comparison + const isLessThanMaxSafeInt = + digits && + (digits.length < MAX_DIGITS || + (digits.length === MAX_DIGITS && digits <= MAX_INT)); + + const isStandardValue = + isString || hasFractionalOrExponential || isLessThanMaxSafeInt; + + if (isStandardValue) return match; + + return '"' + match + 'n"'; + }, + ); +}; + +/** + * Converts a JSON string into a JavaScript value. + * + * Supports parsing of large integers using two strategies: + * 1. Classic fallback: Marks large numbers with "123n" format, then converts to BigInt + * 2. Fast path (JSONParseV2): Uses context.source feature (~2x faster) when available + * + * All other JSON values are parsed exactly like native JSON.parse(). + * + * @param {string} text A valid JSON string. + * @param {Reviver} [reviver] + * A function that transforms the results. This function is called for each member + * of the object. If a member contains nested objects, the nested objects are + * transformed before the parent object is. + * @returns {any} The parsed JavaScript value. + * @throws {SyntaxError} If text is not valid JSON. + */ +const JSONParse = (text, reviver) => { + if (!text) return originalParse(text, reviver); + + try { + if (isContextSourceSupported()) return JSONParseV2(text, reviver); // Shortcut to a faster (2x) and simpler version + + // Find and mark big numbers with "n" + const serializedData = serializeBigInts(text); + + return originalParse(serializedData, (key, value, context) => + convertMarkedBigIntsReviver(key, value, context, reviver), + ); + } catch (error) { + if (error instanceof RangeError) { + const serializedData = serializeBigInts(text); + const parsed = originalParse(serializedData); + + return applyReviverIteratively(parsed, reviver); + } + + throw error; + } +}; + + + +;// CONCATENATED MODULE: ./node_modules/.pnpm/@octokit+request-error@7.1.2/node_modules/@octokit/request-error/dist-src/index.js +class RequestError extends Error { + name; + /** + * http status code + */ + status; + /** + * Request options that lead to the error. + */ + request; + /** + * Response object if a response was received + */ + response; + constructor(message, statusCode, options) { + super(message, { cause: options.cause }); + this.name = "HttpError"; + this.status = Number.parseInt(statusCode); + if (Number.isNaN(this.status)) { + this.status = 0; + } + /* v8 ignore else -- @preserve -- Bug with vitest coverage where it sees an else branch that doesn't exist */ + if ("response" in options) { + this.response = options.response; + } + const requestCopy = Object.assign({}, options.request); + if (options.request.headers.authorization) { + requestCopy.headers = Object.assign({}, options.request.headers, { + authorization: options.request.headers.authorization.replace( + /(? ""; +async function fetchWrapper(requestOptions) { + const fetch = requestOptions.request?.fetch || globalThis.fetch; + if (!fetch) { + throw new Error( + "fetch is not set. Please pass a fetch implementation as new Octokit({ request: { fetch }}). Learn more at https://github.com/octokit/octokit.js/#fetch-missing" + ); + } + const log = requestOptions.request?.log || console; + const parseSuccessResponseBody = requestOptions.request?.parseSuccessResponseBody !== false; + const body = dist_bundle_isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body) ? JSONStringify(requestOptions.body) : requestOptions.body; + const requestHeaders = Object.fromEntries( + Object.entries(requestOptions.headers).map(([name, value]) => [ + name, + String(value) + ]) + ); + let fetchResponse; + try { + fetchResponse = await fetch(requestOptions.url, { + method: requestOptions.method, + body, + redirect: requestOptions.request?.redirect, + headers: requestHeaders, + signal: requestOptions.request?.signal, + // duplex must be set if request.body is ReadableStream or Async Iterables. + // See https://fetch.spec.whatwg.org/#dom-requestinit-duplex. + ...requestOptions.body && { duplex: "half" } + }); + } catch (error) { + let message = "Unknown Error"; + if (error instanceof Error) { + if (error.name === "AbortError") { + error.status = 500; + throw error; + } + message = error.message; + if (error.name === "TypeError" && "cause" in error) { + if (error.cause instanceof Error) { + message = error.cause.message; + } else if (typeof error.cause === "string") { + message = error.cause; + } + } + } + const requestError = new RequestError(message, 500, { + request: requestOptions + }); + requestError.cause = error; + throw requestError; + } + const status = fetchResponse.status; + const url = fetchResponse.url; + const responseHeaders = {}; + for (const [key, value] of fetchResponse.headers) { + responseHeaders[key] = value; + } + const octokitResponse = { + url, + status, + headers: responseHeaders, + data: "" + }; + if ("deprecation" in responseHeaders) { + const matches = responseHeaders.link && responseHeaders.link.match(/<([^<>]+)>; rel="deprecation"/); + const deprecationLink = matches && matches.pop(); + log.warn( + `[@octokit/request] "${requestOptions.method} ${requestOptions.url}" is deprecated. It is scheduled to be removed on ${responseHeaders.sunset}${deprecationLink ? `. See ${deprecationLink}` : ""}` + ); + } + if (status === 204 || status === 205) { + return octokitResponse; + } + if (requestOptions.method === "HEAD") { + if (status < 400) { + return octokitResponse; + } + throw new RequestError(fetchResponse.statusText, status, { + response: octokitResponse, + request: requestOptions + }); + } + if (status === 304) { + octokitResponse.data = await getResponseData(fetchResponse); + throw new RequestError("Not modified", status, { + response: octokitResponse, + request: requestOptions + }); + } + if (status >= 400) { + octokitResponse.data = await getResponseData(fetchResponse); + throw new RequestError(toErrorMessage(octokitResponse.data), status, { + response: octokitResponse, + request: requestOptions + }); + } + octokitResponse.data = parseSuccessResponseBody ? await getResponseData(fetchResponse) : fetchResponse.body; + return octokitResponse; +} +async function getResponseData(response) { + const contentType = response.headers.get("content-type"); + if (!contentType) { + return response.text().catch(noop); + } + const mimetype = dist_parse(contentType); + if (isJSONResponse(mimetype)) { + let text = ""; + try { + text = await response.text(); + return JSONParse(text); + } catch (err) { + return text; + } + } else if (mimetype.type.startsWith("text/") || // `application/octet-stream` is the canonical "arbitrary binary" type + // (RFC 2046) and must never be decoded as text, even when the response + // carries a (misleading) `charset=utf-8` parameter — see #751. + mimetype.parameters.charset?.toLowerCase() === "utf-8" && mimetype.type !== "application/octet-stream") { + return response.text().catch(noop); + } else { + return response.arrayBuffer().catch( + /* v8 ignore next -- @preserve */ + () => new ArrayBuffer(0) + ); + } +} +function isJSONResponse(mimetype) { + return mimetype.type === "application/json" || mimetype.type === "application/scim+json"; +} +function toErrorMessage(data) { + if (typeof data === "string") { + return data; + } + if (data instanceof ArrayBuffer) { + return "Unknown error"; + } + if (typeof data === "object" && data !== null && "message" in data) { + const objectData = data; + const suffix = "documentation_url" in objectData ? ` - ${objectData.documentation_url}` : ""; + return Array.isArray(objectData.errors) ? `${objectData.message}: ${objectData.errors.map((v) => JSON.stringify(v)).join(", ")}${suffix}` : `${objectData.message}${suffix}`; + } + return `Unknown error: ${JSON.stringify(data)}`; +} + +// pkg/dist-src/with-defaults.js +function dist_bundle_withDefaults(oldEndpoint, newDefaults) { + const endpoint2 = oldEndpoint.defaults(newDefaults); + const newApi = function(route, parameters) { + const endpointOptions = endpoint2.merge(route, parameters); + if (!endpointOptions.request || !endpointOptions.request.hook) { + return fetchWrapper(endpoint2.parse(endpointOptions)); + } + const request2 = (route2, parameters2) => { + return fetchWrapper( + endpoint2.parse(endpoint2.merge(route2, parameters2)) + ); + }; + Object.assign(request2, { + endpoint: endpoint2, + defaults: dist_bundle_withDefaults.bind(null, endpoint2) + }); + return endpointOptions.request.hook(request2, endpointOptions); + }; + return Object.assign(newApi, { + endpoint: endpoint2, + defaults: dist_bundle_withDefaults.bind(null, endpoint2) + }); +} + +// pkg/dist-src/index.js +var request = dist_bundle_withDefaults(endpoint, defaults_default); + +/* v8 ignore next -- @preserve */ +/* v8 ignore else -- @preserve */ + +;// CONCATENATED MODULE: ./node_modules/.pnpm/@octokit+graphql@9.0.5/node_modules/@octokit/graphql/dist-bundle/index.js +// pkg/dist-src/index.js + + + +// pkg/dist-src/version.js +var graphql_dist_bundle_VERSION = "0.0.0-development"; + +// pkg/dist-src/with-defaults.js + + +// pkg/dist-src/graphql.js + + +// pkg/dist-src/error.js +function _buildMessageForResponseErrors(data) { + return `Request failed due to following response errors: +` + data.errors.map((e) => ` - ${e.message}`).join("\n"); +} +var GraphqlResponseError = class extends Error { + constructor(request2, headers, response) { + super(_buildMessageForResponseErrors(response)); + this.request = request2; + this.headers = headers; + this.response = response; + this.errors = response.errors; + this.data = response.data; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + } + request; + headers; + response; + name = "GraphqlResponseError"; + errors; + data; +}; + +// pkg/dist-src/graphql.js +var NON_VARIABLE_OPTIONS = [ + "method", + "baseUrl", + "url", + "headers", + "request", + "query", + "mediaType", + "operationName" +]; +var FORBIDDEN_VARIABLE_OPTIONS = ["query", "method", "url"]; +var GHES_V3_SUFFIX_REGEX = /\/api\/v3\/?$/; +function graphql(request2, query, options) { + if (options) { + if (typeof query === "string" && "query" in options) { + return Promise.reject( + new Error(`[@octokit/graphql] "query" cannot be used as variable name`) + ); + } + for (const key in options) { + if (!FORBIDDEN_VARIABLE_OPTIONS.includes(key)) continue; + return Promise.reject( + new Error( + `[@octokit/graphql] "${key}" cannot be used as variable name` + ) + ); + } + } + const parsedOptions = typeof query === "string" ? Object.assign({ query }, options) : query; + const requestOptions = Object.keys( + parsedOptions + ).reduce((result, key) => { + if (NON_VARIABLE_OPTIONS.includes(key)) { + result[key] = parsedOptions[key]; + return result; + } + if (!result.variables) { + result.variables = {}; + } + result.variables[key] = parsedOptions[key]; + return result; + }, {}); + const baseUrl = parsedOptions.baseUrl || request2.endpoint.DEFAULTS.baseUrl; + if (GHES_V3_SUFFIX_REGEX.test(baseUrl)) { + requestOptions.url = baseUrl.replace(GHES_V3_SUFFIX_REGEX, "/api/graphql"); + } + return request2(requestOptions).then((response) => { + if (response.data.errors) { + const headers = {}; + for (const key of Object.keys(response.headers)) { + headers[key] = response.headers[key]; + } + throw new GraphqlResponseError( + requestOptions, + headers, + response.data + ); + } + return response.data.data; + }); +} + +// pkg/dist-src/with-defaults.js +function graphql_dist_bundle_withDefaults(request2, newDefaults) { + const newRequest = request2.defaults(newDefaults); + const newApi = (query, options) => { + return graphql(newRequest, query, options); + }; + return Object.assign(newApi, { + defaults: graphql_dist_bundle_withDefaults.bind(null, newRequest), + endpoint: newRequest.endpoint + }); +} + +// pkg/dist-src/index.js +var graphql2 = graphql_dist_bundle_withDefaults(request, { + headers: { + "user-agent": `octokit-graphql.js/${graphql_dist_bundle_VERSION} ${getUserAgent()}` + }, + method: "POST", + url: "/graphql" +}); +function withCustomRequest(customRequest) { + return graphql_dist_bundle_withDefaults(customRequest, { + method: "POST", + url: "/graphql" + }); +} + +/* v8 ignore if -- @preserve */ + +;// CONCATENATED MODULE: ./node_modules/.pnpm/@octokit+auth-token@6.0.0/node_modules/@octokit/auth-token/dist-bundle/index.js +// pkg/dist-src/is-jwt.js +var b64url = "(?:[a-zA-Z0-9_-]+)"; +var sep = "\\."; +var jwtRE = new RegExp(`^${b64url}${sep}${b64url}${sep}${b64url}$`); +var isJWT = jwtRE.test.bind(jwtRE); + +// pkg/dist-src/auth.js +async function auth(token) { + const isApp = isJWT(token); + const isInstallation = token.startsWith("v1.") || token.startsWith("ghs_"); + const isUserToServer = token.startsWith("ghu_"); + const tokenType = isApp ? "app" : isInstallation ? "installation" : isUserToServer ? "user-to-server" : "oauth"; + return { + type: "token", + token, + tokenType + }; +} + +// pkg/dist-src/with-authorization-prefix.js +function withAuthorizationPrefix(token) { + if (token.split(/\./).length === 3) { + return `bearer ${token}`; + } + return `token ${token}`; +} + +// pkg/dist-src/hook.js +async function hook(token, request, route, parameters) { + const endpoint = request.endpoint.merge( + route, + parameters + ); + endpoint.headers.authorization = withAuthorizationPrefix(token); + return request(endpoint); +} + +// pkg/dist-src/index.js +var createTokenAuth = function createTokenAuth2(token) { + if (!token) { + throw new Error("[@octokit/auth-token] No token passed to createTokenAuth"); + } + if (typeof token !== "string") { + throw new Error( + "[@octokit/auth-token] Token passed to createTokenAuth is not a string" + ); + } + token = token.replace(/^(token|bearer) +/i, ""); + return Object.assign(auth.bind(null, token), { + hook: hook.bind(null, token) + }); +}; + + +;// CONCATENATED MODULE: ./node_modules/.pnpm/@octokit+core@7.0.8/node_modules/@octokit/core/dist-src/version.js +const version_VERSION = "7.0.8"; + + +;// CONCATENATED MODULE: ./node_modules/.pnpm/@octokit+core@7.0.8/node_modules/@octokit/core/dist-src/index.js + + + + + + +const dist_src_noop = () => { +}; +const consoleWarn = console.warn.bind(console); +const consoleError = console.error.bind(console); +function createLogger(logger = {}) { + if (typeof logger.debug !== "function") { + logger.debug = dist_src_noop; + } + if (typeof logger.info !== "function") { + logger.info = dist_src_noop; + } + if (typeof logger.warn !== "function") { + logger.warn = consoleWarn; + } + if (typeof logger.error !== "function") { + logger.error = consoleError; + } + return logger; +} +const userAgentTrail = `octokit-core.js/${version_VERSION} ${getUserAgent()}`; +class Octokit { + static VERSION = version_VERSION; + static defaults(defaults) { + const OctokitWithDefaults = class extends this { + constructor(...args) { + const options = args[0] || {}; + if (typeof defaults === "function") { + super(defaults(options)); + return; + } + super( + Object.assign( + {}, + defaults, + options, + options.userAgent && defaults.userAgent ? { + userAgent: `${options.userAgent} ${defaults.userAgent}` + } : null + ) + ); + } + }; + return OctokitWithDefaults; + } + static plugins = []; + /** + * Attach a plugin (or many) to your Octokit instance. + * + * @example + * const API = Octokit.plugin(plugin1, plugin2, plugin3, ...) + */ + static plugin(...newPlugins) { + const currentPlugins = this.plugins; + const NewOctokit = class extends this { + static plugins = currentPlugins.concat( + newPlugins.filter((plugin) => !currentPlugins.includes(plugin)) + ); + }; + return NewOctokit; + } + constructor(options = {}) { + const hook = new before_after_hook.Collection(); + const requestDefaults = { + baseUrl: request.endpoint.DEFAULTS.baseUrl, + headers: {}, + request: Object.assign({}, options.request, { + // @ts-ignore internal usage only, no need to type + hook: hook.bind(null, "request") + }), + mediaType: { + previews: [], + format: "" + } + }; + requestDefaults.headers["user-agent"] = options.userAgent ? `${options.userAgent} ${userAgentTrail}` : userAgentTrail; + if (options.baseUrl) { + requestDefaults.baseUrl = options.baseUrl; + } + if (options.previews) { + requestDefaults.mediaType.previews = options.previews; + } + if (options.timeZone) { + requestDefaults.headers["time-zone"] = options.timeZone; + } + this.request = request.defaults(requestDefaults); + this.graphql = withCustomRequest(this.request).defaults(requestDefaults); + this.log = createLogger(options.log); + this.hook = hook; + if (!options.authStrategy) { + if (!options.auth) { + this.auth = async () => ({ + type: "unauthenticated" + }); + } else { + const auth = createTokenAuth(options.auth); + hook.wrap("request", auth.hook); + this.auth = auth; + } + } else { + const { authStrategy, ...otherOptions } = options; + const auth = authStrategy( + Object.assign( + { + request: this.request, + log: this.log, + // we pass the current octokit instance as well as its constructor options + // to allow for authentication strategies that return a new octokit instance + // that shares the same internal state as the current one. The original + // requirement for this was the "event-octokit" authentication strategy + // of https://github.com/probot/octokit-auth-probot. + octokit: this, + octokitOptions: otherOptions + }, + options.auth + ) + ); + hook.wrap("request", auth.hook); + this.auth = auth; + } + const classConstructor = this.constructor; + for (let i = 0; i < classConstructor.plugins.length; ++i) { + Object.assign(this, classConstructor.plugins[i](this, options)); + } + } + // assigned during constructor + request; + graphql; + log; + hook; + // TODO: type `octokit.auth` based on passed options.authStrategy + auth; +} + + +;// CONCATENATED MODULE: ./node_modules/.pnpm/@octokit+plugin-rest-endpoint-methods@17.0.0_@octokit+core@7.0.8/node_modules/@octokit/plugin-rest-endpoint-methods/dist-src/version.js +const dist_src_version_VERSION = "17.0.0"; + +//# sourceMappingURL=version.js.map + +;// CONCATENATED MODULE: ./node_modules/.pnpm/@octokit+plugin-rest-endpoint-methods@17.0.0_@octokit+core@7.0.8/node_modules/@octokit/plugin-rest-endpoint-methods/dist-src/generated/endpoints.js +const Endpoints = { + actions: { + addCustomLabelsToSelfHostedRunnerForOrg: [ + "POST /orgs/{org}/actions/runners/{runner_id}/labels" + ], + addCustomLabelsToSelfHostedRunnerForRepo: [ + "POST /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" + ], + addRepoAccessToSelfHostedRunnerGroupInOrg: [ + "PUT /orgs/{org}/actions/runner-groups/{runner_group_id}/repositories/{repository_id}" + ], + addSelectedRepoToOrgSecret: [ + "PUT /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}" + ], + addSelectedRepoToOrgVariable: [ + "PUT /orgs/{org}/actions/variables/{name}/repositories/{repository_id}" + ], + approveWorkflowRun: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/approve" + ], + cancelWorkflowRun: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel" + ], + createEnvironmentVariable: [ + "POST /repos/{owner}/{repo}/environments/{environment_name}/variables" + ], + createHostedRunnerForOrg: ["POST /orgs/{org}/actions/hosted-runners"], + createOrUpdateEnvironmentSecret: [ + "PUT /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}" + ], + createOrUpdateOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}"], + createOrUpdateRepoSecret: [ + "PUT /repos/{owner}/{repo}/actions/secrets/{secret_name}" + ], + createOrgVariable: ["POST /orgs/{org}/actions/variables"], + createRegistrationTokenForOrg: [ + "POST /orgs/{org}/actions/runners/registration-token" + ], + createRegistrationTokenForRepo: [ + "POST /repos/{owner}/{repo}/actions/runners/registration-token" + ], + createRemoveTokenForOrg: ["POST /orgs/{org}/actions/runners/remove-token"], + createRemoveTokenForRepo: [ + "POST /repos/{owner}/{repo}/actions/runners/remove-token" + ], + createRepoVariable: ["POST /repos/{owner}/{repo}/actions/variables"], + createWorkflowDispatch: [ + "POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches" + ], + deleteActionsCacheById: [ + "DELETE /repos/{owner}/{repo}/actions/caches/{cache_id}" ], deleteActionsCacheByKey: [ "DELETE /repos/{owner}/{repo}/actions/caches{?key,ref}" @@ -50064,244 +49560,1264 @@ const Endpoints = { updateAuthenticated: ["PATCH /user"] } }; -var endpoints_default = Endpoints; +var endpoints_default = Endpoints; + +//# sourceMappingURL=endpoints.js.map + +;// CONCATENATED MODULE: ./node_modules/.pnpm/@octokit+plugin-rest-endpoint-methods@17.0.0_@octokit+core@7.0.8/node_modules/@octokit/plugin-rest-endpoint-methods/dist-src/endpoints-to-methods.js + +const endpointMethodsMap = /* @__PURE__ */ new Map(); +for (const [scope, endpoints] of Object.entries(endpoints_default)) { + for (const [methodName, endpoint] of Object.entries(endpoints)) { + const [route, defaults, decorations] = endpoint; + const [method, url] = route.split(/ /); + const endpointDefaults = Object.assign( + { + method, + url + }, + defaults + ); + if (!endpointMethodsMap.has(scope)) { + endpointMethodsMap.set(scope, /* @__PURE__ */ new Map()); + } + endpointMethodsMap.get(scope).set(methodName, { + scope, + methodName, + endpointDefaults, + decorations + }); + } +} +const handler = { + has({ scope }, methodName) { + return endpointMethodsMap.get(scope).has(methodName); + }, + getOwnPropertyDescriptor(target, methodName) { + return { + value: this.get(target, methodName), + // ensures method is in the cache + configurable: true, + writable: true, + enumerable: true + }; + }, + defineProperty(target, methodName, descriptor) { + Object.defineProperty(target.cache, methodName, descriptor); + return true; + }, + deleteProperty(target, methodName) { + delete target.cache[methodName]; + return true; + }, + ownKeys({ scope }) { + return [...endpointMethodsMap.get(scope).keys()]; + }, + set(target, methodName, value) { + return target.cache[methodName] = value; + }, + get({ octokit, scope, cache }, methodName) { + if (cache[methodName]) { + return cache[methodName]; + } + const method = endpointMethodsMap.get(scope).get(methodName); + if (!method) { + return void 0; + } + const { endpointDefaults, decorations } = method; + if (decorations) { + cache[methodName] = decorate( + octokit, + scope, + methodName, + endpointDefaults, + decorations + ); + } else { + cache[methodName] = octokit.request.defaults(endpointDefaults); + } + return cache[methodName]; + } +}; +function endpointsToMethods(octokit) { + const newMethods = {}; + for (const scope of endpointMethodsMap.keys()) { + newMethods[scope] = new Proxy({ octokit, scope, cache: {} }, handler); + } + return newMethods; +} +function decorate(octokit, scope, methodName, defaults, decorations) { + const requestWithDefaults = octokit.request.defaults(defaults); + function withDecorations(...args) { + let options = requestWithDefaults.endpoint.merge(...args); + if (decorations.mapToData) { + options = Object.assign({}, options, { + data: options[decorations.mapToData], + [decorations.mapToData]: void 0 + }); + return requestWithDefaults(options); + } + if (decorations.renamed) { + const [newScope, newMethodName] = decorations.renamed; + octokit.log.warn( + `octokit.${scope}.${methodName}() has been renamed to octokit.${newScope}.${newMethodName}()` + ); + } + if (decorations.deprecated) { + octokit.log.warn(decorations.deprecated); + } + if (decorations.renamedParameters) { + const options2 = requestWithDefaults.endpoint.merge(...args); + for (const [name, alias] of Object.entries( + decorations.renamedParameters + )) { + if (name in options2) { + octokit.log.warn( + `"${name}" parameter is deprecated for "octokit.${scope}.${methodName}()". Use "${alias}" instead` + ); + if (!(alias in options2)) { + options2[alias] = options2[name]; + } + delete options2[name]; + } + } + return requestWithDefaults(options2); + } + return requestWithDefaults(...args); + } + return Object.assign(withDecorations, requestWithDefaults); +} + +//# sourceMappingURL=endpoints-to-methods.js.map + +;// CONCATENATED MODULE: ./node_modules/.pnpm/@octokit+plugin-rest-endpoint-methods@17.0.0_@octokit+core@7.0.8/node_modules/@octokit/plugin-rest-endpoint-methods/dist-src/index.js + + +function restEndpointMethods(octokit) { + const api = endpointsToMethods(octokit); + return { + rest: api + }; +} +restEndpointMethods.VERSION = dist_src_version_VERSION; +function legacyRestEndpointMethods(octokit) { + const api = endpointsToMethods(octokit); + return { + ...api, + rest: api + }; +} +legacyRestEndpointMethods.VERSION = dist_src_version_VERSION; + +//# sourceMappingURL=index.js.map + +;// CONCATENATED MODULE: ./node_modules/.pnpm/@octokit+plugin-paginate-rest@14.0.0_@octokit+core@7.0.8/node_modules/@octokit/plugin-paginate-rest/dist-bundle/index.js +// pkg/dist-src/version.js +var plugin_paginate_rest_dist_bundle_VERSION = "0.0.0-development"; + +// pkg/dist-src/normalize-paginated-list-response.js +function normalizePaginatedListResponse(response) { + if (!response.data) { + return { + ...response, + data: [] + }; + } + const responseNeedsNormalization = ("total_count" in response.data || "total_commits" in response.data) && !("url" in response.data); + if (!responseNeedsNormalization) return response; + const incompleteResults = response.data.incomplete_results; + const repositorySelection = response.data.repository_selection; + const totalCount = response.data.total_count; + const totalCommits = response.data.total_commits; + delete response.data.incomplete_results; + delete response.data.repository_selection; + delete response.data.total_count; + delete response.data.total_commits; + const namespaceKey = Object.keys(response.data)[0]; + const data = response.data[namespaceKey]; + response.data = data; + if (typeof incompleteResults !== "undefined") { + response.data.incomplete_results = incompleteResults; + } + if (typeof repositorySelection !== "undefined") { + response.data.repository_selection = repositorySelection; + } + response.data.total_count = totalCount; + response.data.total_commits = totalCommits; + return response; +} + +// pkg/dist-src/iterator.js +function iterator(octokit, route, parameters) { + const options = typeof route === "function" ? route.endpoint(parameters) : octokit.request.endpoint(route, parameters); + const requestMethod = typeof route === "function" ? route : octokit.request; + const method = options.method; + const headers = options.headers; + let url = options.url; + return { + [Symbol.asyncIterator]: () => ({ + async next() { + if (!url) return { done: true }; + try { + const response = await requestMethod({ method, url, headers }); + const normalizedResponse = normalizePaginatedListResponse(response); + url = ((normalizedResponse.headers.link || "").match( + /<([^<>]+)>;\s*rel="next"/ + ) || [])[1]; + if (!url && "total_commits" in normalizedResponse.data) { + const parsedUrl = new URL(normalizedResponse.url); + const params = parsedUrl.searchParams; + const page = parseInt(params.get("page") || "1", 10); + const per_page = parseInt(params.get("per_page") || "250", 10); + if (page * per_page < normalizedResponse.data.total_commits) { + params.set("page", String(page + 1)); + url = parsedUrl.toString(); + } + } + return { value: normalizedResponse }; + } catch (error) { + if (error.status !== 409) throw error; + url = ""; + return { + value: { + status: 200, + headers: {}, + data: [] + } + }; + } + } + }) + }; +} + +// pkg/dist-src/paginate.js +function paginate(octokit, route, parameters, mapFn) { + if (typeof parameters === "function") { + mapFn = parameters; + parameters = void 0; + } + return gather( + octokit, + [], + iterator(octokit, route, parameters)[Symbol.asyncIterator](), + mapFn + ); +} +function gather(octokit, results, iterator2, mapFn) { + return iterator2.next().then((result) => { + if (result.done) { + return results; + } + let earlyExit = false; + function done() { + earlyExit = true; + } + results = results.concat( + mapFn ? mapFn(result.value, done) : result.value.data + ); + if (earlyExit) { + return results; + } + return gather(octokit, results, iterator2, mapFn); + }); +} + +// pkg/dist-src/compose-paginate.js +var composePaginateRest = Object.assign(paginate, { + iterator +}); + +// pkg/dist-src/generated/paginating-endpoints.js +var paginatingEndpoints = (/* unused pure expression or super */ null && ([ + "GET /advisories", + "GET /app/hook/deliveries", + "GET /app/installation-requests", + "GET /app/installations", + "GET /assignments/{assignment_id}/accepted_assignments", + "GET /classrooms", + "GET /classrooms/{classroom_id}/assignments", + "GET /enterprises/{enterprise}/code-security/configurations", + "GET /enterprises/{enterprise}/code-security/configurations/{configuration_id}/repositories", + "GET /enterprises/{enterprise}/dependabot/alerts", + "GET /enterprises/{enterprise}/teams", + "GET /enterprises/{enterprise}/teams/{enterprise-team}/memberships", + "GET /enterprises/{enterprise}/teams/{enterprise-team}/organizations", + "GET /events", + "GET /gists", + "GET /gists/public", + "GET /gists/starred", + "GET /gists/{gist_id}/comments", + "GET /gists/{gist_id}/commits", + "GET /gists/{gist_id}/forks", + "GET /installation/repositories", + "GET /issues", + "GET /licenses", + "GET /marketplace_listing/plans", + "GET /marketplace_listing/plans/{plan_id}/accounts", + "GET /marketplace_listing/stubbed/plans", + "GET /marketplace_listing/stubbed/plans/{plan_id}/accounts", + "GET /networks/{owner}/{repo}/events", + "GET /notifications", + "GET /organizations", + "GET /organizations/{org}/dependabot/repository-access", + "GET /orgs/{org}/actions/cache/usage-by-repository", + "GET /orgs/{org}/actions/hosted-runners", + "GET /orgs/{org}/actions/permissions/repositories", + "GET /orgs/{org}/actions/permissions/self-hosted-runners/repositories", + "GET /orgs/{org}/actions/runner-groups", + "GET /orgs/{org}/actions/runner-groups/{runner_group_id}/hosted-runners", + "GET /orgs/{org}/actions/runner-groups/{runner_group_id}/repositories", + "GET /orgs/{org}/actions/runner-groups/{runner_group_id}/runners", + "GET /orgs/{org}/actions/runners", + "GET /orgs/{org}/actions/secrets", + "GET /orgs/{org}/actions/secrets/{secret_name}/repositories", + "GET /orgs/{org}/actions/variables", + "GET /orgs/{org}/actions/variables/{name}/repositories", + "GET /orgs/{org}/attestations/repositories", + "GET /orgs/{org}/attestations/{subject_digest}", + "GET /orgs/{org}/blocks", + "GET /orgs/{org}/campaigns", + "GET /orgs/{org}/code-scanning/alerts", + "GET /orgs/{org}/code-security/configurations", + "GET /orgs/{org}/code-security/configurations/{configuration_id}/repositories", + "GET /orgs/{org}/codespaces", + "GET /orgs/{org}/codespaces/secrets", + "GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories", + "GET /orgs/{org}/copilot/billing/seats", + "GET /orgs/{org}/copilot/metrics", + "GET /orgs/{org}/dependabot/alerts", + "GET /orgs/{org}/dependabot/secrets", + "GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories", + "GET /orgs/{org}/events", + "GET /orgs/{org}/failed_invitations", + "GET /orgs/{org}/hooks", + "GET /orgs/{org}/hooks/{hook_id}/deliveries", + "GET /orgs/{org}/insights/api/route-stats/{actor_type}/{actor_id}", + "GET /orgs/{org}/insights/api/subject-stats", + "GET /orgs/{org}/insights/api/user-stats/{user_id}", + "GET /orgs/{org}/installations", + "GET /orgs/{org}/invitations", + "GET /orgs/{org}/invitations/{invitation_id}/teams", + "GET /orgs/{org}/issues", + "GET /orgs/{org}/members", + "GET /orgs/{org}/members/{username}/codespaces", + "GET /orgs/{org}/migrations", + "GET /orgs/{org}/migrations/{migration_id}/repositories", + "GET /orgs/{org}/organization-roles/{role_id}/teams", + "GET /orgs/{org}/organization-roles/{role_id}/users", + "GET /orgs/{org}/outside_collaborators", + "GET /orgs/{org}/packages", + "GET /orgs/{org}/packages/{package_type}/{package_name}/versions", + "GET /orgs/{org}/personal-access-token-requests", + "GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories", + "GET /orgs/{org}/personal-access-tokens", + "GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories", + "GET /orgs/{org}/private-registries", + "GET /orgs/{org}/projects", + "GET /orgs/{org}/projectsV2", + "GET /orgs/{org}/projectsV2/{project_number}/fields", + "GET /orgs/{org}/projectsV2/{project_number}/items", + "GET /orgs/{org}/properties/values", + "GET /orgs/{org}/public_members", + "GET /orgs/{org}/repos", + "GET /orgs/{org}/rulesets", + "GET /orgs/{org}/rulesets/rule-suites", + "GET /orgs/{org}/rulesets/{ruleset_id}/history", + "GET /orgs/{org}/secret-scanning/alerts", + "GET /orgs/{org}/security-advisories", + "GET /orgs/{org}/settings/immutable-releases/repositories", + "GET /orgs/{org}/settings/network-configurations", + "GET /orgs/{org}/team/{team_slug}/copilot/metrics", + "GET /orgs/{org}/teams", + "GET /orgs/{org}/teams/{team_slug}/discussions", + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments", + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions", + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions", + "GET /orgs/{org}/teams/{team_slug}/invitations", + "GET /orgs/{org}/teams/{team_slug}/members", + "GET /orgs/{org}/teams/{team_slug}/projects", + "GET /orgs/{org}/teams/{team_slug}/repos", + "GET /orgs/{org}/teams/{team_slug}/teams", + "GET /projects/{project_id}/collaborators", + "GET /repos/{owner}/{repo}/actions/artifacts", + "GET /repos/{owner}/{repo}/actions/caches", + "GET /repos/{owner}/{repo}/actions/organization-secrets", + "GET /repos/{owner}/{repo}/actions/organization-variables", + "GET /repos/{owner}/{repo}/actions/runners", + "GET /repos/{owner}/{repo}/actions/runs", + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts", + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs", + "GET /repos/{owner}/{repo}/actions/secrets", + "GET /repos/{owner}/{repo}/actions/variables", + "GET /repos/{owner}/{repo}/actions/workflows", + "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs", + "GET /repos/{owner}/{repo}/activity", + "GET /repos/{owner}/{repo}/assignees", + "GET /repos/{owner}/{repo}/attestations/{subject_digest}", + "GET /repos/{owner}/{repo}/branches", + "GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations", + "GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs", + "GET /repos/{owner}/{repo}/code-scanning/alerts", + "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances", + "GET /repos/{owner}/{repo}/code-scanning/analyses", + "GET /repos/{owner}/{repo}/codespaces", + "GET /repos/{owner}/{repo}/codespaces/devcontainers", + "GET /repos/{owner}/{repo}/codespaces/secrets", + "GET /repos/{owner}/{repo}/collaborators", + "GET /repos/{owner}/{repo}/comments", + "GET /repos/{owner}/{repo}/comments/{comment_id}/reactions", + "GET /repos/{owner}/{repo}/commits", + "GET /repos/{owner}/{repo}/commits/{commit_sha}/comments", + "GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls", + "GET /repos/{owner}/{repo}/commits/{ref}/check-runs", + "GET /repos/{owner}/{repo}/commits/{ref}/check-suites", + "GET /repos/{owner}/{repo}/commits/{ref}/status", + "GET /repos/{owner}/{repo}/commits/{ref}/statuses", + "GET /repos/{owner}/{repo}/compare/{basehead}", + "GET /repos/{owner}/{repo}/compare/{base}...{head}", + "GET /repos/{owner}/{repo}/contributors", + "GET /repos/{owner}/{repo}/dependabot/alerts", + "GET /repos/{owner}/{repo}/dependabot/secrets", + "GET /repos/{owner}/{repo}/deployments", + "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses", + "GET /repos/{owner}/{repo}/environments", + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies", + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps", + "GET /repos/{owner}/{repo}/environments/{environment_name}/secrets", + "GET /repos/{owner}/{repo}/environments/{environment_name}/variables", + "GET /repos/{owner}/{repo}/events", + "GET /repos/{owner}/{repo}/forks", + "GET /repos/{owner}/{repo}/hooks", + "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries", + "GET /repos/{owner}/{repo}/invitations", + "GET /repos/{owner}/{repo}/issues", + "GET /repos/{owner}/{repo}/issues/comments", + "GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions", + "GET /repos/{owner}/{repo}/issues/events", + "GET /repos/{owner}/{repo}/issues/{issue_number}/comments", + "GET /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by", + "GET /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocking", + "GET /repos/{owner}/{repo}/issues/{issue_number}/events", + "GET /repos/{owner}/{repo}/issues/{issue_number}/labels", + "GET /repos/{owner}/{repo}/issues/{issue_number}/reactions", + "GET /repos/{owner}/{repo}/issues/{issue_number}/sub_issues", + "GET /repos/{owner}/{repo}/issues/{issue_number}/timeline", + "GET /repos/{owner}/{repo}/keys", + "GET /repos/{owner}/{repo}/labels", + "GET /repos/{owner}/{repo}/milestones", + "GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels", + "GET /repos/{owner}/{repo}/notifications", + "GET /repos/{owner}/{repo}/pages/builds", + "GET /repos/{owner}/{repo}/projects", + "GET /repos/{owner}/{repo}/pulls", + "GET /repos/{owner}/{repo}/pulls/comments", + "GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions", + "GET /repos/{owner}/{repo}/pulls/{pull_number}/comments", + "GET /repos/{owner}/{repo}/pulls/{pull_number}/commits", + "GET /repos/{owner}/{repo}/pulls/{pull_number}/files", + "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews", + "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments", + "GET /repos/{owner}/{repo}/releases", + "GET /repos/{owner}/{repo}/releases/{release_id}/assets", + "GET /repos/{owner}/{repo}/releases/{release_id}/reactions", + "GET /repos/{owner}/{repo}/rules/branches/{branch}", + "GET /repos/{owner}/{repo}/rulesets", + "GET /repos/{owner}/{repo}/rulesets/rule-suites", + "GET /repos/{owner}/{repo}/rulesets/{ruleset_id}/history", + "GET /repos/{owner}/{repo}/secret-scanning/alerts", + "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations", + "GET /repos/{owner}/{repo}/security-advisories", + "GET /repos/{owner}/{repo}/stargazers", + "GET /repos/{owner}/{repo}/subscribers", + "GET /repos/{owner}/{repo}/tags", + "GET /repos/{owner}/{repo}/teams", + "GET /repos/{owner}/{repo}/topics", + "GET /repositories", + "GET /search/code", + "GET /search/commits", + "GET /search/issues", + "GET /search/labels", + "GET /search/repositories", + "GET /search/topics", + "GET /search/users", + "GET /teams/{team_id}/discussions", + "GET /teams/{team_id}/discussions/{discussion_number}/comments", + "GET /teams/{team_id}/discussions/{discussion_number}/comments/{comment_number}/reactions", + "GET /teams/{team_id}/discussions/{discussion_number}/reactions", + "GET /teams/{team_id}/invitations", + "GET /teams/{team_id}/members", + "GET /teams/{team_id}/projects", + "GET /teams/{team_id}/repos", + "GET /teams/{team_id}/teams", + "GET /user/blocks", + "GET /user/codespaces", + "GET /user/codespaces/secrets", + "GET /user/emails", + "GET /user/followers", + "GET /user/following", + "GET /user/gpg_keys", + "GET /user/installations", + "GET /user/installations/{installation_id}/repositories", + "GET /user/issues", + "GET /user/keys", + "GET /user/marketplace_purchases", + "GET /user/marketplace_purchases/stubbed", + "GET /user/memberships/orgs", + "GET /user/migrations", + "GET /user/migrations/{migration_id}/repositories", + "GET /user/orgs", + "GET /user/packages", + "GET /user/packages/{package_type}/{package_name}/versions", + "GET /user/public_emails", + "GET /user/repos", + "GET /user/repository_invitations", + "GET /user/social_accounts", + "GET /user/ssh_signing_keys", + "GET /user/starred", + "GET /user/subscriptions", + "GET /user/teams", + "GET /users", + "GET /users/{username}/attestations/{subject_digest}", + "GET /users/{username}/events", + "GET /users/{username}/events/orgs/{org}", + "GET /users/{username}/events/public", + "GET /users/{username}/followers", + "GET /users/{username}/following", + "GET /users/{username}/gists", + "GET /users/{username}/gpg_keys", + "GET /users/{username}/keys", + "GET /users/{username}/orgs", + "GET /users/{username}/packages", + "GET /users/{username}/projects", + "GET /users/{username}/projectsV2", + "GET /users/{username}/projectsV2/{project_number}/fields", + "GET /users/{username}/projectsV2/{project_number}/items", + "GET /users/{username}/received_events", + "GET /users/{username}/received_events/public", + "GET /users/{username}/repos", + "GET /users/{username}/social_accounts", + "GET /users/{username}/ssh_signing_keys", + "GET /users/{username}/starred", + "GET /users/{username}/subscriptions" +])); + +// pkg/dist-src/paginating-endpoints.js +function isPaginatingEndpoint(arg) { + if (typeof arg === "string") { + return paginatingEndpoints.includes(arg); + } else { + return false; + } +} + +// pkg/dist-src/index.js +function paginateRest(octokit) { + return { + paginate: Object.assign(paginate.bind(null, octokit), { + iterator: iterator.bind(null, octokit) + }) + }; +} +paginateRest.VERSION = plugin_paginate_rest_dist_bundle_VERSION; + + +;// CONCATENATED MODULE: ./node_modules/.pnpm/@actions+github@9.1.1/node_modules/@actions/github/lib/utils.js + + +// octokit + plugins + + + +const context = new Context(); +const baseUrl = getApiBaseUrl(); +const defaults = { + baseUrl, + request: { + agent: getProxyAgent(baseUrl), + fetch: getProxyFetch(baseUrl) + } +}; +const utils_GitHub = Octokit.plugin(restEndpointMethods, paginateRest).defaults(defaults); -//# sourceMappingURL=endpoints.js.map +/** + * Convience function to correctly format Octokit Options to pass into the constructor. + * + * @param token the repo PAT or GITHUB_TOKEN + * @param options other options to set + */ +function utils_getOctokitOptions(token, options) { + const opts = Object.assign({}, options || {}); // Shallow clone - don't mutate the object provided by the caller + // Auth + const auth = Utils.getAuthString(token, opts); + if (auth) { + opts.auth = auth; + } + // Orchestration ID + const userAgent = Utils.getUserAgentWithOrchestrationId(opts.userAgent); + if (userAgent) { + opts.userAgent = userAgent; + } + return opts; +} +//# sourceMappingURL=utils.js.map +;// CONCATENATED MODULE: ./node_modules/.pnpm/@actions+github@9.1.1/node_modules/@actions/github/lib/github.js -;// CONCATENATED MODULE: ./node_modules/.pnpm/@octokit+plugin-rest-endpoint-methods@17.0.0_@octokit+core@7.0.6/node_modules/@octokit/plugin-rest-endpoint-methods/dist-src/endpoints-to-methods.js -const endpointMethodsMap = /* @__PURE__ */ new Map(); -for (const [scope, endpoints] of Object.entries(endpoints_default)) { - for (const [methodName, endpoint] of Object.entries(endpoints)) { - const [route, defaults, decorations] = endpoint; - const [method, url] = route.split(/ /); - const endpointDefaults = Object.assign( - { - method, - url - }, - defaults - ); - if (!endpointMethodsMap.has(scope)) { - endpointMethodsMap.set(scope, /* @__PURE__ */ new Map()); +const github_context = new Context(); +/** + * Returns a hydrated octokit ready to use for GitHub Actions + * + * @param token the repo PAT or GITHUB_TOKEN + * @param options other options to set + */ +function getOctokit(token, options, ...additionalPlugins) { + const GitHubWithPlugins = GitHub.plugin(...additionalPlugins); + return new GitHubWithPlugins(getOctokitOptions(token, options)); +} +//# sourceMappingURL=github.js.map +;// CONCATENATED MODULE: ./src/methods/app-file.ts + + +/** Characters that make an app-file value a glob pattern. */ +const GLOB_CHARS = /[*?[\]{}]/; +/** + * Resolve the app-file input, so it can be a glob as it can with Maestro + * Cloud's action (e.g. `app/build/outputs/apk/release/*.apk`). + * + * A value without glob characters is returned unchanged, and so is one that + * exists as written, so a path that happens to contain `[` or `{` keeps + * working. Anything else is expanded relative to `cwd` and the first match in + * sorted order wins: sorting makes the pick the same on every runner, which + * the order the filesystem lists entries in is not. Directories match too, + * since an iOS simulator build is a `.app` directory. + * + * Uses Node's built-in fs.globSync (Node 22+; the action runs on node24), so + * no glob library is bundled. + */ +function resolveAppFile(appFile, cwd = process.cwd()) { + if (!appFile || + !GLOB_CHARS.test(appFile) || + external_fs_namespaceObject.existsSync(external_path_namespaceObject.resolve(cwd, appFile))) { + return { path: appFile, matches: [] }; } - endpointMethodsMap.get(scope).set(methodName, { - scope, - methodName, - endpointDefaults, - decorations + const matches = external_fs_namespaceObject.globSync(appFile, { cwd }).sort(); + if (matches.length === 0) { + throw new Error(`No file matches the app-file pattern "${appFile}"`); + } + return { path: matches[0], matches }; +} + +;// CONCATENATED MODULE: ./src/methods/params.ts +var params_awaiter = (undefined && undefined.__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()); + }); +}; + + + +function getAndroidApiLevel(apiLevel) { + return apiLevel ? +apiLevel : undefined; +} +function getIOSVersion(iosVersion) { + return iosVersion ? +iosVersion : undefined; +} +function parseTags(tags) { + if (tags === undefined || tags === '' || tags === null || tags.length === 0) + return null; + if (tags.includes(',')) { + const arrayTags = tags.split(',').map((it) => it.trim()); + if (!Array.isArray(arrayTags)) + throw new Error('tags must be an Array.'); + return arrayTags; + } + return [tags]; +} +function parseAndroidDevice(device) { + if (device === undefined || device === '') + return null; + return device; +} +function parseIOSDevice(device) { + if (device === undefined || device === '') + return null; + return device; +} +function getPullRequestTitle() { + var _a; + const pullRequestTitle = (_a = github_context.payload.pull_request) === null || _a === void 0 ? void 0 : _a.title; + if (pullRequestTitle === undefined) + return undefined; + return `${pullRequestTitle}`; +} +function getInferredName() { + var _a; + const pullRequestTitle = getPullRequestTitle(); + if (pullRequestTitle) + return pullRequestTitle; + if (github_context.eventName === 'push') { + const pushPayload = github_context.payload; + const commitMessage = (_a = pushPayload.head_commit) === null || _a === void 0 ? void 0 : _a.message; + if (commitMessage) + return commitMessage; + } + return github_context.sha; +} +/** + * `checkName` names the GitHub check this run posts. It is appended to the + * backend's base name ("DeviceCloud / iOS"), which is what lets a PR that runs + * iOS and Android as two submissions carry two checks that branch protection + * can require separately — GitHub matches required checks by name, so two runs + * sharing one name collapse into a single gate that follows whichever finished + * last. Keep it constant for a given job; a value that varies per commit can + * never be a required check. + */ +function getGithubContextMetadata(checkName) { + var _a, _b, _c, _d, _e; + const ctx = github_context; + const pr = ctx.payload.pull_request; + const rawRef = (_b = (_a = pr === null || pr === void 0 ? void 0 : pr.head) === null || _a === void 0 ? void 0 : _a.ref) !== null && _b !== void 0 ? _b : ctx.ref; + const branch = (_c = rawRef === null || rawRef === void 0 ? void 0 : rawRef.replace(/^refs\/heads\//, '')) !== null && _c !== void 0 ? _c : ''; + // On pull_request events ctx.sha is a throwaway *merge* commit; a GitHub + // check (and the developer-visible commit) must use the PR's head sha. + const headSha = (_e = (_d = pr === null || pr === void 0 ? void 0 : pr.head) === null || _d === void 0 ? void 0 : _d.sha) !== null && _e !== void 0 ? _e : ctx.sha; + const pairs = [ + `gh_sha=${headSha}`, + `gh_run_id=${ctx.runId}`, + `gh_repo=${ctx.repo.owner}/${ctx.repo.repo}`, + ]; + if (branch) + pairs.push(`gh_branch=${branch}`); + if (checkName) + pairs.push(`gh_check_name=${checkName}`); + if (pr) { + pairs.push(`gh_pr_number=${pr.number}`); + if (pr.html_url) + pairs.push(`gh_pr_url=${pr.html_url}`); + } + return pairs; +} +// The CLI accepts 0 and 90 only; fail here with a clear message rather than +// letting 180/270 through to a CLI error. +function parseOrientation(orientation) { + if (!orientation) + return undefined; + const value = parseInt(orientation); + if (value === 0 || value === 90) { + return value; + } + throw new Error(`Invalid orientation: ${orientation}. Must be 0 or 90`); +} +const REPORT_FORMATS = ['junit', 'html', 'html-detailed']; +function parseDownloadArtifacts(value) { + if (!value) + return undefined; + if (value !== 'ALL' && value !== 'FAILED') { + throw new Error(`Invalid download-artifacts value: ${value}. Must be ALL or FAILED`); + } + return value; +} +/** + * app-file as the CLI should get it: a glob is resolved to its first match + * (see resolveAppFile), and the pick is logged so it's visible in the run. + */ +function getAppFilePath(appFile) { + const { path, matches } = resolveAppFile(appFile); + if (matches.length > 1) { + const shown = matches.slice(0, 5).join(', '); + const more = matches.length > 5 ? `, and ${matches.length - 5} more` : ''; + warning(`app-file "${appFile}" matched ${matches.length} paths (${shown}${more}); ` + + `using the first: ${path}`); + } + else if (matches.length === 1) { + info(`app-file "${appFile}" matched ${path}`); + } + return path; +} +function getParameters() { + return params_awaiter(this, void 0, void 0, function* () { + const apiUrl = getInput('api-url', { required: false }) || + 'https://api.devicecloud.dev'; + const apiKey = getInput('api-key', { required: true }); + const name = getInput('name', { required: false }) || getInferredName(); + // Support both 'flows' and 'workspace' inputs (flows takes precedence if both are provided) + const flowsInput = getInput('flows', { required: false }); + const workspaceInput = getInput('workspace', { required: false }); + const workspaceFolder = flowsInput || workspaceInput; + const async = getInput('async', { required: false }) === 'true'; + const androidApiLevelString = getInput('android-api-level', { + required: false, + }); + const iOSVersionString = getInput('ios-version', { required: false }); + const includeTags = parseTags(getInput('include-tags', { required: false })); + const excludeTags = parseTags(getInput('exclude-tags', { required: false })); + const appFileInput = getInput('app-file', { required: false }); + const appBinaryId = getInput('app-binary-id', { required: false }); + const androidDevice = parseAndroidDevice(getInput('android-device', { required: false })); + const iosDevice = parseIOSDevice(getInput('ios-device', { required: false })); + const excludeFlows = getInput('exclude-flows', { required: false }); + const googlePlay = getInput('google-play', { required: false }) === 'true'; + const cancelPrevious = getInput('cancel-previous', { required: false }) === 'true'; + const deviceLocale = getInput('device-locale', { required: false }); + const downloadArtifacts = parseDownloadArtifacts(getInput('download-artifacts', { required: false })); + const maestroVersion = getInput('maestro-version', { required: false }); + const orientation = parseOrientation(getInput('orientation', { required: false })); + const ignoreShaCheck = getInput('ignore-sha-check', { required: false }) === 'true'; + const reportInput = getInput('report', { required: false }); + if (reportInput && + !REPORT_FORMATS.includes(reportInput)) { + throw new Error('Report format must be one of "junit", "html" or "html-detailed"'); + } + const report = (reportInput || undefined); + const config = getInput('config', { required: false }); + const runnerType = getInput('runner-type', { required: false }); + const renderEngine = getInput('render-engine', { required: false }); + const jsonFile = getInput('json-file', { required: false }) === 'true'; + const debug = getInput('debug', { required: false }) === 'true'; + const moropoV1ApiKey = getInput('moropo-v1-api-key', { + required: false, + }); + const useBeta = getInput('use-beta', { required: false }) === 'true'; + const checkName = getInput('check-name', { required: false }).trim(); + const includeGithubContext = getInput('include-github-context', { required: false }) !== 'false'; + const githubContext = includeGithubContext + ? getGithubContextMetadata(checkName) + : undefined; + if (checkName && !includeGithubContext) { + // Without the context there is no sha to post against, so no check at all — + // say so rather than letting the input look like it did something. + warning('check-name is ignored because include-github-context is false: with no ' + + 'commit context attached, DeviceCloud posts no check on this run.'); + } + const maestroChromeOnboarding = getInput('maestro-chrome-onboarding', { required: false }) === 'true'; + const androidNoSnapshot = getInput('android-no-snapshot', { required: false }) === 'true'; + const disableAnimations = getInput('disable-animations', { required: false }) === 'true'; + if (!(appFileInput !== '') !== (appBinaryId !== '')) { + throw new Error('Either app-file or app-binary-id must be used'); + } + const appFilePath = getAppFilePath(appFileInput); + const env = getMultilineInput('env', { required: false }); + // --quiet was always passed before this input was read, so anything but an + // explicit "false" keeps it on. + const quiet = getInput('quiet', { required: false }) !== 'false'; + const androidApiLevel = getAndroidApiLevel(androidApiLevelString); + const iOSVersion = getIOSVersion(iOSVersionString); + const retry = parseInt(getInput('retry', { required: false })) || undefined; + return { + apiUrl, + apiKey, + appFilePath, + workspaceFolder, + env, + async, + androidApiLevel, + iOSVersion, + includeTags, + excludeTags, + appBinaryId, + name, + androidDevice, + iosDevice, + excludeFlows, + googlePlay, + cancelPrevious, + deviceLocale, + downloadArtifacts, + maestroVersion, + orientation, + retry, + ignoreShaCheck, + report, + config, + runnerType, + renderEngine, + jsonFile, + debug, + moropoV1ApiKey, + useBeta, + maestroChromeOnboarding, + androidNoSnapshot, + disableAnimations, + githubContext, + quiet, + }; }); - } } -const handler = { - has({ scope }, methodName) { - return endpointMethodsMap.get(scope).has(methodName); - }, - getOwnPropertyDescriptor(target, methodName) { - return { - value: this.get(target, methodName), - // ensures method is in the cache - configurable: true, - writable: true, - enumerable: true - }; - }, - defineProperty(target, methodName, descriptor) { - Object.defineProperty(target.cache, methodName, descriptor); - return true; - }, - deleteProperty(target, methodName) { - delete target.cache[methodName]; - return true; - }, - ownKeys({ scope }) { - return [...endpointMethodsMap.get(scope).keys()]; - }, - set(target, methodName, value) { - return target.cache[methodName] = value; - }, - get({ octokit, scope, cache }, methodName) { - if (cache[methodName]) { - return cache[methodName]; - } - const method = endpointMethodsMap.get(scope).get(methodName); - if (!method) { - return void 0; + +;// CONCATENATED MODULE: ./src/methods/status.ts +/** + * The console link for the run that superseded this one. The status call's + * consoleUrl deep-links one of THIS run's results, which the newer run does + * not contain, so swap the upload and drop the result (as the CLI does). + */ +function supersedingConsoleUrl(consoleUrl, supersededBy) { + if (!consoleUrl) + return undefined; + try { + const url = new URL(consoleUrl); + url.searchParams.set('upload', supersededBy); + url.searchParams.delete('result'); + return url.toString(); } - const { endpointDefaults, decorations } = method; - if (decorations) { - cache[methodName] = decorate( - octokit, - scope, - methodName, - endpointDefaults, - decorations - ); - } else { - cache[methodName] = octokit.request.defaults(endpointDefaults); + catch (_a) { + return undefined; } - return cache[methodName]; - } -}; -function endpointsToMethods(octokit) { - const newMethods = {}; - for (const scope of endpointMethodsMap.keys()) { - newMethods[scope] = new Proxy({ octokit, scope, cache: {} }, handler); - } - return newMethods; } -function decorate(octokit, scope, methodName, defaults, decorations) { - const requestWithDefaults = octokit.request.defaults(defaults); - function withDecorations(...args) { - let options = requestWithDefaults.endpoint.merge(...args); - if (decorations.mapToData) { - options = Object.assign({}, options, { - data: options[decorations.mapToData], - [decorations.mapToData]: void 0 - }); - return requestWithDefaults(options); +/** + * Decide the job's outcome from the status call and the `dcd cloud` exit code. + * + * A superseded run passes, whatever else is true of it. A newer run from the + * same CI context cancelled its queued tests (cancel-previous), and the API + * rolls those up to FAILED, but the run no longer speaks for the commit. + * Failing the job for it would fail it for work nobody is waiting on. + * `dcd cloud` 5.6.0 exits 0 for such a run; an older CLI exits 2. + * + * Otherwise, fail on either signal. The exit code is authoritative for a run + * that finished badly; the status call can only add failures the CLI could not + * see. A non-terminal status (PENDING/RUNNING) alongside a clean exit is a racy + * or degraded status call, not a failure: the CLI watched the run to + * completion, so warn rather than turn the build red. + */ +function evaluateRun(result, cloudExitCode) { + const supersededBy = typeof result.supersededBy === 'string' ? result.supersededBy : ''; + if (supersededBy) { + const newer = supersedingConsoleUrl(result.consoleUrl, supersededBy); + return { + outcome: 'pass', + uploadStatus: 'SUPERSEDED', + message: `Superseded by ${supersededBy}: a newer run from the same CI context ` + + `replaced this one, so this job does not fail.` + + (newer ? ` Newer run: ${newer}` : ''), + }; } - if (decorations.renamed) { - const [newScope, newMethodName] = decorations.renamed; - octokit.log.warn( - `octokit.${scope}.${methodName}() has been renamed to octokit.${newScope}.${newMethodName}()` - ); + const uploadStatus = result.status || 'PENDING'; + if (cloudExitCode !== 0) { + return { + outcome: 'fail', + uploadStatus, + message: `Test run failed (dcd exited ${cloudExitCode}, status ${result.status}). ` + + `Check flow results for details: ${result.consoleUrl}`, + }; } - if (decorations.deprecated) { - octokit.log.warn(decorations.deprecated); + if (result.status === 'PASSED') { + return { + outcome: 'pass', + uploadStatus, + message: 'Successfully completed test run.', + }; } - if (decorations.renamedParameters) { - const options2 = requestWithDefaults.endpoint.merge(...args); - for (const [name, alias] of Object.entries( - decorations.renamedParameters - )) { - if (name in options2) { - octokit.log.warn( - `"${name}" parameter is deprecated for "octokit.${scope}.${methodName}()". Use "${alias}" instead` - ); - if (!(alias in options2)) { - options2[alias] = options2[name]; - } - delete options2[name]; - } - } - return requestWithDefaults(options2); + if (result.status === 'FAILED' || result.status === 'CANCELLED') { + return { + outcome: 'fail', + uploadStatus, + message: `Test run ${result.status}. Check flow results for details: ${result.consoleUrl}`, + }; } - return requestWithDefaults(...args); - } - return Object.assign(withDecorations, requestWithDefaults); + return { + outcome: 'warn', + uploadStatus, + message: `dcd reported success but the upload status is ${result.status}. ` + + `Treating the run as passed: ${result.consoleUrl}`, + }; } -//# sourceMappingURL=endpoints-to-methods.js.map - -;// CONCATENATED MODULE: ./node_modules/.pnpm/@octokit+plugin-rest-endpoint-methods@17.0.0_@octokit+core@7.0.6/node_modules/@octokit/plugin-rest-endpoint-methods/dist-src/index.js +;// CONCATENATED MODULE: ./src/methods/wrapper-version.ts -function restEndpointMethods(octokit) { - const api = endpointsToMethods(octokit); - return { - rest: api - }; -} -restEndpointMethods.VERSION = VERSION; -function legacyRestEndpointMethods(octokit) { - const api = endpointsToMethods(octokit); - return { - ...api, - rest: api - }; +/** + * The action's own version, read from package.json at RUNTIME. + * + * `entryDir` is the directory of the running entry file: `dist/` in the + * published action and `src/` from source. Both sit one level below + * package.json, so `/../package.json` is the repo root's either way. + * + * This is deliberately not `require('../package.json')` or a JSON import. ncc + * inlines those into dist/index.js, so dist then carried whatever version was + * current when it was last built. v2.5.0 shipped reporting 2.4.0 that way, and + * a release-please release PR (which bumps only package.json) would either tag + * a dist holding the previous version or force a dist rebuild into the release + * commit. The path is built from a parameter so ncc's asset relocator can't + * resolve it at build time and copy package.json into dist/. + * + * Best-effort: returns undefined rather than throwing. + */ +function readWrapperVersion(entryDir) { + try { + const manifest = JSON.parse(external_fs_namespaceObject.readFileSync(external_path_namespaceObject.join(entryDir, '..', 'package.json'), 'utf8')); + return typeof manifest.version === 'string' && manifest.version + ? manifest.version + : undefined; + } + catch (_a) { + return undefined; + } } -legacyRestEndpointMethods.VERSION = VERSION; -//# sourceMappingURL=index.js.map +;// CONCATENATED MODULE: ./src/index.ts +var src_awaiter = (undefined && undefined.__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()); + }); +}; -/***/ }) -/******/ }); -/************************************************************************/ -/******/ // 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] = { -/******/ id: moduleId, -/******/ loaded: false, -/******/ 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]; -/******/ } -/******/ -/******/ // Flag the module as loaded -/******/ module.loaded = true; -/******/ -/******/ // Return the exports of the module -/******/ return module.exports; -/******/ } -/******/ -/************************************************************************/ -/******/ /* webpack/runtime/define property getters */ -/******/ (() => { -/******/ // define getter functions for harmony exports -/******/ __nccwpck_require__.d = (exports, definition) => { -/******/ for(var key in definition) { -/******/ if(__nccwpck_require__.o(definition, key) && !__nccwpck_require__.o(exports, key)) { -/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); -/******/ } -/******/ } -/******/ }; -/******/ })(); -/******/ -/******/ /* webpack/runtime/hasOwnProperty shorthand */ -/******/ (() => { -/******/ __nccwpck_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) -/******/ })(); -/******/ -/******/ /* webpack/runtime/make namespace object */ -/******/ (() => { -/******/ // define __esModule on exports -/******/ __nccwpck_require__.r = (exports) => { -/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { -/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); -/******/ } -/******/ Object.defineProperty(exports, '__esModule', { value: true }); -/******/ }; -/******/ })(); -/******/ -/******/ /* webpack/runtime/node module decorator */ -/******/ (() => { -/******/ __nccwpck_require__.nmd = (module) => { -/******/ module.paths = []; -/******/ if (!module.children) module.children = []; -/******/ return module; -/******/ }; -/******/ })(); -/******/ -/******/ /* webpack/runtime/compat */ -/******/ -/******/ if (typeof __nccwpck_require__ !== 'undefined') __nccwpck_require__.ab = __dirname + "/"; -/******/ -/************************************************************************/ -/******/ -/******/ // startup -/******/ // Load entry module and return exports -/******/ // This entry module is referenced by other modules so it can't be inlined -/******/ var __webpack_exports__ = __nccwpck_require__(6866); -/******/ module.exports = __webpack_exports__; -/******/ + + +const dcdPackageName = '@devicecloud.dev/dcd'; +const escapeShellValue = (value) => { + // Escape special characters that could cause shell interpretation issues + return value.replace(/(["\\'$`!\s\[\]{}()&|;<>*?#^~])/g, '\\$1'); +}; +const executeCommand = (command, log = true) => { + return new Promise((resolve, reject) => { + let output = ''; + const process = (0,external_child_process_namespaceObject.spawn)(command, { shell: true }); + process.stdout.on('data', (data) => { + const chunk = data.toString(); + output += chunk; + if (log) { + console.info(chunk); + } + }); + process.stderr.on('data', (data) => { + const chunk = data.toString(); + output += chunk; + if (log) { + console.error(chunk); + } + }); + process.on('close', (code) => { + resolve({ output, exitCode: code !== null && code !== void 0 ? code : 0 }); + }); + process.on('error', (err) => { + reject(err); + }); + }); +}; +const getTestStatus = (uploadId, apiKey, dcdVersionString, apiUrl) => src_awaiter(void 0, void 0, void 0, function* () { + try { + let command = `npx --yes "${dcdVersionString}" status --json --upload-id ${uploadId} --api-key ${escapeShellValue(apiKey)}`; + if (apiUrl) { + command += ` --api-url ${escapeShellValue(apiUrl)}`; + } + const { output } = yield executeCommand(command, false); + // Filter out non-JSON lines (e.g., npm warnings) + // Find the first line that starts with '{' or '[' (JSON start) + const lines = output.split('\n'); + const jsonStartIndex = lines.findIndex(line => { + const trimmed = line.trim(); + return trimmed.startsWith('{') || trimmed.startsWith('['); + }); + if (jsonStartIndex === -1) { + throw new Error('No JSON found in output'); + } + // Log any warnings that appeared before the JSON output + if (jsonStartIndex > 0) { + const warnings = lines.slice(0, jsonStartIndex).join('\n').trim(); + if (warnings) { + console.warn('npm warnings during status check:\n', warnings); + } + } + // Join from the JSON start to the end + const jsonOutput = lines.slice(jsonStartIndex).join('\n'); + return JSON.parse(jsonOutput); + } + catch (error) { + console.warn('Failed to get test status:', error); + return null; + } +}); +const getLatestDcdVersion = (...args_1) => src_awaiter(void 0, [...args_1], void 0, function* (useBeta = false) { + try { + if (useBeta) { + console.info(`Using beta version of DCD CLI`); + return `${dcdPackageName}@beta`; + } + const { output } = yield executeCommand(`npm view ${dcdPackageName} version`, false); + const version = output.trim(); + console.info(`Latest DCD version from npm: ${version}`); + return `${dcdPackageName}@${version}`; + } + catch (error) { + console.warn('Failed to fetch latest DCD version, falling back to >=4.0.3:', error); + return `${dcdPackageName}@>=4.0.3`; + } +}); +const run = () => src_awaiter(void 0, void 0, void 0, function* () { + var _a, _b; + try { + const { androidApiLevel, androidDevice, apiKey, apiUrl, appBinaryId, appFilePath, async, cancelPrevious, config, deviceLocale, downloadArtifacts, env, excludeFlows, excludeTags, googlePlay, ignoreShaCheck, includeTags, iOSVersion, iosDevice, jsonFile, maestroVersion, name, orientation, report, retry, workspaceFolder, runnerType, renderEngine, debug, moropoV1ApiKey, useBeta, maestroChromeOnboarding, androidNoSnapshot, disableAnimations, githubContext, quiet, } = yield getParameters(); + const REMOVED_MAESTRO_VERSIONS = ['1.39.2', '1.39.7', '2.0.3']; + if (maestroVersion && REMOVED_MAESTRO_VERSIONS.includes(maestroVersion)) { + setFailed(`Maestro version ${maestroVersion} is no longer supported. ` + + `Please upgrade to a newer version. See: https://docs.devicecloud.dev/reference/maestro-versions`); + return; + } + const dcdVersionString = yield getLatestDcdVersion(useBeta); + const params = { + 'android-api-level': androidApiLevel, + 'android-device': androidDevice, + 'api-key': apiKey, + 'api-url': apiUrl, + 'app-binary-id': appBinaryId, + 'app-file': appFilePath, + async, + 'cancel-previous': cancelPrevious, + config, + 'device-locale': deviceLocale, + 'download-artifacts': downloadArtifacts, + 'exclude-flows': excludeFlows, + 'exclude-tags': excludeTags, + flows: workspaceFolder, + 'google-play': googlePlay, + 'ignore-sha-check': ignoreShaCheck, + 'include-tags': includeTags, + 'ios-device': iosDevice, + 'ios-version': iOSVersion, + 'maestro-version': maestroVersion, + name, + orientation, + report, + retry, + 'runner-type': runnerType, + 'render-engine': renderEngine, + 'json-file': jsonFile, + debug, + 'moropo-v1-api-key': moropoV1ApiKey, + 'maestro-chrome-onboarding': maestroChromeOnboarding, + 'android-no-snapshot': androidNoSnapshot, + 'disable-animations': disableAnimations, + }; + let paramsString = Object.keys(params).reduce((acc, key) => { + if (!params[key]) + return acc; + const value = typeof params[key] === 'string' + ? escapeShellValue(params[key]) + : params[key]; + return `${acc} --${key} ${value}`; + }, ''); + if (env && env.length > 0) { + env.forEach((e) => { + let [key, ...rest] = e.split('='); + let value = rest.join('='); + if (value.startsWith('"') && value.endsWith('"')) { + // remove quotes so they dont get escaped + value = value.slice(1, -1); + } + paramsString += ` --env ${key}=${escapeShellValue(value)}`; + }); + } + if (githubContext && githubContext.length > 0) { + githubContext.forEach((pair) => { + paramsString += ` --metadata ${escapeShellValue(pair)}`; + }); + } + // Forward CI identity so DCD notices can target this GitHub Action (e.g. + // "GitHub Action < X"). The CLI reads these env vars; the spawned child + // inherits process.env. Provider alone still enables CI-surface notices. + process.env.DCD_CI_PROVIDER = 'github'; + // Read at runtime, never bundled: see readWrapperVersion. Best-effort, as + // the version is optional. + const wrapperVersion = readWrapperVersion(__dirname); + if (wrapperVersion) { + process.env.DCD_CI_WRAPPER_VERSION = wrapperVersion; + } + // Execute the test command and capture the upload ID + let uploadId = null; + let testOutput = ''; + // The CLI's exit code is the primary verdict: it is computed by the process + // that actually watched the run. 0 = every test passed, 1 = CLI/infra error, + // 2 = the run itself failed (a failed test, or a cancelled one). This used to + // be discarded for anything but 1, leaving the separate `dcd status` call as + // the only gate — so one wrong branch in the API's status rollup turned + // cancelled runs green. + let cloudExitCode = 0; + try { + const { output, exitCode } = yield executeCommand(`npx --yes "${dcdVersionString}" cloud ${paramsString}${quiet ? ' --quiet' : ''}`); + testOutput = output; + cloudExitCode = exitCode; + if (exitCode === 1) { + throw new Error('DeviceCloud CLI failed to run - check your parameters or contact support'); + } + } + finally { + uploadId = + ((_a = testOutput === null || testOutput === void 0 ? void 0 : testOutput.match(/https:\/\/(?:dev\.)?console\.devicecloud\.dev\/results\?upload=([a-zA-Z0-9-]+)/)) === null || _a === void 0 ? void 0 : _a[1]) || null; + } + if (!uploadId) { + throw new Error('Failed to get upload ID from console URL'); + } + // Async mode: the CLI has already submitted the run and exited (saving CI + // minutes). Do NOT poll for results — the DeviceCloud GitHub App reports the + // outcome as a "DeviceCloud" check on the commit/PR when the run completes. + // Just surface the upload id/console URL and exit successfully. + if (async) { + const consoleUrl = ((_b = testOutput === null || testOutput === void 0 ? void 0 : testOutput.match(/https:\/\/(?:dev\.)?console\.devicecloud\.dev\/results\?upload=[a-zA-Z0-9-]+/)) === null || _b === void 0 ? void 0 : _b[0]) || ''; + setOutput('DEVICE_CLOUD_CONSOLE_URL', consoleUrl); + setOutput('DEVICE_CLOUD_UPLOAD_STATUS', 'PENDING'); + setOutput('DEVICE_CLOUD_FLOW_RESULTS', '[]'); + console.info('Async run submitted; not waiting for results.' + + (consoleUrl ? ` Track progress: ${consoleUrl}` : '')); + console.info('Install the DeviceCloud GitHub App to get a pass/fail check on this ' + + 'commit/PR when the run completes: https://docs.devicecloud.dev/ci-cd/github-actions'); + return; + } + // Get the test status and results + const result = yield getTestStatus(uploadId, apiKey, dcdVersionString, apiUrl); + if (result) { + // Superseded (cancel-previous), passed, failed or indeterminate: see + // evaluateRun for how the status and the exit code combine. + const verdict = evaluateRun(result, cloudExitCode); + // Set outputs based on the status results + setOutput('DEVICE_CLOUD_CONSOLE_URL', result.consoleUrl || ''); + setOutput('DEVICE_CLOUD_APP_BINARY_ID', result.appBinaryId || ''); + setOutput('DEVICE_CLOUD_UPLOAD_STATUS', verdict.uploadStatus); + // Format flow results to match expected structure + const flowResults = (result.tests || []).map((test) => ({ + name: test.name, + status: test.status, + })); + setOutput('DEVICE_CLOUD_FLOW_RESULTS', JSON.stringify(flowResults, null, 2)); + if (verdict.outcome === 'fail') { + setFailed(verdict.message); + } + else if (verdict.outcome === 'warn') { + warning(verdict.message); + } + else { + console.info(verdict.message); + } + } + else { + setOutput('DEVICE_CLOUD_UPLOAD_STATUS', 'ERROR'); + setOutput('DEVICE_CLOUD_FLOW_RESULTS', '[]'); + throw new Error('Failed to get test status'); + } + } + catch (error) { + if (typeof error === 'string') { + setFailed(error); + } + else { + setFailed(error.message); + } + } +}); +run(); + +})(); + +module.exports = __webpack_exports__; /******/ })() ; \ No newline at end of file diff --git a/tsconfig.json b/tsconfig.json index bc75b18..c6f7e97 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,8 +1,9 @@ { "compilerOptions": { "target": "es6", - "lib": ["es2016"], - "module": "commonjs", + "lib": ["es2022"], + "module": "esnext", + "moduleResolution": "bundler", "outDir": "./dist", "rootDir": ".", "strict": true, From 5920470d33d4d3d84f350035938314a4d02a2f4a Mon Sep 17 00:00:00 2001 From: finalerock44 Date: Mon, 5 Oct 2026 12:33:49 +0100 Subject: [PATCH 3/3] ci: build dist on every PR and fail on unbundled imports CI only ran the unit tests, and that is all dependabot PRs get, so the TypeScript 7 and @actions ESM bumps merged green and only failed in the Release workflow after they landed on main. Run `pnpm build` in CI. The build alone is not enough: ncc exits 0 when it can't resolve an import, bundling a stub that throws "Cannot find module" when the action runs. Fail when dist/index.js contains one (webpackMissingModule) and list the modules it could not find. --- .github/workflows/ci.yml | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a3ef03f..7bad89f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -27,3 +27,21 @@ jobs: - name: Run unit tests run: pnpm test + + # Dependabot PRs only run this workflow, so the build has to be checked + # here too. Without it the TypeScript 7 bump merged green and only broke + # in the Release workflow's dist rebuild on main. + - name: Build dist + run: pnpm build + + # ncc exits 0 when it can't resolve an import. It bundles a stub that + # throws "Cannot find module" when the action runs instead. That is what + # the ESM-only @actions/core 3 and @actions/github 9 did to a CommonJS + # build: a 36 kB dist/index.js that failed on its first line. + - name: Check every import was bundled + run: | + if grep -q webpackMissingModule dist/index.js; then + echo "::error::dist/index.js has imports ncc could not resolve:" + grep -o "Cannot find module '[^']*'" dist/index.js | sort -u + exit 1 + fi