require('./sourcemap-register.js');/******/ (() => { // webpackBootstrap /******/ var __webpack_modules__ = ({ /***/ 94822: /***/ (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 (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); const core = __importStar(__nccwpck_require__(42186)); const model_1 = __nccwpck_require__(41359); const cli_1 = __nccwpck_require__(55651); const mac_builder_1 = __importDefault(__nccwpck_require__(39364)); const platform_setup_1 = __importDefault(__nccwpck_require__(64423)); async function runMain() { try { if (cli_1.Cli.InitCliMode()) { await cli_1.Cli.RunCli(); return; } model_1.Action.checkCompatibility(); model_1.Cache.verify(); const { workspace, actionFolder } = model_1.Action; const buildParameters = await model_1.BuildParameters.create(); const baseImage = new model_1.ImageTag(buildParameters); let exitCode = -1; if (buildParameters.providerStrategy === 'local') { core.info('Building locally'); await platform_setup_1.default.setup(buildParameters, actionFolder); exitCode = process.platform === 'darwin' ? await mac_builder_1.default.run(actionFolder) : await model_1.Docker.run(baseImage.toString(), { workspace, actionFolder, ...buildParameters, }); } else { await model_1.CloudRunner.run(buildParameters, baseImage.toString()); exitCode = 0; } // Set output await model_1.Output.setBuildVersion(buildParameters.buildVersion); await model_1.Output.setAndroidVersionCode(buildParameters.androidVersionCode); await model_1.Output.setEngineExitCode(exitCode); if (exitCode !== 0) { core.setFailed(`Build failed with exit code ${exitCode}`); } } catch (error) { core.setFailed(error.message); } } runMain(); /***/ }), /***/ 89088: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); const node_path_1 = __importDefault(__nccwpck_require__(49411)); class Action { static get supportedPlatforms() { return ['linux', 'win32', 'darwin']; } static get isRunningLocally() { return process.env.RUNNER_WORKSPACE === undefined; } static get isRunningFromSource() { return node_path_1.default.basename(__dirname) === 'model'; } static get canonicalName() { if (Action.isRunningFromSource) { return node_path_1.default.basename(node_path_1.default.dirname(node_path_1.default.join(node_path_1.default.dirname(__filename), '/..'))); } return 'unity-builder'; } static get rootFolder() { if (Action.isRunningFromSource) { return node_path_1.default.dirname(node_path_1.default.dirname(node_path_1.default.dirname(__filename))); } return node_path_1.default.dirname(node_path_1.default.dirname(__filename)); } static get actionFolder() { return `${Action.rootFolder}/dist`; } static get workspace() { return process.env.GITHUB_WORKSPACE; } static checkCompatibility() { const currentPlatform = process.platform; if (!Action.supportedPlatforms.includes(currentPlatform)) { throw new Error(`Currently ${currentPlatform}-platform is not supported`); } } } exports["default"] = Action; /***/ }), /***/ 43059: /***/ (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 (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", ({ value: true })); const core = __importStar(__nccwpck_require__(42186)); const semver = __importStar(__nccwpck_require__(11383)); class AndroidVersioning { static determineVersionCode(version, inputVersionCode) { if (inputVersionCode === '') { return AndroidVersioning.versionToVersionCode(version); } return inputVersionCode; } static versionToVersionCode(version) { if (version === 'none') { core.info(`Versioning strategy is set to ${version}, so android version code should not be applied.`); return '0'; } const parsedVersion = semver.parse(version); if (!parsedVersion) { core.warning(`Could not parse "${version}" to semver, defaulting android version code to 1`); return '1'; } // The greatest value Google Plays allows is 2100000000. // Allow for 3 patch digits, 3 minor digits and 3 major digits. const versionCode = parsedVersion.major * 1000000 + parsedVersion.minor * 1000 + parsedVersion.patch; if (versionCode >= 2050000000) { throw new Error(`Generated versionCode ${versionCode} is dangerously close to the maximum allowed number 2100000000. Consider a different versioning scheme to be able to continue updating your application.`); } core.info(`Using android versionCode ${versionCode}`); return versionCode.toString(); } static determineSdkManagerParameters(targetSdkVersion) { const parsedVersion = Number.parseInt(targetSdkVersion.slice(-2), 10); return Number.isNaN(parsedVersion) ? '' : `platforms;android-${parsedVersion}`; } } exports["default"] = AndroidVersioning; /***/ }), /***/ 80787: /***/ (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 (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); const nanoid_1 = __nccwpck_require__(17592); const android_versioning_1 = __importDefault(__nccwpck_require__(43059)); const cloud_runner_constants_1 = __importDefault(__nccwpck_require__(10694)); const cloud_runner_guid_1 = __importDefault(__nccwpck_require__(32285)); const input_1 = __importDefault(__nccwpck_require__(91933)); const platform_1 = __importDefault(__nccwpck_require__(9707)); const unity_versioning_1 = __importDefault(__nccwpck_require__(17146)); const versioning_1 = __importDefault(__nccwpck_require__(88729)); const git_repo_1 = __nccwpck_require__(24271); const github_cli_1 = __nccwpck_require__(44990); const cli_1 = __nccwpck_require__(55651); const github_1 = __importDefault(__nccwpck_require__(83654)); const cloud_runner_options_1 = __importDefault(__nccwpck_require__(66965)); const cloud_runner_1 = __importDefault(__nccwpck_require__(79144)); const core = __importStar(__nccwpck_require__(42186)); class BuildParameters { static shouldUseRetainedWorkspaceMode(buildParameters) { return buildParameters.maxRetainedWorkspaces > 0 && cloud_runner_1.default.lockedWorkspace !== ``; } static async create() { const buildFile = this.parseBuildFile(input_1.default.buildName, input_1.default.targetPlatform, input_1.default.androidExportType); const editorVersion = unity_versioning_1.default.determineUnityVersion(input_1.default.projectPath, input_1.default.unityVersion); const buildVersion = await versioning_1.default.determineBuildVersion(input_1.default.versioningStrategy, input_1.default.specifiedVersion); const androidVersionCode = android_versioning_1.default.determineVersionCode(buildVersion, input_1.default.androidVersionCode); const androidSdkManagerParameters = android_versioning_1.default.determineSdkManagerParameters(input_1.default.androidTargetSdkVersion); const androidSymbolExportType = input_1.default.androidSymbolType; if (platform_1.default.isAndroid(input_1.default.targetPlatform)) { switch (androidSymbolExportType) { case 'none': case 'public': case 'debugging': break; default: throw new Error(`Invalid androidSymbolType: ${input_1.default.androidSymbolType}. Must be one of: none, public, debugging`); } } let unitySerial = ''; if (input_1.default.unityLicensingServer === '') { if (!input_1.default.unitySerial && github_1.default.githubInputEnabled) { // No serial was present, so it is a personal license that we need to convert if (!input_1.default.unityLicense) { throw new Error(`Missing Unity License File and no Serial was found. If this is a personal license, make sure to follow the activation steps and set the UNITY_LICENSE GitHub secret or enter a Unity serial number inside the UNITY_SERIAL GitHub secret.`); } unitySerial = this.getSerialFromLicenseFile(input_1.default.unityLicense); } else { unitySerial = input_1.default.unitySerial; } } if (unitySerial !== undefined && unitySerial.length === 27) { core.setSecret(unitySerial); core.setSecret(`${unitySerial.slice(0, -4)}XXXX`); } return { editorVersion, customImage: input_1.default.customImage, unitySerial, unityLicensingServer: input_1.default.unityLicensingServer, skipActivation: input_1.default.skipActivation, runnerTempPath: input_1.default.runnerTempPath, targetPlatform: input_1.default.targetPlatform, projectPath: input_1.default.projectPath, buildProfile: input_1.default.buildProfile, buildName: input_1.default.buildName, buildPath: `${input_1.default.buildsPath}/${input_1.default.targetPlatform}`, buildFile, buildMethod: input_1.default.buildMethod, buildVersion, manualExit: input_1.default.manualExit, enableGpu: input_1.default.enableGpu, androidVersionCode, androidKeystoreName: input_1.default.androidKeystoreName, androidKeystoreBase64: input_1.default.androidKeystoreBase64, androidKeystorePass: input_1.default.androidKeystorePass, androidKeyaliasName: input_1.default.androidKeyaliasName, androidKeyaliasPass: input_1.default.androidKeyaliasPass, androidTargetSdkVersion: input_1.default.androidTargetSdkVersion, androidSdkManagerParameters, androidExportType: input_1.default.androidExportType, androidSymbolType: androidSymbolExportType, customParameters: input_1.default.customParameters, sshAgent: input_1.default.sshAgent, sshPublicKeysDirectoryPath: input_1.default.sshPublicKeysDirectoryPath, gitPrivateToken: input_1.default.gitPrivateToken ?? (await github_cli_1.GithubCliReader.GetGitHubAuthToken()), runAsHostUser: input_1.default.runAsHostUser, chownFilesTo: input_1.default.chownFilesTo, dockerCpuLimit: input_1.default.dockerCpuLimit, dockerMemoryLimit: input_1.default.dockerMemoryLimit, dockerIsolationMode: input_1.default.dockerIsolationMode, containerRegistryRepository: input_1.default.containerRegistryRepository, containerRegistryImageVersion: input_1.default.containerRegistryImageVersion, providerStrategy: cloud_runner_options_1.default.providerStrategy, buildPlatform: cloud_runner_options_1.default.buildPlatform, kubeConfig: cloud_runner_options_1.default.kubeConfig, containerMemory: cloud_runner_options_1.default.containerMemory, containerCpu: cloud_runner_options_1.default.containerCpu, kubeVolumeSize: cloud_runner_options_1.default.kubeVolumeSize, kubeVolume: cloud_runner_options_1.default.kubeVolume, postBuildContainerHooks: cloud_runner_options_1.default.postBuildContainerHooks, preBuildContainerHooks: cloud_runner_options_1.default.preBuildContainerHooks, customJob: cloud_runner_options_1.default.customJob, runNumber: input_1.default.runNumber, branch: input_1.default.branch.replace('/head', '') || (await git_repo_1.GitRepoReader.GetBranch()), cloudRunnerBranch: cloud_runner_options_1.default.cloudRunnerBranch.split('/').reverse()[0], cloudRunnerDebug: cloud_runner_options_1.default.cloudRunnerDebug, githubRepo: (input_1.default.githubRepo ?? (await git_repo_1.GitRepoReader.GetRemote())) || 'game-ci/unity-builder', isCliMode: cli_1.Cli.isCliMode, awsStackName: cloud_runner_options_1.default.awsStackName, gitSha: input_1.default.gitSha, logId: (0, nanoid_1.customAlphabet)(cloud_runner_constants_1.default.alphabet, 9)(), buildGuid: cloud_runner_guid_1.default.generateGuid(input_1.default.runNumber, input_1.default.targetPlatform), commandHooks: cloud_runner_options_1.default.commandHooks, inputPullCommand: cloud_runner_options_1.default.inputPullCommand, pullInputList: cloud_runner_options_1.default.pullInputList, kubeStorageClass: cloud_runner_options_1.default.kubeStorageClass, cacheKey: cloud_runner_options_1.default.cacheKey, maxRetainedWorkspaces: Number.parseInt(cloud_runner_options_1.default.maxRetainedWorkspaces), useLargePackages: cloud_runner_options_1.default.useLargePackages, useCompressionStrategy: cloud_runner_options_1.default.useCompressionStrategy, garbageMaxAge: cloud_runner_options_1.default.garbageMaxAge, githubChecks: cloud_runner_options_1.default.githubChecks, asyncWorkflow: cloud_runner_options_1.default.asyncCloudRunner, githubCheckId: cloud_runner_options_1.default.githubCheckId, finalHooks: cloud_runner_options_1.default.finalHooks, skipLfs: cloud_runner_options_1.default.skipLfs, skipCache: cloud_runner_options_1.default.skipCache, cacheUnityInstallationOnMac: input_1.default.cacheUnityInstallationOnMac, unityHubVersionOnMac: input_1.default.unityHubVersionOnMac, dockerWorkspacePath: input_1.default.dockerWorkspacePath, }; } static parseBuildFile(filename, platform, androidExportType) { if (platform_1.default.isWindows(platform)) { return `${filename}.exe`; } if (platform_1.default.isAndroid(platform)) { switch (androidExportType) { case `androidPackage`: return `${filename}.apk`; case `androidAppBundle`: return `${filename}.aab`; case `androidStudioProject`: return filename; default: throw new Error(`Unknown Android Export Type: ${androidExportType}. Must be one of androidPackage for apk, androidAppBundle for aab, androidStudioProject for android project`); } } return filename; } static getSerialFromLicenseFile(license) { const startKey = ``; const startIndex = license.indexOf(startKey) + startKey.length; if (startIndex < 0) { throw new Error(`License File was corrupted, unable to locate serial`); } const endIndex = license.indexOf(endKey, startIndex); // Slice off the first 4 characters as they are garbage values return Buffer.from(license.slice(startIndex, endIndex), 'base64').toString('binary').slice(4); } } exports["default"] = BuildParameters; /***/ }), /***/ 97134: /***/ (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 (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); const core = __importStar(__nccwpck_require__(42186)); const node_fs_1 = __importDefault(__nccwpck_require__(87561)); const action_1 = __importDefault(__nccwpck_require__(89088)); const project_1 = __importDefault(__nccwpck_require__(88666)); class Cache { static verify() { if (!node_fs_1.default.existsSync(project_1.default.libraryFolder)) { this.notifyAboutCachingPossibility(); } } static notifyAboutCachingPossibility() { if (action_1.default.isRunningLocally) { return; } core.warning(` Library folder does not exist. Consider setting up caching to speed up your workflow, if this is not your first build. `); } } exports["default"] = Cache; /***/ }), /***/ 85301: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CliFunction = exports.CliFunctionsRepository = void 0; class CliFunctionsRepository { static PushCliFunction(target, propertyKey, descriptor, key, description) { CliFunctionsRepository.targets.push({ target, propertyKey, descriptor, key, description, }); } static GetCliFunctions(key) { const results = CliFunctionsRepository.targets.find((x) => x.key === key); if (results === undefined || results.length === 0) { throw new Error(`no CLI mode found for ${key}`); } return results; } static GetAllCliModes() { return CliFunctionsRepository.targets.map((x) => { return { key: x.key, description: x.description, }; }); } // eslint-disable-next-line no-unused-vars static PushCliFunctionSource(cliFunction) { } } exports.CliFunctionsRepository = CliFunctionsRepository; CliFunctionsRepository.targets = []; function CliFunction(key, description) { return (target, propertyKey, descriptor) => { CliFunctionsRepository.PushCliFunction(target, propertyKey, descriptor, key, description); }; } exports.CliFunction = CliFunction; /***/ }), /***/ 55651: /***/ (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 __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Cli = void 0; const commander_ts_1 = __nccwpck_require__(40451); const __1 = __nccwpck_require__(41359); const core = __importStar(__nccwpck_require__(42186)); const action_yaml_1 = __nccwpck_require__(11091); const cloud_runner_logger_1 = __importDefault(__nccwpck_require__(42864)); const cloud_runner_query_override_1 = __importDefault(__nccwpck_require__(52207)); const cli_functions_repository_1 = __nccwpck_require__(85301); const caching_1 = __nccwpck_require__(32885); const lfs_hashing_1 = __nccwpck_require__(16785); const remote_client_1 = __nccwpck_require__(48135); const cloud_runner_options_reader_1 = __importDefault(__nccwpck_require__(96879)); const github_1 = __importDefault(__nccwpck_require__(83654)); class Cli { static get isCliMode() { return Cli.options !== undefined && Cli.options.mode !== undefined && Cli.options.mode !== ''; } static query(key, alternativeKey) { if (Cli.options && Cli.options[key] !== undefined) { return Cli.options[key]; } if (Cli.options && alternativeKey && Cli.options[alternativeKey] !== undefined) { return Cli.options[alternativeKey]; } return; } static InitCliMode() { cli_functions_repository_1.CliFunctionsRepository.PushCliFunctionSource(remote_client_1.RemoteClient); cli_functions_repository_1.CliFunctionsRepository.PushCliFunctionSource(caching_1.Caching); cli_functions_repository_1.CliFunctionsRepository.PushCliFunctionSource(lfs_hashing_1.LfsHashing); const program = new commander_ts_1.Command(); program.version('0.0.1'); const properties = cloud_runner_options_reader_1.default.GetProperties(); const actionYamlReader = new action_yaml_1.ActionYamlReader(); for (const element of properties) { program.option(`--${element} <${element}>`, actionYamlReader.GetActionYamlValue(element)); } program.option('-m, --mode ', cli_functions_repository_1.CliFunctionsRepository.GetAllCliModes() .map((x) => `${x.key} (${x.description})`) .join(` | `)); program.option('--populateOverride ', 'should use override query to pull input false by default'); program.option('--cachePushFrom ', 'cache push from source folder'); program.option('--cachePushTo ', 'cache push to caching folder'); program.option('--artifactName ', 'caching artifact name'); program.option('--select `).join('\n'); return ` Requesting Authorization
${formInputs}
`; } /** * @name endSessionUrl * @api public */ endSessionUrl(params = {}) { assertIssuerConfiguration(this.issuer, 'end_session_endpoint'); const { 0: postLogout, length, } = this.post_logout_redirect_uris || []; const { post_logout_redirect_uri = length === 1 ? postLogout : undefined, } = params; let hint = params.id_token_hint; if (hint instanceof TokenSet) { if (!hint.id_token) { throw new TypeError('id_token not present in TokenSet'); } hint = hint.id_token; } const target = url.parse(this.issuer.end_session_endpoint, true); target.search = null; target.query = { ...params, ...target.query, ...{ post_logout_redirect_uri, id_token_hint: hint, }, }; Object.entries(target.query).forEach(([key, value]) => { if (value === null || value === undefined) { delete target.query[key]; } }); return url.format(target); } /** * @name callbackParams * @api public */ callbackParams(input) { // eslint-disable-line class-methods-use-this const isIncomingMessage = input instanceof stdhttp.IncomingMessage || (input && input.method && input.url); const isString = typeof input === 'string'; if (!isString && !isIncomingMessage) { throw new TypeError('#callbackParams only accepts string urls, http.IncomingMessage or a lookalike'); } if (isIncomingMessage) { switch (input.method) { case 'GET': return pickCb(url.parse(input.url, true).query); case 'POST': if (input.body === undefined) { throw new TypeError('incoming message body missing, include a body parser prior to this method call'); } switch (typeof input.body) { case 'object': case 'string': if (Buffer.isBuffer(input.body)) { return pickCb(querystring.parse(input.body.toString('utf-8'))); } if (typeof input.body === 'string') { return pickCb(querystring.parse(input.body)); } return pickCb(input.body); default: throw new TypeError('invalid IncomingMessage body object'); } default: throw new TypeError('invalid IncomingMessage method'); } } else { return pickCb(url.parse(input, true).query); } } /** * @name callback * @api public */ async callback( redirectUri, parameters, checks = {}, { exchangeBody, clientAssertionPayload, DPoP } = {}, ) { let params = pickCb(parameters); if (checks.jarm && !('response' in parameters)) { throw new RPError({ message: 'expected a JARM response', checks, params, }); } else if ('response' in parameters) { const decrypted = await this.decryptJARM(params.response); params = await this.validateJARM(decrypted); } if (this.default_max_age && !checks.max_age) { checks.max_age = this.default_max_age; } if (params.state && !checks.state) { throw new TypeError('checks.state argument is missing'); } if (!params.state && checks.state) { throw new RPError({ message: 'state missing from the response', checks, params, }); } if (checks.state !== params.state) { throw new RPError({ printf: ['state mismatch, expected %s, got: %s', checks.state, params.state], checks, params, }); } if (params.error) { throw new OPError(params); } const RESPONSE_TYPE_REQUIRED_PARAMS = { code: ['code'], id_token: ['id_token'], token: ['access_token', 'token_type'], }; if (checks.response_type) { for (const type of checks.response_type.split(' ')) { // eslint-disable-line no-restricted-syntax if (type === 'none') { if (params.code || params.id_token || params.access_token) { throw new RPError({ message: 'unexpected params encountered for "none" response', checks, params, }); } } else { for (const param of RESPONSE_TYPE_REQUIRED_PARAMS[type]) { // eslint-disable-line no-restricted-syntax, max-len if (!params[param]) { throw new RPError({ message: `${param} missing from response`, checks, params, }); } } } } } if (params.id_token) { const tokenset = new TokenSet(params); await this.decryptIdToken(tokenset); await this.validateIdToken(tokenset, checks.nonce, 'authorization', checks.max_age, checks.state); if (!params.code) { return tokenset; } } if (params.code) { const tokenset = await this.grant({ ...exchangeBody, grant_type: 'authorization_code', code: params.code, redirect_uri: redirectUri, code_verifier: checks.code_verifier, }, { clientAssertionPayload, DPoP }); await this.decryptIdToken(tokenset); await this.validateIdToken(tokenset, checks.nonce, 'token', checks.max_age); if (params.session_state) { tokenset.session_state = params.session_state; } return tokenset; } return new TokenSet(params); } /** * @name oauthCallback * @api public */ async oauthCallback( redirectUri, parameters, checks = {}, { exchangeBody, clientAssertionPayload, DPoP } = {}, ) { let params = pickCb(parameters); if (checks.jarm && !('response' in parameters)) { throw new RPError({ message: 'expected a JARM response', checks, params, }); } else if ('response' in parameters) { const decrypted = await this.decryptJARM(params.response); params = await this.validateJARM(decrypted); } if (params.state && !checks.state) { throw new TypeError('checks.state argument is missing'); } if (!params.state && checks.state) { throw new RPError({ message: 'state missing from the response', checks, params, }); } if (checks.state !== params.state) { throw new RPError({ printf: ['state mismatch, expected %s, got: %s', checks.state, params.state], checks, params, }); } if (params.error) { throw new OPError(params); } const RESPONSE_TYPE_REQUIRED_PARAMS = { code: ['code'], token: ['access_token', 'token_type'], }; if (checks.response_type) { for (const type of checks.response_type.split(' ')) { // eslint-disable-line no-restricted-syntax if (type === 'none') { if (params.code || params.id_token || params.access_token) { throw new RPError({ message: 'unexpected params encountered for "none" response', checks, params, }); } } if (RESPONSE_TYPE_REQUIRED_PARAMS[type]) { for (const param of RESPONSE_TYPE_REQUIRED_PARAMS[type]) { // eslint-disable-line no-restricted-syntax, max-len if (!params[param]) { throw new RPError({ message: `${param} missing from response`, checks, params, }); } } } } } if (params.code) { return this.grant({ ...exchangeBody, grant_type: 'authorization_code', code: params.code, redirect_uri: redirectUri, code_verifier: checks.code_verifier, }, { clientAssertionPayload, DPoP }); } return new TokenSet(params); } /** * @name decryptIdToken * @api private */ async decryptIdToken(token) { if (!this.id_token_encrypted_response_alg) { return token; } let idToken = token; if (idToken instanceof TokenSet) { if (!idToken.id_token) { throw new TypeError('id_token not present in TokenSet'); } idToken = idToken.id_token; } const expectedAlg = this.id_token_encrypted_response_alg; const expectedEnc = this.id_token_encrypted_response_enc; const result = await this.decryptJWE(idToken, expectedAlg, expectedEnc); if (token instanceof TokenSet) { token.id_token = result; return token; } return result; } async validateJWTUserinfo(body) { const expectedAlg = this.userinfo_signed_response_alg; return this.validateJWT(body, expectedAlg, []); } /** * @name decryptJARM * @api private */ async decryptJARM(response) { if (!this.authorization_encrypted_response_alg) { return response; } const expectedAlg = this.authorization_encrypted_response_alg; const expectedEnc = this.authorization_encrypted_response_enc; return this.decryptJWE(response, expectedAlg, expectedEnc); } /** * @name decryptJWTUserinfo * @api private */ async decryptJWTUserinfo(body) { if (!this.userinfo_encrypted_response_alg) { return body; } const expectedAlg = this.userinfo_encrypted_response_alg; const expectedEnc = this.userinfo_encrypted_response_enc; return this.decryptJWE(body, expectedAlg, expectedEnc); } /** * @name decryptJWE * @api private */ async decryptJWE(jwe, expectedAlg, expectedEnc = 'A128CBC-HS256') { const header = JSON.parse(base64url.decode(jwe.split('.')[0])); if (header.alg !== expectedAlg) { throw new RPError({ printf: ['unexpected JWE alg received, expected %s, got: %s', expectedAlg, header.alg], jwt: jwe, }); } if (header.enc !== expectedEnc) { throw new RPError({ printf: ['unexpected JWE enc received, expected %s, got: %s', expectedEnc, header.enc], jwt: jwe, }); } let keyOrStore; if (expectedAlg.match(/^(?:RSA|ECDH)/)) { keyOrStore = instance(this).get('keystore'); } else { keyOrStore = await this.joseSecret(expectedAlg === 'dir' ? expectedEnc : expectedAlg); } const payload = jose.JWE.decrypt(jwe, keyOrStore); return payload.toString('utf8'); } /** * @name validateIdToken * @api private */ async validateIdToken(tokenSet, nonce, returnedBy, maxAge, state) { let idToken = tokenSet; const expectedAlg = this.id_token_signed_response_alg; const isTokenSet = idToken instanceof TokenSet; if (isTokenSet) { if (!idToken.id_token) { throw new TypeError('id_token not present in TokenSet'); } idToken = idToken.id_token; } idToken = String(idToken); const timestamp = now(); const { protected: header, payload, key } = await this.validateJWT(idToken, expectedAlg); if (maxAge || (maxAge !== null && this.require_auth_time)) { if (!payload.auth_time) { throw new RPError({ message: 'missing required JWT property auth_time', jwt: idToken, }); } if (typeof payload.auth_time !== 'number') { throw new RPError({ message: 'JWT auth_time claim must be a JSON numeric value', jwt: idToken, }); } } if (maxAge && (payload.auth_time + maxAge < timestamp - this[CLOCK_TOLERANCE])) { throw new RPError({ printf: ['too much time has elapsed since the last End-User authentication, max_age %i, auth_time: %i, now %i', maxAge, payload.auth_time, timestamp - this[CLOCK_TOLERANCE]], now: timestamp, tolerance: this[CLOCK_TOLERANCE], auth_time: payload.auth_time, jwt: idToken, }); } if (nonce !== null && (payload.nonce || nonce !== undefined) && payload.nonce !== nonce) { throw new RPError({ printf: ['nonce mismatch, expected %s, got: %s', nonce, payload.nonce], jwt: idToken, }); } const fapi = this.constructor.name === 'FAPIClient'; if (returnedBy === 'authorization') { if (!payload.at_hash && tokenSet.access_token) { throw new RPError({ message: 'missing required property at_hash', jwt: idToken, }); } if (!payload.c_hash && tokenSet.code) { throw new RPError({ message: 'missing required property c_hash', jwt: idToken, }); } if (fapi) { if (!payload.s_hash && (tokenSet.state || state)) { throw new RPError({ message: 'missing required property s_hash', jwt: idToken, }); } } if (payload.s_hash) { if (!state) { throw new TypeError('cannot verify s_hash, "checks.state" property not provided'); } try { tokenHash.validate({ claim: 's_hash', source: 'state' }, payload.s_hash, state, header.alg, key && key.crv); } catch (err) { throw new RPError({ message: err.message, jwt: idToken }); } } } if (fapi && payload.iat < timestamp - 3600) { throw new RPError({ printf: ['JWT issued too far in the past, now %i, iat %i', timestamp, payload.iat], now: timestamp, tolerance: this[CLOCK_TOLERANCE], iat: payload.iat, jwt: idToken, }); } if (tokenSet.access_token && payload.at_hash !== undefined) { try { tokenHash.validate({ claim: 'at_hash', source: 'access_token' }, payload.at_hash, tokenSet.access_token, header.alg, key && key.crv); } catch (err) { throw new RPError({ message: err.message, jwt: idToken }); } } if (tokenSet.code && payload.c_hash !== undefined) { try { tokenHash.validate({ claim: 'c_hash', source: 'code' }, payload.c_hash, tokenSet.code, header.alg, key && key.crv); } catch (err) { throw new RPError({ message: err.message, jwt: idToken }); } } return tokenSet; } /** * @name validateJWT * @api private */ async validateJWT(jwt, expectedAlg, required = ['iss', 'sub', 'aud', 'exp', 'iat']) { const isSelfIssued = this.issuer.issuer === 'https://self-issued.me'; const timestamp = now(); let header; let payload; try { ({ header, payload } = jose.JWT.decode(jwt, { complete: true })); } catch (err) { throw new RPError({ printf: ['failed to decode JWT (%s: %s)', err.name, err.message], jwt, }); } if (header.alg !== expectedAlg) { throw new RPError({ printf: ['unexpected JWT alg received, expected %s, got: %s', expectedAlg, header.alg], jwt, }); } if (isSelfIssued) { required = [...required, 'sub_jwk']; // eslint-disable-line no-param-reassign } required.forEach(verifyPresence.bind(undefined, payload, jwt)); if (payload.iss !== undefined) { let expectedIss = this.issuer.issuer; if (aadIssValidation) { expectedIss = this.issuer.issuer.replace('{tenantid}', payload.tid); } if (payload.iss !== expectedIss) { throw new RPError({ printf: ['unexpected iss value, expected %s, got: %s', expectedIss, payload.iss], jwt, }); } } if (payload.iat !== undefined) { if (typeof payload.iat !== 'number') { throw new RPError({ message: 'JWT iat claim must be a JSON numeric value', jwt, }); } } if (payload.nbf !== undefined) { if (typeof payload.nbf !== 'number') { throw new RPError({ message: 'JWT nbf claim must be a JSON numeric value', jwt, }); } if (payload.nbf > timestamp + this[CLOCK_TOLERANCE]) { throw new RPError({ printf: ['JWT not active yet, now %i, nbf %i', timestamp + this[CLOCK_TOLERANCE], payload.nbf], now: timestamp, tolerance: this[CLOCK_TOLERANCE], nbf: payload.nbf, jwt, }); } } if (payload.exp !== undefined) { if (typeof payload.exp !== 'number') { throw new RPError({ message: 'JWT exp claim must be a JSON numeric value', jwt, }); } if (timestamp - this[CLOCK_TOLERANCE] >= payload.exp) { throw new RPError({ printf: ['JWT expired, now %i, exp %i', timestamp - this[CLOCK_TOLERANCE], payload.exp], now: timestamp, tolerance: this[CLOCK_TOLERANCE], exp: payload.exp, jwt, }); } } if (payload.aud !== undefined) { if (Array.isArray(payload.aud)) { if (payload.aud.length > 1 && !payload.azp) { throw new RPError({ message: 'missing required JWT property azp', jwt, }); } if (!payload.aud.includes(this.client_id)) { throw new RPError({ printf: ['aud is missing the client_id, expected %s to be included in %j', this.client_id, payload.aud], jwt, }); } } else if (payload.aud !== this.client_id) { throw new RPError({ printf: ['aud mismatch, expected %s, got: %s', this.client_id, payload.aud], jwt, }); } } if (payload.azp !== undefined) { let { additionalAuthorizedParties } = instance(this).get('options') || {}; if (typeof additionalAuthorizedParties === 'string') { additionalAuthorizedParties = [this.client_id, additionalAuthorizedParties]; } else if (Array.isArray(additionalAuthorizedParties)) { additionalAuthorizedParties = [this.client_id, ...additionalAuthorizedParties]; } else { additionalAuthorizedParties = [this.client_id]; } if (!additionalAuthorizedParties.includes(payload.azp)) { throw new RPError({ printf: ['azp mismatch, got: %s', payload.azp], jwt, }); } } let key; if (isSelfIssued) { try { assert(isPlainObject(payload.sub_jwk)); key = jose.JWK.asKey(payload.sub_jwk); assert.equal(key.type, 'public'); } catch (err) { throw new RPError({ message: 'failed to use sub_jwk claim as an asymmetric JSON Web Key', jwt, }); } if (key.thumbprint !== payload.sub) { throw new RPError({ message: 'failed to match the subject with sub_jwk', jwt, }); } } else if (header.alg.startsWith('HS')) { key = await this.joseSecret(); } else if (header.alg !== 'none') { key = await this.issuer.queryKeyStore(header); } if (!key && header.alg === 'none') { return { protected: header, payload }; } try { return { ...jose.JWS.verify(jwt, key, { complete: true }), payload, }; } catch (err) { throw new RPError({ message: 'failed to validate JWT signature', jwt, }); } } /** * @name refresh * @api public */ async refresh(refreshToken, { exchangeBody, clientAssertionPayload, DPoP } = {}) { let token = refreshToken; if (token instanceof TokenSet) { if (!token.refresh_token) { throw new TypeError('refresh_token not present in TokenSet'); } token = token.refresh_token; } const tokenset = await this.grant({ ...exchangeBody, grant_type: 'refresh_token', refresh_token: String(token), }, { clientAssertionPayload, DPoP }); if (tokenset.id_token) { await this.decryptIdToken(tokenset); await this.validateIdToken(tokenset, null, 'token', null); if (refreshToken instanceof TokenSet && refreshToken.id_token) { const expectedSub = refreshToken.claims().sub; const actualSub = tokenset.claims().sub; if (actualSub !== expectedSub) { throw new RPError({ printf: ['sub mismatch, expected %s, got: %s', expectedSub, actualSub], jwt: tokenset.id_token, }); } } } return tokenset; } async requestResource( resourceUrl, accessToken, { method, headers, body, DPoP, // eslint-disable-next-line no-nested-ternary tokenType = DPoP ? 'DPoP' : accessToken instanceof TokenSet ? accessToken.token_type : 'Bearer', } = {}, ) { if (accessToken instanceof TokenSet) { if (!accessToken.access_token) { throw new TypeError('access_token not present in TokenSet'); } accessToken = accessToken.access_token; // eslint-disable-line no-param-reassign } const requestOpts = { headers: { Authorization: authorizationHeaderValue(accessToken, tokenType), ...headers, }, body, }; const mTLS = !!this.tls_client_certificate_bound_access_tokens; return request.call(this, { ...requestOpts, responseType: 'buffer', method, url: resourceUrl, }, { accessToken, mTLS, DPoP }); } /** * @name userinfo * @api public */ async userinfo(accessToken, { method = 'GET', via = 'header', tokenType, params, DPoP, } = {}) { assertIssuerConfiguration(this.issuer, 'userinfo_endpoint'); const options = { tokenType, method: String(method).toUpperCase(), DPoP, }; if (options.method !== 'GET' && options.method !== 'POST') { throw new TypeError('#userinfo() method can only be POST or a GET'); } if (via === 'query' && options.method !== 'GET') { throw new TypeError('userinfo endpoints will only parse query strings for GET requests'); } else if (via === 'body' && options.method !== 'POST') { throw new TypeError('can only send body on POST'); } const jwt = !!(this.userinfo_signed_response_alg || this.userinfo_encrypted_response_alg); if (jwt) { options.headers = { Accept: 'application/jwt' }; } else { options.headers = { Accept: 'application/json' }; } const mTLS = !!this.tls_client_certificate_bound_access_tokens; let targetUrl; if (mTLS && this.issuer.mtls_endpoint_aliases) { targetUrl = this.issuer.mtls_endpoint_aliases.userinfo_endpoint; } targetUrl = new url.URL(targetUrl || this.issuer.userinfo_endpoint); // when via is not header we clear the Authorization header and add either // query string parameters or urlencoded body access_token parameter if (via === 'query') { options.headers.Authorization = undefined; targetUrl.searchParams.append('access_token', accessToken instanceof TokenSet ? accessToken.access_token : accessToken); } else if (via === 'body') { options.headers.Authorization = undefined; options.headers['Content-Type'] = 'application/x-www-form-urlencoded'; options.body = new url.URLSearchParams(); options.body.append('access_token', accessToken instanceof TokenSet ? accessToken.access_token : accessToken); } // handle additional parameters, GET via querystring, POST via urlencoded body if (params) { if (options.method === 'GET') { Object.entries(params).forEach(([key, value]) => { targetUrl.searchParams.append(key, value); }); } else if (options.body) { // POST && via body Object.entries(params).forEach(([key, value]) => { options.body.append(key, value); }); } else { // POST && via header options.body = new url.URLSearchParams(); options.headers['Content-Type'] = 'application/x-www-form-urlencoded'; Object.entries(params).forEach(([key, value]) => { options.body.append(key, value); }); } } if (options.body) { options.body = options.body.toString(); } const response = await this.requestResource(targetUrl, accessToken, options); let parsed = processResponse(response, { bearer: true }); if (jwt) { if (!JWT_CONTENT.test(response.headers['content-type'])) { throw new RPError({ message: 'expected application/jwt response from the userinfo_endpoint', response, }); } const body = response.body.toString(); const userinfo = await this.decryptJWTUserinfo(body); if (!this.userinfo_signed_response_alg) { try { parsed = JSON.parse(userinfo); assert(isPlainObject(parsed)); } catch (err) { throw new RPError({ message: 'failed to parse userinfo JWE payload as JSON', jwt: userinfo, }); } } else { ({ payload: parsed } = await this.validateJWTUserinfo(userinfo)); } } else { try { parsed = JSON.parse(response.body); } catch (error) { throw new ParseError(error, response); } } if (accessToken instanceof TokenSet && accessToken.id_token) { const expectedSub = accessToken.claims().sub; if (parsed.sub !== expectedSub) { throw new RPError({ printf: ['userinfo sub mismatch, expected %s, got: %s', expectedSub, parsed.sub], body: parsed, jwt: accessToken.id_token, }); } } return parsed; } /** * @name derivedKey * @api private */ async derivedKey(len) { const cacheKey = `${len}_key`; if (instance(this).has(cacheKey)) { return instance(this).get(cacheKey); } const hash = len <= 256 ? 'sha256' : len <= 384 ? 'sha384' : len <= 512 ? 'sha512' : false; // eslint-disable-line no-nested-ternary if (!hash) { throw new Error('unsupported symmetric encryption key derivation'); } const derivedBuffer = crypto.createHash(hash) .update(this.client_secret) .digest() .slice(0, len / 8); const key = jose.JWK.asKey({ k: base64url.encode(derivedBuffer), kty: 'oct' }); instance(this).set(cacheKey, key); return key; } /** * @name joseSecret * @api private */ async joseSecret(alg) { if (!this.client_secret) { throw new TypeError('client_secret is required'); } if (/^A(\d{3})(?:GCM)?KW$/.test(alg)) { return this.derivedKey(parseInt(RegExp.$1, 10)); } if (/^A(\d{3})(?:GCM|CBC-HS(\d{3}))$/.test(alg)) { return this.derivedKey(parseInt(RegExp.$2 || RegExp.$1, 10)); } if (instance(this).has('jose_secret')) { return instance(this).get('jose_secret'); } const key = jose.JWK.asKey({ k: base64url.encode(this.client_secret), kty: 'oct' }); instance(this).set('jose_secret', key); return key; } /** * @name grant * @api public */ async grant(body, { clientAssertionPayload, DPoP } = {}) { assertIssuerConfiguration(this.issuer, 'token_endpoint'); const response = await authenticatedPost.call( this, 'token', { form: body, responseType: 'json', }, { clientAssertionPayload, DPoP }, ); const responseBody = processResponse(response); return new TokenSet(responseBody); } /** * @name deviceAuthorization * @api public */ async deviceAuthorization(params = {}, { exchangeBody, clientAssertionPayload, DPoP } = {}) { assertIssuerConfiguration(this.issuer, 'device_authorization_endpoint'); assertIssuerConfiguration(this.issuer, 'token_endpoint'); const body = authorizationParams.call(this, { client_id: this.client_id, redirect_uri: null, response_type: null, ...params, }); const response = await authenticatedPost.call( this, 'device_authorization', { responseType: 'json', form: body, }, { clientAssertionPayload, endpointAuthMethod: 'token' }, ); const responseBody = processResponse(response); return new DeviceFlowHandle({ client: this, exchangeBody, clientAssertionPayload, response: responseBody, maxAge: params.max_age, DPoP, }); } /** * @name revoke * @api public */ async revoke(token, hint, { revokeBody, clientAssertionPayload } = {}) { assertIssuerConfiguration(this.issuer, 'revocation_endpoint'); if (hint !== undefined && typeof hint !== 'string') { throw new TypeError('hint must be a string'); } const form = { ...revokeBody, token }; if (hint) { form.token_type_hint = hint; } const response = await authenticatedPost.call( this, 'revocation', { form, }, { clientAssertionPayload }, ); processResponse(response, { body: false }); } /** * @name introspect * @api public */ async introspect(token, hint, { introspectBody, clientAssertionPayload } = {}) { assertIssuerConfiguration(this.issuer, 'introspection_endpoint'); if (hint !== undefined && typeof hint !== 'string') { throw new TypeError('hint must be a string'); } const form = { ...introspectBody, token }; if (hint) { form.token_type_hint = hint; } const response = await authenticatedPost.call( this, 'introspection', { form, responseType: 'json' }, { clientAssertionPayload }, ); const responseBody = processResponse(response); return responseBody; } /** * @name fetchDistributedClaims * @api public */ async fetchDistributedClaims(claims, tokens = {}) { if (!isPlainObject(claims)) { throw new TypeError('claims argument must be a plain object'); } if (!isPlainObject(claims._claim_sources)) { return claims; } if (!isPlainObject(claims._claim_names)) { return claims; } const distributedSources = Object.entries(claims._claim_sources) .filter(([, value]) => value && value.endpoint); await Promise.all(distributedSources.map(async ([sourceName, def]) => { try { const requestOpts = { headers: { Accept: 'application/jwt', Authorization: authorizationHeaderValue(def.access_token || tokens[sourceName]), }, }; const response = await request.call(this, { ...requestOpts, method: 'GET', url: def.endpoint, }); const body = processResponse(response, { bearer: true }); const decoded = await claimJWT.call(this, 'distributed', body); delete claims._claim_sources[sourceName]; Object.entries(claims._claim_names).forEach( assignClaim(claims, decoded, sourceName, false), ); } catch (err) { err.src = sourceName; throw err; } })); cleanUpClaims(claims); return claims; } /** * @name unpackAggregatedClaims * @api public */ async unpackAggregatedClaims(claims) { if (!isPlainObject(claims)) { throw new TypeError('claims argument must be a plain object'); } if (!isPlainObject(claims._claim_sources)) { return claims; } if (!isPlainObject(claims._claim_names)) { return claims; } const aggregatedSources = Object.entries(claims._claim_sources) .filter(([, value]) => value && value.JWT); await Promise.all(aggregatedSources.map(async ([sourceName, def]) => { try { const decoded = await claimJWT.call(this, 'aggregated', def.JWT); delete claims._claim_sources[sourceName]; Object.entries(claims._claim_names).forEach(assignClaim(claims, decoded, sourceName)); } catch (err) { err.src = sourceName; throw err; } })); cleanUpClaims(claims); return claims; } /** * @name register * @api public */ static async register(metadata, options = {}) { const { initialAccessToken, jwks, ...clientOptions } = options; assertIssuerConfiguration(this.issuer, 'registration_endpoint'); if (jwks !== undefined && !(metadata.jwks || metadata.jwks_uri)) { const keystore = getKeystore.call(this, jwks); metadata.jwks = keystore.toJWKS(false); // eslint-disable-next-line no-restricted-syntax for (const jwk of metadata.jwks.keys) { if (jwk.kid.startsWith('DONOTUSE.')) { delete jwk.kid; } } } const response = await request.call(this, { headers: initialAccessToken ? { Authorization: authorizationHeaderValue(initialAccessToken), } : undefined, responseType: 'json', json: metadata, url: this.issuer.registration_endpoint, method: 'POST', }); const responseBody = processResponse(response, { statusCode: 201, bearer: true }); return new this(responseBody, jwks, clientOptions); } /** * @name metadata * @api public */ get metadata() { const copy = {}; instance(this).get('metadata').forEach((value, key) => { copy[key] = value; }); return copy; } /** * @name fromUri * @api public */ static async fromUri(registrationClientUri, registrationAccessToken, jwks, clientOptions) { const response = await request.call(this, { method: 'GET', url: registrationClientUri, responseType: 'json', headers: { Authorization: authorizationHeaderValue(registrationAccessToken) }, }); const responseBody = processResponse(response, { bearer: true }); return new this(responseBody, jwks, clientOptions); } /** * @name requestObject * @api public */ async requestObject(requestObject = {}, { sign: signingAlgorithm = this.request_object_signing_alg || 'none', encrypt: { alg: eKeyManagement = this.request_object_encryption_alg, enc: eContentEncryption = this.request_object_encryption_enc || 'A128CBC-HS256', } = {}, } = {}) { if (!isPlainObject(requestObject)) { throw new TypeError('requestObject must be a plain object'); } let signed; let key; const fapi = this.constructor.name === 'FAPIClient'; const unix = now(); const header = { alg: signingAlgorithm, typ: 'oauth-authz-req+jwt' }; const payload = JSON.stringify(defaults({}, requestObject, { iss: this.client_id, aud: this.issuer.issuer, client_id: this.client_id, jti: random(), iat: unix, exp: unix + 300, ...(fapi ? { nbf: unix } : undefined), })); if (signingAlgorithm === 'none') { signed = [ base64url.encode(JSON.stringify(header)), base64url.encode(payload), '', ].join('.'); } else { const symmetric = signingAlgorithm.startsWith('HS'); if (symmetric) { key = await this.joseSecret(); } else { const keystore = instance(this).get('keystore'); if (!keystore) { throw new TypeError(`no keystore present for client, cannot sign using alg ${signingAlgorithm}`); } key = keystore.get({ alg: signingAlgorithm, use: 'sig' }); if (!key) { throw new TypeError(`no key to sign with found for alg ${signingAlgorithm}`); } } signed = jose.JWS.sign(payload, key, { ...header, kid: symmetric || key.kid.startsWith('DONOTUSE.') ? undefined : key.kid, }); } if (!eKeyManagement) { return signed; } const fields = { alg: eKeyManagement, enc: eContentEncryption, cty: 'oauth-authz-req+jwt' }; if (fields.alg.match(/^(RSA|ECDH)/)) { [key] = await this.issuer.queryKeyStore({ alg: fields.alg, enc: fields.enc, use: 'enc', }, { allowMulti: true }); } else { key = await this.joseSecret(fields.alg === 'dir' ? fields.enc : fields.alg); } return jose.JWE.encrypt(signed, key, { ...fields, kid: key.kty === 'oct' ? undefined : key.kid, }); } /** * @name pushedAuthorizationRequest * @api public */ async pushedAuthorizationRequest(params = {}, { clientAssertionPayload } = {}) { assertIssuerConfiguration(this.issuer, 'pushed_authorization_request_endpoint'); const body = { ...('request' in params ? params : authorizationParams.call(this, params)), client_id: this.client_id, }; const response = await authenticatedPost.call( this, 'pushed_authorization_request', { responseType: 'json', form: body, }, { clientAssertionPayload, endpointAuthMethod: 'token' }, ); const responseBody = processResponse(response, { statusCode: 201 }); if (!('expires_in' in responseBody)) { throw new RPError({ message: 'expected expires_in in Pushed Authorization Successful Response', response, }); } if (typeof responseBody.expires_in !== 'number') { throw new RPError({ message: 'invalid expires_in value in Pushed Authorization Successful Response', response, }); } if (!('request_uri' in responseBody)) { throw new RPError({ message: 'expected request_uri in Pushed Authorization Successful Response', response, }); } if (typeof responseBody.request_uri !== 'string') { throw new RPError({ message: 'invalid request_uri value in Pushed Authorization Successful Response', response, }); } return responseBody; } /** * @name issuer * @api public */ static get issuer() { return issuer; } /** * @name issuer * @api public */ get issuer() { // eslint-disable-line class-methods-use-this return issuer; } /* istanbul ignore next */ [inspect.custom]() { return `${this.constructor.name} ${inspect(this.metadata, { depth: Infinity, colors: process.stdout.isTTY, compact: false, sorted: true, })}`; } }; /** * @name validateJARM * @api private */ async function validateJARM(response) { const expectedAlg = this.authorization_signed_response_alg; const { payload } = await this.validateJWT(response, expectedAlg, ['iss', 'exp', 'aud']); return pickCb(payload); } Object.defineProperty(BaseClient.prototype, 'validateJARM', { enumerable: true, configurable: true, value(...args) { process.emitWarning( "The JARM API implements an OIDF implementer's draft. Breaking draft implementations are included as minor versions of the openid-client library, therefore, the ~ semver operator should be used and close attention be payed to library changelog as well as the drafts themselves.", 'DraftWarning', ); Object.defineProperty(BaseClient.prototype, 'validateJARM', { enumerable: true, configurable: true, value: validateJARM, }); return this.validateJARM(...args); }, }); /** * @name dpopProof * @api private */ function dpopProof(payload, jwk, accessToken) { if (!isPlainObject(payload)) { throw new TypeError('payload must be a plain object'); } let key; try { key = jose.JWK.asKey(jwk); assert(key.type === 'private'); } catch (err) { throw new TypeError('"DPoP" option must be an asymmetric private key to sign the DPoP Proof JWT with'); } let { alg } = key; if (!alg && this.issuer.dpop_signing_alg_values_supported) { const algs = key.algorithms('sign'); alg = this.issuer.dpop_signing_alg_values_supported.find((a) => algs.has(a)); } if (!alg) { [alg] = key.algorithms('sign'); } return jose.JWS.sign({ iat: now(), jti: random(), ath: accessToken ? base64url.encode(crypto.createHash('sha256').update(accessToken).digest()) : undefined, ...payload, }, jwk, { alg, typ: 'dpop+jwt', jwk: pick(key, 'kty', 'crv', 'x', 'y', 'e', 'n'), }); } Object.defineProperty(BaseClient.prototype, 'dpopProof', { enumerable: true, configurable: true, value(...args) { process.emitWarning( 'The DPoP APIs implements an IETF draft (https://www.ietf.org/archive/id/draft-ietf-oauth-dpop-03.html). Breaking draft implementations are included as minor versions of the openid-client library, therefore, the ~ semver operator should be used and close attention be payed to library changelog as well as the drafts themselves.', 'DraftWarning', ); Object.defineProperty(BaseClient.prototype, 'dpopProof', { enumerable: true, configurable: true, value: dpopProof, }); return this.dpopProof(...args); }, }); module.exports.BaseClient = BaseClient; /***/ }), /***/ 60679: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /* eslint-disable camelcase */ const { inspect } = __nccwpck_require__(73837); const { RPError, OPError } = __nccwpck_require__(31151); const instance = __nccwpck_require__(69020); const now = __nccwpck_require__(24393); const { authenticatedPost } = __nccwpck_require__(26633); const processResponse = __nccwpck_require__(59980); const TokenSet = __nccwpck_require__(14974); class DeviceFlowHandle { constructor({ client, exchangeBody, clientAssertionPayload, response, maxAge, DPoP, }) { ['verification_uri', 'user_code', 'device_code'].forEach((prop) => { if (typeof response[prop] !== 'string' || !response[prop]) { throw new RPError(`expected ${prop} string to be returned by Device Authorization Response, got %j`, response[prop]); } }); if (!Number.isSafeInteger(response.expires_in)) { throw new RPError('expected expires_in number to be returned by Device Authorization Response, got %j', response.expires_in); } instance(this).expires_at = now() + response.expires_in; instance(this).client = client; instance(this).DPoP = DPoP; instance(this).maxAge = maxAge; instance(this).exchangeBody = exchangeBody; instance(this).clientAssertionPayload = clientAssertionPayload; instance(this).response = response; instance(this).interval = response.interval * 1000 || 5000; } abort() { instance(this).aborted = true; } async poll({ signal } = {}) { if ((signal && signal.aborted) || instance(this).aborted) { throw new RPError('polling aborted'); } if (this.expired()) { throw new RPError('the device code %j has expired and the device authorization session has concluded', this.device_code); } await new Promise((resolve) => setTimeout(resolve, instance(this).interval)); const response = await authenticatedPost.call( instance(this).client, 'token', { form: { ...instance(this).exchangeBody, grant_type: 'urn:ietf:params:oauth:grant-type:device_code', device_code: this.device_code, }, responseType: 'json', }, { clientAssertionPayload: instance(this).clientAssertionPayload, DPoP: instance(this).DPoP }, ); let responseBody; try { responseBody = processResponse(response); } catch (err) { switch (err instanceof OPError && err.error) { case 'slow_down': instance(this).interval += 5000; case 'authorization_pending': // eslint-disable-line no-fallthrough return this.poll({ signal }); default: throw err; } } const tokenset = new TokenSet(responseBody); if ('id_token' in tokenset) { await instance(this).client.decryptIdToken(tokenset); await instance(this).client.validateIdToken(tokenset, undefined, 'token', instance(this).maxAge); } return tokenset; } get device_code() { return instance(this).response.device_code; } get user_code() { return instance(this).response.user_code; } get verification_uri() { return instance(this).response.verification_uri; } get verification_uri_complete() { return instance(this).response.verification_uri_complete; } get expires_in() { return Math.max.apply(null, [instance(this).expires_at - now(), 0]); } expired() { return this.expires_in === 0; } /* istanbul ignore next */ [inspect.custom]() { return `${this.constructor.name} ${inspect(instance(this).response, { depth: Infinity, colors: process.stdout.isTTY, compact: false, sorted: true, })}`; } } module.exports = DeviceFlowHandle; /***/ }), /***/ 31151: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /* eslint-disable camelcase */ const { format } = __nccwpck_require__(73837); const makeError = __nccwpck_require__(21381); function OPError({ error_description, error, error_uri, session_state, state, scope, }, response) { OPError.super.call(this, !error_description ? error : `${error} (${error_description})`); Object.assign( this, { error }, (error_description && { error_description }), (error_uri && { error_uri }), (state && { state }), (scope && { scope }), (session_state && { session_state }), ); if (response) { Object.defineProperty(this, 'response', { value: response, }); } } makeError(OPError); function RPError(...args) { if (typeof args[0] === 'string') { RPError.super.call(this, format(...args)); } else { const { message, printf, response, ...rest } = args[0]; if (printf) { RPError.super.call(this, format(...printf)); } else { RPError.super.call(this, message); } Object.assign(this, rest); if (response) { Object.defineProperty(this, 'response', { value: response, }); } } } makeError(RPError); module.exports = { OPError, RPError, }; /***/ }), /***/ 68973: /***/ ((module) => { function assertSigningAlgValuesSupport(endpoint, issuer, properties) { if (!issuer[`${endpoint}_endpoint`]) return; const eam = `${endpoint}_endpoint_auth_method`; const easa = `${endpoint}_endpoint_auth_signing_alg`; const easavs = `${endpoint}_endpoint_auth_signing_alg_values_supported`; if (properties[eam] && properties[eam].endsWith('_jwt') && !properties[easa] && !issuer[easavs]) { throw new TypeError(`${easavs} must be configured on the issuer if ${easa} is not defined on a client`); } } function assertIssuerConfiguration(issuer, endpoint) { if (!issuer[endpoint]) { throw new TypeError(`${endpoint} must be configured on the issuer`); } } module.exports = { assertSigningAlgValuesSupport, assertIssuerConfiguration, }; /***/ }), /***/ 23570: /***/ ((module) => { let encode; if (Buffer.isEncoding('base64url')) { encode = (input, encoding = 'utf8') => Buffer.from(input, encoding).toString('base64url'); } else { const fromBase64 = (base64) => base64.replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_'); encode = (input, encoding = 'utf8') => fromBase64(Buffer.from(input, encoding).toString('base64')); } const decode = (input) => Buffer.from(input, 'base64'); module.exports.decode = decode; module.exports.encode = encode; /***/ }), /***/ 26633: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const jose = __nccwpck_require__(87115); const { assertIssuerConfiguration } = __nccwpck_require__(68973); const { random } = __nccwpck_require__(65894); const now = __nccwpck_require__(24393); const request = __nccwpck_require__(8048); const instance = __nccwpck_require__(69020); const merge = __nccwpck_require__(71839); const formUrlEncode = (value) => encodeURIComponent(value).replace(/%20/g, '+'); async function clientAssertion(endpoint, payload) { let alg = this[`${endpoint}_endpoint_auth_signing_alg`]; if (!alg) { assertIssuerConfiguration(this.issuer, `${endpoint}_endpoint_auth_signing_alg_values_supported`); } if (this[`${endpoint}_endpoint_auth_method`] === 'client_secret_jwt') { const key = await this.joseSecret(); if (!alg) { const supported = this.issuer[`${endpoint}_endpoint_auth_signing_alg_values_supported`]; alg = Array.isArray(supported) && supported.find((signAlg) => key.algorithms('sign').has(signAlg)); } return jose.JWS.sign(payload, key, { alg, typ: 'JWT' }); } const keystore = instance(this).get('keystore'); if (!keystore) { throw new TypeError('no client jwks provided for signing a client assertion with'); } if (!alg) { const algs = new Set(); keystore.all().forEach((key) => { key.algorithms('sign').forEach(Set.prototype.add.bind(algs)); }); const supported = this.issuer[`${endpoint}_endpoint_auth_signing_alg_values_supported`]; alg = Array.isArray(supported) && supported.find((signAlg) => algs.has(signAlg)); } const key = keystore.get({ alg, use: 'sig' }); if (!key) { throw new TypeError(`no key found in client jwks to sign a client assertion with using alg ${alg}`); } return jose.JWS.sign(payload, key, { alg, typ: 'JWT', kid: key.kid.startsWith('DONOTUSE.') ? undefined : key.kid }); } async function authFor(endpoint, { clientAssertionPayload } = {}) { const authMethod = this[`${endpoint}_endpoint_auth_method`]; switch (authMethod) { case 'self_signed_tls_client_auth': case 'tls_client_auth': case 'none': return { form: { client_id: this.client_id } }; case 'client_secret_post': if (!this.client_secret) { throw new TypeError('client_secret_post client authentication method requires a client_secret'); } return { form: { client_id: this.client_id, client_secret: this.client_secret } }; case 'private_key_jwt': case 'client_secret_jwt': { const timestamp = now(); const mTLS = endpoint === 'token' && this.tls_client_certificate_bound_access_tokens; const audience = [...new Set([ this.issuer.issuer, this.issuer.token_endpoint, this.issuer[`${endpoint}_endpoint`], mTLS && this.issuer.mtls_endpoint_aliases ? this.issuer.mtls_endpoint_aliases.token_endpoint : undefined, ].filter(Boolean))]; const assertion = await clientAssertion.call(this, endpoint, { iat: timestamp, exp: timestamp + 60, jti: random(), iss: this.client_id, sub: this.client_id, aud: audience, ...clientAssertionPayload, }); return { form: { client_id: this.client_id, client_assertion: assertion, client_assertion_type: 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer', }, }; } default: { // client_secret_basic // This is correct behaviour, see https://tools.ietf.org/html/rfc6749#section-2.3.1 and the // related appendix. (also https://github.com/panva/node-openid-client/pull/91) // > The client identifier is encoded using the // > "application/x-www-form-urlencoded" encoding algorithm per // > Appendix B, and the encoded value is used as the username; the client // > password is encoded using the same algorithm and used as the // > password. if (!this.client_secret) { throw new TypeError('client_secret_basic client authentication method requires a client_secret'); } const encoded = `${formUrlEncode(this.client_id)}:${formUrlEncode(this.client_secret)}`; const value = Buffer.from(encoded).toString('base64'); return { headers: { Authorization: `Basic ${value}` } }; } } } function resolveResponseType() { const { length, 0: value } = this.response_types; if (length === 1) { return value; } return undefined; } function resolveRedirectUri() { const { length, 0: value } = this.redirect_uris || []; if (length === 1) { return value; } return undefined; } async function authenticatedPost(endpoint, opts, { clientAssertionPayload, endpointAuthMethod = endpoint, DPoP, } = {}) { const auth = await authFor.call(this, endpointAuthMethod, { clientAssertionPayload }); const requestOpts = merge(opts, auth); const mTLS = this[`${endpointAuthMethod}_endpoint_auth_method`].includes('tls_client_auth') || (endpoint === 'token' && this.tls_client_certificate_bound_access_tokens); let targetUrl; if (mTLS && this.issuer.mtls_endpoint_aliases) { targetUrl = this.issuer.mtls_endpoint_aliases[`${endpoint}_endpoint`]; } targetUrl = targetUrl || this.issuer[`${endpoint}_endpoint`]; if ('form' in requestOpts) { for (const [key, value] of Object.entries(requestOpts.form)) { // eslint-disable-line no-restricted-syntax, max-len if (typeof value === 'undefined') { delete requestOpts.form[key]; } } } return request.call(this, { ...requestOpts, method: 'POST', url: targetUrl, }, { mTLS, DPoP }); } module.exports = { resolveResponseType, resolveRedirectUri, authFor, authenticatedPost, }; /***/ }), /***/ 6144: /***/ ((module) => { const OIDC_DISCOVERY = '/.well-known/openid-configuration'; const OAUTH2_DISCOVERY = '/.well-known/oauth-authorization-server'; const WEBFINGER = '/.well-known/webfinger'; const REL = 'http://openid.net/specs/connect/1.0/issuer'; const AAD_MULTITENANT_DISCOVERY = [ `https://login.microsoftonline.com/common${OIDC_DISCOVERY}`, `https://login.microsoftonline.com/common/v2.0${OIDC_DISCOVERY}`, `https://login.microsoftonline.com/organizations/v2.0${OIDC_DISCOVERY}`, `https://login.microsoftonline.com/consumers/v2.0${OIDC_DISCOVERY}`, ]; const CLIENT_DEFAULTS = { grant_types: ['authorization_code'], id_token_signed_response_alg: 'RS256', authorization_signed_response_alg: 'RS256', response_types: ['code'], token_endpoint_auth_method: 'client_secret_basic', }; const ISSUER_DEFAULTS = { claim_types_supported: ['normal'], claims_parameter_supported: false, grant_types_supported: ['authorization_code', 'implicit'], request_parameter_supported: false, request_uri_parameter_supported: true, require_request_uri_registration: false, response_modes_supported: ['query', 'fragment'], token_endpoint_auth_methods_supported: ['client_secret_basic'], }; const CALLBACK_PROPERTIES = [ 'access_token', // 6749 'code', // 6749 'error', // 6749 'error_description', // 6749 'error_uri', // 6749 'expires_in', // 6749 'id_token', // Core 1.0 'state', // 6749 'token_type', // 6749 'session_state', // Session Management 'response', // JARM ]; const JWT_CONTENT = /^application\/jwt/; const HTTP_OPTIONS = Symbol('openid-client.custom.http-options'); const CLOCK_TOLERANCE = Symbol('openid-client.custom.clock-tolerance'); module.exports = { AAD_MULTITENANT_DISCOVERY, CALLBACK_PROPERTIES, CLIENT_DEFAULTS, CLOCK_TOLERANCE, HTTP_OPTIONS, ISSUER_DEFAULTS, JWT_CONTENT, OAUTH2_DISCOVERY, OIDC_DISCOVERY, REL, WEBFINGER, }; /***/ }), /***/ 85618: /***/ ((module) => { module.exports = (obj) => JSON.parse(JSON.stringify(obj)); /***/ }), /***/ 44129: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /* eslint-disable no-restricted-syntax, no-continue */ const isPlainObject = __nccwpck_require__(89717); function defaults(deep, target, ...sources) { for (const source of sources) { if (!isPlainObject(source)) { continue; } for (const [key, value] of Object.entries(source)) { /* istanbul ignore if */ if (key === '__proto__' || key === 'constructor') { continue; } if (typeof target[key] === 'undefined' && typeof value !== 'undefined') { target[key] = value; } if (deep && isPlainObject(target[key]) && isPlainObject(value)) { defaults(true, target[key], value); } } } return target; } module.exports = defaults.bind(undefined, false); module.exports.deep = defaults.bind(undefined, true); /***/ }), /***/ 65894: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { createHash, randomBytes } = __nccwpck_require__(6113); const base64url = __nccwpck_require__(23570); const random = (bytes = 32) => base64url.encode(randomBytes(bytes)); module.exports = { random, state: random, nonce: random, codeVerifier: random, codeChallenge: (codeVerifier) => base64url.encode(createHash('sha256').update(codeVerifier).digest()), }; /***/ }), /***/ 61758: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const url = __nccwpck_require__(57310); const { strict: assert } = __nccwpck_require__(39491); module.exports = (target) => { try { const { protocol } = new url.URL(target); assert(protocol.match(/^(https?:)$/)); return true; } catch (err) { throw new TypeError('only valid absolute URLs can be requested'); } }; /***/ }), /***/ 89717: /***/ ((module) => { module.exports = (a) => !!a && a.constructor === Object; /***/ }), /***/ 71839: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /* eslint-disable no-restricted-syntax, no-param-reassign, no-continue */ const isPlainObject = __nccwpck_require__(89717); function merge(target, ...sources) { for (const source of sources) { if (!isPlainObject(source)) { continue; } for (const [key, value] of Object.entries(source)) { /* istanbul ignore if */ if (key === '__proto__' || key === 'constructor') { continue; } if (isPlainObject(target[key]) && isPlainObject(value)) { target[key] = merge(target[key], value); } else if (typeof value !== 'undefined') { target[key] = value; } } } return target; } module.exports = merge; /***/ }), /***/ 70260: /***/ ((module) => { module.exports = function pick(object, ...paths) { const obj = {}; for (const path of paths) { // eslint-disable-line no-restricted-syntax if (object[path]) { obj[path] = object[path]; } } return obj; }; /***/ }), /***/ 59980: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { STATUS_CODES } = __nccwpck_require__(13685); const { format } = __nccwpck_require__(73837); const { OPError } = __nccwpck_require__(31151); const REGEXP = /(\w+)=("[^"]*")/g; const throwAuthenticateErrors = (response) => { const params = {}; try { while ((REGEXP.exec(response.headers['www-authenticate'])) !== null) { if (RegExp.$1 && RegExp.$2) { params[RegExp.$1] = RegExp.$2.slice(1, -1); } } } catch (err) {} if (params.error) { throw new OPError(params, response); } }; const isStandardBodyError = (response) => { let result = false; try { let jsonbody; if (typeof response.body !== 'object' || Buffer.isBuffer(response.body)) { jsonbody = JSON.parse(response.body); } else { jsonbody = response.body; } result = typeof jsonbody.error === 'string' && jsonbody.error.length; if (result) response.body = jsonbody; } catch (err) {} return result; }; function processResponse(response, { statusCode = 200, body = true, bearer = false } = {}) { if (response.statusCode !== statusCode) { if (bearer) { throwAuthenticateErrors(response); } if (isStandardBodyError(response)) { throw new OPError(response.body, response); } throw new OPError({ error: format('expected %i %s, got: %i %s', statusCode, STATUS_CODES[statusCode], response.statusCode, STATUS_CODES[response.statusCode]), }, response); } if (body && !response.body) { throw new OPError({ error: format('expected %i %s with body but no body was returned', statusCode, STATUS_CODES[statusCode]), }, response); } return response.body; } module.exports = processResponse; /***/ }), /***/ 8048: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const Got = __nccwpck_require__(93061); const pkg = __nccwpck_require__(51513); const { deep: defaultsDeep } = __nccwpck_require__(44129); const isAbsoluteUrl = __nccwpck_require__(61758); const { HTTP_OPTIONS } = __nccwpck_require__(6144); let DEFAULT_HTTP_OPTIONS; let got; const setDefaults = (options) => { DEFAULT_HTTP_OPTIONS = defaultsDeep({}, options, DEFAULT_HTTP_OPTIONS); got = Got.extend(DEFAULT_HTTP_OPTIONS); }; setDefaults({ followRedirect: false, headers: { 'User-Agent': `${pkg.name}/${pkg.version} (${pkg.homepage})` }, retry: 0, timeout: 3500, throwHttpErrors: false, }); module.exports = async function request(options, { accessToken, mTLS = false, DPoP } = {}) { const { url } = options; isAbsoluteUrl(url); const optsFn = this[HTTP_OPTIONS]; let opts = options; if (DPoP && 'dpopProof' in this) { opts.headers = opts.headers || {}; opts.headers.DPoP = this.dpopProof({ htu: url, htm: options.method, }, DPoP, accessToken); } if (optsFn) { opts = optsFn.call(this, defaultsDeep({}, opts, DEFAULT_HTTP_OPTIONS)); } if ( mTLS && ( (!opts.key || !opts.cert) && (!opts.https || !((opts.https.key && opts.https.certificate) || opts.https.pfx)) ) ) { throw new TypeError('mutual-TLS certificate and key not set'); } return got(opts); }; module.exports.setDefaults = setDefaults; /***/ }), /***/ 24393: /***/ ((module) => { module.exports = () => Math.floor(Date.now() / 1000); /***/ }), /***/ 69020: /***/ ((module) => { const privateProps = new WeakMap(); module.exports = (ctx) => { if (!privateProps.has(ctx)) { privateProps.set(ctx, new Map([['metadata', new Map()]])); } return privateProps.get(ctx); }; /***/ }), /***/ 10304: /***/ ((module) => { // Credit: https://github.com/rohe/pyoidc/blob/master/src/oic/utils/webfinger.py // -- Normalization -- // A string of any other type is interpreted as a URI either the form of scheme // "://" authority path-abempty [ "?" query ] [ "#" fragment ] or authority // path-abempty [ "?" query ] [ "#" fragment ] per RFC 3986 [RFC3986] and is // normalized according to the following rules: // // If the user input Identifier does not have an RFC 3986 [RFC3986] scheme // portion, the string is interpreted as [userinfo "@"] host [":" port] // path-abempty [ "?" query ] [ "#" fragment ] per RFC 3986 [RFC3986]. // If the userinfo component is present and all of the path component, query // component, and port component are empty, the acct scheme is assumed. In this // case, the normalized URI is formed by prefixing acct: to the string as the // scheme. Per the 'acct' URI Scheme [I‑D.ietf‑appsawg‑acct‑uri], if there is an // at-sign character ('@') in the userinfo component, it needs to be // percent-encoded as described in RFC 3986 [RFC3986]. // For all other inputs without a scheme portion, the https scheme is assumed, // and the normalized URI is formed by prefixing https:// to the string as the // scheme. // If the resulting URI contains a fragment portion, it MUST be stripped off // together with the fragment delimiter character "#". // The WebFinger [I‑D.ietf‑appsawg‑webfinger] Resource in this case is the // resulting URI, and the WebFinger Host is the authority component. // // Note: Since the definition of authority in RFC 3986 [RFC3986] is // [ userinfo "@" ] host [ ":" port ], it is legal to have a user input // identifier like userinfo@host:port, e.g., alice@example.com:8080. const PORT = /^\d+$/; function hasScheme(input) { if (input.includes('://')) return true; const authority = input.replace(/(\/|\?)/g, '#').split('#')[0]; if (authority.includes(':')) { const index = authority.indexOf(':'); const hostOrPort = authority.slice(index + 1); if (!PORT.test(hostOrPort)) { return true; } } return false; } function acctSchemeAssumed(input) { if (!input.includes('@')) return false; const parts = input.split('@'); const host = parts[parts.length - 1]; return !(host.includes(':') || host.includes('/') || host.includes('?')); } function normalize(input) { if (typeof input !== 'string') { throw new TypeError('input must be a string'); } let output; if (hasScheme(input)) { output = input; } else if (acctSchemeAssumed(input)) { output = `acct:${input}`; } else { output = `https://${input}`; } return output.split('#')[0]; } module.exports = normalize; /***/ }), /***/ 22881: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const Issuer = __nccwpck_require__(14470); const { OPError, RPError } = __nccwpck_require__(31151); const Registry = __nccwpck_require__(70011); const Strategy = __nccwpck_require__(84114); const TokenSet = __nccwpck_require__(14974); const { CLOCK_TOLERANCE, HTTP_OPTIONS } = __nccwpck_require__(6144); const generators = __nccwpck_require__(65894); const { setDefaults } = __nccwpck_require__(8048); module.exports = { Issuer, Registry, Strategy, TokenSet, errors: { OPError, RPError, }, custom: { setHttpOptionsDefaults: setDefaults, http_options: HTTP_OPTIONS, clock_tolerance: CLOCK_TOLERANCE, }, generators, }; /***/ }), /***/ 14470: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /* eslint-disable max-classes-per-file */ const { inspect } = __nccwpck_require__(73837); const url = __nccwpck_require__(57310); const AggregateError = __nccwpck_require__(61231); const jose = __nccwpck_require__(87115); const LRU = __nccwpck_require__(7129); const objectHash = __nccwpck_require__(24856); const { RPError } = __nccwpck_require__(31151); const getClient = __nccwpck_require__(49609); const registry = __nccwpck_require__(70011); const processResponse = __nccwpck_require__(59980); const webfingerNormalize = __nccwpck_require__(10304); const instance = __nccwpck_require__(69020); const request = __nccwpck_require__(8048); const { assertIssuerConfiguration } = __nccwpck_require__(68973); const { ISSUER_DEFAULTS, OIDC_DISCOVERY, OAUTH2_DISCOVERY, WEBFINGER, REL, AAD_MULTITENANT_DISCOVERY, } = __nccwpck_require__(6144); const AAD_MULTITENANT = Symbol('AAD_MULTITENANT'); class Issuer { /** * @name constructor * @api public */ constructor(meta = {}) { const aadIssValidation = meta[AAD_MULTITENANT]; delete meta[AAD_MULTITENANT]; ['introspection', 'revocation'].forEach((endpoint) => { // if intro/revocation endpoint auth specific meta is missing use the token ones if they // are defined if ( meta[`${endpoint}_endpoint`] && meta[`${endpoint}_endpoint_auth_methods_supported`] === undefined && meta[`${endpoint}_endpoint_auth_signing_alg_values_supported`] === undefined ) { if (meta.token_endpoint_auth_methods_supported) { meta[`${endpoint}_endpoint_auth_methods_supported`] = meta.token_endpoint_auth_methods_supported; } if (meta.token_endpoint_auth_signing_alg_values_supported) { meta[`${endpoint}_endpoint_auth_signing_alg_values_supported`] = meta.token_endpoint_auth_signing_alg_values_supported; } } }); Object.entries(meta).forEach(([key, value]) => { instance(this).get('metadata').set(key, value); if (!this[key]) { Object.defineProperty(this, key, { get() { return instance(this).get('metadata').get(key); }, enumerable: true, }); } }); instance(this).set('cache', new LRU({ max: 100 })); registry.set(this.issuer, this); const Client = getClient(this, aadIssValidation); Object.defineProperties(this, { Client: { value: Client }, FAPIClient: { value: class FAPIClient extends Client {} }, }); } /** * @name keystore * @api public */ async keystore(reload = false) { assertIssuerConfiguration(this, 'jwks_uri'); const keystore = instance(this).get('keystore'); const cache = instance(this).get('cache'); if (reload || !keystore) { cache.reset(); const response = await request.call(this, { method: 'GET', responseType: 'json', url: this.jwks_uri, }); const jwks = processResponse(response); const joseKeyStore = jose.JWKS.asKeyStore(jwks, { ignoreErrors: true }); cache.set('throttle', true, 60 * 1000); instance(this).set('keystore', joseKeyStore); return joseKeyStore; } return keystore; } /** * @name queryKeyStore * @api private */ async queryKeyStore({ kid, kty, alg, use, key_ops: ops, }, { allowMulti = false } = {}) { const cache = instance(this).get('cache'); const def = { kid, kty, alg, use, key_ops: ops, }; const defHash = objectHash(def, { algorithm: 'sha256', ignoreUnknown: true, unorderedArrays: true, unorderedSets: true, }); // refresh keystore on every unknown key but also only upto once every minute const freshJwksUri = cache.get(defHash) || cache.get('throttle'); const keystore = await this.keystore(!freshJwksUri); const keys = keystore.all(def); if (keys.length === 0) { throw new RPError({ printf: ["no valid key found in issuer's jwks_uri for key parameters %j", def], jwks: keystore, }); } if (!allowMulti && keys.length > 1 && !kid) { throw new RPError({ printf: ["multiple matching keys found in issuer's jwks_uri for key parameters %j, kid must be provided in this case", def], jwks: keystore, }); } cache.set(defHash, true); return new jose.JWKS.KeyStore(keys); } /** * @name metadata * @api public */ get metadata() { const copy = {}; instance(this).get('metadata').forEach((value, key) => { copy[key] = value; }); return copy; } /** * @name webfinger * @api public */ static async webfinger(input) { const resource = webfingerNormalize(input); const { host } = url.parse(resource); const webfingerUrl = `https://${host}${WEBFINGER}`; const response = await request.call(this, { method: 'GET', url: webfingerUrl, responseType: 'json', searchParams: { resource, rel: REL }, followRedirect: true, }); const body = processResponse(response); const location = Array.isArray(body.links) && body.links.find((link) => typeof link === 'object' && link.rel === REL && link.href); if (!location) { throw new RPError({ message: 'no issuer found in webfinger response', body, }); } if (typeof location.href !== 'string' || !location.href.startsWith('https://')) { throw new RPError({ printf: ['invalid issuer location %s', location.href], body, }); } const expectedIssuer = location.href; if (registry.has(expectedIssuer)) { return registry.get(expectedIssuer); } const issuer = await this.discover(expectedIssuer); if (issuer.issuer !== expectedIssuer) { registry.delete(issuer.issuer); throw new RPError('discovered issuer mismatch, expected %s, got: %s', expectedIssuer, issuer.issuer); } return issuer; } /** * @name discover * @api public */ static async discover(uri) { const parsed = url.parse(uri); if (parsed.pathname.includes('/.well-known/')) { const response = await request.call(this, { method: 'GET', responseType: 'json', url: uri, }); const body = processResponse(response); return new Issuer({ ...ISSUER_DEFAULTS, ...body, [AAD_MULTITENANT]: !!AAD_MULTITENANT_DISCOVERY.find( (discoveryURL) => uri.startsWith(discoveryURL), ), }); } const pathnames = []; if (parsed.pathname.endsWith('/')) { pathnames.push(`${parsed.pathname}${OIDC_DISCOVERY.substring(1)}`); } else { pathnames.push(`${parsed.pathname}${OIDC_DISCOVERY}`); } if (parsed.pathname === '/') { pathnames.push(`${OAUTH2_DISCOVERY}`); } else { pathnames.push(`${OAUTH2_DISCOVERY}${parsed.pathname}`); } const errors = []; // eslint-disable-next-line no-restricted-syntax for (const pathname of pathnames) { try { const wellKnownUri = url.format({ ...parsed, pathname }); // eslint-disable-next-line no-await-in-loop const response = await request.call(this, { method: 'GET', responseType: 'json', url: wellKnownUri, }); const body = processResponse(response); return new Issuer({ ...ISSUER_DEFAULTS, ...body, [AAD_MULTITENANT]: !!AAD_MULTITENANT_DISCOVERY.find( (discoveryURL) => wellKnownUri.startsWith(discoveryURL), ), }); } catch (err) { errors.push(err); } } const err = new AggregateError(errors); err.message = `Issuer.discover() failed.${err.message.split('\n') .filter((line) => !line.startsWith(' at')).join('\n')}`; throw err; } /* istanbul ignore next */ [inspect.custom]() { return `${this.constructor.name} ${inspect(this.metadata, { depth: Infinity, colors: process.stdout.isTTY, compact: false, sorted: true, })}`; } } module.exports = Issuer; /***/ }), /***/ 70011: /***/ ((module) => { const REGISTRY = new Map(); module.exports = REGISTRY; /***/ }), /***/ 84114: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /* eslint-disable no-underscore-dangle */ const url = __nccwpck_require__(57310); const { format } = __nccwpck_require__(73837); const cloneDeep = __nccwpck_require__(85618); const { RPError, OPError } = __nccwpck_require__(31151); const { BaseClient } = __nccwpck_require__(49609); const { random, codeChallenge } = __nccwpck_require__(65894); const pick = __nccwpck_require__(70260); const { resolveResponseType, resolveRedirectUri } = __nccwpck_require__(26633); function verified(err, user, info = {}) { if (err) { this.error(err); } else if (!user) { this.fail(info); } else { this.success(user, info); } } /** * @name constructor * @api public */ function OpenIDConnectStrategy({ client, params = {}, passReqToCallback = false, sessionKey, usePKCE = true, extras = {}, } = {}, verify) { if (!(client instanceof BaseClient)) { throw new TypeError('client must be an instance of openid-client Client'); } if (typeof verify !== 'function') { throw new TypeError('verify callback must be a function'); } if (!client.issuer || !client.issuer.issuer) { throw new TypeError('client must have an issuer with an identifier'); } this._client = client; this._issuer = client.issuer; this._verify = verify; this._passReqToCallback = passReqToCallback; this._usePKCE = usePKCE; this._key = sessionKey || `oidc:${url.parse(this._issuer.issuer).hostname}`; this._params = cloneDeep(params); this._extras = cloneDeep(extras); if (!this._params.response_type) this._params.response_type = resolveResponseType.call(client); if (!this._params.redirect_uri) this._params.redirect_uri = resolveRedirectUri.call(client); if (!this._params.scope) this._params.scope = 'openid'; if (this._usePKCE === true) { const supportedMethods = Array.isArray(this._issuer.code_challenge_methods_supported) ? this._issuer.code_challenge_methods_supported : false; if (supportedMethods && supportedMethods.includes('S256')) { this._usePKCE = 'S256'; } else if (supportedMethods && supportedMethods.includes('plain')) { this._usePKCE = 'plain'; } else if (supportedMethods) { throw new TypeError('neither code_challenge_method supported by the client is supported by the issuer'); } else { this._usePKCE = 'S256'; } } else if (typeof this._usePKCE === 'string' && !['plain', 'S256'].includes(this._usePKCE)) { throw new TypeError(`${this._usePKCE} is not valid/implemented PKCE code_challenge_method`); } this.name = url.parse(client.issuer.issuer).hostname; } OpenIDConnectStrategy.prototype.authenticate = function authenticate(req, options) { (async () => { const client = this._client; if (!req.session) { throw new TypeError('authentication requires session support'); } const reqParams = client.callbackParams(req); const sessionKey = this._key; /* start authentication request */ if (Object.keys(reqParams).length === 0) { // provide options object with extra authentication parameters const params = { state: random(), ...this._params, ...options, }; if (!params.nonce && params.response_type.includes('id_token')) { params.nonce = random(); } req.session[sessionKey] = pick(params, 'nonce', 'state', 'max_age', 'response_type'); if (this._usePKCE && params.response_type.includes('code')) { const verifier = random(); req.session[sessionKey].code_verifier = verifier; switch (this._usePKCE) { // eslint-disable-line default-case case 'S256': params.code_challenge = codeChallenge(verifier); params.code_challenge_method = 'S256'; break; case 'plain': params.code_challenge = verifier; break; } } this.redirect(client.authorizationUrl(params)); return; } /* end authentication request */ /* start authentication response */ const session = req.session[sessionKey]; if (Object.keys(session || {}).length === 0) { throw new Error(format('did not find expected authorization request details in session, req.session["%s"] is %j', sessionKey, session)); } const { state, nonce, max_age: maxAge, code_verifier: codeVerifier, response_type: responseType, } = session; try { delete req.session[sessionKey]; } catch (err) {} const opts = { redirect_uri: this._params.redirect_uri, ...options, }; const checks = { state, nonce, max_age: maxAge, code_verifier: codeVerifier, response_type: responseType, }; const tokenset = await client.callback(opts.redirect_uri, reqParams, checks, this._extras); const passReq = this._passReqToCallback; const loadUserinfo = this._verify.length > (passReq ? 3 : 2) && client.issuer.userinfo_endpoint; const args = [tokenset, verified.bind(this)]; if (loadUserinfo) { if (!tokenset.access_token) { throw new RPError({ message: 'expected access_token to be returned when asking for userinfo in verify callback', tokenset, }); } const userinfo = await client.userinfo(tokenset); args.splice(1, 0, userinfo); } if (passReq) { args.unshift(req); } this._verify(...args); /* end authentication response */ })().catch((error) => { if ( (error instanceof OPError && error.error !== 'server_error' && !error.error.startsWith('invalid')) || error instanceof RPError ) { this.fail(error); } else { this.error(error); } }); }; module.exports = OpenIDConnectStrategy; /***/ }), /***/ 14974: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const base64url = __nccwpck_require__(23570); const now = __nccwpck_require__(24393); class TokenSet { /** * @name constructor * @api public */ constructor(values) { Object.assign(this, values); } /** * @name expires_in= * @api public */ set expires_in(value) { // eslint-disable-line camelcase this.expires_at = now() + Number(value); } /** * @name expires_in * @api public */ get expires_in() { // eslint-disable-line camelcase return Math.max.apply(null, [this.expires_at - now(), 0]); } /** * @name expired * @api public */ expired() { return this.expires_in === 0; } /** * @name claims * @api public */ claims() { if (!this.id_token) { throw new TypeError('id_token not present in TokenSet'); } return JSON.parse(base64url.decode(this.id_token.split('.')[1])); } } module.exports = TokenSet; /***/ }), /***/ 67551: /***/ ((module) => { /*! ***************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ /* global global, define, System, Reflect, Promise */ var __extends; var __assign; var __rest; var __decorate; var __param; var __metadata; var __awaiter; var __generator; var __exportStar; var __values; var __read; var __spread; var __spreadArrays; var __await; var __asyncGenerator; var __asyncDelegator; var __asyncValues; var __makeTemplateObject; var __importStar; var __importDefault; var __classPrivateFieldGet; var __classPrivateFieldSet; var __createBinding; (function (factory) { var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {}; if (typeof define === "function" && define.amd) { define("tslib", ["exports"], function (exports) { factory(createExporter(root, createExporter(exports))); }); } else if ( true && typeof module.exports === "object") { factory(createExporter(root, createExporter(module.exports))); } else { factory(createExporter(root)); } function createExporter(exports, previous) { if (exports !== root) { if (typeof Object.create === "function") { Object.defineProperty(exports, "__esModule", { value: true }); } else { exports.__esModule = true; } } return function (id, v) { return exports[id] = previous ? previous(id, v) : v; }; } }) (function (exporter) { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; __extends = function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; __assign = Object.assign || function (t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; __rest = function (s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; __decorate = function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; __param = function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; __metadata = function (metadataKey, metadataValue) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); }; __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()); }); }; __generator = function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; __createBinding = function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; }; __exportStar = function (m, exports) { for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) exports[p] = m[p]; }; __values = function (o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); }; __read = function (o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; }; __spread = function () { for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); return ar; }; __spreadArrays = function () { for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j]; return r; }; __await = function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }; __asyncGenerator = function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var g = generator.apply(thisArg, _arguments || []), i, q = []; return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; __asyncDelegator = function (o) { var i, p; return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } }; __asyncValues = function (o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator], i; return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } }; __makeTemplateObject = function (cooked, raw) { if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } return cooked; }; __importStar = function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result["default"] = mod; return result; }; __importDefault = function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; __classPrivateFieldGet = function (receiver, privateMap) { if (!privateMap.has(receiver)) { throw new TypeError("attempted to get private field on non-instance"); } return privateMap.get(receiver); }; __classPrivateFieldSet = function (receiver, privateMap, value) { if (!privateMap.has(receiver)) { throw new TypeError("attempted to set private field on non-instance"); } privateMap.set(receiver, value); return value; }; exporter("__extends", __extends); exporter("__assign", __assign); exporter("__rest", __rest); exporter("__decorate", __decorate); exporter("__param", __param); exporter("__metadata", __metadata); exporter("__awaiter", __awaiter); exporter("__generator", __generator); exporter("__exportStar", __exportStar); exporter("__createBinding", __createBinding); exporter("__values", __values); exporter("__read", __read); exporter("__spread", __spread); exporter("__spreadArrays", __spreadArrays); exporter("__await", __await); exporter("__asyncGenerator", __asyncGenerator); exporter("__asyncDelegator", __asyncDelegator); exporter("__asyncValues", __asyncValues); exporter("__makeTemplateObject", __makeTemplateObject); exporter("__importStar", __importStar); exporter("__importDefault", __importDefault); exporter("__classPrivateFieldGet", __classPrivateFieldGet); exporter("__classPrivateFieldSet", __classPrivateFieldSet); }); /***/ }), /***/ 40334: /***/ ((module) => { "use strict"; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // pkg/dist-src/index.js var dist_src_exports = {}; __export(dist_src_exports, { createTokenAuth: () => createTokenAuth }); module.exports = __toCommonJS(dist_src_exports); // pkg/dist-src/auth.js var REGEX_IS_INSTALLATION_LEGACY = /^v1\./; var REGEX_IS_INSTALLATION = /^ghs_/; var REGEX_IS_USER_TO_SERVER = /^ghu_/; async function auth(token) { const isApp = token.split(/\./).length === 3; const isInstallation = REGEX_IS_INSTALLATION_LEGACY.test(token) || REGEX_IS_INSTALLATION.test(token); const isUserToServer = REGEX_IS_USER_TO_SERVER.test(token); 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) }); }; // Annotate the CommonJS export names for ESM import in node: 0 && (0); /***/ }), /***/ 76762: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // pkg/dist-src/index.js var dist_src_exports = {}; __export(dist_src_exports, { Octokit: () => Octokit }); module.exports = __toCommonJS(dist_src_exports); var import_universal_user_agent = __nccwpck_require__(45030); var import_before_after_hook = __nccwpck_require__(83682); var import_request = __nccwpck_require__(36234); var import_graphql = __nccwpck_require__(88467); var import_auth_token = __nccwpck_require__(40334); // pkg/dist-src/version.js var VERSION = "5.1.0"; // pkg/dist-src/index.js var noop = () => { }; var consoleWarn = console.warn.bind(console); var consoleError = console.error.bind(console); var userAgentTrail = `octokit-core.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}`; var Octokit = class { static { this.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 { this.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 { this.plugins = currentPlugins.concat( newPlugins.filter((plugin) => !currentPlugins.includes(plugin)) ); } }; return NewOctokit; } constructor(options = {}) { const hook = new import_before_after_hook.Collection(); const requestDefaults = { baseUrl: import_request.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 = import_request.request.defaults(requestDefaults); this.graphql = (0, import_graphql.withCustomRequest)(this.request).defaults(requestDefaults); this.log = Object.assign( { debug: noop, info: noop, warn: consoleWarn, error: consoleError }, options.log ); this.hook = hook; if (!options.authStrategy) { if (!options.auth) { this.auth = async () => ({ type: "unauthenticated" }); } else { const auth = (0, import_auth_token.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)); } } }; // Annotate the CommonJS export names for ESM import in node: 0 && (0); /***/ }), /***/ 59440: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // pkg/dist-src/index.js var dist_src_exports = {}; __export(dist_src_exports, { endpoint: () => endpoint }); module.exports = __toCommonJS(dist_src_exports); // pkg/dist-src/defaults.js var import_universal_user_agent = __nccwpck_require__(45030); // pkg/dist-src/version.js var VERSION = "9.0.4"; // pkg/dist-src/defaults.js var userAgent = `octokit-endpoint.js/${VERSION} ${(0, import_universal_user_agent.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); } // 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 = 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+|\W+$/g, "").split(/,/); } function extractUrlVariableNames(url) { const matches = url.match(urlVariableRegex); if (!matches) { return []; } return matches.map(removeNonChars).reduce((a, b) => 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 === "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(/[\w-]+(?=-preview)/g) || []; headers.accept = previewsFromAcceptHeader.concat(options.mediaType.previews).map((preview) => { 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); // Annotate the CommonJS export names for ESM import in node: 0 && (0); /***/ }), /***/ 88467: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // pkg/dist-src/index.js var dist_src_exports = {}; __export(dist_src_exports, { GraphqlResponseError: () => GraphqlResponseError, graphql: () => graphql2, withCustomRequest: () => withCustomRequest }); module.exports = __toCommonJS(dist_src_exports); var import_request3 = __nccwpck_require__(36234); var import_universal_user_agent = __nccwpck_require__(45030); // pkg/dist-src/version.js var VERSION = "7.0.2"; // pkg/dist-src/with-defaults.js var import_request2 = __nccwpck_require__(36234); // pkg/dist-src/graphql.js var import_request = __nccwpck_require__(36234); // 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.name = "GraphqlResponseError"; this.errors = response.errors; this.data = response.data; if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); } } }; // pkg/dist-src/graphql.js var NON_VARIABLE_OPTIONS = [ "method", "baseUrl", "url", "headers", "request", "query", "mediaType" ]; 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 withDefaults(request2, newDefaults) { const newRequest = request2.defaults(newDefaults); const newApi = (query, options) => { return graphql(newRequest, query, options); }; return Object.assign(newApi, { defaults: withDefaults.bind(null, newRequest), endpoint: newRequest.endpoint }); } // pkg/dist-src/index.js var graphql2 = withDefaults(import_request3.request, { headers: { "user-agent": `octokit-graphql.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` }, method: "POST", url: "/graphql" }); function withCustomRequest(customRequest) { return withDefaults(customRequest, { method: "POST", url: "/graphql" }); } // Annotate the CommonJS export names for ESM import in node: 0 && (0); /***/ }), /***/ 10537: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // pkg/dist-src/index.js var dist_src_exports = {}; __export(dist_src_exports, { RequestError: () => RequestError }); module.exports = __toCommonJS(dist_src_exports); var import_deprecation = __nccwpck_require__(58932); var import_once = __toESM(__nccwpck_require__(1223)); var logOnceCode = (0, import_once.default)((deprecation) => console.warn(deprecation)); var logOnceHeaders = (0, import_once.default)((deprecation) => console.warn(deprecation)); var RequestError = class extends Error { constructor(message, statusCode, options) { super(message); if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); } this.name = "HttpError"; this.status = statusCode; let headers; if ("headers" in options && typeof options.headers !== "undefined") { headers = options.headers; } if ("response" in options) { this.response = options.response; headers = options.response.headers; } const requestCopy = Object.assign({}, options.request); if (options.request.headers.authorization) { requestCopy.headers = Object.assign({}, options.request.headers, { authorization: options.request.headers.authorization.replace( / .*$/, " [REDACTED]" ) }); } requestCopy.url = requestCopy.url.replace(/\bclient_secret=\w+/g, "client_secret=[REDACTED]").replace(/\baccess_token=\w+/g, "access_token=[REDACTED]"); this.request = requestCopy; Object.defineProperty(this, "code", { get() { logOnceCode( new import_deprecation.Deprecation( "[@octokit/request-error] `error.code` is deprecated, use `error.status`." ) ); return statusCode; } }); Object.defineProperty(this, "headers", { get() { logOnceHeaders( new import_deprecation.Deprecation( "[@octokit/request-error] `error.headers` is deprecated, use `error.response.headers`." ) ); return headers || {}; } }); } }; // Annotate the CommonJS export names for ESM import in node: 0 && (0); /***/ }), /***/ 36234: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // pkg/dist-src/index.js var dist_src_exports = {}; __export(dist_src_exports, { request: () => request }); module.exports = __toCommonJS(dist_src_exports); var import_endpoint = __nccwpck_require__(59440); var import_universal_user_agent = __nccwpck_require__(45030); // pkg/dist-src/version.js var VERSION = "8.2.0"; // pkg/dist-src/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/fetch-wrapper.js var import_request_error = __nccwpck_require__(10537); // pkg/dist-src/get-buffer-response.js function getBufferResponse(response) { return response.arrayBuffer(); } // pkg/dist-src/fetch-wrapper.js function fetchWrapper(requestOptions) { var _a, _b, _c; const log = requestOptions.request && requestOptions.request.log ? requestOptions.request.log : console; const parseSuccessResponseBody = ((_a = requestOptions.request) == null ? void 0 : _a.parseSuccessResponseBody) !== false; if (isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body)) { requestOptions.body = JSON.stringify(requestOptions.body); } let headers = {}; let status; let url; let { fetch } = globalThis; if ((_b = requestOptions.request) == null ? void 0 : _b.fetch) { fetch = requestOptions.request.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" ); } return fetch(requestOptions.url, { method: requestOptions.method, body: requestOptions.body, headers: requestOptions.headers, signal: (_c = requestOptions.request) == null ? void 0 : _c.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" } }).then(async (response) => { url = response.url; status = response.status; for (const keyAndValue of response.headers) { headers[keyAndValue[0]] = keyAndValue[1]; } if ("deprecation" in headers) { const matches = headers.link && headers.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 ${headers.sunset}${deprecationLink ? `. See ${deprecationLink}` : ""}` ); } if (status === 204 || status === 205) { return; } if (requestOptions.method === "HEAD") { if (status < 400) { return; } throw new import_request_error.RequestError(response.statusText, status, { response: { url, status, headers, data: void 0 }, request: requestOptions }); } if (status === 304) { throw new import_request_error.RequestError("Not modified", status, { response: { url, status, headers, data: await getResponseData(response) }, request: requestOptions }); } if (status >= 400) { const data = await getResponseData(response); const error = new import_request_error.RequestError(toErrorMessage(data), status, { response: { url, status, headers, data }, request: requestOptions }); throw error; } return parseSuccessResponseBody ? await getResponseData(response) : response.body; }).then((data) => { return { status, url, headers, data }; }).catch((error) => { if (error instanceof import_request_error.RequestError) throw error; else if (error.name === "AbortError") throw error; let 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; } } throw new import_request_error.RequestError(message, 500, { request: requestOptions }); }); } async function getResponseData(response) { const contentType = response.headers.get("content-type"); if (/application\/json/.test(contentType)) { return response.json().catch(() => response.text()).catch(() => ""); } if (!contentType || /^text\/|charset=utf-8$/.test(contentType)) { return response.text(); } return getBufferResponse(response); } function toErrorMessage(data) { if (typeof data === "string") return data; let suffix; if ("documentation_url" in data) { suffix = ` - ${data.documentation_url}`; } else { suffix = ""; } if ("message" in data) { if (Array.isArray(data.errors)) { return `${data.message}: ${data.errors.map(JSON.stringify).join(", ")}${suffix}`; } return `${data.message}${suffix}`; } return `Unknown error: ${JSON.stringify(data)}`; } // pkg/dist-src/with-defaults.js function 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: withDefaults.bind(null, endpoint2) }); return endpointOptions.request.hook(request2, endpointOptions); }; return Object.assign(newApi, { endpoint: endpoint2, defaults: withDefaults.bind(null, endpoint2) }); } // pkg/dist-src/index.js var request = withDefaults(import_endpoint.endpoint, { headers: { "user-agent": `octokit-request.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` } }); // Annotate the CommonJS export names for ESM import in node: 0 && (0); /***/ }), /***/ 57171: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ContextAPI = void 0; const NoopContextManager_1 = __nccwpck_require__(54118); const global_utils_1 = __nccwpck_require__(85135); const diag_1 = __nccwpck_require__(11877); const API_NAME = 'context'; const NOOP_CONTEXT_MANAGER = new NoopContextManager_1.NoopContextManager(); /** * Singleton object which represents the entry point to the OpenTelemetry Context API */ class ContextAPI { /** Empty private constructor prevents end users from constructing a new instance of the API */ constructor() { } /** Get the singleton instance of the Context API */ static getInstance() { if (!this._instance) { this._instance = new ContextAPI(); } return this._instance; } /** * Set the current context manager. * * @returns true if the context manager was successfully registered, else false */ setGlobalContextManager(contextManager) { return (0, global_utils_1.registerGlobal)(API_NAME, contextManager, diag_1.DiagAPI.instance()); } /** * Get the currently active context */ active() { return this._getContextManager().active(); } /** * Execute a function with an active context * * @param context context to be active during function execution * @param fn function to execute in a context * @param thisArg optional receiver to be used for calling fn * @param args optional arguments forwarded to fn */ with(context, fn, thisArg, ...args) { return this._getContextManager().with(context, fn, thisArg, ...args); } /** * Bind a context to a target function or event emitter * * @param context context to bind to the event emitter or function. Defaults to the currently active context * @param target function or event emitter to bind */ bind(context, target) { return this._getContextManager().bind(context, target); } _getContextManager() { return (0, global_utils_1.getGlobal)(API_NAME) || NOOP_CONTEXT_MANAGER; } /** Disable and remove the global context manager */ disable() { this._getContextManager().disable(); (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance()); } } exports.ContextAPI = ContextAPI; //# sourceMappingURL=context.js.map /***/ }), /***/ 11877: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DiagAPI = void 0; const ComponentLogger_1 = __nccwpck_require__(17978); const logLevelLogger_1 = __nccwpck_require__(99639); const types_1 = __nccwpck_require__(78077); const global_utils_1 = __nccwpck_require__(85135); const API_NAME = 'diag'; /** * Singleton object which represents the entry point to the OpenTelemetry internal * diagnostic API */ class DiagAPI { /** * Private internal constructor * @private */ constructor() { function _logProxy(funcName) { return function (...args) { const logger = (0, global_utils_1.getGlobal)('diag'); // shortcut if logger not set if (!logger) return; return logger[funcName](...args); }; } // Using self local variable for minification purposes as 'this' cannot be minified const self = this; // DiagAPI specific functions const setLogger = (logger, optionsOrLogLevel = { logLevel: types_1.DiagLogLevel.INFO }) => { var _a, _b, _c; if (logger === self) { // There isn't much we can do here. // Logging to the console might break the user application. // Try to log to self. If a logger was previously registered it will receive the log. const err = new Error('Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation'); self.error((_a = err.stack) !== null && _a !== void 0 ? _a : err.message); return false; } if (typeof optionsOrLogLevel === 'number') { optionsOrLogLevel = { logLevel: optionsOrLogLevel, }; } const oldLogger = (0, global_utils_1.getGlobal)('diag'); const newLogger = (0, logLevelLogger_1.createLogLevelDiagLogger)((_b = optionsOrLogLevel.logLevel) !== null && _b !== void 0 ? _b : types_1.DiagLogLevel.INFO, logger); // There already is an logger registered. We'll let it know before overwriting it. if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) { const stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : ''; oldLogger.warn(`Current logger will be overwritten from ${stack}`); newLogger.warn(`Current logger will overwrite one already registered from ${stack}`); } return (0, global_utils_1.registerGlobal)('diag', newLogger, self, true); }; self.setLogger = setLogger; self.disable = () => { (0, global_utils_1.unregisterGlobal)(API_NAME, self); }; self.createComponentLogger = (options) => { return new ComponentLogger_1.DiagComponentLogger(options); }; self.verbose = _logProxy('verbose'); self.debug = _logProxy('debug'); self.info = _logProxy('info'); self.warn = _logProxy('warn'); self.error = _logProxy('error'); } /** Get the singleton instance of the DiagAPI API */ static instance() { if (!this._instance) { this._instance = new DiagAPI(); } return this._instance; } } exports.DiagAPI = DiagAPI; //# sourceMappingURL=diag.js.map /***/ }), /***/ 17696: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.MetricsAPI = void 0; const NoopMeterProvider_1 = __nccwpck_require__(72647); const global_utils_1 = __nccwpck_require__(85135); const diag_1 = __nccwpck_require__(11877); const API_NAME = 'metrics'; /** * Singleton object which represents the entry point to the OpenTelemetry Metrics API */ class MetricsAPI { /** Empty private constructor prevents end users from constructing a new instance of the API */ constructor() { } /** Get the singleton instance of the Metrics API */ static getInstance() { if (!this._instance) { this._instance = new MetricsAPI(); } return this._instance; } /** * Set the current global meter provider. * Returns true if the meter provider was successfully registered, else false. */ setGlobalMeterProvider(provider) { return (0, global_utils_1.registerGlobal)(API_NAME, provider, diag_1.DiagAPI.instance()); } /** * Returns the global meter provider. */ getMeterProvider() { return (0, global_utils_1.getGlobal)(API_NAME) || NoopMeterProvider_1.NOOP_METER_PROVIDER; } /** * Returns a meter from the global meter provider. */ getMeter(name, version, options) { return this.getMeterProvider().getMeter(name, version, options); } /** Remove the global meter provider */ disable() { (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance()); } } exports.MetricsAPI = MetricsAPI; //# sourceMappingURL=metrics.js.map /***/ }), /***/ 89909: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PropagationAPI = void 0; const global_utils_1 = __nccwpck_require__(85135); const NoopTextMapPropagator_1 = __nccwpck_require__(72368); const TextMapPropagator_1 = __nccwpck_require__(80865); const context_helpers_1 = __nccwpck_require__(37682); const utils_1 = __nccwpck_require__(28136); const diag_1 = __nccwpck_require__(11877); const API_NAME = 'propagation'; const NOOP_TEXT_MAP_PROPAGATOR = new NoopTextMapPropagator_1.NoopTextMapPropagator(); /** * Singleton object which represents the entry point to the OpenTelemetry Propagation API */ class PropagationAPI { /** Empty private constructor prevents end users from constructing a new instance of the API */ constructor() { this.createBaggage = utils_1.createBaggage; this.getBaggage = context_helpers_1.getBaggage; this.getActiveBaggage = context_helpers_1.getActiveBaggage; this.setBaggage = context_helpers_1.setBaggage; this.deleteBaggage = context_helpers_1.deleteBaggage; } /** Get the singleton instance of the Propagator API */ static getInstance() { if (!this._instance) { this._instance = new PropagationAPI(); } return this._instance; } /** * Set the current propagator. * * @returns true if the propagator was successfully registered, else false */ setGlobalPropagator(propagator) { return (0, global_utils_1.registerGlobal)(API_NAME, propagator, diag_1.DiagAPI.instance()); } /** * Inject context into a carrier to be propagated inter-process * * @param context Context carrying tracing data to inject * @param carrier carrier to inject context into * @param setter Function used to set values on the carrier */ inject(context, carrier, setter = TextMapPropagator_1.defaultTextMapSetter) { return this._getGlobalPropagator().inject(context, carrier, setter); } /** * Extract context from a carrier * * @param context Context which the newly created context will inherit from * @param carrier Carrier to extract context from * @param getter Function used to extract keys from a carrier */ extract(context, carrier, getter = TextMapPropagator_1.defaultTextMapGetter) { return this._getGlobalPropagator().extract(context, carrier, getter); } /** * Return a list of all fields which may be used by the propagator. */ fields() { return this._getGlobalPropagator().fields(); } /** Remove the global propagator */ disable() { (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance()); } _getGlobalPropagator() { return (0, global_utils_1.getGlobal)(API_NAME) || NOOP_TEXT_MAP_PROPAGATOR; } } exports.PropagationAPI = PropagationAPI; //# sourceMappingURL=propagation.js.map /***/ }), /***/ 81539: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.TraceAPI = void 0; const global_utils_1 = __nccwpck_require__(85135); const ProxyTracerProvider_1 = __nccwpck_require__(2285); const spancontext_utils_1 = __nccwpck_require__(49745); const context_utils_1 = __nccwpck_require__(23326); const diag_1 = __nccwpck_require__(11877); const API_NAME = 'trace'; /** * Singleton object which represents the entry point to the OpenTelemetry Tracing API */ class TraceAPI { /** Empty private constructor prevents end users from constructing a new instance of the API */ constructor() { this._proxyTracerProvider = new ProxyTracerProvider_1.ProxyTracerProvider(); this.wrapSpanContext = spancontext_utils_1.wrapSpanContext; this.isSpanContextValid = spancontext_utils_1.isSpanContextValid; this.deleteSpan = context_utils_1.deleteSpan; this.getSpan = context_utils_1.getSpan; this.getActiveSpan = context_utils_1.getActiveSpan; this.getSpanContext = context_utils_1.getSpanContext; this.setSpan = context_utils_1.setSpan; this.setSpanContext = context_utils_1.setSpanContext; } /** Get the singleton instance of the Trace API */ static getInstance() { if (!this._instance) { this._instance = new TraceAPI(); } return this._instance; } /** * Set the current global tracer. * * @returns true if the tracer provider was successfully registered, else false */ setGlobalTracerProvider(provider) { const success = (0, global_utils_1.registerGlobal)(API_NAME, this._proxyTracerProvider, diag_1.DiagAPI.instance()); if (success) { this._proxyTracerProvider.setDelegate(provider); } return success; } /** * Returns the global tracer provider. */ getTracerProvider() { return (0, global_utils_1.getGlobal)(API_NAME) || this._proxyTracerProvider; } /** * Returns a tracer from the global tracer provider. */ getTracer(name, version) { return this.getTracerProvider().getTracer(name, version); } /** Remove the global tracer provider */ disable() { (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance()); this._proxyTracerProvider = new ProxyTracerProvider_1.ProxyTracerProvider(); } } exports.TraceAPI = TraceAPI; //# sourceMappingURL=trace.js.map /***/ }), /***/ 37682: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.deleteBaggage = exports.setBaggage = exports.getActiveBaggage = exports.getBaggage = void 0; const context_1 = __nccwpck_require__(57171); const context_2 = __nccwpck_require__(78242); /** * Baggage key */ const BAGGAGE_KEY = (0, context_2.createContextKey)('OpenTelemetry Baggage Key'); /** * Retrieve the current baggage from the given context * * @param {Context} Context that manage all context values * @returns {Baggage} Extracted baggage from the context */ function getBaggage(context) { return context.getValue(BAGGAGE_KEY) || undefined; } exports.getBaggage = getBaggage; /** * Retrieve the current baggage from the active/current context * * @returns {Baggage} Extracted baggage from the context */ function getActiveBaggage() { return getBaggage(context_1.ContextAPI.getInstance().active()); } exports.getActiveBaggage = getActiveBaggage; /** * Store a baggage in the given context * * @param {Context} Context that manage all context values * @param {Baggage} baggage that will be set in the actual context */ function setBaggage(context, baggage) { return context.setValue(BAGGAGE_KEY, baggage); } exports.setBaggage = setBaggage; /** * Delete the baggage stored in the given context * * @param {Context} Context that manage all context values */ function deleteBaggage(context) { return context.deleteValue(BAGGAGE_KEY); } exports.deleteBaggage = deleteBaggage; //# sourceMappingURL=context-helpers.js.map /***/ }), /***/ 84811: /***/ ((__unused_webpack_module, exports) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.BaggageImpl = void 0; class BaggageImpl { constructor(entries) { this._entries = entries ? new Map(entries) : new Map(); } getEntry(key) { const entry = this._entries.get(key); if (!entry) { return undefined; } return Object.assign({}, entry); } getAllEntries() { return Array.from(this._entries.entries()).map(([k, v]) => [k, v]); } setEntry(key, entry) { const newBaggage = new BaggageImpl(this._entries); newBaggage._entries.set(key, entry); return newBaggage; } removeEntry(key) { const newBaggage = new BaggageImpl(this._entries); newBaggage._entries.delete(key); return newBaggage; } removeEntries(...keys) { const newBaggage = new BaggageImpl(this._entries); for (const key of keys) { newBaggage._entries.delete(key); } return newBaggage; } clear() { return new BaggageImpl(); } } exports.BaggageImpl = BaggageImpl; //# sourceMappingURL=baggage-impl.js.map /***/ }), /***/ 23542: /***/ ((__unused_webpack_module, exports) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.baggageEntryMetadataSymbol = void 0; /** * Symbol used to make BaggageEntryMetadata an opaque type */ exports.baggageEntryMetadataSymbol = Symbol('BaggageEntryMetadata'); //# sourceMappingURL=symbol.js.map /***/ }), /***/ 28136: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.baggageEntryMetadataFromString = exports.createBaggage = void 0; const diag_1 = __nccwpck_require__(11877); const baggage_impl_1 = __nccwpck_require__(84811); const symbol_1 = __nccwpck_require__(23542); const diag = diag_1.DiagAPI.instance(); /** * Create a new Baggage with optional entries * * @param entries An array of baggage entries the new baggage should contain */ function createBaggage(entries = {}) { return new baggage_impl_1.BaggageImpl(new Map(Object.entries(entries))); } exports.createBaggage = createBaggage; /** * Create a serializable BaggageEntryMetadata object from a string. * * @param str string metadata. Format is currently not defined by the spec and has no special meaning. * */ function baggageEntryMetadataFromString(str) { if (typeof str !== 'string') { diag.error(`Cannot create baggage metadata from unknown type: ${typeof str}`); str = ''; } return { __TYPE__: symbol_1.baggageEntryMetadataSymbol, toString() { return str; }, }; } exports.baggageEntryMetadataFromString = baggageEntryMetadataFromString; //# sourceMappingURL=utils.js.map /***/ }), /***/ 7393: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.context = void 0; // Split module-level variable definition into separate files to allow // tree-shaking on each api instance. const context_1 = __nccwpck_require__(57171); /** Entrypoint for context API */ exports.context = context_1.ContextAPI.getInstance(); //# sourceMappingURL=context-api.js.map /***/ }), /***/ 54118: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NoopContextManager = void 0; const context_1 = __nccwpck_require__(78242); class NoopContextManager { active() { return context_1.ROOT_CONTEXT; } with(_context, fn, thisArg, ...args) { return fn.call(thisArg, ...args); } bind(_context, target) { return target; } enable() { return this; } disable() { return this; } } exports.NoopContextManager = NoopContextManager; //# sourceMappingURL=NoopContextManager.js.map /***/ }), /***/ 78242: /***/ ((__unused_webpack_module, exports) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ROOT_CONTEXT = exports.createContextKey = void 0; /** Get a key to uniquely identify a context value */ function createContextKey(description) { // The specification states that for the same input, multiple calls should // return different keys. Due to the nature of the JS dependency management // system, this creates problems where multiple versions of some package // could hold different keys for the same property. // // Therefore, we use Symbol.for which returns the same key for the same input. return Symbol.for(description); } exports.createContextKey = createContextKey; class BaseContext { /** * Construct a new context which inherits values from an optional parent context. * * @param parentContext a context from which to inherit values */ constructor(parentContext) { // for minification const self = this; self._currentContext = parentContext ? new Map(parentContext) : new Map(); self.getValue = (key) => self._currentContext.get(key); self.setValue = (key, value) => { const context = new BaseContext(self._currentContext); context._currentContext.set(key, value); return context; }; self.deleteValue = (key) => { const context = new BaseContext(self._currentContext); context._currentContext.delete(key); return context; }; } } /** The root context is used as the default parent context when there is no active context */ exports.ROOT_CONTEXT = new BaseContext(); //# sourceMappingURL=context.js.map /***/ }), /***/ 39721: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.diag = void 0; // Split module-level variable definition into separate files to allow // tree-shaking on each api instance. const diag_1 = __nccwpck_require__(11877); /** * Entrypoint for Diag API. * Defines Diagnostic handler used for internal diagnostic logging operations. * The default provides a Noop DiagLogger implementation which may be changed via the * diag.setLogger(logger: DiagLogger) function. */ exports.diag = diag_1.DiagAPI.instance(); //# sourceMappingURL=diag-api.js.map /***/ }), /***/ 17978: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DiagComponentLogger = void 0; const global_utils_1 = __nccwpck_require__(85135); /** * Component Logger which is meant to be used as part of any component which * will add automatically additional namespace in front of the log message. * It will then forward all message to global diag logger * @example * const cLogger = diag.createComponentLogger({ namespace: '@opentelemetry/instrumentation-http' }); * cLogger.debug('test'); * // @opentelemetry/instrumentation-http test */ class DiagComponentLogger { constructor(props) { this._namespace = props.namespace || 'DiagComponentLogger'; } debug(...args) { return logProxy('debug', this._namespace, args); } error(...args) { return logProxy('error', this._namespace, args); } info(...args) { return logProxy('info', this._namespace, args); } warn(...args) { return logProxy('warn', this._namespace, args); } verbose(...args) { return logProxy('verbose', this._namespace, args); } } exports.DiagComponentLogger = DiagComponentLogger; function logProxy(funcName, namespace, args) { const logger = (0, global_utils_1.getGlobal)('diag'); // shortcut if logger not set if (!logger) { return; } args.unshift(namespace); return logger[funcName](...args); } //# sourceMappingURL=ComponentLogger.js.map /***/ }), /***/ 3041: /***/ ((__unused_webpack_module, exports) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DiagConsoleLogger = void 0; const consoleMap = [ { n: 'error', c: 'error' }, { n: 'warn', c: 'warn' }, { n: 'info', c: 'info' }, { n: 'debug', c: 'debug' }, { n: 'verbose', c: 'trace' }, ]; /** * A simple Immutable Console based diagnostic logger which will output any messages to the Console. * If you want to limit the amount of logging to a specific level or lower use the * {@link createLogLevelDiagLogger} */ class DiagConsoleLogger { constructor() { function _consoleFunc(funcName) { return function (...args) { if (console) { // Some environments only expose the console when the F12 developer console is open // eslint-disable-next-line no-console let theFunc = console[funcName]; if (typeof theFunc !== 'function') { // Not all environments support all functions // eslint-disable-next-line no-console theFunc = console.log; } // One last final check if (typeof theFunc === 'function') { return theFunc.apply(console, args); } } }; } for (let i = 0; i < consoleMap.length; i++) { this[consoleMap[i].n] = _consoleFunc(consoleMap[i].c); } } } exports.DiagConsoleLogger = DiagConsoleLogger; //# sourceMappingURL=consoleLogger.js.map /***/ }), /***/ 99639: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createLogLevelDiagLogger = void 0; const types_1 = __nccwpck_require__(78077); function createLogLevelDiagLogger(maxLevel, logger) { if (maxLevel < types_1.DiagLogLevel.NONE) { maxLevel = types_1.DiagLogLevel.NONE; } else if (maxLevel > types_1.DiagLogLevel.ALL) { maxLevel = types_1.DiagLogLevel.ALL; } // In case the logger is null or undefined logger = logger || {}; function _filterFunc(funcName, theLevel) { const theFunc = logger[funcName]; if (typeof theFunc === 'function' && maxLevel >= theLevel) { return theFunc.bind(logger); } return function () { }; } return { error: _filterFunc('error', types_1.DiagLogLevel.ERROR), warn: _filterFunc('warn', types_1.DiagLogLevel.WARN), info: _filterFunc('info', types_1.DiagLogLevel.INFO), debug: _filterFunc('debug', types_1.DiagLogLevel.DEBUG), verbose: _filterFunc('verbose', types_1.DiagLogLevel.VERBOSE), }; } exports.createLogLevelDiagLogger = createLogLevelDiagLogger; //# sourceMappingURL=logLevelLogger.js.map /***/ }), /***/ 78077: /***/ ((__unused_webpack_module, exports) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DiagLogLevel = void 0; /** * Defines the available internal logging levels for the diagnostic logger, the numeric values * of the levels are defined to match the original values from the initial LogLevel to avoid * compatibility/migration issues for any implementation that assume the numeric ordering. */ var DiagLogLevel; (function (DiagLogLevel) { /** Diagnostic Logging level setting to disable all logging (except and forced logs) */ DiagLogLevel[DiagLogLevel["NONE"] = 0] = "NONE"; /** Identifies an error scenario */ DiagLogLevel[DiagLogLevel["ERROR"] = 30] = "ERROR"; /** Identifies a warning scenario */ DiagLogLevel[DiagLogLevel["WARN"] = 50] = "WARN"; /** General informational log message */ DiagLogLevel[DiagLogLevel["INFO"] = 60] = "INFO"; /** General debug log message */ DiagLogLevel[DiagLogLevel["DEBUG"] = 70] = "DEBUG"; /** * Detailed trace level logging should only be used for development, should only be set * in a development environment. */ DiagLogLevel[DiagLogLevel["VERBOSE"] = 80] = "VERBOSE"; /** Used to set the logging level to include all logging */ DiagLogLevel[DiagLogLevel["ALL"] = 9999] = "ALL"; })(DiagLogLevel = exports.DiagLogLevel || (exports.DiagLogLevel = {})); //# sourceMappingURL=types.js.map /***/ }), /***/ 65163: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.trace = exports.propagation = exports.metrics = exports.diag = exports.context = exports.INVALID_SPAN_CONTEXT = exports.INVALID_TRACEID = exports.INVALID_SPANID = exports.isValidSpanId = exports.isValidTraceId = exports.isSpanContextValid = exports.createTraceState = exports.TraceFlags = exports.SpanStatusCode = exports.SpanKind = exports.SamplingDecision = exports.ProxyTracerProvider = exports.ProxyTracer = exports.defaultTextMapSetter = exports.defaultTextMapGetter = exports.ValueType = exports.createNoopMeter = exports.DiagLogLevel = exports.DiagConsoleLogger = exports.ROOT_CONTEXT = exports.createContextKey = exports.baggageEntryMetadataFromString = void 0; var utils_1 = __nccwpck_require__(28136); Object.defineProperty(exports, "baggageEntryMetadataFromString", ({ enumerable: true, get: function () { return utils_1.baggageEntryMetadataFromString; } })); // Context APIs var context_1 = __nccwpck_require__(78242); Object.defineProperty(exports, "createContextKey", ({ enumerable: true, get: function () { return context_1.createContextKey; } })); Object.defineProperty(exports, "ROOT_CONTEXT", ({ enumerable: true, get: function () { return context_1.ROOT_CONTEXT; } })); // Diag APIs var consoleLogger_1 = __nccwpck_require__(3041); Object.defineProperty(exports, "DiagConsoleLogger", ({ enumerable: true, get: function () { return consoleLogger_1.DiagConsoleLogger; } })); var types_1 = __nccwpck_require__(78077); Object.defineProperty(exports, "DiagLogLevel", ({ enumerable: true, get: function () { return types_1.DiagLogLevel; } })); // Metrics APIs var NoopMeter_1 = __nccwpck_require__(4837); Object.defineProperty(exports, "createNoopMeter", ({ enumerable: true, get: function () { return NoopMeter_1.createNoopMeter; } })); var Metric_1 = __nccwpck_require__(89999); Object.defineProperty(exports, "ValueType", ({ enumerable: true, get: function () { return Metric_1.ValueType; } })); // Propagation APIs var TextMapPropagator_1 = __nccwpck_require__(80865); Object.defineProperty(exports, "defaultTextMapGetter", ({ enumerable: true, get: function () { return TextMapPropagator_1.defaultTextMapGetter; } })); Object.defineProperty(exports, "defaultTextMapSetter", ({ enumerable: true, get: function () { return TextMapPropagator_1.defaultTextMapSetter; } })); var ProxyTracer_1 = __nccwpck_require__(43503); Object.defineProperty(exports, "ProxyTracer", ({ enumerable: true, get: function () { return ProxyTracer_1.ProxyTracer; } })); var ProxyTracerProvider_1 = __nccwpck_require__(2285); Object.defineProperty(exports, "ProxyTracerProvider", ({ enumerable: true, get: function () { return ProxyTracerProvider_1.ProxyTracerProvider; } })); var SamplingResult_1 = __nccwpck_require__(33209); Object.defineProperty(exports, "SamplingDecision", ({ enumerable: true, get: function () { return SamplingResult_1.SamplingDecision; } })); var span_kind_1 = __nccwpck_require__(31424); Object.defineProperty(exports, "SpanKind", ({ enumerable: true, get: function () { return span_kind_1.SpanKind; } })); var status_1 = __nccwpck_require__(48845); Object.defineProperty(exports, "SpanStatusCode", ({ enumerable: true, get: function () { return status_1.SpanStatusCode; } })); var trace_flags_1 = __nccwpck_require__(26905); Object.defineProperty(exports, "TraceFlags", ({ enumerable: true, get: function () { return trace_flags_1.TraceFlags; } })); var utils_2 = __nccwpck_require__(32615); Object.defineProperty(exports, "createTraceState", ({ enumerable: true, get: function () { return utils_2.createTraceState; } })); var spancontext_utils_1 = __nccwpck_require__(49745); Object.defineProperty(exports, "isSpanContextValid", ({ enumerable: true, get: function () { return spancontext_utils_1.isSpanContextValid; } })); Object.defineProperty(exports, "isValidTraceId", ({ enumerable: true, get: function () { return spancontext_utils_1.isValidTraceId; } })); Object.defineProperty(exports, "isValidSpanId", ({ enumerable: true, get: function () { return spancontext_utils_1.isValidSpanId; } })); var invalid_span_constants_1 = __nccwpck_require__(91760); Object.defineProperty(exports, "INVALID_SPANID", ({ enumerable: true, get: function () { return invalid_span_constants_1.INVALID_SPANID; } })); Object.defineProperty(exports, "INVALID_TRACEID", ({ enumerable: true, get: function () { return invalid_span_constants_1.INVALID_TRACEID; } })); Object.defineProperty(exports, "INVALID_SPAN_CONTEXT", ({ enumerable: true, get: function () { return invalid_span_constants_1.INVALID_SPAN_CONTEXT; } })); // Split module-level variable definition into separate files to allow // tree-shaking on each api instance. const context_api_1 = __nccwpck_require__(7393); Object.defineProperty(exports, "context", ({ enumerable: true, get: function () { return context_api_1.context; } })); const diag_api_1 = __nccwpck_require__(39721); Object.defineProperty(exports, "diag", ({ enumerable: true, get: function () { return diag_api_1.diag; } })); const metrics_api_1 = __nccwpck_require__(72601); Object.defineProperty(exports, "metrics", ({ enumerable: true, get: function () { return metrics_api_1.metrics; } })); const propagation_api_1 = __nccwpck_require__(17591); Object.defineProperty(exports, "propagation", ({ enumerable: true, get: function () { return propagation_api_1.propagation; } })); const trace_api_1 = __nccwpck_require__(98989); Object.defineProperty(exports, "trace", ({ enumerable: true, get: function () { return trace_api_1.trace; } })); // Default export. exports["default"] = { context: context_api_1.context, diag: diag_api_1.diag, metrics: metrics_api_1.metrics, propagation: propagation_api_1.propagation, trace: trace_api_1.trace, }; //# sourceMappingURL=index.js.map /***/ }), /***/ 85135: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.unregisterGlobal = exports.getGlobal = exports.registerGlobal = void 0; const platform_1 = __nccwpck_require__(99957); const version_1 = __nccwpck_require__(98996); const semver_1 = __nccwpck_require__(81522); const major = version_1.VERSION.split('.')[0]; const GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for(`opentelemetry.js.api.${major}`); const _global = platform_1._globalThis; function registerGlobal(type, instance, diag, allowOverride = false) { var _a; const api = (_global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a !== void 0 ? _a : { version: version_1.VERSION, }); if (!allowOverride && api[type]) { // already registered an API of this type const err = new Error(`@opentelemetry/api: Attempted duplicate registration of API: ${type}`); diag.error(err.stack || err.message); return false; } if (api.version !== version_1.VERSION) { // All registered APIs must be of the same version exactly const err = new Error(`@opentelemetry/api: Registration of version v${api.version} for ${type} does not match previously registered API v${version_1.VERSION}`); diag.error(err.stack || err.message); return false; } api[type] = instance; diag.debug(`@opentelemetry/api: Registered a global for ${type} v${version_1.VERSION}.`); return true; } exports.registerGlobal = registerGlobal; function getGlobal(type) { var _a, _b; const globalVersion = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a === void 0 ? void 0 : _a.version; if (!globalVersion || !(0, semver_1.isCompatible)(globalVersion)) { return; } return (_b = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b === void 0 ? void 0 : _b[type]; } exports.getGlobal = getGlobal; function unregisterGlobal(type, diag) { diag.debug(`@opentelemetry/api: Unregistering a global for ${type} v${version_1.VERSION}.`); const api = _global[GLOBAL_OPENTELEMETRY_API_KEY]; if (api) { delete api[type]; } } exports.unregisterGlobal = unregisterGlobal; //# sourceMappingURL=global-utils.js.map /***/ }), /***/ 81522: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isCompatible = exports._makeCompatibilityCheck = void 0; const version_1 = __nccwpck_require__(98996); const re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/; /** * Create a function to test an API version to see if it is compatible with the provided ownVersion. * * The returned function has the following semantics: * - Exact match is always compatible * - Major versions must match exactly * - 1.x package cannot use global 2.x package * - 2.x package cannot use global 1.x package * - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API * - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects * - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3 * - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor * - Patch and build tag differences are not considered at this time * * @param ownVersion version which should be checked against */ function _makeCompatibilityCheck(ownVersion) { const acceptedVersions = new Set([ownVersion]); const rejectedVersions = new Set(); const myVersionMatch = ownVersion.match(re); if (!myVersionMatch) { // we cannot guarantee compatibility so we always return noop return () => false; } const ownVersionParsed = { major: +myVersionMatch[1], minor: +myVersionMatch[2], patch: +myVersionMatch[3], prerelease: myVersionMatch[4], }; // if ownVersion has a prerelease tag, versions must match exactly if (ownVersionParsed.prerelease != null) { return function isExactmatch(globalVersion) { return globalVersion === ownVersion; }; } function _reject(v) { rejectedVersions.add(v); return false; } function _accept(v) { acceptedVersions.add(v); return true; } return function isCompatible(globalVersion) { if (acceptedVersions.has(globalVersion)) { return true; } if (rejectedVersions.has(globalVersion)) { return false; } const globalVersionMatch = globalVersion.match(re); if (!globalVersionMatch) { // cannot parse other version // we cannot guarantee compatibility so we always noop return _reject(globalVersion); } const globalVersionParsed = { major: +globalVersionMatch[1], minor: +globalVersionMatch[2], patch: +globalVersionMatch[3], prerelease: globalVersionMatch[4], }; // if globalVersion has a prerelease tag, versions must match exactly if (globalVersionParsed.prerelease != null) { return _reject(globalVersion); } // major versions must match if (ownVersionParsed.major !== globalVersionParsed.major) { return _reject(globalVersion); } if (ownVersionParsed.major === 0) { if (ownVersionParsed.minor === globalVersionParsed.minor && ownVersionParsed.patch <= globalVersionParsed.patch) { return _accept(globalVersion); } return _reject(globalVersion); } if (ownVersionParsed.minor <= globalVersionParsed.minor) { return _accept(globalVersion); } return _reject(globalVersion); }; } exports._makeCompatibilityCheck = _makeCompatibilityCheck; /** * Test an API version to see if it is compatible with this API. * * - Exact match is always compatible * - Major versions must match exactly * - 1.x package cannot use global 2.x package * - 2.x package cannot use global 1.x package * - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API * - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects * - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3 * - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor * - Patch and build tag differences are not considered at this time * * @param version version of the API requesting an instance of the global API */ exports.isCompatible = _makeCompatibilityCheck(version_1.VERSION); //# sourceMappingURL=semver.js.map /***/ }), /***/ 72601: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.metrics = void 0; // Split module-level variable definition into separate files to allow // tree-shaking on each api instance. const metrics_1 = __nccwpck_require__(17696); /** Entrypoint for metrics API */ exports.metrics = metrics_1.MetricsAPI.getInstance(); //# sourceMappingURL=metrics-api.js.map /***/ }), /***/ 89999: /***/ ((__unused_webpack_module, exports) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ValueType = void 0; /** The Type of value. It describes how the data is reported. */ var ValueType; (function (ValueType) { ValueType[ValueType["INT"] = 0] = "INT"; ValueType[ValueType["DOUBLE"] = 1] = "DOUBLE"; })(ValueType = exports.ValueType || (exports.ValueType = {})); //# sourceMappingURL=Metric.js.map /***/ }), /***/ 4837: /***/ ((__unused_webpack_module, exports) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createNoopMeter = exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC = exports.NOOP_OBSERVABLE_GAUGE_METRIC = exports.NOOP_OBSERVABLE_COUNTER_METRIC = exports.NOOP_UP_DOWN_COUNTER_METRIC = exports.NOOP_HISTOGRAM_METRIC = exports.NOOP_COUNTER_METRIC = exports.NOOP_METER = exports.NoopObservableUpDownCounterMetric = exports.NoopObservableGaugeMetric = exports.NoopObservableCounterMetric = exports.NoopObservableMetric = exports.NoopHistogramMetric = exports.NoopUpDownCounterMetric = exports.NoopCounterMetric = exports.NoopMetric = exports.NoopMeter = void 0; /** * NoopMeter is a noop implementation of the {@link Meter} interface. It reuses * constant NoopMetrics for all of its methods. */ class NoopMeter { constructor() { } /** * @see {@link Meter.createHistogram} */ createHistogram(_name, _options) { return exports.NOOP_HISTOGRAM_METRIC; } /** * @see {@link Meter.createCounter} */ createCounter(_name, _options) { return exports.NOOP_COUNTER_METRIC; } /** * @see {@link Meter.createUpDownCounter} */ createUpDownCounter(_name, _options) { return exports.NOOP_UP_DOWN_COUNTER_METRIC; } /** * @see {@link Meter.createObservableGauge} */ createObservableGauge(_name, _options) { return exports.NOOP_OBSERVABLE_GAUGE_METRIC; } /** * @see {@link Meter.createObservableCounter} */ createObservableCounter(_name, _options) { return exports.NOOP_OBSERVABLE_COUNTER_METRIC; } /** * @see {@link Meter.createObservableUpDownCounter} */ createObservableUpDownCounter(_name, _options) { return exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC; } /** * @see {@link Meter.addBatchObservableCallback} */ addBatchObservableCallback(_callback, _observables) { } /** * @see {@link Meter.removeBatchObservableCallback} */ removeBatchObservableCallback(_callback) { } } exports.NoopMeter = NoopMeter; class NoopMetric { } exports.NoopMetric = NoopMetric; class NoopCounterMetric extends NoopMetric { add(_value, _attributes) { } } exports.NoopCounterMetric = NoopCounterMetric; class NoopUpDownCounterMetric extends NoopMetric { add(_value, _attributes) { } } exports.NoopUpDownCounterMetric = NoopUpDownCounterMetric; class NoopHistogramMetric extends NoopMetric { record(_value, _attributes) { } } exports.NoopHistogramMetric = NoopHistogramMetric; class NoopObservableMetric { addCallback(_callback) { } removeCallback(_callback) { } } exports.NoopObservableMetric = NoopObservableMetric; class NoopObservableCounterMetric extends NoopObservableMetric { } exports.NoopObservableCounterMetric = NoopObservableCounterMetric; class NoopObservableGaugeMetric extends NoopObservableMetric { } exports.NoopObservableGaugeMetric = NoopObservableGaugeMetric; class NoopObservableUpDownCounterMetric extends NoopObservableMetric { } exports.NoopObservableUpDownCounterMetric = NoopObservableUpDownCounterMetric; exports.NOOP_METER = new NoopMeter(); // Synchronous instruments exports.NOOP_COUNTER_METRIC = new NoopCounterMetric(); exports.NOOP_HISTOGRAM_METRIC = new NoopHistogramMetric(); exports.NOOP_UP_DOWN_COUNTER_METRIC = new NoopUpDownCounterMetric(); // Asynchronous instruments exports.NOOP_OBSERVABLE_COUNTER_METRIC = new NoopObservableCounterMetric(); exports.NOOP_OBSERVABLE_GAUGE_METRIC = new NoopObservableGaugeMetric(); exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC = new NoopObservableUpDownCounterMetric(); /** * Create a no-op Meter */ function createNoopMeter() { return exports.NOOP_METER; } exports.createNoopMeter = createNoopMeter; //# sourceMappingURL=NoopMeter.js.map /***/ }), /***/ 72647: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NOOP_METER_PROVIDER = exports.NoopMeterProvider = void 0; const NoopMeter_1 = __nccwpck_require__(4837); /** * An implementation of the {@link MeterProvider} which returns an impotent Meter * for all calls to `getMeter` */ class NoopMeterProvider { getMeter(_name, _version, _options) { return NoopMeter_1.NOOP_METER; } } exports.NoopMeterProvider = NoopMeterProvider; exports.NOOP_METER_PROVIDER = new NoopMeterProvider(); //# sourceMappingURL=NoopMeterProvider.js.map /***/ }), /***/ 99957: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __exportStar = (this && this.__exportStar) || function(m, exports) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); }; Object.defineProperty(exports, "__esModule", ({ value: true })); __exportStar(__nccwpck_require__(87200), exports); //# sourceMappingURL=index.js.map /***/ }), /***/ 89406: /***/ ((__unused_webpack_module, exports) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports._globalThis = void 0; /** only globals that common to node and browsers are allowed */ // eslint-disable-next-line node/no-unsupported-features/es-builtins exports._globalThis = typeof globalThis === 'object' ? globalThis : global; //# sourceMappingURL=globalThis.js.map /***/ }), /***/ 87200: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __exportStar = (this && this.__exportStar) || function(m, exports) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); }; Object.defineProperty(exports, "__esModule", ({ value: true })); __exportStar(__nccwpck_require__(89406), exports); //# sourceMappingURL=index.js.map /***/ }), /***/ 17591: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.propagation = void 0; // Split module-level variable definition into separate files to allow // tree-shaking on each api instance. const propagation_1 = __nccwpck_require__(89909); /** Entrypoint for propagation API */ exports.propagation = propagation_1.PropagationAPI.getInstance(); //# sourceMappingURL=propagation-api.js.map /***/ }), /***/ 72368: /***/ ((__unused_webpack_module, exports) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NoopTextMapPropagator = void 0; /** * No-op implementations of {@link TextMapPropagator}. */ class NoopTextMapPropagator { /** Noop inject function does nothing */ inject(_context, _carrier) { } /** Noop extract function does nothing and returns the input context */ extract(context, _carrier) { return context; } fields() { return []; } } exports.NoopTextMapPropagator = NoopTextMapPropagator; //# sourceMappingURL=NoopTextMapPropagator.js.map /***/ }), /***/ 80865: /***/ ((__unused_webpack_module, exports) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.defaultTextMapSetter = exports.defaultTextMapGetter = void 0; exports.defaultTextMapGetter = { get(carrier, key) { if (carrier == null) { return undefined; } return carrier[key]; }, keys(carrier) { if (carrier == null) { return []; } return Object.keys(carrier); }, }; exports.defaultTextMapSetter = { set(carrier, key, value) { if (carrier == null) { return; } carrier[key] = value; }, }; //# sourceMappingURL=TextMapPropagator.js.map /***/ }), /***/ 98989: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.trace = void 0; // Split module-level variable definition into separate files to allow // tree-shaking on each api instance. const trace_1 = __nccwpck_require__(81539); /** Entrypoint for trace API */ exports.trace = trace_1.TraceAPI.getInstance(); //# sourceMappingURL=trace-api.js.map /***/ }), /***/ 81462: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NonRecordingSpan = void 0; const invalid_span_constants_1 = __nccwpck_require__(91760); /** * The NonRecordingSpan is the default {@link Span} that is used when no Span * implementation is available. All operations are no-op including context * propagation. */ class NonRecordingSpan { constructor(_spanContext = invalid_span_constants_1.INVALID_SPAN_CONTEXT) { this._spanContext = _spanContext; } // Returns a SpanContext. spanContext() { return this._spanContext; } // By default does nothing setAttribute(_key, _value) { return this; } // By default does nothing setAttributes(_attributes) { return this; } // By default does nothing addEvent(_name, _attributes) { return this; } // By default does nothing setStatus(_status) { return this; } // By default does nothing updateName(_name) { return this; } // By default does nothing end(_endTime) { } // isRecording always returns false for NonRecordingSpan. isRecording() { return false; } // By default does nothing recordException(_exception, _time) { } } exports.NonRecordingSpan = NonRecordingSpan; //# sourceMappingURL=NonRecordingSpan.js.map /***/ }), /***/ 17606: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NoopTracer = void 0; const context_1 = __nccwpck_require__(57171); const context_utils_1 = __nccwpck_require__(23326); const NonRecordingSpan_1 = __nccwpck_require__(81462); const spancontext_utils_1 = __nccwpck_require__(49745); const contextApi = context_1.ContextAPI.getInstance(); /** * No-op implementations of {@link Tracer}. */ class NoopTracer { // startSpan starts a noop span. startSpan(name, options, context = contextApi.active()) { const root = Boolean(options === null || options === void 0 ? void 0 : options.root); if (root) { return new NonRecordingSpan_1.NonRecordingSpan(); } const parentFromContext = context && (0, context_utils_1.getSpanContext)(context); if (isSpanContext(parentFromContext) && (0, spancontext_utils_1.isSpanContextValid)(parentFromContext)) { return new NonRecordingSpan_1.NonRecordingSpan(parentFromContext); } else { return new NonRecordingSpan_1.NonRecordingSpan(); } } startActiveSpan(name, arg2, arg3, arg4) { let opts; let ctx; let fn; if (arguments.length < 2) { return; } else if (arguments.length === 2) { fn = arg2; } else if (arguments.length === 3) { opts = arg2; fn = arg3; } else { opts = arg2; ctx = arg3; fn = arg4; } const parentContext = ctx !== null && ctx !== void 0 ? ctx : contextApi.active(); const span = this.startSpan(name, opts, parentContext); const contextWithSpanSet = (0, context_utils_1.setSpan)(parentContext, span); return contextApi.with(contextWithSpanSet, fn, undefined, span); } } exports.NoopTracer = NoopTracer; function isSpanContext(spanContext) { return (typeof spanContext === 'object' && typeof spanContext['spanId'] === 'string' && typeof spanContext['traceId'] === 'string' && typeof spanContext['traceFlags'] === 'number'); } //# sourceMappingURL=NoopTracer.js.map /***/ }), /***/ 23259: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.NoopTracerProvider = void 0; const NoopTracer_1 = __nccwpck_require__(17606); /** * An implementation of the {@link TracerProvider} which returns an impotent * Tracer for all calls to `getTracer`. * * All operations are no-op. */ class NoopTracerProvider { getTracer(_name, _version, _options) { return new NoopTracer_1.NoopTracer(); } } exports.NoopTracerProvider = NoopTracerProvider; //# sourceMappingURL=NoopTracerProvider.js.map /***/ }), /***/ 43503: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ProxyTracer = void 0; const NoopTracer_1 = __nccwpck_require__(17606); const NOOP_TRACER = new NoopTracer_1.NoopTracer(); /** * Proxy tracer provided by the proxy tracer provider */ class ProxyTracer { constructor(_provider, name, version, options) { this._provider = _provider; this.name = name; this.version = version; this.options = options; } startSpan(name, options, context) { return this._getTracer().startSpan(name, options, context); } startActiveSpan(_name, _options, _context, _fn) { const tracer = this._getTracer(); return Reflect.apply(tracer.startActiveSpan, tracer, arguments); } /** * Try to get a tracer from the proxy tracer provider. * If the proxy tracer provider has no delegate, return a noop tracer. */ _getTracer() { if (this._delegate) { return this._delegate; } const tracer = this._provider.getDelegateTracer(this.name, this.version, this.options); if (!tracer) { return NOOP_TRACER; } this._delegate = tracer; return this._delegate; } } exports.ProxyTracer = ProxyTracer; //# sourceMappingURL=ProxyTracer.js.map /***/ }), /***/ 2285: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ProxyTracerProvider = void 0; const ProxyTracer_1 = __nccwpck_require__(43503); const NoopTracerProvider_1 = __nccwpck_require__(23259); const NOOP_TRACER_PROVIDER = new NoopTracerProvider_1.NoopTracerProvider(); /** * Tracer provider which provides {@link ProxyTracer}s. * * Before a delegate is set, tracers provided are NoOp. * When a delegate is set, traces are provided from the delegate. * When a delegate is set after tracers have already been provided, * all tracers already provided will use the provided delegate implementation. */ class ProxyTracerProvider { /** * Get a {@link ProxyTracer} */ getTracer(name, version, options) { var _a; return ((_a = this.getDelegateTracer(name, version, options)) !== null && _a !== void 0 ? _a : new ProxyTracer_1.ProxyTracer(this, name, version, options)); } getDelegate() { var _a; return (_a = this._delegate) !== null && _a !== void 0 ? _a : NOOP_TRACER_PROVIDER; } /** * Set the delegate tracer provider */ setDelegate(delegate) { this._delegate = delegate; } getDelegateTracer(name, version, options) { var _a; return (_a = this._delegate) === null || _a === void 0 ? void 0 : _a.getTracer(name, version, options); } } exports.ProxyTracerProvider = ProxyTracerProvider; //# sourceMappingURL=ProxyTracerProvider.js.map /***/ }), /***/ 33209: /***/ ((__unused_webpack_module, exports) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SamplingDecision = void 0; /** * @deprecated use the one declared in @opentelemetry/sdk-trace-base instead. * A sampling decision that determines how a {@link Span} will be recorded * and collected. */ var SamplingDecision; (function (SamplingDecision) { /** * `Span.isRecording() === false`, span will not be recorded and all events * and attributes will be dropped. */ SamplingDecision[SamplingDecision["NOT_RECORD"] = 0] = "NOT_RECORD"; /** * `Span.isRecording() === true`, but `Sampled` flag in {@link TraceFlags} * MUST NOT be set. */ SamplingDecision[SamplingDecision["RECORD"] = 1] = "RECORD"; /** * `Span.isRecording() === true` AND `Sampled` flag in {@link TraceFlags} * MUST be set. */ SamplingDecision[SamplingDecision["RECORD_AND_SAMPLED"] = 2] = "RECORD_AND_SAMPLED"; })(SamplingDecision = exports.SamplingDecision || (exports.SamplingDecision = {})); //# sourceMappingURL=SamplingResult.js.map /***/ }), /***/ 23326: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getSpanContext = exports.setSpanContext = exports.deleteSpan = exports.setSpan = exports.getActiveSpan = exports.getSpan = void 0; const context_1 = __nccwpck_require__(78242); const NonRecordingSpan_1 = __nccwpck_require__(81462); const context_2 = __nccwpck_require__(57171); /** * span key */ const SPAN_KEY = (0, context_1.createContextKey)('OpenTelemetry Context Key SPAN'); /** * Return the span if one exists * * @param context context to get span from */ function getSpan(context) { return context.getValue(SPAN_KEY) || undefined; } exports.getSpan = getSpan; /** * Gets the span from the current context, if one exists. */ function getActiveSpan() { return getSpan(context_2.ContextAPI.getInstance().active()); } exports.getActiveSpan = getActiveSpan; /** * Set the span on a context * * @param context context to use as parent * @param span span to set active */ function setSpan(context, span) { return context.setValue(SPAN_KEY, span); } exports.setSpan = setSpan; /** * Remove current span stored in the context * * @param context context to delete span from */ function deleteSpan(context) { return context.deleteValue(SPAN_KEY); } exports.deleteSpan = deleteSpan; /** * Wrap span context in a NoopSpan and set as span in a new * context * * @param context context to set active span on * @param spanContext span context to be wrapped */ function setSpanContext(context, spanContext) { return setSpan(context, new NonRecordingSpan_1.NonRecordingSpan(spanContext)); } exports.setSpanContext = setSpanContext; /** * Get the span context of the span if it exists. * * @param context context to get values from */ function getSpanContext(context) { var _a; return (_a = getSpan(context)) === null || _a === void 0 ? void 0 : _a.spanContext(); } exports.getSpanContext = getSpanContext; //# sourceMappingURL=context-utils.js.map /***/ }), /***/ 62110: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.TraceStateImpl = void 0; const tracestate_validators_1 = __nccwpck_require__(54864); const MAX_TRACE_STATE_ITEMS = 32; const MAX_TRACE_STATE_LEN = 512; const LIST_MEMBERS_SEPARATOR = ','; const LIST_MEMBER_KEY_VALUE_SPLITTER = '='; /** * TraceState must be a class and not a simple object type because of the spec * requirement (https://www.w3.org/TR/trace-context/#tracestate-field). * * Here is the list of allowed mutations: * - New key-value pair should be added into the beginning of the list * - The value of any key can be updated. Modified keys MUST be moved to the * beginning of the list. */ class TraceStateImpl { constructor(rawTraceState) { this._internalState = new Map(); if (rawTraceState) this._parse(rawTraceState); } set(key, value) { // TODO: Benchmark the different approaches(map vs list) and // use the faster one. const traceState = this._clone(); if (traceState._internalState.has(key)) { traceState._internalState.delete(key); } traceState._internalState.set(key, value); return traceState; } unset(key) { const traceState = this._clone(); traceState._internalState.delete(key); return traceState; } get(key) { return this._internalState.get(key); } serialize() { return this._keys() .reduce((agg, key) => { agg.push(key + LIST_MEMBER_KEY_VALUE_SPLITTER + this.get(key)); return agg; }, []) .join(LIST_MEMBERS_SEPARATOR); } _parse(rawTraceState) { if (rawTraceState.length > MAX_TRACE_STATE_LEN) return; this._internalState = rawTraceState .split(LIST_MEMBERS_SEPARATOR) .reverse() // Store in reverse so new keys (.set(...)) will be placed at the beginning .reduce((agg, part) => { const listMember = part.trim(); // Optional Whitespace (OWS) handling const i = listMember.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER); if (i !== -1) { const key = listMember.slice(0, i); const value = listMember.slice(i + 1, part.length); if ((0, tracestate_validators_1.validateKey)(key) && (0, tracestate_validators_1.validateValue)(value)) { agg.set(key, value); } else { // TODO: Consider to add warning log } } return agg; }, new Map()); // Because of the reverse() requirement, trunc must be done after map is created if (this._internalState.size > MAX_TRACE_STATE_ITEMS) { this._internalState = new Map(Array.from(this._internalState.entries()) .reverse() // Use reverse same as original tracestate parse chain .slice(0, MAX_TRACE_STATE_ITEMS)); } } _keys() { return Array.from(this._internalState.keys()).reverse(); } _clone() { const traceState = new TraceStateImpl(); traceState._internalState = new Map(this._internalState); return traceState; } } exports.TraceStateImpl = TraceStateImpl; //# sourceMappingURL=tracestate-impl.js.map /***/ }), /***/ 54864: /***/ ((__unused_webpack_module, exports) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.validateValue = exports.validateKey = void 0; const VALID_KEY_CHAR_RANGE = '[_0-9a-z-*/]'; const VALID_KEY = `[a-z]${VALID_KEY_CHAR_RANGE}{0,255}`; const VALID_VENDOR_KEY = `[a-z0-9]${VALID_KEY_CHAR_RANGE}{0,240}@[a-z]${VALID_KEY_CHAR_RANGE}{0,13}`; const VALID_KEY_REGEX = new RegExp(`^(?:${VALID_KEY}|${VALID_VENDOR_KEY})$`); const VALID_VALUE_BASE_REGEX = /^[ -~]{0,255}[!-~]$/; const INVALID_VALUE_COMMA_EQUAL_REGEX = /,|=/; /** * Key is opaque string up to 256 characters printable. It MUST begin with a * lowercase letter, and can only contain lowercase letters a-z, digits 0-9, * underscores _, dashes -, asterisks *, and forward slashes /. * For multi-tenant vendor scenarios, an at sign (@) can be used to prefix the * vendor name. Vendors SHOULD set the tenant ID at the beginning of the key. * see https://www.w3.org/TR/trace-context/#key */ function validateKey(key) { return VALID_KEY_REGEX.test(key); } exports.validateKey = validateKey; /** * Value is opaque string up to 256 characters printable ASCII RFC0020 * characters (i.e., the range 0x20 to 0x7E) except comma , and =. */ function validateValue(value) { return (VALID_VALUE_BASE_REGEX.test(value) && !INVALID_VALUE_COMMA_EQUAL_REGEX.test(value)); } exports.validateValue = validateValue; //# sourceMappingURL=tracestate-validators.js.map /***/ }), /***/ 32615: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createTraceState = void 0; const tracestate_impl_1 = __nccwpck_require__(62110); function createTraceState(rawTraceState) { return new tracestate_impl_1.TraceStateImpl(rawTraceState); } exports.createTraceState = createTraceState; //# sourceMappingURL=utils.js.map /***/ }), /***/ 91760: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.INVALID_SPAN_CONTEXT = exports.INVALID_TRACEID = exports.INVALID_SPANID = void 0; const trace_flags_1 = __nccwpck_require__(26905); exports.INVALID_SPANID = '0000000000000000'; exports.INVALID_TRACEID = '00000000000000000000000000000000'; exports.INVALID_SPAN_CONTEXT = { traceId: exports.INVALID_TRACEID, spanId: exports.INVALID_SPANID, traceFlags: trace_flags_1.TraceFlags.NONE, }; //# sourceMappingURL=invalid-span-constants.js.map /***/ }), /***/ 31424: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SpanKind = void 0; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var SpanKind; (function (SpanKind) { /** Default value. Indicates that the span is used internally. */ SpanKind[SpanKind["INTERNAL"] = 0] = "INTERNAL"; /** * Indicates that the span covers server-side handling of an RPC or other * remote request. */ SpanKind[SpanKind["SERVER"] = 1] = "SERVER"; /** * Indicates that the span covers the client-side wrapper around an RPC or * other remote request. */ SpanKind[SpanKind["CLIENT"] = 2] = "CLIENT"; /** * Indicates that the span describes producer sending a message to a * broker. Unlike client and server, there is no direct critical path latency * relationship between producer and consumer spans. */ SpanKind[SpanKind["PRODUCER"] = 3] = "PRODUCER"; /** * Indicates that the span describes consumer receiving a message from a * broker. Unlike client and server, there is no direct critical path latency * relationship between producer and consumer spans. */ SpanKind[SpanKind["CONSUMER"] = 4] = "CONSUMER"; })(SpanKind = exports.SpanKind || (exports.SpanKind = {})); //# sourceMappingURL=span_kind.js.map /***/ }), /***/ 49745: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.wrapSpanContext = exports.isSpanContextValid = exports.isValidSpanId = exports.isValidTraceId = void 0; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ const invalid_span_constants_1 = __nccwpck_require__(91760); const NonRecordingSpan_1 = __nccwpck_require__(81462); const VALID_TRACEID_REGEX = /^([0-9a-f]{32})$/i; const VALID_SPANID_REGEX = /^[0-9a-f]{16}$/i; function isValidTraceId(traceId) { return VALID_TRACEID_REGEX.test(traceId) && traceId !== invalid_span_constants_1.INVALID_TRACEID; } exports.isValidTraceId = isValidTraceId; function isValidSpanId(spanId) { return VALID_SPANID_REGEX.test(spanId) && spanId !== invalid_span_constants_1.INVALID_SPANID; } exports.isValidSpanId = isValidSpanId; /** * Returns true if this {@link SpanContext} is valid. * @return true if this {@link SpanContext} is valid. */ function isSpanContextValid(spanContext) { return (isValidTraceId(spanContext.traceId) && isValidSpanId(spanContext.spanId)); } exports.isSpanContextValid = isSpanContextValid; /** * Wrap the given {@link SpanContext} in a new non-recording {@link Span} * * @param spanContext span context to be wrapped * @returns a new non-recording {@link Span} with the provided context */ function wrapSpanContext(spanContext) { return new NonRecordingSpan_1.NonRecordingSpan(spanContext); } exports.wrapSpanContext = wrapSpanContext; //# sourceMappingURL=spancontext-utils.js.map /***/ }), /***/ 48845: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SpanStatusCode = void 0; /** * An enumeration of status codes. */ var SpanStatusCode; (function (SpanStatusCode) { /** * The default status. */ SpanStatusCode[SpanStatusCode["UNSET"] = 0] = "UNSET"; /** * The operation has been validated by an Application developer or * Operator to have completed successfully. */ SpanStatusCode[SpanStatusCode["OK"] = 1] = "OK"; /** * The operation contains an error. */ SpanStatusCode[SpanStatusCode["ERROR"] = 2] = "ERROR"; })(SpanStatusCode = exports.SpanStatusCode || (exports.SpanStatusCode = {})); //# sourceMappingURL=status.js.map /***/ }), /***/ 26905: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.TraceFlags = void 0; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var TraceFlags; (function (TraceFlags) { /** Represents no flag set. */ TraceFlags[TraceFlags["NONE"] = 0] = "NONE"; /** Bit to represent whether trace is sampled in trace flags. */ TraceFlags[TraceFlags["SAMPLED"] = 1] = "SAMPLED"; })(TraceFlags = exports.TraceFlags || (exports.TraceFlags = {})); //# sourceMappingURL=trace_flags.js.map /***/ }), /***/ 98996: /***/ ((__unused_webpack_module, exports) => { "use strict"; /* * Copyright The OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.VERSION = void 0; // this is autogenerated file, see scripts/version-update.js exports.VERSION = '1.4.1'; //# sourceMappingURL=version.js.map /***/ }), /***/ 39436: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { define } = __nccwpck_require__(93998) const base = __nccwpck_require__(33318) const constants = __nccwpck_require__(90998) const decoders = __nccwpck_require__(5017) const encoders = __nccwpck_require__(2246) module.exports = { base, constants, decoders, define, encoders } /***/ }), /***/ 93998: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { inherits } = __nccwpck_require__(73837) const encoders = __nccwpck_require__(2246) const decoders = __nccwpck_require__(5017) module.exports.define = function define (name, body) { return new Entity(name, body) } function Entity (name, body) { this.name = name this.body = body this.decoders = {} this.encoders = {} } Entity.prototype._createNamed = function createNamed (Base) { const name = this.name function Generated (entity) { this._initNamed(entity, name) } inherits(Generated, Base) Generated.prototype._initNamed = function _initNamed (entity, name) { Base.call(this, entity, name) } return new Generated(this) } Entity.prototype._getDecoder = function _getDecoder (enc) { enc = enc || 'der' // Lazily create decoder if (!Object.prototype.hasOwnProperty.call(this.decoders, enc)) { this.decoders[enc] = this._createNamed(decoders[enc]) } return this.decoders[enc] } Entity.prototype.decode = function decode (data, enc, options) { return this._getDecoder(enc).decode(data, options) } Entity.prototype._getEncoder = function _getEncoder (enc) { enc = enc || 'der' // Lazily create encoder if (!Object.prototype.hasOwnProperty.call(this.encoders, enc)) { this.encoders[enc] = this._createNamed(encoders[enc]) } return this.encoders[enc] } Entity.prototype.encode = function encode (data, enc, /* internal */ reporter) { return this._getEncoder(enc).encode(data, reporter) } /***/ }), /***/ 28424: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { inherits } = __nccwpck_require__(73837) const { Reporter } = __nccwpck_require__(93026) function DecoderBuffer (base, options) { Reporter.call(this, options) if (!Buffer.isBuffer(base)) { this.error('Input not Buffer') return } this.base = base this.offset = 0 this.length = base.length } inherits(DecoderBuffer, Reporter) DecoderBuffer.isDecoderBuffer = function isDecoderBuffer (data) { if (data instanceof DecoderBuffer) { return true } // Or accept compatible API const isCompatible = typeof data === 'object' && Buffer.isBuffer(data.base) && data.constructor.name === 'DecoderBuffer' && typeof data.offset === 'number' && typeof data.length === 'number' && typeof data.save === 'function' && typeof data.restore === 'function' && typeof data.isEmpty === 'function' && typeof data.readUInt8 === 'function' && typeof data.skip === 'function' && typeof data.raw === 'function' return isCompatible } DecoderBuffer.prototype.save = function save () { return { offset: this.offset, reporter: Reporter.prototype.save.call(this) } } DecoderBuffer.prototype.restore = function restore (save) { // Return skipped data const res = new DecoderBuffer(this.base) res.offset = save.offset res.length = this.offset this.offset = save.offset Reporter.prototype.restore.call(this, save.reporter) return res } DecoderBuffer.prototype.isEmpty = function isEmpty () { return this.offset === this.length } DecoderBuffer.prototype.readUInt8 = function readUInt8 (fail) { if (this.offset + 1 <= this.length) { return this.base.readUInt8(this.offset++, true) } else { return this.error(fail || 'DecoderBuffer overrun') } } DecoderBuffer.prototype.skip = function skip (bytes, fail) { if (!(this.offset + bytes <= this.length)) { return this.error(fail || 'DecoderBuffer overrun') } const res = new DecoderBuffer(this.base) // Share reporter state res._reporterState = this._reporterState res.offset = this.offset res.length = this.offset + bytes this.offset += bytes return res } DecoderBuffer.prototype.raw = function raw (save) { return this.base.slice(save ? save.offset : this.offset, this.length) } function EncoderBuffer (value, reporter) { if (Array.isArray(value)) { this.length = 0 this.value = value.map(function (item) { if (!EncoderBuffer.isEncoderBuffer(item)) { item = new EncoderBuffer(item, reporter) } this.length += item.length return item }, this) } else if (typeof value === 'number') { if (!(value >= 0 && value <= 0xff)) { return reporter.error('non-byte EncoderBuffer value') } this.value = value this.length = 1 } else if (typeof value === 'string') { this.value = value this.length = Buffer.byteLength(value) } else if (Buffer.isBuffer(value)) { this.value = value this.length = value.length } else { return reporter.error(`Unsupported type: ${typeof value}`) } } EncoderBuffer.isEncoderBuffer = function isEncoderBuffer (data) { if (data instanceof EncoderBuffer) { return true } // Or accept compatible API const isCompatible = typeof data === 'object' && data.constructor.name === 'EncoderBuffer' && typeof data.length === 'number' && typeof data.join === 'function' return isCompatible } EncoderBuffer.prototype.join = function join (out, offset) { if (!out) { out = Buffer.alloc(this.length) } if (!offset) { offset = 0 } if (this.length === 0) { return out } if (Array.isArray(this.value)) { this.value.forEach(function (item) { item.join(out, offset) offset += item.length }) } else { if (typeof this.value === 'number') { out[offset] = this.value } else if (typeof this.value === 'string') { out.write(this.value, offset) } else if (Buffer.isBuffer(this.value)) { this.value.copy(out, offset) } offset += this.length } return out } module.exports = { DecoderBuffer, EncoderBuffer } /***/ }), /***/ 33318: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { Reporter } = __nccwpck_require__(93026) const { DecoderBuffer, EncoderBuffer } = __nccwpck_require__(28424) const Node = __nccwpck_require__(48674) module.exports = { DecoderBuffer, EncoderBuffer, Node, Reporter } /***/ }), /***/ 48674: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { strict: assert } = __nccwpck_require__(39491) const { Reporter } = __nccwpck_require__(93026) const { DecoderBuffer, EncoderBuffer } = __nccwpck_require__(28424) // Supported tags const tags = [ 'seq', 'seqof', 'set', 'setof', 'objid', 'bool', 'gentime', 'utctime', 'null_', 'enum', 'int', 'objDesc', 'bitstr', 'bmpstr', 'charstr', 'genstr', 'graphstr', 'ia5str', 'iso646str', 'numstr', 'octstr', 'printstr', 't61str', 'unistr', 'utf8str', 'videostr' ] // Public methods list const methods = [ 'key', 'obj', 'use', 'optional', 'explicit', 'implicit', 'def', 'choice', 'any', 'contains' ].concat(tags) // Overrided methods list const overrided = [ '_peekTag', '_decodeTag', '_use', '_decodeStr', '_decodeObjid', '_decodeTime', '_decodeNull', '_decodeInt', '_decodeBool', '_decodeList', '_encodeComposite', '_encodeStr', '_encodeObjid', '_encodeTime', '_encodeNull', '_encodeInt', '_encodeBool' ] function Node (enc, parent, name) { const state = {} this._baseState = state state.name = name state.enc = enc state.parent = parent || null state.children = null // State state.tag = null state.args = null state.reverseArgs = null state.choice = null state.optional = false state.any = false state.obj = false state.use = null state.useDecoder = null state.key = null state.default = null state.explicit = null state.implicit = null state.contains = null // Should create new instance on each method if (!state.parent) { state.children = [] this._wrap() } } const stateProps = [ 'enc', 'parent', 'children', 'tag', 'args', 'reverseArgs', 'choice', 'optional', 'any', 'obj', 'use', 'alteredUse', 'key', 'default', 'explicit', 'implicit', 'contains' ] Node.prototype.clone = function clone () { const state = this._baseState const cstate = {} stateProps.forEach(function (prop) { cstate[prop] = state[prop] }) const res = new this.constructor(cstate.parent) res._baseState = cstate return res } Node.prototype._wrap = function wrap () { const state = this._baseState methods.forEach(function (method) { this[method] = function _wrappedMethod () { const clone = new this.constructor(this) state.children.push(clone) return clone[method].apply(clone, arguments) } }, this) } Node.prototype._init = function init (body) { const state = this._baseState assert(state.parent === null) body.call(this) // Filter children state.children = state.children.filter(function (child) { return child._baseState.parent === this }, this) assert.equal(state.children.length, 1, 'Root node can have only one child') } Node.prototype._useArgs = function useArgs (args) { const state = this._baseState // Filter children and args const children = args.filter(function (arg) { return arg instanceof this.constructor }, this) args = args.filter(function (arg) { return !(arg instanceof this.constructor) }, this) if (children.length !== 0) { assert(state.children === null) state.children = children // Replace parent to maintain backward link children.forEach(function (child) { child._baseState.parent = this }, this) } if (args.length !== 0) { assert(state.args === null) state.args = args state.reverseArgs = args.map(function (arg) { if (typeof arg !== 'object' || arg.constructor !== Object) { return arg } const res = {} Object.keys(arg).forEach(function (key) { if (key == (key | 0)) { key |= 0 } // eslint-disable-line eqeqeq const value = arg[key] res[value] = key }) return res }) } } // // Overrided methods // overrided.forEach(function (method) { Node.prototype[method] = function _overrided () { const state = this._baseState throw new Error(`${method} not implemented for encoding: ${state.enc}`) } }) // // Public methods // tags.forEach(function (tag) { Node.prototype[tag] = function _tagMethod () { const state = this._baseState const args = Array.prototype.slice.call(arguments) assert(state.tag === null) state.tag = tag this._useArgs(args) return this } }) Node.prototype.use = function use (item) { assert(item) const state = this._baseState assert(state.use === null) state.use = item return this } Node.prototype.optional = function optional () { const state = this._baseState state.optional = true return this } Node.prototype.def = function def (val) { const state = this._baseState assert(state.default === null) state.default = val state.optional = true return this } Node.prototype.explicit = function explicit (num) { const state = this._baseState assert(state.explicit === null && state.implicit === null) state.explicit = num return this } Node.prototype.implicit = function implicit (num) { const state = this._baseState assert(state.explicit === null && state.implicit === null) state.implicit = num return this } Node.prototype.obj = function obj () { const state = this._baseState const args = Array.prototype.slice.call(arguments) state.obj = true if (args.length !== 0) { this._useArgs(args) } return this } Node.prototype.key = function key (newKey) { const state = this._baseState assert(state.key === null) state.key = newKey return this } Node.prototype.any = function any () { const state = this._baseState state.any = true return this } Node.prototype.choice = function choice (obj) { const state = this._baseState assert(state.choice === null) state.choice = obj this._useArgs(Object.keys(obj).map(function (key) { return obj[key] })) return this } Node.prototype.contains = function contains (item) { const state = this._baseState assert(state.use === null) state.contains = item return this } // // Decoding // Node.prototype._decode = function decode (input, options) { const state = this._baseState // Decode root node if (state.parent === null) { return input.wrapResult(state.children[0]._decode(input, options)) } let result = state.default let present = true let prevKey = null if (state.key !== null) { prevKey = input.enterKey(state.key) } // Check if tag is there if (state.optional) { let tag = null if (state.explicit !== null) { tag = state.explicit } else if (state.implicit !== null) { tag = state.implicit } else if (state.tag !== null) { tag = state.tag } if (tag === null && !state.any) { // Trial and Error const save = input.save() try { if (state.choice === null) { this._decodeGeneric(state.tag, input, options) } else { this._decodeChoice(input, options) } present = true } catch (e) { present = false } input.restore(save) } else { present = this._peekTag(input, tag, state.any) if (input.isError(present)) { return present } } } // Push object on stack let prevObj if (state.obj && present) { prevObj = input.enterObject() } if (present) { // Unwrap explicit values if (state.explicit !== null) { const explicit = this._decodeTag(input, state.explicit) if (input.isError(explicit)) { return explicit } input = explicit } const start = input.offset // Unwrap implicit and normal values if (state.use === null && state.choice === null) { let save if (state.any) { save = input.save() } const body = this._decodeTag( input, state.implicit !== null ? state.implicit : state.tag, state.any ) if (input.isError(body)) { return body } if (state.any) { result = input.raw(save) } else { input = body } } if (options && options.track && state.tag !== null) { options.track(input.path(), start, input.length, 'tagged') } if (options && options.track && state.tag !== null) { options.track(input.path(), input.offset, input.length, 'content') } // Select proper method for tag if (state.any) { // no-op } else if (state.choice === null) { result = this._decodeGeneric(state.tag, input, options) } else { result = this._decodeChoice(input, options) } if (input.isError(result)) { return result } // Decode children if (!state.any && state.choice === null && state.children !== null) { state.children.forEach(function decodeChildren (child) { // NOTE: We are ignoring errors here, to let parser continue with other // parts of encoded data child._decode(input, options) }) } // Decode contained/encoded by schema, only in bit or octet strings if (state.contains && (state.tag === 'octstr' || state.tag === 'bitstr')) { const data = new DecoderBuffer(result) result = this._getUse(state.contains, input._reporterState.obj) ._decode(data, options) } } // Pop object if (state.obj && present) { result = input.leaveObject(prevObj) } // Set key if (state.key !== null && (result !== null || present === true)) { input.leaveKey(prevKey, state.key, result) } else if (prevKey !== null) { input.exitKey(prevKey) } return result } Node.prototype._decodeGeneric = function decodeGeneric (tag, input, options) { const state = this._baseState if (tag === 'seq' || tag === 'set') { return null } if (tag === 'seqof' || tag === 'setof') { return this._decodeList(input, tag, state.args[0], options) } else if (/str$/.test(tag)) { return this._decodeStr(input, tag, options) } else if (tag === 'objid' && state.args) { return this._decodeObjid(input, state.args[0], state.args[1], options) } else if (tag === 'objid') { return this._decodeObjid(input, null, null, options) } else if (tag === 'gentime' || tag === 'utctime') { return this._decodeTime(input, tag, options) } else if (tag === 'null_') { return this._decodeNull(input, options) } else if (tag === 'bool') { return this._decodeBool(input, options) } else if (tag === 'objDesc') { return this._decodeStr(input, tag, options) } else if (tag === 'int' || tag === 'enum') { return this._decodeInt(input, state.args && state.args[0], options) } if (state.use !== null) { return this._getUse(state.use, input._reporterState.obj) ._decode(input, options) } else { return input.error(`unknown tag: ${tag}`) } } Node.prototype._getUse = function _getUse (entity, obj) { const state = this._baseState // Create altered use decoder if implicit is set state.useDecoder = this._use(entity, obj) assert(state.useDecoder._baseState.parent === null) state.useDecoder = state.useDecoder._baseState.children[0] if (state.implicit !== state.useDecoder._baseState.implicit) { state.useDecoder = state.useDecoder.clone() state.useDecoder._baseState.implicit = state.implicit } return state.useDecoder } Node.prototype._decodeChoice = function decodeChoice (input, options) { const state = this._baseState let result = null let match = false Object.keys(state.choice).some(function (key) { const save = input.save() const node = state.choice[key] try { const value = node._decode(input, options) if (input.isError(value)) { return false } result = { type: key, value: value } match = true } catch (e) { input.restore(save) return false } return true }, this) if (!match) { return input.error('Choice not matched') } return result } // // Encoding // Node.prototype._createEncoderBuffer = function createEncoderBuffer (data) { return new EncoderBuffer(data, this.reporter) } Node.prototype._encode = function encode (data, reporter, parent) { const state = this._baseState if (state.default !== null && state.default === data) { return } const result = this._encodeValue(data, reporter, parent) if (result === undefined) { return } if (this._skipDefault(result, reporter, parent)) { return } return result } Node.prototype._encodeValue = function encode (data, reporter, parent) { const state = this._baseState // Decode root node if (state.parent === null) { return state.children[0]._encode(data, reporter || new Reporter()) } let result = null // Set reporter to share it with a child class this.reporter = reporter // Check if data is there if (state.optional && data === undefined) { if (state.default !== null) { data = state.default } else { return } } // Encode children first let content = null let primitive = false if (state.any) { // Anything that was given is translated to buffer result = this._createEncoderBuffer(data) } else if (state.choice) { result = this._encodeChoice(data, reporter) } else if (state.contains) { content = this._getUse(state.contains, parent)._encode(data, reporter) primitive = true } else if (state.children) { content = state.children.map(function (child) { if (child._baseState.tag === 'null_') { return child._encode(null, reporter, data) } if (child._baseState.key === null) { return reporter.error('Child should have a key') } const prevKey = reporter.enterKey(child._baseState.key) if (typeof data !== 'object') { return reporter.error('Child expected, but input is not object') } const res = child._encode(data[child._baseState.key], reporter, data) reporter.leaveKey(prevKey) return res }, this).filter(function (child) { return child }) content = this._createEncoderBuffer(content) } else { if (state.tag === 'seqof' || state.tag === 'setof') { if (!(state.args && state.args.length === 1)) { return reporter.error(`Too many args for: ${state.tag}`) } if (!Array.isArray(data)) { return reporter.error('seqof/setof, but data is not Array') } const child = this.clone() child._baseState.implicit = null content = this._createEncoderBuffer(data.map(function (item) { const state = this._baseState return this._getUse(state.args[0], data)._encode(item, reporter) }, child)) } else if (state.use !== null) { result = this._getUse(state.use, parent)._encode(data, reporter) } else { content = this._encodePrimitive(state.tag, data) primitive = true } } // Encode data itself if (!state.any && state.choice === null) { const tag = state.implicit !== null ? state.implicit : state.tag const cls = state.implicit === null ? 'universal' : 'context' if (tag === null) { if (state.use === null) { reporter.error('Tag could be omitted only for .use()') } } else { if (state.use === null) { result = this._encodeComposite(tag, primitive, cls, content) } } } // Wrap in explicit if (state.explicit !== null) { result = this._encodeComposite(state.explicit, false, 'context', result) } return result } Node.prototype._encodeChoice = function encodeChoice (data, reporter) { const state = this._baseState const node = state.choice[data.type] if (!node) { assert( false, `${data.type} not found in ${JSON.stringify(Object.keys(state.choice))}` ) } return node._encode(data.value, reporter) } Node.prototype._encodePrimitive = function encodePrimitive (tag, data) { const state = this._baseState if (/str$/.test(tag)) { return this._encodeStr(data, tag) } else if (tag === 'objid' && state.args) { return this._encodeObjid(data, state.reverseArgs[0], state.args[1]) } else if (tag === 'objid') { return this._encodeObjid(data, null, null) } else if (tag === 'gentime' || tag === 'utctime') { return this._encodeTime(data, tag) } else if (tag === 'null_') { return this._encodeNull() } else if (tag === 'int' || tag === 'enum') { return this._encodeInt(data, state.args && state.reverseArgs[0]) } else if (tag === 'bool') { return this._encodeBool(data) } else if (tag === 'objDesc') { return this._encodeStr(data, tag) } else { throw new Error(`Unsupported tag: ${tag}`) } } Node.prototype._isNumstr = function isNumstr (str) { return /^[0-9 ]*$/.test(str) } Node.prototype._isPrintstr = function isPrintstr (str) { return /^[A-Za-z0-9 '()+,-./:=?]*$/.test(str) } module.exports = Node /***/ }), /***/ 93026: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { const { inherits } = __nccwpck_require__(73837) function Reporter (options) { this._reporterState = { obj: null, path: [], options: options || {}, errors: [] } } Reporter.prototype.isError = function isError (obj) { return obj instanceof ReporterError } Reporter.prototype.save = function save () { const state = this._reporterState return { obj: state.obj, pathLen: state.path.length } } Reporter.prototype.restore = function restore (data) { const state = this._reporterState state.obj = data.obj state.path = state.path.slice(0, data.pathLen) } Reporter.prototype.enterKey = function enterKey (key) { return this._reporterState.path.push(key) } Reporter.prototype.exitKey = function exitKey (index) { const state = this._reporterState state.path = state.path.slice(0, index - 1) } Reporter.prototype.leaveKey = function leaveKey (index, key, value) { const state = this._reporterState this.exitKey(index) if (state.obj !== null) { state.obj[key] = value } } Reporter.prototype.path = function path () { return this._reporterState.path.join('/') } Reporter.prototype.enterObject = function enterObject () { const state = this._reporterState const prev = state.obj state.obj = {} return prev } Reporter.prototype.leaveObject = function leaveObject (prev) { const state = this._reporterState const now = state.obj state.obj = prev return now } Reporter.prototype.error = function error (msg) { let err const state = this._reporterState const inherited = msg instanceof ReporterError if (inherited) { err = msg } else { err = new ReporterError(state.path.map(function (elem) { return `[${JSON.stringify(elem)}]` }).join(''), msg.message || msg, msg.stack) } if (!state.options.partial) { throw err } if (!inherited) { state.errors.push(err) } return err } Reporter.prototype.wrapResult = function wrapResult (result) { const state = this._reporterState if (!state.options.partial) { return result } return { result: this.isError(result) ? null : result, errors: state.errors } } function ReporterError (path, msg) { this.path = path this.rethrow(msg) } inherits(ReporterError, Error) ReporterError.prototype.rethrow = function rethrow (msg) { this.message = `${msg} at: ${this.path || '(shallow)'}` if (Error.captureStackTrace) { Error.captureStackTrace(this, ReporterError) } if (!this.stack) { try { // IE only adds stack when thrown throw new Error(this.message) } catch (e) { this.stack = e.stack } } return this } exports.Reporter = Reporter /***/ }), /***/ 96018: /***/ ((__unused_webpack_module, exports) => { // Helper function reverse (map) { const res = {} Object.keys(map).forEach(function (key) { // Convert key to integer if it is stringified if ((key | 0) == key) { key = key | 0 } // eslint-disable-line eqeqeq const value = map[key] res[value] = key }) return res } exports.tagClass = { 0: 'universal', 1: 'application', 2: 'context', 3: 'private' } exports.tagClassByName = reverse(exports.tagClass) exports.tag = { 0x00: 'end', 0x01: 'bool', 0x02: 'int', 0x03: 'bitstr', 0x04: 'octstr', 0x05: 'null_', 0x06: 'objid', 0x07: 'objDesc', 0x08: 'external', 0x09: 'real', 0x0a: 'enum', 0x0b: 'embed', 0x0c: 'utf8str', 0x0d: 'relativeOid', 0x10: 'seq', 0x11: 'set', 0x12: 'numstr', 0x13: 'printstr', 0x14: 't61str', 0x15: 'videostr', 0x16: 'ia5str', 0x17: 'utctime', 0x18: 'gentime', 0x19: 'graphstr', 0x1a: 'iso646str', 0x1b: 'genstr', 0x1c: 'unistr', 0x1d: 'charstr', 0x1e: 'bmpstr' } exports.tagByName = reverse(exports.tag) /***/ }), /***/ 90998: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { module.exports = { der: __nccwpck_require__(96018) } /***/ }), /***/ 44798: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /* global BigInt */ const { inherits } = __nccwpck_require__(73837) const { DecoderBuffer } = __nccwpck_require__(28424) const Node = __nccwpck_require__(48674) // Import DER constants const der = __nccwpck_require__(96018) function DERDecoder (entity) { this.enc = 'der' this.name = entity.name this.entity = entity // Construct base tree this.tree = new DERNode() this.tree._init(entity.body) } DERDecoder.prototype.decode = function decode (data, options) { if (!DecoderBuffer.isDecoderBuffer(data)) { data = new DecoderBuffer(data, options) } return this.tree._decode(data, options) } // Tree methods function DERNode (parent) { Node.call(this, 'der', parent) } inherits(DERNode, Node) DERNode.prototype._peekTag = function peekTag (buffer, tag, any) { if (buffer.isEmpty()) { return false } const state = buffer.save() const decodedTag = derDecodeTag(buffer, `Failed to peek tag: "${tag}"`) if (buffer.isError(decodedTag)) { return decodedTag } buffer.restore(state) return decodedTag.tag === tag || decodedTag.tagStr === tag || (decodedTag.tagStr + 'of') === tag || any } DERNode.prototype._decodeTag = function decodeTag (buffer, tag, any) { const decodedTag = derDecodeTag(buffer, `Failed to decode tag of "${tag}"`) if (buffer.isError(decodedTag)) { return decodedTag } let len = derDecodeLen(buffer, decodedTag.primitive, `Failed to get length of "${tag}"`) // Failure if (buffer.isError(len)) { return len } if (!any && decodedTag.tag !== tag && decodedTag.tagStr !== tag && decodedTag.tagStr + 'of' !== tag) { return buffer.error(`Failed to match tag: "${tag}"`) } if (decodedTag.primitive || len !== null) { return buffer.skip(len, `Failed to match body of: "${tag}"`) } // Indefinite length... find END tag const state = buffer.save() const res = this._skipUntilEnd( buffer, `Failed to skip indefinite length body: "${this.tag}"`) if (buffer.isError(res)) { return res } len = buffer.offset - state.offset buffer.restore(state) return buffer.skip(len, `Failed to match body of: "${tag}"`) } DERNode.prototype._skipUntilEnd = function skipUntilEnd (buffer, fail) { for (;;) { const tag = derDecodeTag(buffer, fail) if (buffer.isError(tag)) { return tag } const len = derDecodeLen(buffer, tag.primitive, fail) if (buffer.isError(len)) { return len } let res if (tag.primitive || len !== null) { res = buffer.skip(len) } else { res = this._skipUntilEnd(buffer, fail) } // Failure if (buffer.isError(res)) { return res } if (tag.tagStr === 'end') { break } } } DERNode.prototype._decodeList = function decodeList (buffer, tag, decoder, options) { const result = [] while (!buffer.isEmpty()) { const possibleEnd = this._peekTag(buffer, 'end') if (buffer.isError(possibleEnd)) { return possibleEnd } const res = decoder.decode(buffer, 'der', options) if (buffer.isError(res) && possibleEnd) { break } result.push(res) } return result } DERNode.prototype._decodeStr = function decodeStr (buffer, tag) { if (tag === 'bitstr') { const unused = buffer.readUInt8() if (buffer.isError(unused)) { return unused } return { unused: unused, data: buffer.raw() } } else if (tag === 'bmpstr') { const raw = buffer.raw() if (raw.length % 2 === 1) { return buffer.error('Decoding of string type: bmpstr length mismatch') } let str = '' for (let i = 0; i < raw.length / 2; i++) { str += String.fromCharCode(raw.readUInt16BE(i * 2)) } return str } else if (tag === 'numstr') { const numstr = buffer.raw().toString('ascii') if (!this._isNumstr(numstr)) { return buffer.error('Decoding of string type: numstr unsupported characters') } return numstr } else if (tag === 'octstr') { return buffer.raw() } else if (tag === 'objDesc') { return buffer.raw() } else if (tag === 'printstr') { const printstr = buffer.raw().toString('ascii') if (!this._isPrintstr(printstr)) { return buffer.error('Decoding of string type: printstr unsupported characters') } return printstr } else if (/str$/.test(tag)) { return buffer.raw().toString() } else { return buffer.error(`Decoding of string type: ${tag} unsupported`) } } DERNode.prototype._decodeObjid = function decodeObjid (buffer, values, relative) { let result const identifiers = [] let ident = 0 let subident = 0 while (!buffer.isEmpty()) { subident = buffer.readUInt8() ident <<= 7 ident |= subident & 0x7f if ((subident & 0x80) === 0) { identifiers.push(ident) ident = 0 } } if (subident & 0x80) { identifiers.push(ident) } const first = (identifiers[0] / 40) | 0 const second = identifiers[0] % 40 if (relative) { result = identifiers } else { result = [first, second].concat(identifiers.slice(1)) } if (values) { let tmp = values[result.join(' ')] if (tmp === undefined) { tmp = values[result.join('.')] } if (tmp !== undefined) { result = tmp } } return result } DERNode.prototype._decodeTime = function decodeTime (buffer, tag) { const str = buffer.raw().toString() let year let mon let day let hour let min let sec if (tag === 'gentime') { year = str.slice(0, 4) | 0 mon = str.slice(4, 6) | 0 day = str.slice(6, 8) | 0 hour = str.slice(8, 10) | 0 min = str.slice(10, 12) | 0 sec = str.slice(12, 14) | 0 } else if (tag === 'utctime') { year = str.slice(0, 2) | 0 mon = str.slice(2, 4) | 0 day = str.slice(4, 6) | 0 hour = str.slice(6, 8) | 0 min = str.slice(8, 10) | 0 sec = str.slice(10, 12) | 0 if (year < 70) { year = 2000 + year } else { year = 1900 + year } } else { return buffer.error(`Decoding ${tag} time is not supported yet`) } return Date.UTC(year, mon - 1, day, hour, min, sec, 0) } DERNode.prototype._decodeNull = function decodeNull () { return null } DERNode.prototype._decodeBool = function decodeBool (buffer) { const res = buffer.readUInt8() if (buffer.isError(res)) { return res } else { return res !== 0 } } DERNode.prototype._decodeInt = function decodeInt (buffer, values) { // Bigint, return as it is (assume big endian) const raw = buffer.raw() let res = BigInt(`0x${raw.toString('hex')}`) if (values) { res = values[res.toString(10)] || res } return res } DERNode.prototype._use = function use (entity, obj) { if (typeof entity === 'function') { entity = entity(obj) } return entity._getDecoder('der').tree } // Utility methods function derDecodeTag (buf, fail) { let tag = buf.readUInt8(fail) if (buf.isError(tag)) { return tag } const cls = der.tagClass[tag >> 6] const primitive = (tag & 0x20) === 0 // Multi-octet tag - load if ((tag & 0x1f) === 0x1f) { let oct = tag tag = 0 while ((oct & 0x80) === 0x80) { oct = buf.readUInt8(fail) if (buf.isError(oct)) { return oct } tag <<= 7 tag |= oct & 0x7f } } else { tag &= 0x1f } const tagStr = der.tag[tag] return { cls: cls, primitive: primitive, tag: tag, tagStr: tagStr } } function derDecodeLen (buf, primitive, fail) { let len = buf.readUInt8(fail) if (buf.isError(len)) { return len } // Indefinite form if (!primitive && len === 0x80) { return null } // Definite form if ((len & 0x80) === 0) { // Short form return len } // Long form const num = len & 0x7f if (num > 4) { return buf.error('length octect is too long') } len = 0 for (let i = 0; i < num; i++) { len <<= 8 const j = buf.readUInt8(fail) if (buf.isError(j)) { return j } len |= j } return len } module.exports = DERDecoder /***/ }), /***/ 5017: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { module.exports = { der: __nccwpck_require__(44798), pem: __nccwpck_require__(33956) } /***/ }), /***/ 33956: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { inherits } = __nccwpck_require__(73837) const DERDecoder = __nccwpck_require__(44798) function PEMDecoder (entity) { DERDecoder.call(this, entity) this.enc = 'pem' } inherits(PEMDecoder, DERDecoder) PEMDecoder.prototype.decode = function decode (data, options) { const lines = data.toString().split(/[\r\n]+/g) const label = options.label.toUpperCase() const re = /^-----(BEGIN|END) ([^-]+)-----$/ let start = -1 let end = -1 for (let i = 0; i < lines.length; i++) { const match = lines[i].match(re) if (match === null) { continue } if (match[2] !== label) { continue } if (start === -1) { if (match[1] !== 'BEGIN') { break } start = i } else { if (match[1] !== 'END') { break } end = i break } } if (start === -1 || end === -1) { throw new Error(`PEM section not found for: ${label}`) } const base64 = lines.slice(start + 1, end).join('') // Remove excessive symbols base64.replace(/[^a-z0-9+/=]+/gi, '') const input = Buffer.from(base64, 'base64') return DERDecoder.prototype.decode.call(this, input, options) } module.exports = PEMDecoder /***/ }), /***/ 20846: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /* global BigInt */ const { inherits } = __nccwpck_require__(73837) const Node = __nccwpck_require__(48674) const der = __nccwpck_require__(96018) function DEREncoder (entity) { this.enc = 'der' this.name = entity.name this.entity = entity // Construct base tree this.tree = new DERNode() this.tree._init(entity.body) } DEREncoder.prototype.encode = function encode (data, reporter) { return this.tree._encode(data, reporter).join() } // Tree methods function DERNode (parent) { Node.call(this, 'der', parent) } inherits(DERNode, Node) DERNode.prototype._encodeComposite = function encodeComposite (tag, primitive, cls, content) { const encodedTag = encodeTag(tag, primitive, cls, this.reporter) // Short form if (content.length < 0x80) { const header = Buffer.alloc(2) header[0] = encodedTag header[1] = content.length return this._createEncoderBuffer([header, content]) } // Long form // Count octets required to store length let lenOctets = 1 for (let i = content.length; i >= 0x100; i >>= 8) { lenOctets++ } const header = Buffer.alloc(1 + 1 + lenOctets) header[0] = encodedTag header[1] = 0x80 | lenOctets for (let i = 1 + lenOctets, j = content.length; j > 0; i--, j >>= 8) { header[i] = j & 0xff } return this._createEncoderBuffer([header, content]) } DERNode.prototype._encodeStr = function encodeStr (str, tag) { if (tag === 'bitstr') { return this._createEncoderBuffer([str.unused | 0, str.data]) } else if (tag === 'bmpstr') { const buf = Buffer.alloc(str.length * 2) for (let i = 0; i < str.length; i++) { buf.writeUInt16BE(str.charCodeAt(i), i * 2) } return this._createEncoderBuffer(buf) } else if (tag === 'numstr') { if (!this._isNumstr(str)) { return this.reporter.error('Encoding of string type: numstr supports only digits and space') } return this._createEncoderBuffer(str) } else if (tag === 'printstr') { if (!this._isPrintstr(str)) { return this.reporter.error('Encoding of string type: printstr supports only latin upper and lower case letters, digits, space, apostrophe, left and rigth parenthesis, plus sign, comma, hyphen, dot, slash, colon, equal sign, question mark') } return this._createEncoderBuffer(str) } else if (/str$/.test(tag)) { return this._createEncoderBuffer(str) } else if (tag === 'objDesc') { return this._createEncoderBuffer(str) } else { return this.reporter.error(`Encoding of string type: ${tag} unsupported`) } } DERNode.prototype._encodeObjid = function encodeObjid (id, values, relative) { if (typeof id === 'string') { if (!values) { return this.reporter.error('string objid given, but no values map found') } if (!Object.prototype.hasOwnProperty.call(values, id)) { return this.reporter.error('objid not found in values map') } id = values[id].split(/[\s.]+/g) for (let i = 0; i < id.length; i++) { id[i] |= 0 } } else if (Array.isArray(id)) { id = id.slice() for (let i = 0; i < id.length; i++) { id[i] |= 0 } } if (!Array.isArray(id)) { return this.reporter.error(`objid() should be either array or string, got: ${JSON.stringify(id)}`) } if (!relative) { if (id[1] >= 40) { return this.reporter.error('Second objid identifier OOB') } id.splice(0, 2, id[0] * 40 + id[1]) } // Count number of octets let size = 0 for (let i = 0; i < id.length; i++) { let ident = id[i] for (size++; ident >= 0x80; ident >>= 7) { size++ } } const objid = Buffer.alloc(size) let offset = objid.length - 1 for (let i = id.length - 1; i >= 0; i--) { let ident = id[i] objid[offset--] = ident & 0x7f while ((ident >>= 7) > 0) { objid[offset--] = 0x80 | (ident & 0x7f) } } return this._createEncoderBuffer(objid) } function two (num) { if (num < 10) { return `0${num}` } else { return num } } DERNode.prototype._encodeTime = function encodeTime (time, tag) { let str const date = new Date(time) if (tag === 'gentime') { str = [ two(date.getUTCFullYear()), two(date.getUTCMonth() + 1), two(date.getUTCDate()), two(date.getUTCHours()), two(date.getUTCMinutes()), two(date.getUTCSeconds()), 'Z' ].join('') } else if (tag === 'utctime') { str = [ two(date.getUTCFullYear() % 100), two(date.getUTCMonth() + 1), two(date.getUTCDate()), two(date.getUTCHours()), two(date.getUTCMinutes()), two(date.getUTCSeconds()), 'Z' ].join('') } else { this.reporter.error(`Encoding ${tag} time is not supported yet`) } return this._encodeStr(str, 'octstr') } DERNode.prototype._encodeNull = function encodeNull () { return this._createEncoderBuffer('') } function bnToBuf (bn) { var hex = BigInt(bn).toString(16) if (hex.length % 2) { hex = '0' + hex } var len = hex.length / 2 var u8 = new Uint8Array(len) var i = 0 var j = 0 while (i < len) { u8[i] = parseInt(hex.slice(j, j + 2), 16) i += 1 j += 2 } return u8 } DERNode.prototype._encodeInt = function encodeInt (num, values) { if (typeof num === 'string') { if (!values) { return this.reporter.error('String int or enum given, but no values map') } if (!Object.prototype.hasOwnProperty.call(values, num)) { return this.reporter.error(`Values map doesn't contain: ${JSON.stringify(num)}`) } num = values[num] } if (typeof num === 'bigint') { const numArray = [...bnToBuf(num)] if (numArray[0] & 0x80) { numArray.unshift(0) } num = Buffer.from(numArray) } if (Buffer.isBuffer(num)) { let size = num.length if (num.length === 0) { size++ } const out = Buffer.alloc(size) num.copy(out) if (num.length === 0) { out[0] = 0 } return this._createEncoderBuffer(out) } if (num < 0x80) { return this._createEncoderBuffer(num) } if (num < 0x100) { return this._createEncoderBuffer([0, num]) } let size = 1 for (let i = num; i >= 0x100; i >>= 8) { size++ } const out = new Array(size) for (let i = out.length - 1; i >= 0; i--) { out[i] = num & 0xff num >>= 8 } if (out[0] & 0x80) { out.unshift(0) } return this._createEncoderBuffer(Buffer.from(out)) } DERNode.prototype._encodeBool = function encodeBool (value) { return this._createEncoderBuffer(value ? 0xff : 0) } DERNode.prototype._use = function use (entity, obj) { if (typeof entity === 'function') { entity = entity(obj) } return entity._getEncoder('der').tree } DERNode.prototype._skipDefault = function skipDefault (dataBuffer, reporter, parent) { const state = this._baseState let i if (state.default === null) { return false } const data = dataBuffer.join() if (state.defaultBuffer === undefined) { state.defaultBuffer = this._encodeValue(state.default, reporter, parent).join() } if (data.length !== state.defaultBuffer.length) { return false } for (i = 0; i < data.length; i++) { if (data[i] !== state.defaultBuffer[i]) { return false } } return true } // Utility methods function encodeTag (tag, primitive, cls, reporter) { let res if (tag === 'seqof') { tag = 'seq' } else if (tag === 'setof') { tag = 'set' } if (Object.prototype.hasOwnProperty.call(der.tagByName, tag)) { res = der.tagByName[tag] } else if (typeof tag === 'number' && (tag | 0) === tag) { res = tag } else { return reporter.error(`Unknown tag: ${tag}`) } if (res >= 0x1f) { return reporter.error('Multi-octet tag encoding unsupported') } if (!primitive) { res |= 0x20 } res |= (der.tagClassByName[cls || 'universal'] << 6) return res } module.exports = DEREncoder /***/ }), /***/ 2246: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { module.exports = { der: __nccwpck_require__(20846), pem: __nccwpck_require__(26217) } /***/ }), /***/ 26217: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { inherits } = __nccwpck_require__(73837) const DEREncoder = __nccwpck_require__(20846) function PEMEncoder (entity) { DEREncoder.call(this, entity) this.enc = 'pem' } inherits(PEMEncoder, DEREncoder) PEMEncoder.prototype.encode = function encode (data, options) { const buf = DEREncoder.prototype.encode.call(this, data) const p = buf.toString('base64') const out = [`-----BEGIN ${options.label}-----`] for (let i = 0; i < p.length; i += 64) { out.push(p.slice(i, i + 64)) } out.push(`-----END ${options.label}-----`) return out.join('\n') } module.exports = PEMEncoder /***/ }), /***/ 29912: /***/ (function(__unused_webpack_module, exports) { "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.ClientStreamingCall = void 0; /** * A client streaming RPC call. This means that the clients sends 0, 1, or * more messages to the server, and the server replies with exactly one * message. */ class ClientStreamingCall { constructor(method, requestHeaders, request, headers, response, status, trailers) { this.method = method; this.requestHeaders = requestHeaders; this.requests = request; this.headers = headers; this.response = response; this.status = status; this.trailers = trailers; } /** * Instead of awaiting the response status and trailers, you can * just as well await this call itself to receive the server outcome. * Note that it may still be valid to send more request messages. */ then(onfulfilled, onrejected) { return this.promiseFinished().then(value => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, reason => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); } promiseFinished() { return __awaiter(this, void 0, void 0, function* () { let [headers, response, status, trailers] = yield Promise.all([this.headers, this.response, this.status, this.trailers]); return { method: this.method, requestHeaders: this.requestHeaders, headers, response, status, trailers }; }); } } exports.ClientStreamingCall = ClientStreamingCall; /***/ }), /***/ 85702: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Deferred = exports.DeferredState = void 0; var DeferredState; (function (DeferredState) { DeferredState[DeferredState["PENDING"] = 0] = "PENDING"; DeferredState[DeferredState["REJECTED"] = 1] = "REJECTED"; DeferredState[DeferredState["RESOLVED"] = 2] = "RESOLVED"; })(DeferredState = exports.DeferredState || (exports.DeferredState = {})); /** * A deferred promise. This is a "controller" for a promise, which lets you * pass a promise around and reject or resolve it from the outside. * * Warning: This class is to be used with care. Using it can make code very * difficult to read. It is intended for use in library code that exposes * promises, not for regular business logic. */ class Deferred { /** * @param preventUnhandledRejectionWarning - prevents the warning * "Unhandled Promise rejection" by adding a noop rejection handler. * Working with calls returned from the runtime-rpc package in an * async function usually means awaiting one call property after * the other. This means that the "status" is not being awaited when * an earlier await for the "headers" is rejected. This causes the * "unhandled promise reject" warning. A more correct behaviour for * calls might be to become aware whether at least one of the * promises is handled and swallow the rejection warning for the * others. */ constructor(preventUnhandledRejectionWarning = true) { this._state = DeferredState.PENDING; this._promise = new Promise((resolve, reject) => { this._resolve = resolve; this._reject = reject; }); if (preventUnhandledRejectionWarning) { this._promise.catch(_ => { }); } } /** * Get the current state of the promise. */ get state() { return this._state; } /** * Get the deferred promise. */ get promise() { return this._promise; } /** * Resolve the promise. Throws if the promise is already resolved or rejected. */ resolve(value) { if (this.state !== DeferredState.PENDING) throw new Error(`cannot resolve ${DeferredState[this.state].toLowerCase()}`); this._resolve(value); this._state = DeferredState.RESOLVED; } /** * Reject the promise. Throws if the promise is already resolved or rejected. */ reject(reason) { if (this.state !== DeferredState.PENDING) throw new Error(`cannot reject ${DeferredState[this.state].toLowerCase()}`); this._reject(reason); this._state = DeferredState.REJECTED; } /** * Resolve the promise. Ignore if not pending. */ resolvePending(val) { if (this._state === DeferredState.PENDING) this.resolve(val); } /** * Reject the promise. Ignore if not pending. */ rejectPending(reason) { if (this._state === DeferredState.PENDING) this.reject(reason); } } exports.Deferred = Deferred; /***/ }), /***/ 17042: /***/ (function(__unused_webpack_module, exports) { "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.DuplexStreamingCall = void 0; /** * A duplex streaming RPC call. This means that the clients sends an * arbitrary amount of messages to the server, while at the same time, * the server sends an arbitrary amount of messages to the client. */ class DuplexStreamingCall { constructor(method, requestHeaders, request, headers, response, status, trailers) { this.method = method; this.requestHeaders = requestHeaders; this.requests = request; this.headers = headers; this.responses = response; this.status = status; this.trailers = trailers; } /** * Instead of awaiting the response status and trailers, you can * just as well await this call itself to receive the server outcome. * Note that it may still be valid to send more request messages. */ then(onfulfilled, onrejected) { return this.promiseFinished().then(value => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, reason => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); } promiseFinished() { return __awaiter(this, void 0, void 0, function* () { let [headers, status, trailers] = yield Promise.all([this.headers, this.status, this.trailers]); return { method: this.method, requestHeaders: this.requestHeaders, headers, status, trailers, }; }); } } exports.DuplexStreamingCall = DuplexStreamingCall; /***/ }), /***/ 60012: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Public API of the rpc runtime. // Note: we do not use `export * from ...` to help tree shakers, // webpack verbose output hints that this should be useful Object.defineProperty(exports, "__esModule", ({ value: true })); var service_type_1 = __nccwpck_require__(14107); Object.defineProperty(exports, "ServiceType", ({ enumerable: true, get: function () { return service_type_1.ServiceType; } })); var reflection_info_1 = __nccwpck_require__(44331); Object.defineProperty(exports, "readMethodOptions", ({ enumerable: true, get: function () { return reflection_info_1.readMethodOptions; } })); Object.defineProperty(exports, "readMethodOption", ({ enumerable: true, get: function () { return reflection_info_1.readMethodOption; } })); Object.defineProperty(exports, "readServiceOption", ({ enumerable: true, get: function () { return reflection_info_1.readServiceOption; } })); var rpc_error_1 = __nccwpck_require__(63159); Object.defineProperty(exports, "RpcError", ({ enumerable: true, get: function () { return rpc_error_1.RpcError; } })); var rpc_options_1 = __nccwpck_require__(67386); Object.defineProperty(exports, "mergeRpcOptions", ({ enumerable: true, get: function () { return rpc_options_1.mergeRpcOptions; } })); var rpc_output_stream_1 = __nccwpck_require__(76637); Object.defineProperty(exports, "RpcOutputStreamController", ({ enumerable: true, get: function () { return rpc_output_stream_1.RpcOutputStreamController; } })); var test_transport_1 = __nccwpck_require__(87008); Object.defineProperty(exports, "TestTransport", ({ enumerable: true, get: function () { return test_transport_1.TestTransport; } })); var deferred_1 = __nccwpck_require__(85702); Object.defineProperty(exports, "Deferred", ({ enumerable: true, get: function () { return deferred_1.Deferred; } })); Object.defineProperty(exports, "DeferredState", ({ enumerable: true, get: function () { return deferred_1.DeferredState; } })); var duplex_streaming_call_1 = __nccwpck_require__(17042); Object.defineProperty(exports, "DuplexStreamingCall", ({ enumerable: true, get: function () { return duplex_streaming_call_1.DuplexStreamingCall; } })); var client_streaming_call_1 = __nccwpck_require__(29912); Object.defineProperty(exports, "ClientStreamingCall", ({ enumerable: true, get: function () { return client_streaming_call_1.ClientStreamingCall; } })); var server_streaming_call_1 = __nccwpck_require__(30066); Object.defineProperty(exports, "ServerStreamingCall", ({ enumerable: true, get: function () { return server_streaming_call_1.ServerStreamingCall; } })); var unary_call_1 = __nccwpck_require__(84175); Object.defineProperty(exports, "UnaryCall", ({ enumerable: true, get: function () { return unary_call_1.UnaryCall; } })); var rpc_interceptor_1 = __nccwpck_require__(51680); Object.defineProperty(exports, "stackIntercept", ({ enumerable: true, get: function () { return rpc_interceptor_1.stackIntercept; } })); Object.defineProperty(exports, "stackDuplexStreamingInterceptors", ({ enumerable: true, get: function () { return rpc_interceptor_1.stackDuplexStreamingInterceptors; } })); Object.defineProperty(exports, "stackClientStreamingInterceptors", ({ enumerable: true, get: function () { return rpc_interceptor_1.stackClientStreamingInterceptors; } })); Object.defineProperty(exports, "stackServerStreamingInterceptors", ({ enumerable: true, get: function () { return rpc_interceptor_1.stackServerStreamingInterceptors; } })); Object.defineProperty(exports, "stackUnaryInterceptors", ({ enumerable: true, get: function () { return rpc_interceptor_1.stackUnaryInterceptors; } })); var server_call_context_1 = __nccwpck_require__(25320); Object.defineProperty(exports, "ServerCallContextController", ({ enumerable: true, get: function () { return server_call_context_1.ServerCallContextController; } })); /***/ }), /***/ 44331: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.readServiceOption = exports.readMethodOption = exports.readMethodOptions = exports.normalizeMethodInfo = void 0; const runtime_1 = __nccwpck_require__(37001); /** * Turns PartialMethodInfo into MethodInfo. */ function normalizeMethodInfo(method, service) { var _a, _b, _c; let m = method; m.service = service; m.localName = (_a = m.localName) !== null && _a !== void 0 ? _a : runtime_1.lowerCamelCase(m.name); // noinspection PointlessBooleanExpressionJS m.serverStreaming = !!m.serverStreaming; // noinspection PointlessBooleanExpressionJS m.clientStreaming = !!m.clientStreaming; m.options = (_b = m.options) !== null && _b !== void 0 ? _b : {}; m.idempotency = (_c = m.idempotency) !== null && _c !== void 0 ? _c : undefined; return m; } exports.normalizeMethodInfo = normalizeMethodInfo; /** * Read custom method options from a generated service client. * * @deprecated use readMethodOption() */ function readMethodOptions(service, methodName, extensionName, extensionType) { var _a; const options = (_a = service.methods.find((m, i) => m.localName === methodName || i === methodName)) === null || _a === void 0 ? void 0 : _a.options; return options && options[extensionName] ? extensionType.fromJson(options[extensionName]) : undefined; } exports.readMethodOptions = readMethodOptions; function readMethodOption(service, methodName, extensionName, extensionType) { var _a; const options = (_a = service.methods.find((m, i) => m.localName === methodName || i === methodName)) === null || _a === void 0 ? void 0 : _a.options; if (!options) { return undefined; } const optionVal = options[extensionName]; if (optionVal === undefined) { return optionVal; } return extensionType ? extensionType.fromJson(optionVal) : optionVal; } exports.readMethodOption = readMethodOption; function readServiceOption(service, extensionName, extensionType) { const options = service.options; if (!options) { return undefined; } const optionVal = options[extensionName]; if (optionVal === undefined) { return optionVal; } return extensionType ? extensionType.fromJson(optionVal) : optionVal; } exports.readServiceOption = readServiceOption; /***/ }), /***/ 63159: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.RpcError = void 0; /** * An error that occurred while calling a RPC method. */ class RpcError extends Error { constructor(message, code = 'UNKNOWN', meta) { super(message); this.name = 'RpcError'; // see https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#example Object.setPrototypeOf(this, new.target.prototype); this.code = code; this.meta = meta !== null && meta !== void 0 ? meta : {}; } toString() { const l = [this.name + ': ' + this.message]; if (this.code) { l.push(''); l.push('Code: ' + this.code); } if (this.serviceName && this.methodName) { l.push('Method: ' + this.serviceName + '/' + this.methodName); } let m = Object.entries(this.meta); if (m.length) { l.push(''); l.push('Meta:'); for (let [k, v] of m) { l.push(` ${k}: ${v}`); } } return l.join('\n'); } } exports.RpcError = RpcError; /***/ }), /***/ 51680: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.stackDuplexStreamingInterceptors = exports.stackClientStreamingInterceptors = exports.stackServerStreamingInterceptors = exports.stackUnaryInterceptors = exports.stackIntercept = void 0; const runtime_1 = __nccwpck_require__(37001); /** * Creates a "stack" of of all interceptors specified in the given `RpcOptions`. * Used by generated client implementations. * @internal */ function stackIntercept(kind, transport, method, options, input) { var _a, _b, _c, _d; if (kind == "unary") { let tail = (mtd, inp, opt) => transport.unary(mtd, inp, opt); for (const curr of ((_a = options.interceptors) !== null && _a !== void 0 ? _a : []).filter(i => i.interceptUnary).reverse()) { const next = tail; tail = (mtd, inp, opt) => curr.interceptUnary(next, mtd, inp, opt); } return tail(method, input, options); } if (kind == "serverStreaming") { let tail = (mtd, inp, opt) => transport.serverStreaming(mtd, inp, opt); for (const curr of ((_b = options.interceptors) !== null && _b !== void 0 ? _b : []).filter(i => i.interceptServerStreaming).reverse()) { const next = tail; tail = (mtd, inp, opt) => curr.interceptServerStreaming(next, mtd, inp, opt); } return tail(method, input, options); } if (kind == "clientStreaming") { let tail = (mtd, opt) => transport.clientStreaming(mtd, opt); for (const curr of ((_c = options.interceptors) !== null && _c !== void 0 ? _c : []).filter(i => i.interceptClientStreaming).reverse()) { const next = tail; tail = (mtd, opt) => curr.interceptClientStreaming(next, mtd, opt); } return tail(method, options); } if (kind == "duplex") { let tail = (mtd, opt) => transport.duplex(mtd, opt); for (const curr of ((_d = options.interceptors) !== null && _d !== void 0 ? _d : []).filter(i => i.interceptDuplex).reverse()) { const next = tail; tail = (mtd, opt) => curr.interceptDuplex(next, mtd, opt); } return tail(method, options); } runtime_1.assertNever(kind); } exports.stackIntercept = stackIntercept; /** * @deprecated replaced by `stackIntercept()`, still here to support older generated code */ function stackUnaryInterceptors(transport, method, input, options) { return stackIntercept("unary", transport, method, options, input); } exports.stackUnaryInterceptors = stackUnaryInterceptors; /** * @deprecated replaced by `stackIntercept()`, still here to support older generated code */ function stackServerStreamingInterceptors(transport, method, input, options) { return stackIntercept("serverStreaming", transport, method, options, input); } exports.stackServerStreamingInterceptors = stackServerStreamingInterceptors; /** * @deprecated replaced by `stackIntercept()`, still here to support older generated code */ function stackClientStreamingInterceptors(transport, method, options) { return stackIntercept("clientStreaming", transport, method, options); } exports.stackClientStreamingInterceptors = stackClientStreamingInterceptors; /** * @deprecated replaced by `stackIntercept()`, still here to support older generated code */ function stackDuplexStreamingInterceptors(transport, method, options) { return stackIntercept("duplex", transport, method, options); } exports.stackDuplexStreamingInterceptors = stackDuplexStreamingInterceptors; /***/ }), /***/ 67386: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.mergeRpcOptions = void 0; const runtime_1 = __nccwpck_require__(37001); /** * Merges custom RPC options with defaults. Returns a new instance and keeps * the "defaults" and the "options" unmodified. * * Merges `RpcMetadata` "meta", overwriting values from "defaults" with * values from "options". Does not append values to existing entries. * * Merges "jsonOptions", including "jsonOptions.typeRegistry", by creating * a new array that contains types from "options.jsonOptions.typeRegistry" * first, then types from "defaults.jsonOptions.typeRegistry". * * Merges "binaryOptions". * * Merges "interceptors" by creating a new array that contains interceptors * from "defaults" first, then interceptors from "options". * * Works with objects that extend `RpcOptions`, but only if the added * properties are of type Date, primitive like string, boolean, or Array * of primitives. If you have other property types, you have to merge them * yourself. */ function mergeRpcOptions(defaults, options) { if (!options) return defaults; let o = {}; copy(defaults, o); copy(options, o); for (let key of Object.keys(options)) { let val = options[key]; switch (key) { case "jsonOptions": o.jsonOptions = runtime_1.mergeJsonOptions(defaults.jsonOptions, o.jsonOptions); break; case "binaryOptions": o.binaryOptions = runtime_1.mergeBinaryOptions(defaults.binaryOptions, o.binaryOptions); break; case "meta": o.meta = {}; copy(defaults.meta, o.meta); copy(options.meta, o.meta); break; case "interceptors": o.interceptors = defaults.interceptors ? defaults.interceptors.concat(val) : val.concat(); break; } } return o; } exports.mergeRpcOptions = mergeRpcOptions; function copy(a, into) { if (!a) return; let c = into; for (let [k, v] of Object.entries(a)) { if (v instanceof Date) c[k] = new Date(v.getTime()); else if (Array.isArray(v)) c[k] = v.concat(); else c[k] = v; } } /***/ }), /***/ 76637: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.RpcOutputStreamController = void 0; const deferred_1 = __nccwpck_require__(85702); const runtime_1 = __nccwpck_require__(37001); /** * A `RpcOutputStream` that you control. */ class RpcOutputStreamController { constructor() { this._lis = { nxt: [], msg: [], err: [], cmp: [], }; this._closed = false; } // --- RpcOutputStream callback API onNext(callback) { return this.addLis(callback, this._lis.nxt); } onMessage(callback) { return this.addLis(callback, this._lis.msg); } onError(callback) { return this.addLis(callback, this._lis.err); } onComplete(callback) { return this.addLis(callback, this._lis.cmp); } addLis(callback, list) { list.push(callback); return () => { let i = list.indexOf(callback); if (i >= 0) list.splice(i, 1); }; } // remove all listeners clearLis() { for (let l of Object.values(this._lis)) l.splice(0, l.length); } // --- Controller API /** * Is this stream already closed by a completion or error? */ get closed() { return this._closed !== false; } /** * Emit message, close with error, or close successfully, but only one * at a time. * Can be used to wrap a stream by using the other stream's `onNext`. */ notifyNext(message, error, complete) { runtime_1.assert((message ? 1 : 0) + (error ? 1 : 0) + (complete ? 1 : 0) <= 1, 'only one emission at a time'); if (message) this.notifyMessage(message); if (error) this.notifyError(error); if (complete) this.notifyComplete(); } /** * Emits a new message. Throws if stream is closed. * * Triggers onNext and onMessage callbacks. */ notifyMessage(message) { runtime_1.assert(!this.closed, 'stream is closed'); this.pushIt({ value: message, done: false }); this._lis.msg.forEach(l => l(message)); this._lis.nxt.forEach(l => l(message, undefined, false)); } /** * Closes the stream with an error. Throws if stream is closed. * * Triggers onNext and onError callbacks. */ notifyError(error) { runtime_1.assert(!this.closed, 'stream is closed'); this._closed = error; this.pushIt(error); this._lis.err.forEach(l => l(error)); this._lis.nxt.forEach(l => l(undefined, error, false)); this.clearLis(); } /** * Closes the stream successfully. Throws if stream is closed. * * Triggers onNext and onComplete callbacks. */ notifyComplete() { runtime_1.assert(!this.closed, 'stream is closed'); this._closed = true; this.pushIt({ value: null, done: true }); this._lis.cmp.forEach(l => l()); this._lis.nxt.forEach(l => l(undefined, undefined, true)); this.clearLis(); } /** * Creates an async iterator (that can be used with `for await {...}`) * to consume the stream. * * Some things to note: * - If an error occurs, the `for await` will throw it. * - If an error occurred before the `for await` was started, `for await` * will re-throw it. * - If the stream is already complete, the `for await` will be empty. * - If your `for await` consumes slower than the stream produces, * for example because you are relaying messages in a slow operation, * messages are queued. */ [Symbol.asyncIterator]() { // init the iterator state, enabling pushIt() if (!this._itState) { this._itState = { q: [] }; } // if we are closed, we are definitely not receiving any more messages. // but we can't let the iterator get stuck. we want to either: // a) finish the new iterator immediately, because we are completed // b) reject the new iterator, because we errored if (this._closed === true) this.pushIt({ value: null, done: true }); else if (this._closed !== false) this.pushIt(this._closed); // the async iterator return { next: () => { let state = this._itState; runtime_1.assert(state, "bad state"); // if we don't have a state here, code is broken // there should be no pending result. // did the consumer call next() before we resolved our previous result promise? runtime_1.assert(!state.p, "iterator contract broken"); // did we produce faster than the iterator consumed? // return the oldest result from the queue. let first = state.q.shift(); if (first) return ("value" in first) ? Promise.resolve(first) : Promise.reject(first); // we have no result ATM, but we promise one. // as soon as we have a result, we must resolve promise. state.p = new deferred_1.Deferred(); return state.p.promise; }, }; } // "push" a new iterator result. // this either resolves a pending promise, or enqueues the result. pushIt(result) { let state = this._itState; if (!state) return; // is the consumer waiting for us? if (state.p) { // yes, consumer is waiting for this promise. const p = state.p; runtime_1.assert(p.state == deferred_1.DeferredState.PENDING, "iterator contract broken"); // resolve the promise ("value" in result) ? p.resolve(result) : p.reject(result); // must cleanup, otherwise iterator.next() would pick it up again. delete state.p; } else { // we are producing faster than the iterator consumes. // push result onto queue. state.q.push(result); } } } exports.RpcOutputStreamController = RpcOutputStreamController; /***/ }), /***/ 25320: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ServerCallContextController = void 0; class ServerCallContextController { constructor(method, headers, deadline, sendResponseHeadersFn, defaultStatus = { code: 'OK', detail: '' }) { this._cancelled = false; this._listeners = []; this.method = method; this.headers = headers; this.deadline = deadline; this.trailers = {}; this._sendRH = sendResponseHeadersFn; this.status = defaultStatus; } /** * Set the call cancelled. * * Invokes all callbacks registered with onCancel() and * sets `cancelled = true`. */ notifyCancelled() { if (!this._cancelled) { this._cancelled = true; for (let l of this._listeners) { l(); } } } /** * Send response headers. */ sendResponseHeaders(data) { this._sendRH(data); } /** * Is the call cancelled? * * When the client closes the connection before the server * is done, the call is cancelled. * * If you want to cancel a request on the server, throw a * RpcError with the CANCELLED status code. */ get cancelled() { return this._cancelled; } /** * Add a callback for cancellation. */ onCancel(callback) { const l = this._listeners; l.push(callback); return () => { let i = l.indexOf(callback); if (i >= 0) l.splice(i, 1); }; } } exports.ServerCallContextController = ServerCallContextController; /***/ }), /***/ 30066: /***/ (function(__unused_webpack_module, exports) { "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.ServerStreamingCall = void 0; /** * A server streaming RPC call. The client provides exactly one input message * but the server may respond with 0, 1, or more messages. */ class ServerStreamingCall { constructor(method, requestHeaders, request, headers, response, status, trailers) { this.method = method; this.requestHeaders = requestHeaders; this.request = request; this.headers = headers; this.responses = response; this.status = status; this.trailers = trailers; } /** * Instead of awaiting the response status and trailers, you can * just as well await this call itself to receive the server outcome. * You should first setup some listeners to the `request` to * see the actual messages the server replied with. */ then(onfulfilled, onrejected) { return this.promiseFinished().then(value => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, reason => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); } promiseFinished() { return __awaiter(this, void 0, void 0, function* () { let [headers, status, trailers] = yield Promise.all([this.headers, this.status, this.trailers]); return { method: this.method, requestHeaders: this.requestHeaders, request: this.request, headers, status, trailers, }; }); } } exports.ServerStreamingCall = ServerStreamingCall; /***/ }), /***/ 14107: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ServiceType = void 0; const reflection_info_1 = __nccwpck_require__(44331); class ServiceType { constructor(typeName, methods, options) { this.typeName = typeName; this.methods = methods.map(i => reflection_info_1.normalizeMethodInfo(i, this)); this.options = options !== null && options !== void 0 ? options : {}; } } exports.ServiceType = ServiceType; /***/ }), /***/ 87008: /***/ (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.TestTransport = void 0; const rpc_error_1 = __nccwpck_require__(63159); const runtime_1 = __nccwpck_require__(37001); const rpc_output_stream_1 = __nccwpck_require__(76637); const rpc_options_1 = __nccwpck_require__(67386); const unary_call_1 = __nccwpck_require__(84175); const server_streaming_call_1 = __nccwpck_require__(30066); const client_streaming_call_1 = __nccwpck_require__(29912); const duplex_streaming_call_1 = __nccwpck_require__(17042); /** * Transport for testing. */ class TestTransport { /** * Initialize with mock data. Omitted fields have default value. */ constructor(data) { /** * Suppress warning / error about uncaught rejections of * "status" and "trailers". */ this.suppressUncaughtRejections = true; this.headerDelay = 10; this.responseDelay = 50; this.betweenResponseDelay = 10; this.afterResponseDelay = 10; this.data = data !== null && data !== void 0 ? data : {}; } /** * Sent message(s) during the last operation. */ get sentMessages() { if (this.lastInput instanceof TestInputStream) { return this.lastInput.sent; } else if (typeof this.lastInput == "object") { return [this.lastInput.single]; } return []; } /** * Sending message(s) completed? */ get sendComplete() { if (this.lastInput instanceof TestInputStream) { return this.lastInput.completed; } else if (typeof this.lastInput == "object") { return true; } return false; } // Creates a promise for response headers from the mock data. promiseHeaders() { var _a; const headers = (_a = this.data.headers) !== null && _a !== void 0 ? _a : TestTransport.defaultHeaders; return headers instanceof rpc_error_1.RpcError ? Promise.reject(headers) : Promise.resolve(headers); } // Creates a promise for a single, valid, message from the mock data. promiseSingleResponse(method) { if (this.data.response instanceof rpc_error_1.RpcError) { return Promise.reject(this.data.response); } let r; if (Array.isArray(this.data.response)) { runtime_1.assert(this.data.response.length > 0); r = this.data.response[0]; } else if (this.data.response !== undefined) { r = this.data.response; } else { r = method.O.create(); } runtime_1.assert(method.O.is(r)); return Promise.resolve(r); } /** * Pushes response messages from the mock data to the output stream. * If an error response, status or trailers are mocked, the stream is * closed with the respective error. * Otherwise, stream is completed successfully. * * The returned promise resolves when the stream is closed. It should * not reject. If it does, code is broken. */ streamResponses(method, stream, abort) { return __awaiter(this, void 0, void 0, function* () { // normalize "data.response" into an array of valid output messages const messages = []; if (this.data.response === undefined) { messages.push(method.O.create()); } else if (Array.isArray(this.data.response)) { for (let msg of this.data.response) { runtime_1.assert(method.O.is(msg)); messages.push(msg); } } else if (!(this.data.response instanceof rpc_error_1.RpcError)) { runtime_1.assert(method.O.is(this.data.response)); messages.push(this.data.response); } // start the stream with an initial delay. // if the request is cancelled, notify() error and exit. try { yield delay(this.responseDelay, abort)(undefined); } catch (error) { stream.notifyError(error); return; } // if error response was mocked, notify() error (stream is now closed with error) and exit. if (this.data.response instanceof rpc_error_1.RpcError) { stream.notifyError(this.data.response); return; } // regular response messages were mocked. notify() them. for (let msg of messages) { stream.notifyMessage(msg); // add a short delay between responses // if the request is cancelled, notify() error and exit. try { yield delay(this.betweenResponseDelay, abort)(undefined); } catch (error) { stream.notifyError(error); return; } } // error status was mocked, notify() error (stream is now closed with error) and exit. if (this.data.status instanceof rpc_error_1.RpcError) { stream.notifyError(this.data.status); return; } // error trailers were mocked, notify() error (stream is now closed with error) and exit. if (this.data.trailers instanceof rpc_error_1.RpcError) { stream.notifyError(this.data.trailers); return; } // stream completed successfully stream.notifyComplete(); }); } // Creates a promise for response status from the mock data. promiseStatus() { var _a; const status = (_a = this.data.status) !== null && _a !== void 0 ? _a : TestTransport.defaultStatus; return status instanceof rpc_error_1.RpcError ? Promise.reject(status) : Promise.resolve(status); } // Creates a promise for response trailers from the mock data. promiseTrailers() { var _a; const trailers = (_a = this.data.trailers) !== null && _a !== void 0 ? _a : TestTransport.defaultTrailers; return trailers instanceof rpc_error_1.RpcError ? Promise.reject(trailers) : Promise.resolve(trailers); } maybeSuppressUncaught(...promise) { if (this.suppressUncaughtRejections) { for (let p of promise) { p.catch(() => { }); } } } mergeOptions(options) { return rpc_options_1.mergeRpcOptions({}, options); } unary(method, input, options) { var _a; const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders() .then(delay(this.headerDelay, options.abort)), responsePromise = headersPromise .catch(_ => { }) .then(delay(this.responseDelay, options.abort)) .then(_ => this.promiseSingleResponse(method)), statusPromise = responsePromise .catch(_ => { }) .then(delay(this.afterResponseDelay, options.abort)) .then(_ => this.promiseStatus()), trailersPromise = responsePromise .catch(_ => { }) .then(delay(this.afterResponseDelay, options.abort)) .then(_ => this.promiseTrailers()); this.maybeSuppressUncaught(statusPromise, trailersPromise); this.lastInput = { single: input }; return new unary_call_1.UnaryCall(method, requestHeaders, input, headersPromise, responsePromise, statusPromise, trailersPromise); } serverStreaming(method, input, options) { var _a; const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders() .then(delay(this.headerDelay, options.abort)), outputStream = new rpc_output_stream_1.RpcOutputStreamController(), responseStreamClosedPromise = headersPromise .then(delay(this.responseDelay, options.abort)) .catch(() => { }) .then(() => this.streamResponses(method, outputStream, options.abort)) .then(delay(this.afterResponseDelay, options.abort)), statusPromise = responseStreamClosedPromise .then(() => this.promiseStatus()), trailersPromise = responseStreamClosedPromise .then(() => this.promiseTrailers()); this.maybeSuppressUncaught(statusPromise, trailersPromise); this.lastInput = { single: input }; return new server_streaming_call_1.ServerStreamingCall(method, requestHeaders, input, headersPromise, outputStream, statusPromise, trailersPromise); } clientStreaming(method, options) { var _a; const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders() .then(delay(this.headerDelay, options.abort)), responsePromise = headersPromise .catch(_ => { }) .then(delay(this.responseDelay, options.abort)) .then(_ => this.promiseSingleResponse(method)), statusPromise = responsePromise .catch(_ => { }) .then(delay(this.afterResponseDelay, options.abort)) .then(_ => this.promiseStatus()), trailersPromise = responsePromise .catch(_ => { }) .then(delay(this.afterResponseDelay, options.abort)) .then(_ => this.promiseTrailers()); this.maybeSuppressUncaught(statusPromise, trailersPromise); this.lastInput = new TestInputStream(this.data, options.abort); return new client_streaming_call_1.ClientStreamingCall(method, requestHeaders, this.lastInput, headersPromise, responsePromise, statusPromise, trailersPromise); } duplex(method, options) { var _a; const requestHeaders = (_a = options.meta) !== null && _a !== void 0 ? _a : {}, headersPromise = this.promiseHeaders() .then(delay(this.headerDelay, options.abort)), outputStream = new rpc_output_stream_1.RpcOutputStreamController(), responseStreamClosedPromise = headersPromise .then(delay(this.responseDelay, options.abort)) .catch(() => { }) .then(() => this.streamResponses(method, outputStream, options.abort)) .then(delay(this.afterResponseDelay, options.abort)), statusPromise = responseStreamClosedPromise .then(() => this.promiseStatus()), trailersPromise = responseStreamClosedPromise .then(() => this.promiseTrailers()); this.maybeSuppressUncaught(statusPromise, trailersPromise); this.lastInput = new TestInputStream(this.data, options.abort); return new duplex_streaming_call_1.DuplexStreamingCall(method, requestHeaders, this.lastInput, headersPromise, outputStream, statusPromise, trailersPromise); } } exports.TestTransport = TestTransport; TestTransport.defaultHeaders = { responseHeader: "test" }; TestTransport.defaultStatus = { code: "OK", detail: "all good" }; TestTransport.defaultTrailers = { responseTrailer: "test" }; function delay(ms, abort) { return (v) => new Promise((resolve, reject) => { if (abort === null || abort === void 0 ? void 0 : abort.aborted) { reject(new rpc_error_1.RpcError("user cancel", "CANCELLED")); } else { const id = setTimeout(() => resolve(v), ms); if (abort) { abort.addEventListener("abort", ev => { clearTimeout(id); reject(new rpc_error_1.RpcError("user cancel", "CANCELLED")); }); } } }); } class TestInputStream { constructor(data, abort) { this._completed = false; this._sent = []; this.data = data; this.abort = abort; } get sent() { return this._sent; } get completed() { return this._completed; } send(message) { if (this.data.inputMessage instanceof rpc_error_1.RpcError) { return Promise.reject(this.data.inputMessage); } const delayMs = this.data.inputMessage === undefined ? 10 : this.data.inputMessage; return Promise.resolve(undefined) .then(() => { this._sent.push(message); }) .then(delay(delayMs, this.abort)); } complete() { if (this.data.inputComplete instanceof rpc_error_1.RpcError) { return Promise.reject(this.data.inputComplete); } const delayMs = this.data.inputComplete === undefined ? 10 : this.data.inputComplete; return Promise.resolve(undefined) .then(() => { this._completed = true; }) .then(delay(delayMs, this.abort)); } } /***/ }), /***/ 84175: /***/ (function(__unused_webpack_module, exports) { "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.UnaryCall = void 0; /** * A unary RPC call. Unary means there is exactly one input message and * exactly one output message unless an error occurred. */ class UnaryCall { constructor(method, requestHeaders, request, headers, response, status, trailers) { this.method = method; this.requestHeaders = requestHeaders; this.request = request; this.headers = headers; this.response = response; this.status = status; this.trailers = trailers; } /** * If you are only interested in the final outcome of this call, * you can await it to receive a `FinishedUnaryCall`. */ then(onfulfilled, onrejected) { return this.promiseFinished().then(value => onfulfilled ? Promise.resolve(onfulfilled(value)) : value, reason => onrejected ? Promise.resolve(onrejected(reason)) : Promise.reject(reason)); } promiseFinished() { return __awaiter(this, void 0, void 0, function* () { let [headers, response, status, trailers] = yield Promise.all([this.headers, this.response, this.status, this.trailers]); return { method: this.method, requestHeaders: this.requestHeaders, request: this.request, headers, response, status, trailers }; }); } } exports.UnaryCall = UnaryCall; /***/ }), /***/ 54253: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.assertFloat32 = exports.assertUInt32 = exports.assertInt32 = exports.assertNever = exports.assert = void 0; /** * assert that condition is true or throw error (with message) */ function assert(condition, msg) { if (!condition) { throw new Error(msg); } } exports.assert = assert; /** * assert that value cannot exist = type `never`. throw runtime error if it does. */ function assertNever(value, msg) { throw new Error(msg !== null && msg !== void 0 ? msg : 'Unexpected object: ' + value); } exports.assertNever = assertNever; const FLOAT32_MAX = 3.4028234663852886e+38, FLOAT32_MIN = -3.4028234663852886e+38, UINT32_MAX = 0xFFFFFFFF, INT32_MAX = 0X7FFFFFFF, INT32_MIN = -0X80000000; function assertInt32(arg) { if (typeof arg !== "number") throw new Error('invalid int 32: ' + typeof arg); if (!Number.isInteger(arg) || arg > INT32_MAX || arg < INT32_MIN) throw new Error('invalid int 32: ' + arg); } exports.assertInt32 = assertInt32; function assertUInt32(arg) { if (typeof arg !== "number") throw new Error('invalid uint 32: ' + typeof arg); if (!Number.isInteger(arg) || arg > UINT32_MAX || arg < 0) throw new Error('invalid uint 32: ' + arg); } exports.assertUInt32 = assertUInt32; function assertFloat32(arg) { if (typeof arg !== "number") throw new Error('invalid float 32: ' + typeof arg); if (!Number.isFinite(arg)) return; if (arg > FLOAT32_MAX || arg < FLOAT32_MIN) throw new Error('invalid float 32: ' + arg); } exports.assertFloat32 = assertFloat32; /***/ }), /***/ 20196: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.base64encode = exports.base64decode = void 0; // lookup table from base64 character to byte let encTable = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); // lookup table from base64 character *code* to byte because lookup by number is fast let decTable = []; for (let i = 0; i < encTable.length; i++) decTable[encTable[i].charCodeAt(0)] = i; // support base64url variants decTable["-".charCodeAt(0)] = encTable.indexOf("+"); decTable["_".charCodeAt(0)] = encTable.indexOf("/"); /** * Decodes a base64 string to a byte array. * * - ignores white-space, including line breaks and tabs * - allows inner padding (can decode concatenated base64 strings) * - does not require padding * - understands base64url encoding: * "-" instead of "+", * "_" instead of "/", * no padding */ function base64decode(base64Str) { // estimate byte size, not accounting for inner padding and whitespace let es = base64Str.length * 3 / 4; // if (es % 3 !== 0) // throw new Error('invalid base64 string'); if (base64Str[base64Str.length - 2] == '=') es -= 2; else if (base64Str[base64Str.length - 1] == '=') es -= 1; let bytes = new Uint8Array(es), bytePos = 0, // position in byte array groupPos = 0, // position in base64 group b, // current byte p = 0 // previous byte ; for (let i = 0; i < base64Str.length; i++) { b = decTable[base64Str.charCodeAt(i)]; if (b === undefined) { // noinspection FallThroughInSwitchStatementJS switch (base64Str[i]) { case '=': groupPos = 0; // reset state when padding found case '\n': case '\r': case '\t': case ' ': continue; // skip white-space, and padding default: throw Error(`invalid base64 string.`); } } switch (groupPos) { case 0: p = b; groupPos = 1; break; case 1: bytes[bytePos++] = p << 2 | (b & 48) >> 4; p = b; groupPos = 2; break; case 2: bytes[bytePos++] = (p & 15) << 4 | (b & 60) >> 2; p = b; groupPos = 3; break; case 3: bytes[bytePos++] = (p & 3) << 6 | b; groupPos = 0; break; } } if (groupPos == 1) throw Error(`invalid base64 string.`); return bytes.subarray(0, bytePos); } exports.base64decode = base64decode; /** * Encodes a byte array to a base64 string. * Adds padding at the end. * Does not insert newlines. */ function base64encode(bytes) { let base64 = '', groupPos = 0, // position in base64 group b, // current byte p = 0; // carry over from previous byte for (let i = 0; i < bytes.length; i++) { b = bytes[i]; switch (groupPos) { case 0: base64 += encTable[b >> 2]; p = (b & 3) << 4; groupPos = 1; break; case 1: base64 += encTable[p | b >> 4]; p = (b & 15) << 2; groupPos = 2; break; case 2: base64 += encTable[p | b >> 6]; base64 += encTable[b & 63]; groupPos = 0; break; } } // padding required? if (groupPos) { base64 += encTable[p]; base64 += '='; if (groupPos == 1) base64 += '='; } return base64; } exports.base64encode = base64encode; /***/ }), /***/ 84921: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.WireType = exports.mergeBinaryOptions = exports.UnknownFieldHandler = void 0; /** * This handler implements the default behaviour for unknown fields. * When reading data, unknown fields are stored on the message, in a * symbol property. * When writing data, the symbol property is queried and unknown fields * are serialized into the output again. */ var UnknownFieldHandler; (function (UnknownFieldHandler) { /** * The symbol used to store unknown fields for a message. * The property must conform to `UnknownFieldContainer`. */ UnknownFieldHandler.symbol = Symbol.for("protobuf-ts/unknown"); /** * Store an unknown field during binary read directly on the message. * This method is compatible with `BinaryReadOptions.readUnknownField`. */ UnknownFieldHandler.onRead = (typeName, message, fieldNo, wireType, data) => { let container = is(message) ? message[UnknownFieldHandler.symbol] : message[UnknownFieldHandler.symbol] = []; container.push({ no: fieldNo, wireType, data }); }; /** * Write unknown fields stored for the message to the writer. * This method is compatible with `BinaryWriteOptions.writeUnknownFields`. */ UnknownFieldHandler.onWrite = (typeName, message, writer) => { for (let { no, wireType, data } of UnknownFieldHandler.list(message)) writer.tag(no, wireType).raw(data); }; /** * List unknown fields stored for the message. * Note that there may be multiples fields with the same number. */ UnknownFieldHandler.list = (message, fieldNo) => { if (is(message)) { let all = message[UnknownFieldHandler.symbol]; return fieldNo ? all.filter(uf => uf.no == fieldNo) : all; } return []; }; /** * Returns the last unknown field by field number. */ UnknownFieldHandler.last = (message, fieldNo) => UnknownFieldHandler.list(message, fieldNo).slice(-1)[0]; const is = (message) => message && Array.isArray(message[UnknownFieldHandler.symbol]); })(UnknownFieldHandler = exports.UnknownFieldHandler || (exports.UnknownFieldHandler = {})); /** * Merges binary write or read options. Later values override earlier values. */ function mergeBinaryOptions(a, b) { return Object.assign(Object.assign({}, a), b); } exports.mergeBinaryOptions = mergeBinaryOptions; /** * Protobuf binary format wire types. * * A wire type provides just enough information to find the length of the * following value. * * See https://developers.google.com/protocol-buffers/docs/encoding#structure */ var WireType; (function (WireType) { /** * Used for int32, int64, uint32, uint64, sint32, sint64, bool, enum */ WireType[WireType["Varint"] = 0] = "Varint"; /** * Used for fixed64, sfixed64, double. * Always 8 bytes with little-endian byte order. */ WireType[WireType["Bit64"] = 1] = "Bit64"; /** * Used for string, bytes, embedded messages, packed repeated fields * * Only repeated numeric types (types which use the varint, 32-bit, * or 64-bit wire types) can be packed. In proto3, such fields are * packed by default. */ WireType[WireType["LengthDelimited"] = 2] = "LengthDelimited"; /** * Used for groups * @deprecated */ WireType[WireType["StartGroup"] = 3] = "StartGroup"; /** * Used for groups * @deprecated */ WireType[WireType["EndGroup"] = 4] = "EndGroup"; /** * Used for fixed32, sfixed32, float. * Always 4 bytes with little-endian byte order. */ WireType[WireType["Bit32"] = 5] = "Bit32"; })(WireType = exports.WireType || (exports.WireType = {})); /***/ }), /***/ 65210: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.BinaryReader = exports.binaryReadOptions = void 0; const binary_format_contract_1 = __nccwpck_require__(84921); const pb_long_1 = __nccwpck_require__(47777); const goog_varint_1 = __nccwpck_require__(30433); const defaultsRead = { readUnknownField: true, readerFactory: bytes => new BinaryReader(bytes), }; /** * Make options for reading binary data form partial options. */ function binaryReadOptions(options) { return options ? Object.assign(Object.assign({}, defaultsRead), options) : defaultsRead; } exports.binaryReadOptions = binaryReadOptions; class BinaryReader { constructor(buf, textDecoder) { this.varint64 = goog_varint_1.varint64read; // dirty cast for `this` /** * Read a `uint32` field, an unsigned 32 bit varint. */ this.uint32 = goog_varint_1.varint32read; // dirty cast for `this` and access to protected `buf` this.buf = buf; this.len = buf.length; this.pos = 0; this.view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength); this.textDecoder = textDecoder !== null && textDecoder !== void 0 ? textDecoder : new TextDecoder("utf-8", { fatal: true, ignoreBOM: true, }); } /** * Reads a tag - field number and wire type. */ tag() { let tag = this.uint32(), fieldNo = tag >>> 3, wireType = tag & 7; if (fieldNo <= 0 || wireType < 0 || wireType > 5) throw new Error("illegal tag: field no " + fieldNo + " wire type " + wireType); return [fieldNo, wireType]; } /** * Skip one element on the wire and return the skipped data. * Supports WireType.StartGroup since v2.0.0-alpha.23. */ skip(wireType) { let start = this.pos; // noinspection FallThroughInSwitchStatementJS switch (wireType) { case binary_format_contract_1.WireType.Varint: while (this.buf[this.pos++] & 0x80) { // ignore } break; case binary_format_contract_1.WireType.Bit64: this.pos += 4; case binary_format_contract_1.WireType.Bit32: this.pos += 4; break; case binary_format_contract_1.WireType.LengthDelimited: let len = this.uint32(); this.pos += len; break; case binary_format_contract_1.WireType.StartGroup: // From descriptor.proto: Group type is deprecated, not supported in proto3. // But we must still be able to parse and treat as unknown. let t; while ((t = this.tag()[1]) !== binary_format_contract_1.WireType.EndGroup) { this.skip(t); } break; default: throw new Error("cant skip wire type " + wireType); } this.assertBounds(); return this.buf.subarray(start, this.pos); } /** * Throws error if position in byte array is out of range. */ assertBounds() { if (this.pos > this.len) throw new RangeError("premature EOF"); } /** * Read a `int32` field, a signed 32 bit varint. */ int32() { return this.uint32() | 0; } /** * Read a `sint32` field, a signed, zigzag-encoded 32-bit varint. */ sint32() { let zze = this.uint32(); // decode zigzag return (zze >>> 1) ^ -(zze & 1); } /** * Read a `int64` field, a signed 64-bit varint. */ int64() { return new pb_long_1.PbLong(...this.varint64()); } /** * Read a `uint64` field, an unsigned 64-bit varint. */ uint64() { return new pb_long_1.PbULong(...this.varint64()); } /** * Read a `sint64` field, a signed, zig-zag-encoded 64-bit varint. */ sint64() { let [lo, hi] = this.varint64(); // decode zig zag let s = -(lo & 1); lo = ((lo >>> 1 | (hi & 1) << 31) ^ s); hi = (hi >>> 1 ^ s); return new pb_long_1.PbLong(lo, hi); } /** * Read a `bool` field, a variant. */ bool() { let [lo, hi] = this.varint64(); return lo !== 0 || hi !== 0; } /** * Read a `fixed32` field, an unsigned, fixed-length 32-bit integer. */ fixed32() { return this.view.getUint32((this.pos += 4) - 4, true); } /** * Read a `sfixed32` field, a signed, fixed-length 32-bit integer. */ sfixed32() { return this.view.getInt32((this.pos += 4) - 4, true); } /** * Read a `fixed64` field, an unsigned, fixed-length 64 bit integer. */ fixed64() { return new pb_long_1.PbULong(this.sfixed32(), this.sfixed32()); } /** * Read a `fixed64` field, a signed, fixed-length 64-bit integer. */ sfixed64() { return new pb_long_1.PbLong(this.sfixed32(), this.sfixed32()); } /** * Read a `float` field, 32-bit floating point number. */ float() { return this.view.getFloat32((this.pos += 4) - 4, true); } /** * Read a `double` field, a 64-bit floating point number. */ double() { return this.view.getFloat64((this.pos += 8) - 8, true); } /** * Read a `bytes` field, length-delimited arbitrary data. */ bytes() { let len = this.uint32(); let start = this.pos; this.pos += len; this.assertBounds(); return this.buf.subarray(start, start + len); } /** * Read a `string` field, length-delimited data converted to UTF-8 text. */ string() { return this.textDecoder.decode(this.bytes()); } } exports.BinaryReader = BinaryReader; /***/ }), /***/ 44354: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.BinaryWriter = exports.binaryWriteOptions = void 0; const pb_long_1 = __nccwpck_require__(47777); const goog_varint_1 = __nccwpck_require__(30433); const assert_1 = __nccwpck_require__(54253); const defaultsWrite = { writeUnknownFields: true, writerFactory: () => new BinaryWriter(), }; /** * Make options for writing binary data form partial options. */ function binaryWriteOptions(options) { return options ? Object.assign(Object.assign({}, defaultsWrite), options) : defaultsWrite; } exports.binaryWriteOptions = binaryWriteOptions; class BinaryWriter { constructor(textEncoder) { /** * Previous fork states. */ this.stack = []; this.textEncoder = textEncoder !== null && textEncoder !== void 0 ? textEncoder : new TextEncoder(); this.chunks = []; this.buf = []; } /** * Return all bytes written and reset this writer. */ finish() { this.chunks.push(new Uint8Array(this.buf)); // flush the buffer let len = 0; for (let i = 0; i < this.chunks.length; i++) len += this.chunks[i].length; let bytes = new Uint8Array(len); let offset = 0; for (let i = 0; i < this.chunks.length; i++) { bytes.set(this.chunks[i], offset); offset += this.chunks[i].length; } this.chunks = []; return bytes; } /** * Start a new fork for length-delimited data like a message * or a packed repeated field. * * Must be joined later with `join()`. */ fork() { this.stack.push({ chunks: this.chunks, buf: this.buf }); this.chunks = []; this.buf = []; return this; } /** * Join the last fork. Write its length and bytes, then * return to the previous state. */ join() { // get chunk of fork let chunk = this.finish(); // restore previous state let prev = this.stack.pop(); if (!prev) throw new Error('invalid state, fork stack empty'); this.chunks = prev.chunks; this.buf = prev.buf; // write length of chunk as varint this.uint32(chunk.byteLength); return this.raw(chunk); } /** * Writes a tag (field number and wire type). * * Equivalent to `uint32( (fieldNo << 3 | type) >>> 0 )`. * * Generated code should compute the tag ahead of time and call `uint32()`. */ tag(fieldNo, type) { return this.uint32((fieldNo << 3 | type) >>> 0); } /** * Write a chunk of raw bytes. */ raw(chunk) { if (this.buf.length) { this.chunks.push(new Uint8Array(this.buf)); this.buf = []; } this.chunks.push(chunk); return this; } /** * Write a `uint32` value, an unsigned 32 bit varint. */ uint32(value) { assert_1.assertUInt32(value); // write value as varint 32, inlined for speed while (value > 0x7f) { this.buf.push((value & 0x7f) | 0x80); value = value >>> 7; } this.buf.push(value); return this; } /** * Write a `int32` value, a signed 32 bit varint. */ int32(value) { assert_1.assertInt32(value); goog_varint_1.varint32write(value, this.buf); return this; } /** * Write a `bool` value, a variant. */ bool(value) { this.buf.push(value ? 1 : 0); return this; } /** * Write a `bytes` value, length-delimited arbitrary data. */ bytes(value) { this.uint32(value.byteLength); // write length of chunk as varint return this.raw(value); } /** * Write a `string` value, length-delimited data converted to UTF-8 text. */ string(value) { let chunk = this.textEncoder.encode(value); this.uint32(chunk.byteLength); // write length of chunk as varint return this.raw(chunk); } /** * Write a `float` value, 32-bit floating point number. */ float(value) { assert_1.assertFloat32(value); let chunk = new Uint8Array(4); new DataView(chunk.buffer).setFloat32(0, value, true); return this.raw(chunk); } /** * Write a `double` value, a 64-bit floating point number. */ double(value) { let chunk = new Uint8Array(8); new DataView(chunk.buffer).setFloat64(0, value, true); return this.raw(chunk); } /** * Write a `fixed32` value, an unsigned, fixed-length 32-bit integer. */ fixed32(value) { assert_1.assertUInt32(value); let chunk = new Uint8Array(4); new DataView(chunk.buffer).setUint32(0, value, true); return this.raw(chunk); } /** * Write a `sfixed32` value, a signed, fixed-length 32-bit integer. */ sfixed32(value) { assert_1.assertInt32(value); let chunk = new Uint8Array(4); new DataView(chunk.buffer).setInt32(0, value, true); return this.raw(chunk); } /** * Write a `sint32` value, a signed, zigzag-encoded 32-bit varint. */ sint32(value) { assert_1.assertInt32(value); // zigzag encode value = ((value << 1) ^ (value >> 31)) >>> 0; goog_varint_1.varint32write(value, this.buf); return this; } /** * Write a `fixed64` value, a signed, fixed-length 64-bit integer. */ sfixed64(value) { let chunk = new Uint8Array(8); let view = new DataView(chunk.buffer); let long = pb_long_1.PbLong.from(value); view.setInt32(0, long.lo, true); view.setInt32(4, long.hi, true); return this.raw(chunk); } /** * Write a `fixed64` value, an unsigned, fixed-length 64 bit integer. */ fixed64(value) { let chunk = new Uint8Array(8); let view = new DataView(chunk.buffer); let long = pb_long_1.PbULong.from(value); view.setInt32(0, long.lo, true); view.setInt32(4, long.hi, true); return this.raw(chunk); } /** * Write a `int64` value, a signed 64-bit varint. */ int64(value) { let long = pb_long_1.PbLong.from(value); goog_varint_1.varint64write(long.lo, long.hi, this.buf); return this; } /** * Write a `sint64` value, a signed, zig-zag-encoded 64-bit varint. */ sint64(value) { let long = pb_long_1.PbLong.from(value), // zigzag encode sign = long.hi >> 31, lo = (long.lo << 1) ^ sign, hi = ((long.hi << 1) | (long.lo >>> 31)) ^ sign; goog_varint_1.varint64write(lo, hi, this.buf); return this; } /** * Write a `uint64` value, an unsigned 64-bit varint. */ uint64(value) { let long = pb_long_1.PbULong.from(value); goog_varint_1.varint64write(long.lo, long.hi, this.buf); return this; } } exports.BinaryWriter = BinaryWriter; /***/ }), /***/ 20085: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.listEnumNumbers = exports.listEnumNames = exports.listEnumValues = exports.isEnumObject = void 0; /** * Is this a lookup object generated by Typescript, for a Typescript enum * generated by protobuf-ts? * * - No `const enum` (enum must not be inlined, we need reverse mapping). * - No string enum (we need int32 for protobuf). * - Must have a value for 0 (otherwise, we would need to support custom default values). */ function isEnumObject(arg) { if (typeof arg != 'object' || arg === null) { return false; } if (!arg.hasOwnProperty(0)) { return false; } for (let k of Object.keys(arg)) { let num = parseInt(k); if (!Number.isNaN(num)) { // is there a name for the number? let nam = arg[num]; if (nam === undefined) return false; // does the name resolve back to the number? if (arg[nam] !== num) return false; } else { // is there a number for the name? let num = arg[k]; if (num === undefined) return false; // is it a string enum? if (typeof num !== 'number') return false; // do we know the number? if (arg[num] === undefined) return false; } } return true; } exports.isEnumObject = isEnumObject; /** * Lists all values of a Typescript enum, as an array of objects with a "name" * property and a "number" property. * * Note that it is possible that a number appears more than once, because it is * possible to have aliases in an enum. * * Throws if the enum does not adhere to the rules of enums generated by * protobuf-ts. See `isEnumObject()`. */ function listEnumValues(enumObject) { if (!isEnumObject(enumObject)) throw new Error("not a typescript enum object"); let values = []; for (let [name, number] of Object.entries(enumObject)) if (typeof number == "number") values.push({ name, number }); return values; } exports.listEnumValues = listEnumValues; /** * Lists the names of a Typescript enum. * * Throws if the enum does not adhere to the rules of enums generated by * protobuf-ts. See `isEnumObject()`. */ function listEnumNames(enumObject) { return listEnumValues(enumObject).map(val => val.name); } exports.listEnumNames = listEnumNames; /** * Lists the numbers of a Typescript enum. * * Throws if the enum does not adhere to the rules of enums generated by * protobuf-ts. See `isEnumObject()`. */ function listEnumNumbers(enumObject) { return listEnumValues(enumObject) .map(val => val.number) .filter((num, index, arr) => arr.indexOf(num) == index); } exports.listEnumNumbers = listEnumNumbers; /***/ }), /***/ 30433: /***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright 2008 Google Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Code generated by the Protocol Buffer compiler is owned by the owner // of the input file used when generating it. This code is not // standalone and requires a support library to be linked with it. This // support library is itself covered by the above license. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.varint32read = exports.varint32write = exports.int64toString = exports.int64fromString = exports.varint64write = exports.varint64read = void 0; /** * Read a 64 bit varint as two JS numbers. * * Returns tuple: * [0]: low bits * [0]: high bits * * Copyright 2008 Google Inc. All rights reserved. * * See https://github.com/protocolbuffers/protobuf/blob/8a71927d74a4ce34efe2d8769fda198f52d20d12/js/experimental/runtime/kernel/buffer_decoder.js#L175 */ function varint64read() { let lowBits = 0; let highBits = 0; for (let shift = 0; shift < 28; shift += 7) { let b = this.buf[this.pos++]; lowBits |= (b & 0x7F) << shift; if ((b & 0x80) == 0) { this.assertBounds(); return [lowBits, highBits]; } } let middleByte = this.buf[this.pos++]; // last four bits of the first 32 bit number lowBits |= (middleByte & 0x0F) << 28; // 3 upper bits are part of the next 32 bit number highBits = (middleByte & 0x70) >> 4; if ((middleByte & 0x80) == 0) { this.assertBounds(); return [lowBits, highBits]; } for (let shift = 3; shift <= 31; shift += 7) { let b = this.buf[this.pos++]; highBits |= (b & 0x7F) << shift; if ((b & 0x80) == 0) { this.assertBounds(); return [lowBits, highBits]; } } throw new Error('invalid varint'); } exports.varint64read = varint64read; /** * Write a 64 bit varint, given as two JS numbers, to the given bytes array. * * Copyright 2008 Google Inc. All rights reserved. * * See https://github.com/protocolbuffers/protobuf/blob/8a71927d74a4ce34efe2d8769fda198f52d20d12/js/experimental/runtime/kernel/writer.js#L344 */ function varint64write(lo, hi, bytes) { for (let i = 0; i < 28; i = i + 7) { const shift = lo >>> i; const hasNext = !((shift >>> 7) == 0 && hi == 0); const byte = (hasNext ? shift | 0x80 : shift) & 0xFF; bytes.push(byte); if (!hasNext) { return; } } const splitBits = ((lo >>> 28) & 0x0F) | ((hi & 0x07) << 4); const hasMoreBits = !((hi >> 3) == 0); bytes.push((hasMoreBits ? splitBits | 0x80 : splitBits) & 0xFF); if (!hasMoreBits) { return; } for (let i = 3; i < 31; i = i + 7) { const shift = hi >>> i; const hasNext = !((shift >>> 7) == 0); const byte = (hasNext ? shift | 0x80 : shift) & 0xFF; bytes.push(byte); if (!hasNext) { return; } } bytes.push((hi >>> 31) & 0x01); } exports.varint64write = varint64write; // constants for binary math const TWO_PWR_32_DBL = (1 << 16) * (1 << 16); /** * Parse decimal string of 64 bit integer value as two JS numbers. * * Returns tuple: * [0]: minus sign? * [1]: low bits * [2]: high bits * * Copyright 2008 Google Inc. */ function int64fromString(dec) { // Check for minus sign. let minus = dec[0] == '-'; if (minus) dec = dec.slice(1); // Work 6 decimal digits at a time, acting like we're converting base 1e6 // digits to binary. This is safe to do with floating point math because // Number.isSafeInteger(ALL_32_BITS * 1e6) == true. const base = 1e6; let lowBits = 0; let highBits = 0; function add1e6digit(begin, end) { // Note: Number('') is 0. const digit1e6 = Number(dec.slice(begin, end)); highBits *= base; lowBits = lowBits * base + digit1e6; // Carry bits from lowBits to highBits if (lowBits >= TWO_PWR_32_DBL) { highBits = highBits + ((lowBits / TWO_PWR_32_DBL) | 0); lowBits = lowBits % TWO_PWR_32_DBL; } } add1e6digit(-24, -18); add1e6digit(-18, -12); add1e6digit(-12, -6); add1e6digit(-6); return [minus, lowBits, highBits]; } exports.int64fromString = int64fromString; /** * Format 64 bit integer value (as two JS numbers) to decimal string. * * Copyright 2008 Google Inc. */ function int64toString(bitsLow, bitsHigh) { // Skip the expensive conversion if the number is small enough to use the // built-in conversions. if ((bitsHigh >>> 0) <= 0x1FFFFF) { return '' + (TWO_PWR_32_DBL * bitsHigh + (bitsLow >>> 0)); } // What this code is doing is essentially converting the input number from // base-2 to base-1e7, which allows us to represent the 64-bit range with // only 3 (very large) digits. Those digits are then trivial to convert to // a base-10 string. // The magic numbers used here are - // 2^24 = 16777216 = (1,6777216) in base-1e7. // 2^48 = 281474976710656 = (2,8147497,6710656) in base-1e7. // Split 32:32 representation into 16:24:24 representation so our // intermediate digits don't overflow. let low = bitsLow & 0xFFFFFF; let mid = (((bitsLow >>> 24) | (bitsHigh << 8)) >>> 0) & 0xFFFFFF; let high = (bitsHigh >> 16) & 0xFFFF; // Assemble our three base-1e7 digits, ignoring carries. The maximum // value in a digit at this step is representable as a 48-bit integer, which // can be stored in a 64-bit floating point number. let digitA = low + (mid * 6777216) + (high * 6710656); let digitB = mid + (high * 8147497); let digitC = (high * 2); // Apply carries from A to B and from B to C. let base = 10000000; if (digitA >= base) { digitB += Math.floor(digitA / base); digitA %= base; } if (digitB >= base) { digitC += Math.floor(digitB / base); digitB %= base; } // Convert base-1e7 digits to base-10, with optional leading zeroes. function decimalFrom1e7(digit1e7, needLeadingZeros) { let partial = digit1e7 ? String(digit1e7) : ''; if (needLeadingZeros) { return '0000000'.slice(partial.length) + partial; } return partial; } return decimalFrom1e7(digitC, /*needLeadingZeros=*/ 0) + decimalFrom1e7(digitB, /*needLeadingZeros=*/ digitC) + // If the final 1e7 digit didn't need leading zeros, we would have // returned via the trivial code path at the top. decimalFrom1e7(digitA, /*needLeadingZeros=*/ 1); } exports.int64toString = int64toString; /** * Write a 32 bit varint, signed or unsigned. Same as `varint64write(0, value, bytes)` * * Copyright 2008 Google Inc. All rights reserved. * * See https://github.com/protocolbuffers/protobuf/blob/1b18833f4f2a2f681f4e4a25cdf3b0a43115ec26/js/binary/encoder.js#L144 */ function varint32write(value, bytes) { if (value >= 0) { // write value as varint 32 while (value > 0x7f) { bytes.push((value & 0x7f) | 0x80); value = value >>> 7; } bytes.push(value); } else { for (let i = 0; i < 9; i++) { bytes.push(value & 127 | 128); value = value >> 7; } bytes.push(1); } } exports.varint32write = varint32write; /** * Read an unsigned 32 bit varint. * * See https://github.com/protocolbuffers/protobuf/blob/8a71927d74a4ce34efe2d8769fda198f52d20d12/js/experimental/runtime/kernel/buffer_decoder.js#L220 */ function varint32read() { let b = this.buf[this.pos++]; let result = b & 0x7F; if ((b & 0x80) == 0) { this.assertBounds(); return result; } b = this.buf[this.pos++]; result |= (b & 0x7F) << 7; if ((b & 0x80) == 0) { this.assertBounds(); return result; } b = this.buf[this.pos++]; result |= (b & 0x7F) << 14; if ((b & 0x80) == 0) { this.assertBounds(); return result; } b = this.buf[this.pos++]; result |= (b & 0x7F) << 21; if ((b & 0x80) == 0) { this.assertBounds(); return result; } // Extract only last 4 bits b = this.buf[this.pos++]; result |= (b & 0x0F) << 28; for (let readBytes = 5; ((b & 0x80) !== 0) && readBytes < 10; readBytes++) b = this.buf[this.pos++]; if ((b & 0x80) != 0) throw new Error('invalid varint'); this.assertBounds(); // Result can have 32 bits, convert it to unsigned return result >>> 0; } exports.varint32read = varint32read; /***/ }), /***/ 37001: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Public API of the protobuf-ts runtime. // Note: we do not use `export * from ...` to help tree shakers, // webpack verbose output hints that this should be useful Object.defineProperty(exports, "__esModule", ({ value: true })); // Convenience JSON typings and corresponding type guards var json_typings_1 = __nccwpck_require__(70661); Object.defineProperty(exports, "typeofJsonValue", ({ enumerable: true, get: function () { return json_typings_1.typeofJsonValue; } })); Object.defineProperty(exports, "isJsonObject", ({ enumerable: true, get: function () { return json_typings_1.isJsonObject; } })); // Base 64 encoding var base64_1 = __nccwpck_require__(20196); Object.defineProperty(exports, "base64decode", ({ enumerable: true, get: function () { return base64_1.base64decode; } })); Object.defineProperty(exports, "base64encode", ({ enumerable: true, get: function () { return base64_1.base64encode; } })); // UTF8 encoding var protobufjs_utf8_1 = __nccwpck_require__(95290); Object.defineProperty(exports, "utf8read", ({ enumerable: true, get: function () { return protobufjs_utf8_1.utf8read; } })); // Binary format contracts, options for reading and writing, for example var binary_format_contract_1 = __nccwpck_require__(84921); Object.defineProperty(exports, "WireType", ({ enumerable: true, get: function () { return binary_format_contract_1.WireType; } })); Object.defineProperty(exports, "mergeBinaryOptions", ({ enumerable: true, get: function () { return binary_format_contract_1.mergeBinaryOptions; } })); Object.defineProperty(exports, "UnknownFieldHandler", ({ enumerable: true, get: function () { return binary_format_contract_1.UnknownFieldHandler; } })); // Standard IBinaryReader implementation var binary_reader_1 = __nccwpck_require__(65210); Object.defineProperty(exports, "BinaryReader", ({ enumerable: true, get: function () { return binary_reader_1.BinaryReader; } })); Object.defineProperty(exports, "binaryReadOptions", ({ enumerable: true, get: function () { return binary_reader_1.binaryReadOptions; } })); // Standard IBinaryWriter implementation var binary_writer_1 = __nccwpck_require__(44354); Object.defineProperty(exports, "BinaryWriter", ({ enumerable: true, get: function () { return binary_writer_1.BinaryWriter; } })); Object.defineProperty(exports, "binaryWriteOptions", ({ enumerable: true, get: function () { return binary_writer_1.binaryWriteOptions; } })); // Int64 and UInt64 implementations required for the binary format var pb_long_1 = __nccwpck_require__(47777); Object.defineProperty(exports, "PbLong", ({ enumerable: true, get: function () { return pb_long_1.PbLong; } })); Object.defineProperty(exports, "PbULong", ({ enumerable: true, get: function () { return pb_long_1.PbULong; } })); // JSON format contracts, options for reading and writing, for example var json_format_contract_1 = __nccwpck_require__(48139); Object.defineProperty(exports, "jsonReadOptions", ({ enumerable: true, get: function () { return json_format_contract_1.jsonReadOptions; } })); Object.defineProperty(exports, "jsonWriteOptions", ({ enumerable: true, get: function () { return json_format_contract_1.jsonWriteOptions; } })); Object.defineProperty(exports, "mergeJsonOptions", ({ enumerable: true, get: function () { return json_format_contract_1.mergeJsonOptions; } })); // Message type contract var message_type_contract_1 = __nccwpck_require__(1682); Object.defineProperty(exports, "MESSAGE_TYPE", ({ enumerable: true, get: function () { return message_type_contract_1.MESSAGE_TYPE; } })); // Message type implementation via reflection var message_type_1 = __nccwpck_require__(63664); Object.defineProperty(exports, "MessageType", ({ enumerable: true, get: function () { return message_type_1.MessageType; } })); // Reflection info, generated by the plugin, exposed to the user, used by reflection ops var reflection_info_1 = __nccwpck_require__(21370); Object.defineProperty(exports, "ScalarType", ({ enumerable: true, get: function () { return reflection_info_1.ScalarType; } })); Object.defineProperty(exports, "LongType", ({ enumerable: true, get: function () { return reflection_info_1.LongType; } })); Object.defineProperty(exports, "RepeatType", ({ enumerable: true, get: function () { return reflection_info_1.RepeatType; } })); Object.defineProperty(exports, "normalizeFieldInfo", ({ enumerable: true, get: function () { return reflection_info_1.normalizeFieldInfo; } })); Object.defineProperty(exports, "readFieldOptions", ({ enumerable: true, get: function () { return reflection_info_1.readFieldOptions; } })); Object.defineProperty(exports, "readFieldOption", ({ enumerable: true, get: function () { return reflection_info_1.readFieldOption; } })); Object.defineProperty(exports, "readMessageOption", ({ enumerable: true, get: function () { return reflection_info_1.readMessageOption; } })); // Message operations via reflection var reflection_type_check_1 = __nccwpck_require__(20903); Object.defineProperty(exports, "ReflectionTypeCheck", ({ enumerable: true, get: function () { return reflection_type_check_1.ReflectionTypeCheck; } })); var reflection_create_1 = __nccwpck_require__(60390); Object.defineProperty(exports, "reflectionCreate", ({ enumerable: true, get: function () { return reflection_create_1.reflectionCreate; } })); var reflection_scalar_default_1 = __nccwpck_require__(74863); Object.defineProperty(exports, "reflectionScalarDefault", ({ enumerable: true, get: function () { return reflection_scalar_default_1.reflectionScalarDefault; } })); var reflection_merge_partial_1 = __nccwpck_require__(7869); Object.defineProperty(exports, "reflectionMergePartial", ({ enumerable: true, get: function () { return reflection_merge_partial_1.reflectionMergePartial; } })); var reflection_equals_1 = __nccwpck_require__(39473); Object.defineProperty(exports, "reflectionEquals", ({ enumerable: true, get: function () { return reflection_equals_1.reflectionEquals; } })); var reflection_binary_reader_1 = __nccwpck_require__(91593); Object.defineProperty(exports, "ReflectionBinaryReader", ({ enumerable: true, get: function () { return reflection_binary_reader_1.ReflectionBinaryReader; } })); var reflection_binary_writer_1 = __nccwpck_require__(57170); Object.defineProperty(exports, "ReflectionBinaryWriter", ({ enumerable: true, get: function () { return reflection_binary_writer_1.ReflectionBinaryWriter; } })); var reflection_json_reader_1 = __nccwpck_require__(229); Object.defineProperty(exports, "ReflectionJsonReader", ({ enumerable: true, get: function () { return reflection_json_reader_1.ReflectionJsonReader; } })); var reflection_json_writer_1 = __nccwpck_require__(68980); Object.defineProperty(exports, "ReflectionJsonWriter", ({ enumerable: true, get: function () { return reflection_json_writer_1.ReflectionJsonWriter; } })); var reflection_contains_message_type_1 = __nccwpck_require__(67317); Object.defineProperty(exports, "containsMessageType", ({ enumerable: true, get: function () { return reflection_contains_message_type_1.containsMessageType; } })); // Oneof helpers var oneof_1 = __nccwpck_require__(78531); Object.defineProperty(exports, "isOneofGroup", ({ enumerable: true, get: function () { return oneof_1.isOneofGroup; } })); Object.defineProperty(exports, "setOneofValue", ({ enumerable: true, get: function () { return oneof_1.setOneofValue; } })); Object.defineProperty(exports, "getOneofValue", ({ enumerable: true, get: function () { return oneof_1.getOneofValue; } })); Object.defineProperty(exports, "clearOneofValue", ({ enumerable: true, get: function () { return oneof_1.clearOneofValue; } })); Object.defineProperty(exports, "getSelectedOneofValue", ({ enumerable: true, get: function () { return oneof_1.getSelectedOneofValue; } })); // Enum object type guard and reflection util, may be interesting to the user. var enum_object_1 = __nccwpck_require__(20085); Object.defineProperty(exports, "listEnumValues", ({ enumerable: true, get: function () { return enum_object_1.listEnumValues; } })); Object.defineProperty(exports, "listEnumNames", ({ enumerable: true, get: function () { return enum_object_1.listEnumNames; } })); Object.defineProperty(exports, "listEnumNumbers", ({ enumerable: true, get: function () { return enum_object_1.listEnumNumbers; } })); Object.defineProperty(exports, "isEnumObject", ({ enumerable: true, get: function () { return enum_object_1.isEnumObject; } })); // lowerCamelCase() is exported for plugin, rpc-runtime and other rpc packages var lower_camel_case_1 = __nccwpck_require__(34772); Object.defineProperty(exports, "lowerCamelCase", ({ enumerable: true, get: function () { return lower_camel_case_1.lowerCamelCase; } })); // assertion functions are exported for plugin, may also be useful to user var assert_1 = __nccwpck_require__(54253); Object.defineProperty(exports, "assert", ({ enumerable: true, get: function () { return assert_1.assert; } })); Object.defineProperty(exports, "assertNever", ({ enumerable: true, get: function () { return assert_1.assertNever; } })); Object.defineProperty(exports, "assertInt32", ({ enumerable: true, get: function () { return assert_1.assertInt32; } })); Object.defineProperty(exports, "assertUInt32", ({ enumerable: true, get: function () { return assert_1.assertUInt32; } })); Object.defineProperty(exports, "assertFloat32", ({ enumerable: true, get: function () { return assert_1.assertFloat32; } })); /***/ }), /***/ 48139: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.mergeJsonOptions = exports.jsonWriteOptions = exports.jsonReadOptions = void 0; const defaultsWrite = { emitDefaultValues: false, enumAsInteger: false, useProtoFieldName: false, prettySpaces: 0, }, defaultsRead = { ignoreUnknownFields: false, }; /** * Make options for reading JSON data from partial options. */ function jsonReadOptions(options) { return options ? Object.assign(Object.assign({}, defaultsRead), options) : defaultsRead; } exports.jsonReadOptions = jsonReadOptions; /** * Make options for writing JSON data from partial options. */ function jsonWriteOptions(options) { return options ? Object.assign(Object.assign({}, defaultsWrite), options) : defaultsWrite; } exports.jsonWriteOptions = jsonWriteOptions; /** * Merges JSON write or read options. Later values override earlier values. Type registries are merged. */ function mergeJsonOptions(a, b) { var _a, _b; let c = Object.assign(Object.assign({}, a), b); c.typeRegistry = [...((_a = a === null || a === void 0 ? void 0 : a.typeRegistry) !== null && _a !== void 0 ? _a : []), ...((_b = b === null || b === void 0 ? void 0 : b.typeRegistry) !== null && _b !== void 0 ? _b : [])]; return c; } exports.mergeJsonOptions = mergeJsonOptions; /***/ }), /***/ 70661: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isJsonObject = exports.typeofJsonValue = void 0; /** * Get the type of a JSON value. * Distinguishes between array, null and object. */ function typeofJsonValue(value) { let t = typeof value; if (t == "object") { if (Array.isArray(value)) return "array"; if (value === null) return "null"; } return t; } exports.typeofJsonValue = typeofJsonValue; /** * Is this a JSON object (instead of an array or null)? */ function isJsonObject(value) { return value !== null && typeof value == "object" && !Array.isArray(value); } exports.isJsonObject = isJsonObject; /***/ }), /***/ 34772: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.lowerCamelCase = void 0; /** * Converts snake_case to lowerCamelCase. * * Should behave like protoc: * https://github.com/protocolbuffers/protobuf/blob/e8ae137c96444ea313485ed1118c5e43b2099cf1/src/google/protobuf/compiler/java/java_helpers.cc#L118 */ function lowerCamelCase(snakeCase) { let capNext = false; const sb = []; for (let i = 0; i < snakeCase.length; i++) { let next = snakeCase.charAt(i); if (next == '_') { capNext = true; } else if (/\d/.test(next)) { sb.push(next); capNext = true; } else if (capNext) { sb.push(next.toUpperCase()); capNext = false; } else if (i == 0) { sb.push(next.toLowerCase()); } else { sb.push(next); } } return sb.join(''); } exports.lowerCamelCase = lowerCamelCase; /***/ }), /***/ 1682: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.MESSAGE_TYPE = void 0; /** * The symbol used as a key on message objects to store the message type. * * Note that this is an experimental feature - it is here to stay, but * implementation details may change without notice. */ exports.MESSAGE_TYPE = Symbol.for("protobuf-ts/message-type"); /***/ }), /***/ 63664: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.MessageType = void 0; const message_type_contract_1 = __nccwpck_require__(1682); const reflection_info_1 = __nccwpck_require__(21370); const reflection_type_check_1 = __nccwpck_require__(20903); const reflection_json_reader_1 = __nccwpck_require__(229); const reflection_json_writer_1 = __nccwpck_require__(68980); const reflection_binary_reader_1 = __nccwpck_require__(91593); const reflection_binary_writer_1 = __nccwpck_require__(57170); const reflection_create_1 = __nccwpck_require__(60390); const reflection_merge_partial_1 = __nccwpck_require__(7869); const json_typings_1 = __nccwpck_require__(70661); const json_format_contract_1 = __nccwpck_require__(48139); const reflection_equals_1 = __nccwpck_require__(39473); const binary_writer_1 = __nccwpck_require__(44354); const binary_reader_1 = __nccwpck_require__(65210); const baseDescriptors = Object.getOwnPropertyDescriptors(Object.getPrototypeOf({})); /** * This standard message type provides reflection-based * operations to work with a message. */ class MessageType { constructor(name, fields, options) { this.defaultCheckDepth = 16; this.typeName = name; this.fields = fields.map(reflection_info_1.normalizeFieldInfo); this.options = options !== null && options !== void 0 ? options : {}; this.messagePrototype = Object.create(null, Object.assign(Object.assign({}, baseDescriptors), { [message_type_contract_1.MESSAGE_TYPE]: { value: this } })); this.refTypeCheck = new reflection_type_check_1.ReflectionTypeCheck(this); this.refJsonReader = new reflection_json_reader_1.ReflectionJsonReader(this); this.refJsonWriter = new reflection_json_writer_1.ReflectionJsonWriter(this); this.refBinReader = new reflection_binary_reader_1.ReflectionBinaryReader(this); this.refBinWriter = new reflection_binary_writer_1.ReflectionBinaryWriter(this); } create(value) { let message = reflection_create_1.reflectionCreate(this); if (value !== undefined) { reflection_merge_partial_1.reflectionMergePartial(this, message, value); } return message; } /** * Clone the message. * * Unknown fields are discarded. */ clone(message) { let copy = this.create(); reflection_merge_partial_1.reflectionMergePartial(this, copy, message); return copy; } /** * Determines whether two message of the same type have the same field values. * Checks for deep equality, traversing repeated fields, oneof groups, maps * and messages recursively. * Will also return true if both messages are `undefined`. */ equals(a, b) { return reflection_equals_1.reflectionEquals(this, a, b); } /** * Is the given value assignable to our message type * and contains no [excess properties](https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks)? */ is(arg, depth = this.defaultCheckDepth) { return this.refTypeCheck.is(arg, depth, false); } /** * Is the given value assignable to our message type, * regardless of [excess properties](https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks)? */ isAssignable(arg, depth = this.defaultCheckDepth) { return this.refTypeCheck.is(arg, depth, true); } /** * Copy partial data into the target message. */ mergePartial(target, source) { reflection_merge_partial_1.reflectionMergePartial(this, target, source); } /** * Create a new message from binary format. */ fromBinary(data, options) { let opt = binary_reader_1.binaryReadOptions(options); return this.internalBinaryRead(opt.readerFactory(data), data.byteLength, opt); } /** * Read a new message from a JSON value. */ fromJson(json, options) { return this.internalJsonRead(json, json_format_contract_1.jsonReadOptions(options)); } /** * Read a new message from a JSON string. * This is equivalent to `T.fromJson(JSON.parse(json))`. */ fromJsonString(json, options) { let value = JSON.parse(json); return this.fromJson(value, options); } /** * Write the message to canonical JSON value. */ toJson(message, options) { return this.internalJsonWrite(message, json_format_contract_1.jsonWriteOptions(options)); } /** * Convert the message to canonical JSON string. * This is equivalent to `JSON.stringify(T.toJson(t))` */ toJsonString(message, options) { var _a; let value = this.toJson(message, options); return JSON.stringify(value, null, (_a = options === null || options === void 0 ? void 0 : options.prettySpaces) !== null && _a !== void 0 ? _a : 0); } /** * Write the message to binary format. */ toBinary(message, options) { let opt = binary_writer_1.binaryWriteOptions(options); return this.internalBinaryWrite(message, opt.writerFactory(), opt).finish(); } /** * This is an internal method. If you just want to read a message from * JSON, use `fromJson()` or `fromJsonString()`. * * Reads JSON value and merges the fields into the target * according to protobuf rules. If the target is omitted, * a new instance is created first. */ internalJsonRead(json, options, target) { if (json !== null && typeof json == "object" && !Array.isArray(json)) { let message = target !== null && target !== void 0 ? target : this.create(); this.refJsonReader.read(json, message, options); return message; } throw new Error(`Unable to parse message ${this.typeName} from JSON ${json_typings_1.typeofJsonValue(json)}.`); } /** * This is an internal method. If you just want to write a message * to JSON, use `toJson()` or `toJsonString(). * * Writes JSON value and returns it. */ internalJsonWrite(message, options) { return this.refJsonWriter.write(message, options); } /** * This is an internal method. If you just want to write a message * in binary format, use `toBinary()`. * * Serializes the message in binary format and appends it to the given * writer. Returns passed writer. */ internalBinaryWrite(message, writer, options) { this.refBinWriter.write(message, writer, options); return writer; } /** * This is an internal method. If you just want to read a message from * binary data, use `fromBinary()`. * * Reads data from binary format and merges the fields into * the target according to protobuf rules. If the target is * omitted, a new instance is created first. */ internalBinaryRead(reader, length, options, target) { let message = target !== null && target !== void 0 ? target : this.create(); this.refBinReader.read(reader, message, options, length); return message; } } exports.MessageType = MessageType; /***/ }), /***/ 78531: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getSelectedOneofValue = exports.clearOneofValue = exports.setUnknownOneofValue = exports.setOneofValue = exports.getOneofValue = exports.isOneofGroup = void 0; /** * Is the given value a valid oneof group? * * We represent protobuf `oneof` as algebraic data types (ADT) in generated * code. But when working with messages of unknown type, the ADT does not * help us. * * This type guard checks if the given object adheres to the ADT rules, which * are as follows: * * 1) Must be an object. * * 2) Must have a "oneofKind" discriminator property. * * 3) If "oneofKind" is `undefined`, no member field is selected. The object * must not have any other properties. * * 4) If "oneofKind" is a `string`, the member field with this name is * selected. * * 5) If a member field is selected, the object must have a second property * with this name. The property must not be `undefined`. * * 6) No extra properties are allowed. The object has either one property * (no selection) or two properties (selection). * */ function isOneofGroup(any) { if (typeof any != 'object' || any === null || !any.hasOwnProperty('oneofKind')) { return false; } switch (typeof any.oneofKind) { case "string": if (any[any.oneofKind] === undefined) return false; return Object.keys(any).length == 2; case "undefined": return Object.keys(any).length == 1; default: return false; } } exports.isOneofGroup = isOneofGroup; /** * Returns the value of the given field in a oneof group. */ function getOneofValue(oneof, kind) { return oneof[kind]; } exports.getOneofValue = getOneofValue; function setOneofValue(oneof, kind, value) { if (oneof.oneofKind !== undefined) { delete oneof[oneof.oneofKind]; } oneof.oneofKind = kind; if (value !== undefined) { oneof[kind] = value; } } exports.setOneofValue = setOneofValue; function setUnknownOneofValue(oneof, kind, value) { if (oneof.oneofKind !== undefined) { delete oneof[oneof.oneofKind]; } oneof.oneofKind = kind; if (value !== undefined && kind !== undefined) { oneof[kind] = value; } } exports.setUnknownOneofValue = setUnknownOneofValue; /** * Removes the selected field in a oneof group. * * Note that the recommended way to modify a oneof group is to set * a new object: * * ```ts * message.result = { oneofKind: undefined }; * ``` */ function clearOneofValue(oneof) { if (oneof.oneofKind !== undefined) { delete oneof[oneof.oneofKind]; } oneof.oneofKind = undefined; } exports.clearOneofValue = clearOneofValue; /** * Returns the selected value of the given oneof group. * * Not that the recommended way to access a oneof group is to check * the "oneofKind" property and let TypeScript narrow down the union * type for you: * * ```ts * if (message.result.oneofKind === "error") { * message.result.error; // string * } * ``` * * In the rare case you just need the value, and do not care about * which protobuf field is selected, you can use this function * for convenience. */ function getSelectedOneofValue(oneof) { if (oneof.oneofKind === undefined) { return undefined; } return oneof[oneof.oneofKind]; } exports.getSelectedOneofValue = getSelectedOneofValue; /***/ }), /***/ 47777: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.PbLong = exports.PbULong = exports.detectBi = void 0; const goog_varint_1 = __nccwpck_require__(30433); let BI; function detectBi() { const dv = new DataView(new ArrayBuffer(8)); const ok = globalThis.BigInt !== undefined && typeof dv.getBigInt64 === "function" && typeof dv.getBigUint64 === "function" && typeof dv.setBigInt64 === "function" && typeof dv.setBigUint64 === "function"; BI = ok ? { MIN: BigInt("-9223372036854775808"), MAX: BigInt("9223372036854775807"), UMIN: BigInt("0"), UMAX: BigInt("18446744073709551615"), C: BigInt, V: dv, } : undefined; } exports.detectBi = detectBi; detectBi(); function assertBi(bi) { if (!bi) throw new Error("BigInt unavailable, see https://github.com/timostamm/protobuf-ts/blob/v1.0.8/MANUAL.md#bigint-support"); } // used to validate from(string) input (when bigint is unavailable) const RE_DECIMAL_STR = /^-?[0-9]+$/; // constants for binary math const TWO_PWR_32_DBL = 0x100000000; const HALF_2_PWR_32 = 0x080000000; // base class for PbLong and PbULong provides shared code class SharedPbLong { /** * Create a new instance with the given bits. */ constructor(lo, hi) { this.lo = lo | 0; this.hi = hi | 0; } /** * Is this instance equal to 0? */ isZero() { return this.lo == 0 && this.hi == 0; } /** * Convert to a native number. */ toNumber() { let result = this.hi * TWO_PWR_32_DBL + (this.lo >>> 0); if (!Number.isSafeInteger(result)) throw new Error("cannot convert to safe number"); return result; } } /** * 64-bit unsigned integer as two 32-bit values. * Converts between `string`, `number` and `bigint` representations. */ class PbULong extends SharedPbLong { /** * Create instance from a `string`, `number` or `bigint`. */ static from(value) { if (BI) // noinspection FallThroughInSwitchStatementJS switch (typeof value) { case "string": if (value == "0") return this.ZERO; if (value == "") throw new Error('string is no integer'); value = BI.C(value); case "number": if (value === 0) return this.ZERO; value = BI.C(value); case "bigint": if (!value) return this.ZERO; if (value < BI.UMIN) throw new Error('signed value for ulong'); if (value > BI.UMAX) throw new Error('ulong too large'); BI.V.setBigUint64(0, value, true); return new PbULong(BI.V.getInt32(0, true), BI.V.getInt32(4, true)); } else switch (typeof value) { case "string": if (value == "0") return this.ZERO; value = value.trim(); if (!RE_DECIMAL_STR.test(value)) throw new Error('string is no integer'); let [minus, lo, hi] = goog_varint_1.int64fromString(value); if (minus) throw new Error('signed value for ulong'); return new PbULong(lo, hi); case "number": if (value == 0) return this.ZERO; if (!Number.isSafeInteger(value)) throw new Error('number is no integer'); if (value < 0) throw new Error('signed value for ulong'); return new PbULong(value, value / TWO_PWR_32_DBL); } throw new Error('unknown value ' + typeof value); } /** * Convert to decimal string. */ toString() { return BI ? this.toBigInt().toString() : goog_varint_1.int64toString(this.lo, this.hi); } /** * Convert to native bigint. */ toBigInt() { assertBi(BI); BI.V.setInt32(0, this.lo, true); BI.V.setInt32(4, this.hi, true); return BI.V.getBigUint64(0, true); } } exports.PbULong = PbULong; /** * ulong 0 singleton. */ PbULong.ZERO = new PbULong(0, 0); /** * 64-bit signed integer as two 32-bit values. * Converts between `string`, `number` and `bigint` representations. */ class PbLong extends SharedPbLong { /** * Create instance from a `string`, `number` or `bigint`. */ static from(value) { if (BI) // noinspection FallThroughInSwitchStatementJS switch (typeof value) { case "string": if (value == "0") return this.ZERO; if (value == "") throw new Error('string is no integer'); value = BI.C(value); case "number": if (value === 0) return this.ZERO; value = BI.C(value); case "bigint": if (!value) return this.ZERO; if (value < BI.MIN) throw new Error('signed long too small'); if (value > BI.MAX) throw new Error('signed long too large'); BI.V.setBigInt64(0, value, true); return new PbLong(BI.V.getInt32(0, true), BI.V.getInt32(4, true)); } else switch (typeof value) { case "string": if (value == "0") return this.ZERO; value = value.trim(); if (!RE_DECIMAL_STR.test(value)) throw new Error('string is no integer'); let [minus, lo, hi] = goog_varint_1.int64fromString(value); if (minus) { if (hi > HALF_2_PWR_32 || (hi == HALF_2_PWR_32 && lo != 0)) throw new Error('signed long too small'); } else if (hi >= HALF_2_PWR_32) throw new Error('signed long too large'); let pbl = new PbLong(lo, hi); return minus ? pbl.negate() : pbl; case "number": if (value == 0) return this.ZERO; if (!Number.isSafeInteger(value)) throw new Error('number is no integer'); return value > 0 ? new PbLong(value, value / TWO_PWR_32_DBL) : new PbLong(-value, -value / TWO_PWR_32_DBL).negate(); } throw new Error('unknown value ' + typeof value); } /** * Do we have a minus sign? */ isNegative() { return (this.hi & HALF_2_PWR_32) !== 0; } /** * Negate two's complement. * Invert all the bits and add one to the result. */ negate() { let hi = ~this.hi, lo = this.lo; if (lo) lo = ~lo + 1; else hi += 1; return new PbLong(lo, hi); } /** * Convert to decimal string. */ toString() { if (BI) return this.toBigInt().toString(); if (this.isNegative()) { let n = this.negate(); return '-' + goog_varint_1.int64toString(n.lo, n.hi); } return goog_varint_1.int64toString(this.lo, this.hi); } /** * Convert to native bigint. */ toBigInt() { assertBi(BI); BI.V.setInt32(0, this.lo, true); BI.V.setInt32(4, this.hi, true); return BI.V.getBigInt64(0, true); } } exports.PbLong = PbLong; /** * long 0 singleton. */ PbLong.ZERO = new PbLong(0, 0); /***/ }), /***/ 95290: /***/ ((__unused_webpack_module, exports) => { "use strict"; // Copyright (c) 2016, Daniel Wirtz All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of its author, nor the names of its contributors // may be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Object.defineProperty(exports, "__esModule", ({ value: true })); exports.utf8read = void 0; const fromCharCodes = (chunk) => String.fromCharCode.apply(String, chunk); /** * @deprecated This function will no longer be exported with the next major * release, since protobuf-ts has switch to TextDecoder API. If you need this * function, please migrate to @protobufjs/utf8. For context, see * https://github.com/timostamm/protobuf-ts/issues/184 * * Reads UTF8 bytes as a string. * * See [protobufjs / utf8](https://github.com/protobufjs/protobuf.js/blob/9893e35b854621cce64af4bf6be2cff4fb892796/lib/utf8/index.js#L40) * * Copyright (c) 2016, Daniel Wirtz */ function utf8read(bytes) { if (bytes.length < 1) return ""; let pos = 0, // position in bytes parts = [], chunk = [], i = 0, // char offset t; // temporary let len = bytes.length; while (pos < len) { t = bytes[pos++]; if (t < 128) chunk[i++] = t; else if (t > 191 && t < 224) chunk[i++] = (t & 31) << 6 | bytes[pos++] & 63; else if (t > 239 && t < 365) { t = ((t & 7) << 18 | (bytes[pos++] & 63) << 12 | (bytes[pos++] & 63) << 6 | bytes[pos++] & 63) - 0x10000; chunk[i++] = 0xD800 + (t >> 10); chunk[i++] = 0xDC00 + (t & 1023); } else chunk[i++] = (t & 15) << 12 | (bytes[pos++] & 63) << 6 | bytes[pos++] & 63; if (i > 8191) { parts.push(fromCharCodes(chunk)); i = 0; } } if (parts.length) { if (i) parts.push(fromCharCodes(chunk.slice(0, i))); return parts.join(""); } return fromCharCodes(chunk.slice(0, i)); } exports.utf8read = utf8read; /***/ }), /***/ 91593: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ReflectionBinaryReader = void 0; const binary_format_contract_1 = __nccwpck_require__(84921); const reflection_info_1 = __nccwpck_require__(21370); const reflection_long_convert_1 = __nccwpck_require__(24612); const reflection_scalar_default_1 = __nccwpck_require__(74863); /** * Reads proto3 messages in binary format using reflection information. * * https://developers.google.com/protocol-buffers/docs/encoding */ class ReflectionBinaryReader { constructor(info) { this.info = info; } prepare() { var _a; if (!this.fieldNoToField) { const fieldsInput = (_a = this.info.fields) !== null && _a !== void 0 ? _a : []; this.fieldNoToField = new Map(fieldsInput.map(field => [field.no, field])); } } /** * Reads a message from binary format into the target message. * * Repeated fields are appended. Map entries are added, overwriting * existing keys. * * If a message field is already present, it will be merged with the * new data. */ read(reader, message, options, length) { this.prepare(); const end = length === undefined ? reader.len : reader.pos + length; while (reader.pos < end) { // read the tag and find the field const [fieldNo, wireType] = reader.tag(), field = this.fieldNoToField.get(fieldNo); if (!field) { let u = options.readUnknownField; if (u == "throw") throw new Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.info.typeName}`); let d = reader.skip(wireType); if (u !== false) (u === true ? binary_format_contract_1.UnknownFieldHandler.onRead : u)(this.info.typeName, message, fieldNo, wireType, d); continue; } // target object for the field we are reading let target = message, repeated = field.repeat, localName = field.localName; // if field is member of oneof ADT, use ADT as target if (field.oneof) { target = target[field.oneof]; // if other oneof member selected, set new ADT if (target.oneofKind !== localName) target = message[field.oneof] = { oneofKind: localName }; } // we have handled oneof above, we just have read the value into `target[localName]` switch (field.kind) { case "scalar": case "enum": let T = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T; let L = field.kind == "scalar" ? field.L : undefined; if (repeated) { let arr = target[localName]; // safe to assume presence of array, oneof cannot contain repeated values if (wireType == binary_format_contract_1.WireType.LengthDelimited && T != reflection_info_1.ScalarType.STRING && T != reflection_info_1.ScalarType.BYTES) { let e = reader.uint32() + reader.pos; while (reader.pos < e) arr.push(this.scalar(reader, T, L)); } else arr.push(this.scalar(reader, T, L)); } else target[localName] = this.scalar(reader, T, L); break; case "message": if (repeated) { let arr = target[localName]; // safe to assume presence of array, oneof cannot contain repeated values let msg = field.T().internalBinaryRead(reader, reader.uint32(), options); arr.push(msg); } else target[localName] = field.T().internalBinaryRead(reader, reader.uint32(), options, target[localName]); break; case "map": let [mapKey, mapVal] = this.mapEntry(field, reader, options); // safe to assume presence of map object, oneof cannot contain repeated values target[localName][mapKey] = mapVal; break; } } } /** * Read a map field, expecting key field = 1, value field = 2 */ mapEntry(field, reader, options) { let length = reader.uint32(); let end = reader.pos + length; let key = undefined; // javascript only allows number or string for object properties let val = undefined; while (reader.pos < end) { let [fieldNo, wireType] = reader.tag(); switch (fieldNo) { case 1: if (field.K == reflection_info_1.ScalarType.BOOL) key = reader.bool().toString(); else // long types are read as string, number types are okay as number key = this.scalar(reader, field.K, reflection_info_1.LongType.STRING); break; case 2: switch (field.V.kind) { case "scalar": val = this.scalar(reader, field.V.T, field.V.L); break; case "enum": val = reader.int32(); break; case "message": val = field.V.T().internalBinaryRead(reader, reader.uint32(), options); break; } break; default: throw new Error(`Unknown field ${fieldNo} (wire type ${wireType}) in map entry for ${this.info.typeName}#${field.name}`); } } if (key === undefined) { let keyRaw = reflection_scalar_default_1.reflectionScalarDefault(field.K); key = field.K == reflection_info_1.ScalarType.BOOL ? keyRaw.toString() : keyRaw; } if (val === undefined) switch (field.V.kind) { case "scalar": val = reflection_scalar_default_1.reflectionScalarDefault(field.V.T, field.V.L); break; case "enum": val = 0; break; case "message": val = field.V.T().create(); break; } return [key, val]; } scalar(reader, type, longType) { switch (type) { case reflection_info_1.ScalarType.INT32: return reader.int32(); case reflection_info_1.ScalarType.STRING: return reader.string(); case reflection_info_1.ScalarType.BOOL: return reader.bool(); case reflection_info_1.ScalarType.DOUBLE: return reader.double(); case reflection_info_1.ScalarType.FLOAT: return reader.float(); case reflection_info_1.ScalarType.INT64: return reflection_long_convert_1.reflectionLongConvert(reader.int64(), longType); case reflection_info_1.ScalarType.UINT64: return reflection_long_convert_1.reflectionLongConvert(reader.uint64(), longType); case reflection_info_1.ScalarType.FIXED64: return reflection_long_convert_1.reflectionLongConvert(reader.fixed64(), longType); case reflection_info_1.ScalarType.FIXED32: return reader.fixed32(); case reflection_info_1.ScalarType.BYTES: return reader.bytes(); case reflection_info_1.ScalarType.UINT32: return reader.uint32(); case reflection_info_1.ScalarType.SFIXED32: return reader.sfixed32(); case reflection_info_1.ScalarType.SFIXED64: return reflection_long_convert_1.reflectionLongConvert(reader.sfixed64(), longType); case reflection_info_1.ScalarType.SINT32: return reader.sint32(); case reflection_info_1.ScalarType.SINT64: return reflection_long_convert_1.reflectionLongConvert(reader.sint64(), longType); } } } exports.ReflectionBinaryReader = ReflectionBinaryReader; /***/ }), /***/ 57170: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ReflectionBinaryWriter = void 0; const binary_format_contract_1 = __nccwpck_require__(84921); const reflection_info_1 = __nccwpck_require__(21370); const assert_1 = __nccwpck_require__(54253); const pb_long_1 = __nccwpck_require__(47777); /** * Writes proto3 messages in binary format using reflection information. * * https://developers.google.com/protocol-buffers/docs/encoding */ class ReflectionBinaryWriter { constructor(info) { this.info = info; } prepare() { if (!this.fields) { const fieldsInput = this.info.fields ? this.info.fields.concat() : []; this.fields = fieldsInput.sort((a, b) => a.no - b.no); } } /** * Writes the message to binary format. */ write(message, writer, options) { this.prepare(); for (const field of this.fields) { let value, // this will be our field value, whether it is member of a oneof or not emitDefault, // whether we emit the default value (only true for oneof members) repeated = field.repeat, localName = field.localName; // handle oneof ADT if (field.oneof) { const group = message[field.oneof]; if (group.oneofKind !== localName) continue; // if field is not selected, skip value = group[localName]; emitDefault = true; } else { value = message[localName]; emitDefault = false; } // we have handled oneof above. we just have to honor `emitDefault`. switch (field.kind) { case "scalar": case "enum": let T = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T; if (repeated) { assert_1.assert(Array.isArray(value)); if (repeated == reflection_info_1.RepeatType.PACKED) this.packed(writer, T, field.no, value); else for (const item of value) this.scalar(writer, T, field.no, item, true); } else if (value === undefined) assert_1.assert(field.opt); else this.scalar(writer, T, field.no, value, emitDefault || field.opt); break; case "message": if (repeated) { assert_1.assert(Array.isArray(value)); for (const item of value) this.message(writer, options, field.T(), field.no, item); } else { this.message(writer, options, field.T(), field.no, value); } break; case "map": assert_1.assert(typeof value == 'object' && value !== null); for (const [key, val] of Object.entries(value)) this.mapEntry(writer, options, field, key, val); break; } } let u = options.writeUnknownFields; if (u !== false) (u === true ? binary_format_contract_1.UnknownFieldHandler.onWrite : u)(this.info.typeName, message, writer); } mapEntry(writer, options, field, key, value) { writer.tag(field.no, binary_format_contract_1.WireType.LengthDelimited); writer.fork(); // javascript only allows number or string for object properties // we convert from our representation to the protobuf type let keyValue = key; switch (field.K) { case reflection_info_1.ScalarType.INT32: case reflection_info_1.ScalarType.FIXED32: case reflection_info_1.ScalarType.UINT32: case reflection_info_1.ScalarType.SFIXED32: case reflection_info_1.ScalarType.SINT32: keyValue = Number.parseInt(key); break; case reflection_info_1.ScalarType.BOOL: assert_1.assert(key == 'true' || key == 'false'); keyValue = key == 'true'; break; } // write key, expecting key field number = 1 this.scalar(writer, field.K, 1, keyValue, true); // write value, expecting value field number = 2 switch (field.V.kind) { case 'scalar': this.scalar(writer, field.V.T, 2, value, true); break; case 'enum': this.scalar(writer, reflection_info_1.ScalarType.INT32, 2, value, true); break; case 'message': this.message(writer, options, field.V.T(), 2, value); break; } writer.join(); } message(writer, options, handler, fieldNo, value) { if (value === undefined) return; handler.internalBinaryWrite(value, writer.tag(fieldNo, binary_format_contract_1.WireType.LengthDelimited).fork(), options); writer.join(); } /** * Write a single scalar value. */ scalar(writer, type, fieldNo, value, emitDefault) { let [wireType, method, isDefault] = this.scalarInfo(type, value); if (!isDefault || emitDefault) { writer.tag(fieldNo, wireType); writer[method](value); } } /** * Write an array of scalar values in packed format. */ packed(writer, type, fieldNo, value) { if (!value.length) return; assert_1.assert(type !== reflection_info_1.ScalarType.BYTES && type !== reflection_info_1.ScalarType.STRING); // write tag writer.tag(fieldNo, binary_format_contract_1.WireType.LengthDelimited); // begin length-delimited writer.fork(); // write values without tags let [, method,] = this.scalarInfo(type); for (let i = 0; i < value.length; i++) writer[method](value[i]); // end length delimited writer.join(); } /** * Get information for writing a scalar value. * * Returns tuple: * [0]: appropriate WireType * [1]: name of the appropriate method of IBinaryWriter * [2]: whether the given value is a default value * * If argument `value` is omitted, [2] is always false. */ scalarInfo(type, value) { let t = binary_format_contract_1.WireType.Varint; let m; let i = value === undefined; let d = value === 0; switch (type) { case reflection_info_1.ScalarType.INT32: m = "int32"; break; case reflection_info_1.ScalarType.STRING: d = i || !value.length; t = binary_format_contract_1.WireType.LengthDelimited; m = "string"; break; case reflection_info_1.ScalarType.BOOL: d = value === false; m = "bool"; break; case reflection_info_1.ScalarType.UINT32: m = "uint32"; break; case reflection_info_1.ScalarType.DOUBLE: t = binary_format_contract_1.WireType.Bit64; m = "double"; break; case reflection_info_1.ScalarType.FLOAT: t = binary_format_contract_1.WireType.Bit32; m = "float"; break; case reflection_info_1.ScalarType.INT64: d = i || pb_long_1.PbLong.from(value).isZero(); m = "int64"; break; case reflection_info_1.ScalarType.UINT64: d = i || pb_long_1.PbULong.from(value).isZero(); m = "uint64"; break; case reflection_info_1.ScalarType.FIXED64: d = i || pb_long_1.PbULong.from(value).isZero(); t = binary_format_contract_1.WireType.Bit64; m = "fixed64"; break; case reflection_info_1.ScalarType.BYTES: d = i || !value.byteLength; t = binary_format_contract_1.WireType.LengthDelimited; m = "bytes"; break; case reflection_info_1.ScalarType.FIXED32: t = binary_format_contract_1.WireType.Bit32; m = "fixed32"; break; case reflection_info_1.ScalarType.SFIXED32: t = binary_format_contract_1.WireType.Bit32; m = "sfixed32"; break; case reflection_info_1.ScalarType.SFIXED64: d = i || pb_long_1.PbLong.from(value).isZero(); t = binary_format_contract_1.WireType.Bit64; m = "sfixed64"; break; case reflection_info_1.ScalarType.SINT32: m = "sint32"; break; case reflection_info_1.ScalarType.SINT64: d = i || pb_long_1.PbLong.from(value).isZero(); m = "sint64"; break; } return [t, m, i || d]; } } exports.ReflectionBinaryWriter = ReflectionBinaryWriter; /***/ }), /***/ 67317: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.containsMessageType = void 0; const message_type_contract_1 = __nccwpck_require__(1682); /** * Check if the provided object is a proto message. * * Note that this is an experimental feature - it is here to stay, but * implementation details may change without notice. */ function containsMessageType(msg) { return msg[message_type_contract_1.MESSAGE_TYPE] != null; } exports.containsMessageType = containsMessageType; /***/ }), /***/ 60390: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.reflectionCreate = void 0; const reflection_scalar_default_1 = __nccwpck_require__(74863); const message_type_contract_1 = __nccwpck_require__(1682); /** * Creates an instance of the generic message, using the field * information. */ function reflectionCreate(type) { /** * This ternary can be removed in the next major version. * The `Object.create()` code path utilizes a new `messagePrototype` * property on the `IMessageType` which has this same `MESSAGE_TYPE` * non-enumerable property on it. Doing it this way means that we only * pay the cost of `Object.defineProperty()` once per `IMessageType` * class of once per "instance". The falsy code path is only provided * for backwards compatibility in cases where the runtime library is * updated without also updating the generated code. */ const msg = type.messagePrototype ? Object.create(type.messagePrototype) : Object.defineProperty({}, message_type_contract_1.MESSAGE_TYPE, { value: type }); for (let field of type.fields) { let name = field.localName; if (field.opt) continue; if (field.oneof) msg[field.oneof] = { oneofKind: undefined }; else if (field.repeat) msg[name] = []; else switch (field.kind) { case "scalar": msg[name] = reflection_scalar_default_1.reflectionScalarDefault(field.T, field.L); break; case "enum": // we require 0 to be default value for all enums msg[name] = 0; break; case "map": msg[name] = {}; break; } } return msg; } exports.reflectionCreate = reflectionCreate; /***/ }), /***/ 39473: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.reflectionEquals = void 0; const reflection_info_1 = __nccwpck_require__(21370); /** * Determines whether two message of the same type have the same field values. * Checks for deep equality, traversing repeated fields, oneof groups, maps * and messages recursively. * Will also return true if both messages are `undefined`. */ function reflectionEquals(info, a, b) { if (a === b) return true; if (!a || !b) return false; for (let field of info.fields) { let localName = field.localName; let val_a = field.oneof ? a[field.oneof][localName] : a[localName]; let val_b = field.oneof ? b[field.oneof][localName] : b[localName]; switch (field.kind) { case "enum": case "scalar": let t = field.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.T; if (!(field.repeat ? repeatedPrimitiveEq(t, val_a, val_b) : primitiveEq(t, val_a, val_b))) return false; break; case "map": if (!(field.V.kind == "message" ? repeatedMsgEq(field.V.T(), objectValues(val_a), objectValues(val_b)) : repeatedPrimitiveEq(field.V.kind == "enum" ? reflection_info_1.ScalarType.INT32 : field.V.T, objectValues(val_a), objectValues(val_b)))) return false; break; case "message": let T = field.T(); if (!(field.repeat ? repeatedMsgEq(T, val_a, val_b) : T.equals(val_a, val_b))) return false; break; } } return true; } exports.reflectionEquals = reflectionEquals; const objectValues = Object.values; function primitiveEq(type, a, b) { if (a === b) return true; if (type !== reflection_info_1.ScalarType.BYTES) return false; let ba = a; let bb = b; if (ba.length !== bb.length) return false; for (let i = 0; i < ba.length; i++) if (ba[i] != bb[i]) return false; return true; } function repeatedPrimitiveEq(type, a, b) { if (a.length !== b.length) return false; for (let i = 0; i < a.length; i++) if (!primitiveEq(type, a[i], b[i])) return false; return true; } function repeatedMsgEq(type, a, b) { if (a.length !== b.length) return false; for (let i = 0; i < a.length; i++) if (!type.equals(a[i], b[i])) return false; return true; } /***/ }), /***/ 21370: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.readMessageOption = exports.readFieldOption = exports.readFieldOptions = exports.normalizeFieldInfo = exports.RepeatType = exports.LongType = exports.ScalarType = void 0; const lower_camel_case_1 = __nccwpck_require__(34772); /** * Scalar value types. This is a subset of field types declared by protobuf * enum google.protobuf.FieldDescriptorProto.Type The types GROUP and MESSAGE * are omitted, but the numerical values are identical. */ var ScalarType; (function (ScalarType) { // 0 is reserved for errors. // Order is weird for historical reasons. ScalarType[ScalarType["DOUBLE"] = 1] = "DOUBLE"; ScalarType[ScalarType["FLOAT"] = 2] = "FLOAT"; // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if // negative values are likely. ScalarType[ScalarType["INT64"] = 3] = "INT64"; ScalarType[ScalarType["UINT64"] = 4] = "UINT64"; // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if // negative values are likely. ScalarType[ScalarType["INT32"] = 5] = "INT32"; ScalarType[ScalarType["FIXED64"] = 6] = "FIXED64"; ScalarType[ScalarType["FIXED32"] = 7] = "FIXED32"; ScalarType[ScalarType["BOOL"] = 8] = "BOOL"; ScalarType[ScalarType["STRING"] = 9] = "STRING"; // Tag-delimited aggregate. // Group type is deprecated and not supported in proto3. However, Proto3 // implementations should still be able to parse the group wire format and // treat group fields as unknown fields. // TYPE_GROUP = 10, // TYPE_MESSAGE = 11, // Length-delimited aggregate. // New in version 2. ScalarType[ScalarType["BYTES"] = 12] = "BYTES"; ScalarType[ScalarType["UINT32"] = 13] = "UINT32"; // TYPE_ENUM = 14, ScalarType[ScalarType["SFIXED32"] = 15] = "SFIXED32"; ScalarType[ScalarType["SFIXED64"] = 16] = "SFIXED64"; ScalarType[ScalarType["SINT32"] = 17] = "SINT32"; ScalarType[ScalarType["SINT64"] = 18] = "SINT64"; })(ScalarType = exports.ScalarType || (exports.ScalarType = {})); /** * JavaScript representation of 64 bit integral types. Equivalent to the * field option "jstype". * * By default, protobuf-ts represents 64 bit types as `bigint`. * * You can change the default behaviour by enabling the plugin parameter * `long_type_string`, which will represent 64 bit types as `string`. * * Alternatively, you can change the behaviour for individual fields * with the field option "jstype": * * ```protobuf * uint64 my_field = 1 [jstype = JS_STRING]; * uint64 other_field = 2 [jstype = JS_NUMBER]; * ``` */ var LongType; (function (LongType) { /** * Use JavaScript `bigint`. * * Field option `[jstype = JS_NORMAL]`. */ LongType[LongType["BIGINT"] = 0] = "BIGINT"; /** * Use JavaScript `string`. * * Field option `[jstype = JS_STRING]`. */ LongType[LongType["STRING"] = 1] = "STRING"; /** * Use JavaScript `number`. * * Large values will loose precision. * * Field option `[jstype = JS_NUMBER]`. */ LongType[LongType["NUMBER"] = 2] = "NUMBER"; })(LongType = exports.LongType || (exports.LongType = {})); /** * Protobuf 2.1.0 introduced packed repeated fields. * Setting the field option `[packed = true]` enables packing. * * In proto3, all repeated fields are packed by default. * Setting the field option `[packed = false]` disables packing. * * Packed repeated fields are encoded with a single tag, * then a length-delimiter, then the element values. * * Unpacked repeated fields are encoded with a tag and * value for each element. * * `bytes` and `string` cannot be packed. */ var RepeatType; (function (RepeatType) { /** * The field is not repeated. */ RepeatType[RepeatType["NO"] = 0] = "NO"; /** * The field is repeated and should be packed. * Invalid for `bytes` and `string`, they cannot be packed. */ RepeatType[RepeatType["PACKED"] = 1] = "PACKED"; /** * The field is repeated but should not be packed. * The only valid repeat type for repeated `bytes` and `string`. */ RepeatType[RepeatType["UNPACKED"] = 2] = "UNPACKED"; })(RepeatType = exports.RepeatType || (exports.RepeatType = {})); /** * Turns PartialFieldInfo into FieldInfo. */ function normalizeFieldInfo(field) { var _a, _b, _c, _d; field.localName = (_a = field.localName) !== null && _a !== void 0 ? _a : lower_camel_case_1.lowerCamelCase(field.name); field.jsonName = (_b = field.jsonName) !== null && _b !== void 0 ? _b : lower_camel_case_1.lowerCamelCase(field.name); field.repeat = (_c = field.repeat) !== null && _c !== void 0 ? _c : RepeatType.NO; field.opt = (_d = field.opt) !== null && _d !== void 0 ? _d : (field.repeat ? false : field.oneof ? false : field.kind == "message"); return field; } exports.normalizeFieldInfo = normalizeFieldInfo; /** * Read custom field options from a generated message type. * * @deprecated use readFieldOption() */ function readFieldOptions(messageType, fieldName, extensionName, extensionType) { var _a; const options = (_a = messageType.fields.find((m, i) => m.localName == fieldName || i == fieldName)) === null || _a === void 0 ? void 0 : _a.options; return options && options[extensionName] ? extensionType.fromJson(options[extensionName]) : undefined; } exports.readFieldOptions = readFieldOptions; function readFieldOption(messageType, fieldName, extensionName, extensionType) { var _a; const options = (_a = messageType.fields.find((m, i) => m.localName == fieldName || i == fieldName)) === null || _a === void 0 ? void 0 : _a.options; if (!options) { return undefined; } const optionVal = options[extensionName]; if (optionVal === undefined) { return optionVal; } return extensionType ? extensionType.fromJson(optionVal) : optionVal; } exports.readFieldOption = readFieldOption; function readMessageOption(messageType, extensionName, extensionType) { const options = messageType.options; const optionVal = options[extensionName]; if (optionVal === undefined) { return optionVal; } return extensionType ? extensionType.fromJson(optionVal) : optionVal; } exports.readMessageOption = readMessageOption; /***/ }), /***/ 229: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ReflectionJsonReader = void 0; const json_typings_1 = __nccwpck_require__(70661); const base64_1 = __nccwpck_require__(20196); const reflection_info_1 = __nccwpck_require__(21370); const pb_long_1 = __nccwpck_require__(47777); const assert_1 = __nccwpck_require__(54253); const reflection_long_convert_1 = __nccwpck_require__(24612); /** * Reads proto3 messages in canonical JSON format using reflection information. * * https://developers.google.com/protocol-buffers/docs/proto3#json */ class ReflectionJsonReader { constructor(info) { this.info = info; } prepare() { var _a; if (this.fMap === undefined) { this.fMap = {}; const fieldsInput = (_a = this.info.fields) !== null && _a !== void 0 ? _a : []; for (const field of fieldsInput) { this.fMap[field.name] = field; this.fMap[field.jsonName] = field; this.fMap[field.localName] = field; } } } // Cannot parse JSON for #. assert(condition, fieldName, jsonValue) { if (!condition) { let what = json_typings_1.typeofJsonValue(jsonValue); if (what == "number" || what == "boolean") what = jsonValue.toString(); throw new Error(`Cannot parse JSON ${what} for ${this.info.typeName}#${fieldName}`); } } /** * Reads a message from canonical JSON format into the target message. * * Repeated fields are appended. Map entries are added, overwriting * existing keys. * * If a message field is already present, it will be merged with the * new data. */ read(input, message, options) { this.prepare(); const oneofsHandled = []; for (const [jsonKey, jsonValue] of Object.entries(input)) { const field = this.fMap[jsonKey]; if (!field) { if (!options.ignoreUnknownFields) throw new Error(`Found unknown field while reading ${this.info.typeName} from JSON format. JSON key: ${jsonKey}`); continue; } const localName = field.localName; // handle oneof ADT let target; // this will be the target for the field value, whether it is member of a oneof or not if (field.oneof) { if (jsonValue === null && (field.kind !== 'enum' || field.T()[0] !== 'google.protobuf.NullValue')) { continue; } // since json objects are unordered by specification, it is not possible to take the last of multiple oneofs if (oneofsHandled.includes(field.oneof)) throw new Error(`Multiple members of the oneof group "${field.oneof}" of ${this.info.typeName} are present in JSON.`); oneofsHandled.push(field.oneof); target = message[field.oneof] = { oneofKind: localName }; } else { target = message; } // we have handled oneof above. we just have read the value into `target`. if (field.kind == 'map') { if (jsonValue === null) { continue; } // check input this.assert(json_typings_1.isJsonObject(jsonValue), field.name, jsonValue); // our target to put map entries into const fieldObj = target[localName]; // read entries for (const [jsonObjKey, jsonObjValue] of Object.entries(jsonValue)) { this.assert(jsonObjValue !== null, field.name + " map value", null); // read value let val; switch (field.V.kind) { case "message": val = field.V.T().internalJsonRead(jsonObjValue, options); break; case "enum": val = this.enum(field.V.T(), jsonObjValue, field.name, options.ignoreUnknownFields); if (val === false) continue; break; case "scalar": val = this.scalar(jsonObjValue, field.V.T, field.V.L, field.name); break; } this.assert(val !== undefined, field.name + " map value", jsonObjValue); // read key let key = jsonObjKey; if (field.K == reflection_info_1.ScalarType.BOOL) key = key == "true" ? true : key == "false" ? false : key; key = this.scalar(key, field.K, reflection_info_1.LongType.STRING, field.name).toString(); fieldObj[key] = val; } } else if (field.repeat) { if (jsonValue === null) continue; // check input this.assert(Array.isArray(jsonValue), field.name, jsonValue); // our target to put array entries into const fieldArr = target[localName]; // read array entries for (const jsonItem of jsonValue) { this.assert(jsonItem !== null, field.name, null); let val; switch (field.kind) { case "message": val = field.T().internalJsonRead(jsonItem, options); break; case "enum": val = this.enum(field.T(), jsonItem, field.name, options.ignoreUnknownFields); if (val === false) continue; break; case "scalar": val = this.scalar(jsonItem, field.T, field.L, field.name); break; } this.assert(val !== undefined, field.name, jsonValue); fieldArr.push(val); } } else { switch (field.kind) { case "message": if (jsonValue === null && field.T().typeName != 'google.protobuf.Value') { this.assert(field.oneof === undefined, field.name + " (oneof member)", null); continue; } target[localName] = field.T().internalJsonRead(jsonValue, options, target[localName]); break; case "enum": let val = this.enum(field.T(), jsonValue, field.name, options.ignoreUnknownFields); if (val === false) continue; target[localName] = val; break; case "scalar": target[localName] = this.scalar(jsonValue, field.T, field.L, field.name); break; } } } } /** * Returns `false` for unrecognized string representations. * * google.protobuf.NullValue accepts only JSON `null` (or the old `"NULL_VALUE"`). */ enum(type, json, fieldName, ignoreUnknownFields) { if (type[0] == 'google.protobuf.NullValue') assert_1.assert(json === null || json === "NULL_VALUE", `Unable to parse field ${this.info.typeName}#${fieldName}, enum ${type[0]} only accepts null.`); if (json === null) // we require 0 to be default value for all enums return 0; switch (typeof json) { case "number": assert_1.assert(Number.isInteger(json), `Unable to parse field ${this.info.typeName}#${fieldName}, enum can only be integral number, got ${json}.`); return json; case "string": let localEnumName = json; if (type[2] && json.substring(0, type[2].length) === type[2]) // lookup without the shared prefix localEnumName = json.substring(type[2].length); let enumNumber = type[1][localEnumName]; if (typeof enumNumber === 'undefined' && ignoreUnknownFields) { return false; } assert_1.assert(typeof enumNumber == "number", `Unable to parse field ${this.info.typeName}#${fieldName}, enum ${type[0]} has no value for "${json}".`); return enumNumber; } assert_1.assert(false, `Unable to parse field ${this.info.typeName}#${fieldName}, cannot parse enum value from ${typeof json}".`); } scalar(json, type, longType, fieldName) { let e; try { switch (type) { // float, double: JSON value will be a number or one of the special string values "NaN", "Infinity", and "-Infinity". // Either numbers or strings are accepted. Exponent notation is also accepted. case reflection_info_1.ScalarType.DOUBLE: case reflection_info_1.ScalarType.FLOAT: if (json === null) return .0; if (json === "NaN") return Number.NaN; if (json === "Infinity") return Number.POSITIVE_INFINITY; if (json === "-Infinity") return Number.NEGATIVE_INFINITY; if (json === "") { e = "empty string"; break; } if (typeof json == "string" && json.trim().length !== json.length) { e = "extra whitespace"; break; } if (typeof json != "string" && typeof json != "number") { break; } let float = Number(json); if (Number.isNaN(float)) { e = "not a number"; break; } if (!Number.isFinite(float)) { // infinity and -infinity are handled by string representation above, so this is an error e = "too large or small"; break; } if (type == reflection_info_1.ScalarType.FLOAT) assert_1.assertFloat32(float); return float; // int32, fixed32, uint32: JSON value will be a decimal number. Either numbers or strings are accepted. case reflection_info_1.ScalarType.INT32: case reflection_info_1.ScalarType.FIXED32: case reflection_info_1.ScalarType.SFIXED32: case reflection_info_1.ScalarType.SINT32: case reflection_info_1.ScalarType.UINT32: if (json === null) return 0; let int32; if (typeof json == "number") int32 = json; else if (json === "") e = "empty string"; else if (typeof json == "string") { if (json.trim().length !== json.length) e = "extra whitespace"; else int32 = Number(json); } if (int32 === undefined) break; if (type == reflection_info_1.ScalarType.UINT32) assert_1.assertUInt32(int32); else assert_1.assertInt32(int32); return int32; // int64, fixed64, uint64: JSON value will be a decimal string. Either numbers or strings are accepted. case reflection_info_1.ScalarType.INT64: case reflection_info_1.ScalarType.SFIXED64: case reflection_info_1.ScalarType.SINT64: if (json === null) return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.ZERO, longType); if (typeof json != "number" && typeof json != "string") break; return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.from(json), longType); case reflection_info_1.ScalarType.FIXED64: case reflection_info_1.ScalarType.UINT64: if (json === null) return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.ZERO, longType); if (typeof json != "number" && typeof json != "string") break; return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.from(json), longType); // bool: case reflection_info_1.ScalarType.BOOL: if (json === null) return false; if (typeof json !== "boolean") break; return json; // string: case reflection_info_1.ScalarType.STRING: if (json === null) return ""; if (typeof json !== "string") { e = "extra whitespace"; break; } try { encodeURIComponent(json); } catch (e) { e = "invalid UTF8"; break; } return json; // bytes: JSON value will be the data encoded as a string using standard base64 encoding with paddings. // Either standard or URL-safe base64 encoding with/without paddings are accepted. case reflection_info_1.ScalarType.BYTES: if (json === null || json === "") return new Uint8Array(0); if (typeof json !== 'string') break; return base64_1.base64decode(json); } } catch (error) { e = error.message; } this.assert(false, fieldName + (e ? " - " + e : ""), json); } } exports.ReflectionJsonReader = ReflectionJsonReader; /***/ }), /***/ 68980: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ReflectionJsonWriter = void 0; const base64_1 = __nccwpck_require__(20196); const pb_long_1 = __nccwpck_require__(47777); const reflection_info_1 = __nccwpck_require__(21370); const assert_1 = __nccwpck_require__(54253); /** * Writes proto3 messages in canonical JSON format using reflection * information. * * https://developers.google.com/protocol-buffers/docs/proto3#json */ class ReflectionJsonWriter { constructor(info) { var _a; this.fields = (_a = info.fields) !== null && _a !== void 0 ? _a : []; } /** * Converts the message to a JSON object, based on the field descriptors. */ write(message, options) { const json = {}, source = message; for (const field of this.fields) { // field is not part of a oneof, simply write as is if (!field.oneof) { let jsonValue = this.field(field, source[field.localName], options); if (jsonValue !== undefined) json[options.useProtoFieldName ? field.name : field.jsonName] = jsonValue; continue; } // field is part of a oneof const group = source[field.oneof]; if (group.oneofKind !== field.localName) continue; // not selected, skip const opt = field.kind == 'scalar' || field.kind == 'enum' ? Object.assign(Object.assign({}, options), { emitDefaultValues: true }) : options; let jsonValue = this.field(field, group[field.localName], opt); assert_1.assert(jsonValue !== undefined); json[options.useProtoFieldName ? field.name : field.jsonName] = jsonValue; } return json; } field(field, value, options) { let jsonValue = undefined; if (field.kind == 'map') { assert_1.assert(typeof value == "object" && value !== null); const jsonObj = {}; switch (field.V.kind) { case "scalar": for (const [entryKey, entryValue] of Object.entries(value)) { const val = this.scalar(field.V.T, entryValue, field.name, false, true); assert_1.assert(val !== undefined); jsonObj[entryKey.toString()] = val; // JSON standard allows only (double quoted) string as property key } break; case "message": const messageType = field.V.T(); for (const [entryKey, entryValue] of Object.entries(value)) { const val = this.message(messageType, entryValue, field.name, options); assert_1.assert(val !== undefined); jsonObj[entryKey.toString()] = val; // JSON standard allows only (double quoted) string as property key } break; case "enum": const enumInfo = field.V.T(); for (const [entryKey, entryValue] of Object.entries(value)) { assert_1.assert(entryValue === undefined || typeof entryValue == 'number'); const val = this.enum(enumInfo, entryValue, field.name, false, true, options.enumAsInteger); assert_1.assert(val !== undefined); jsonObj[entryKey.toString()] = val; // JSON standard allows only (double quoted) string as property key } break; } if (options.emitDefaultValues || Object.keys(jsonObj).length > 0) jsonValue = jsonObj; } else if (field.repeat) { assert_1.assert(Array.isArray(value)); const jsonArr = []; switch (field.kind) { case "scalar": for (let i = 0; i < value.length; i++) { const val = this.scalar(field.T, value[i], field.name, field.opt, true); assert_1.assert(val !== undefined); jsonArr.push(val); } break; case "enum": const enumInfo = field.T(); for (let i = 0; i < value.length; i++) { assert_1.assert(value[i] === undefined || typeof value[i] == 'number'); const val = this.enum(enumInfo, value[i], field.name, field.opt, true, options.enumAsInteger); assert_1.assert(val !== undefined); jsonArr.push(val); } break; case "message": const messageType = field.T(); for (let i = 0; i < value.length; i++) { const val = this.message(messageType, value[i], field.name, options); assert_1.assert(val !== undefined); jsonArr.push(val); } break; } // add converted array to json output if (options.emitDefaultValues || jsonArr.length > 0 || options.emitDefaultValues) jsonValue = jsonArr; } else { switch (field.kind) { case "scalar": jsonValue = this.scalar(field.T, value, field.name, field.opt, options.emitDefaultValues); break; case "enum": jsonValue = this.enum(field.T(), value, field.name, field.opt, options.emitDefaultValues, options.enumAsInteger); break; case "message": jsonValue = this.message(field.T(), value, field.name, options); break; } } return jsonValue; } /** * Returns `null` as the default for google.protobuf.NullValue. */ enum(type, value, fieldName, optional, emitDefaultValues, enumAsInteger) { if (type[0] == 'google.protobuf.NullValue') return !emitDefaultValues && !optional ? undefined : null; if (value === undefined) { assert_1.assert(optional); return undefined; } if (value === 0 && !emitDefaultValues && !optional) // we require 0 to be default value for all enums return undefined; assert_1.assert(typeof value == 'number'); assert_1.assert(Number.isInteger(value)); if (enumAsInteger || !type[1].hasOwnProperty(value)) // if we don't now the enum value, just return the number return value; if (type[2]) // restore the dropped prefix return type[2] + type[1][value]; return type[1][value]; } message(type, value, fieldName, options) { if (value === undefined) return options.emitDefaultValues ? null : undefined; return type.internalJsonWrite(value, options); } scalar(type, value, fieldName, optional, emitDefaultValues) { if (value === undefined) { assert_1.assert(optional); return undefined; } const ed = emitDefaultValues || optional; // noinspection FallThroughInSwitchStatementJS switch (type) { // int32, fixed32, uint32: JSON value will be a decimal number. Either numbers or strings are accepted. case reflection_info_1.ScalarType.INT32: case reflection_info_1.ScalarType.SFIXED32: case reflection_info_1.ScalarType.SINT32: if (value === 0) return ed ? 0 : undefined; assert_1.assertInt32(value); return value; case reflection_info_1.ScalarType.FIXED32: case reflection_info_1.ScalarType.UINT32: if (value === 0) return ed ? 0 : undefined; assert_1.assertUInt32(value); return value; // float, double: JSON value will be a number or one of the special string values "NaN", "Infinity", and "-Infinity". // Either numbers or strings are accepted. Exponent notation is also accepted. case reflection_info_1.ScalarType.FLOAT: assert_1.assertFloat32(value); case reflection_info_1.ScalarType.DOUBLE: if (value === 0) return ed ? 0 : undefined; assert_1.assert(typeof value == 'number'); if (Number.isNaN(value)) return 'NaN'; if (value === Number.POSITIVE_INFINITY) return 'Infinity'; if (value === Number.NEGATIVE_INFINITY) return '-Infinity'; return value; // string: case reflection_info_1.ScalarType.STRING: if (value === "") return ed ? '' : undefined; assert_1.assert(typeof value == 'string'); return value; // bool: case reflection_info_1.ScalarType.BOOL: if (value === false) return ed ? false : undefined; assert_1.assert(typeof value == 'boolean'); return value; // JSON value will be a decimal string. Either numbers or strings are accepted. case reflection_info_1.ScalarType.UINT64: case reflection_info_1.ScalarType.FIXED64: assert_1.assert(typeof value == 'number' || typeof value == 'string' || typeof value == 'bigint'); let ulong = pb_long_1.PbULong.from(value); if (ulong.isZero() && !ed) return undefined; return ulong.toString(); // JSON value will be a decimal string. Either numbers or strings are accepted. case reflection_info_1.ScalarType.INT64: case reflection_info_1.ScalarType.SFIXED64: case reflection_info_1.ScalarType.SINT64: assert_1.assert(typeof value == 'number' || typeof value == 'string' || typeof value == 'bigint'); let long = pb_long_1.PbLong.from(value); if (long.isZero() && !ed) return undefined; return long.toString(); // bytes: JSON value will be the data encoded as a string using standard base64 encoding with paddings. // Either standard or URL-safe base64 encoding with/without paddings are accepted. case reflection_info_1.ScalarType.BYTES: assert_1.assert(value instanceof Uint8Array); if (!value.byteLength) return ed ? "" : undefined; return base64_1.base64encode(value); } } } exports.ReflectionJsonWriter = ReflectionJsonWriter; /***/ }), /***/ 24612: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.reflectionLongConvert = void 0; const reflection_info_1 = __nccwpck_require__(21370); /** * Utility method to convert a PbLong or PbUlong to a JavaScript * representation during runtime. * * Works with generated field information, `undefined` is equivalent * to `STRING`. */ function reflectionLongConvert(long, type) { switch (type) { case reflection_info_1.LongType.BIGINT: return long.toBigInt(); case reflection_info_1.LongType.NUMBER: return long.toNumber(); default: // case undefined: // case LongType.STRING: return long.toString(); } } exports.reflectionLongConvert = reflectionLongConvert; /***/ }), /***/ 7869: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.reflectionMergePartial = void 0; /** * Copy partial data into the target message. * * If a singular scalar or enum field is present in the source, it * replaces the field in the target. * * If a singular message field is present in the source, it is merged * with the target field by calling mergePartial() of the responsible * message type. * * If a repeated field is present in the source, its values replace * all values in the target array, removing extraneous values. * Repeated message fields are copied, not merged. * * If a map field is present in the source, entries are added to the * target map, replacing entries with the same key. Entries that only * exist in the target remain. Entries with message values are copied, * not merged. * * Note that this function differs from protobuf merge semantics, * which appends repeated fields. */ function reflectionMergePartial(info, target, source) { let fieldValue, // the field value we are working with input = source, output; // where we want our field value to go for (let field of info.fields) { let name = field.localName; if (field.oneof) { const group = input[field.oneof]; // this is the oneof`s group in the source if ((group === null || group === void 0 ? void 0 : group.oneofKind) == undefined) { // the user is free to omit continue; // we skip this field, and all other members too } fieldValue = group[name]; // our value comes from the the oneof group of the source output = target[field.oneof]; // and our output is the oneof group of the target output.oneofKind = group.oneofKind; // always update discriminator if (fieldValue == undefined) { delete output[name]; // remove any existing value continue; // skip further work on field } } else { fieldValue = input[name]; // we are using the source directly output = target; // we want our field value to go directly into the target if (fieldValue == undefined) { continue; // skip further work on field, existing value is used as is } } if (field.repeat) output[name].length = fieldValue.length; // resize target array to match source array // now we just work with `fieldValue` and `output` to merge the value switch (field.kind) { case "scalar": case "enum": if (field.repeat) for (let i = 0; i < fieldValue.length; i++) output[name][i] = fieldValue[i]; // not a reference type else output[name] = fieldValue; // not a reference type break; case "message": let T = field.T(); if (field.repeat) for (let i = 0; i < fieldValue.length; i++) output[name][i] = T.create(fieldValue[i]); else if (output[name] === undefined) output[name] = T.create(fieldValue); // nothing to merge with else T.mergePartial(output[name], fieldValue); break; case "map": // Map and repeated fields are simply overwritten, not appended or merged switch (field.V.kind) { case "scalar": case "enum": Object.assign(output[name], fieldValue); // elements are not reference types break; case "message": let T = field.V.T(); for (let k of Object.keys(fieldValue)) output[name][k] = T.create(fieldValue[k]); break; } break; } } } exports.reflectionMergePartial = reflectionMergePartial; /***/ }), /***/ 74863: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.reflectionScalarDefault = void 0; const reflection_info_1 = __nccwpck_require__(21370); const reflection_long_convert_1 = __nccwpck_require__(24612); const pb_long_1 = __nccwpck_require__(47777); /** * Creates the default value for a scalar type. */ function reflectionScalarDefault(type, longType = reflection_info_1.LongType.STRING) { switch (type) { case reflection_info_1.ScalarType.BOOL: return false; case reflection_info_1.ScalarType.UINT64: case reflection_info_1.ScalarType.FIXED64: return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbULong.ZERO, longType); case reflection_info_1.ScalarType.INT64: case reflection_info_1.ScalarType.SFIXED64: case reflection_info_1.ScalarType.SINT64: return reflection_long_convert_1.reflectionLongConvert(pb_long_1.PbLong.ZERO, longType); case reflection_info_1.ScalarType.DOUBLE: case reflection_info_1.ScalarType.FLOAT: return 0.0; case reflection_info_1.ScalarType.BYTES: return new Uint8Array(0); case reflection_info_1.ScalarType.STRING: return ""; default: // case ScalarType.INT32: // case ScalarType.UINT32: // case ScalarType.SINT32: // case ScalarType.FIXED32: // case ScalarType.SFIXED32: return 0; } } exports.reflectionScalarDefault = reflectionScalarDefault; /***/ }), /***/ 20903: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ReflectionTypeCheck = void 0; const reflection_info_1 = __nccwpck_require__(21370); const oneof_1 = __nccwpck_require__(78531); // noinspection JSMethodCanBeStatic class ReflectionTypeCheck { constructor(info) { var _a; this.fields = (_a = info.fields) !== null && _a !== void 0 ? _a : []; } prepare() { if (this.data) return; const req = [], known = [], oneofs = []; for (let field of this.fields) { if (field.oneof) { if (!oneofs.includes(field.oneof)) { oneofs.push(field.oneof); req.push(field.oneof); known.push(field.oneof); } } else { known.push(field.localName); switch (field.kind) { case "scalar": case "enum": if (!field.opt || field.repeat) req.push(field.localName); break; case "message": if (field.repeat) req.push(field.localName); break; case "map": req.push(field.localName); break; } } } this.data = { req, known, oneofs: Object.values(oneofs) }; } /** * Is the argument a valid message as specified by the * reflection information? * * Checks all field types recursively. The `depth` * specifies how deep into the structure the check will be. * * With a depth of 0, only the presence of fields * is checked. * * With a depth of 1 or more, the field types are checked. * * With a depth of 2 or more, the members of map, repeated * and message fields are checked. * * Message fields will be checked recursively with depth - 1. * * The number of map entries / repeated values being checked * is < depth. */ is(message, depth, allowExcessProperties = false) { if (depth < 0) return true; if (message === null || message === undefined || typeof message != 'object') return false; this.prepare(); let keys = Object.keys(message), data = this.data; // if a required field is missing in arg, this cannot be a T if (keys.length < data.req.length || data.req.some(n => !keys.includes(n))) return false; if (!allowExcessProperties) { // if the arg contains a key we dont know, this is not a literal T if (keys.some(k => !data.known.includes(k))) return false; } // "With a depth of 0, only the presence and absence of fields is checked." // "With a depth of 1 or more, the field types are checked." if (depth < 1) { return true; } // check oneof group for (const name of data.oneofs) { const group = message[name]; if (!oneof_1.isOneofGroup(group)) return false; if (group.oneofKind === undefined) continue; const field = this.fields.find(f => f.localName === group.oneofKind); if (!field) return false; // we found no field, but have a kind, something is wrong if (!this.field(group[group.oneofKind], field, allowExcessProperties, depth)) return false; } // check types for (const field of this.fields) { if (field.oneof !== undefined) continue; if (!this.field(message[field.localName], field, allowExcessProperties, depth)) return false; } return true; } field(arg, field, allowExcessProperties, depth) { let repeated = field.repeat; switch (field.kind) { case "scalar": if (arg === undefined) return field.opt; if (repeated) return this.scalars(arg, field.T, depth, field.L); return this.scalar(arg, field.T, field.L); case "enum": if (arg === undefined) return field.opt; if (repeated) return this.scalars(arg, reflection_info_1.ScalarType.INT32, depth); return this.scalar(arg, reflection_info_1.ScalarType.INT32); case "message": if (arg === undefined) return true; if (repeated) return this.messages(arg, field.T(), allowExcessProperties, depth); return this.message(arg, field.T(), allowExcessProperties, depth); case "map": if (typeof arg != 'object' || arg === null) return false; if (depth < 2) return true; if (!this.mapKeys(arg, field.K, depth)) return false; switch (field.V.kind) { case "scalar": return this.scalars(Object.values(arg), field.V.T, depth, field.V.L); case "enum": return this.scalars(Object.values(arg), reflection_info_1.ScalarType.INT32, depth); case "message": return this.messages(Object.values(arg), field.V.T(), allowExcessProperties, depth); } break; } return true; } message(arg, type, allowExcessProperties, depth) { if (allowExcessProperties) { return type.isAssignable(arg, depth); } return type.is(arg, depth); } messages(arg, type, allowExcessProperties, depth) { if (!Array.isArray(arg)) return false; if (depth < 2) return true; if (allowExcessProperties) { for (let i = 0; i < arg.length && i < depth; i++) if (!type.isAssignable(arg[i], depth - 1)) return false; } else { for (let i = 0; i < arg.length && i < depth; i++) if (!type.is(arg[i], depth - 1)) return false; } return true; } scalar(arg, type, longType) { let argType = typeof arg; switch (type) { case reflection_info_1.ScalarType.UINT64: case reflection_info_1.ScalarType.FIXED64: case reflection_info_1.ScalarType.INT64: case reflection_info_1.ScalarType.SFIXED64: case reflection_info_1.ScalarType.SINT64: switch (longType) { case reflection_info_1.LongType.BIGINT: return argType == "bigint"; case reflection_info_1.LongType.NUMBER: return argType == "number" && !isNaN(arg); default: return argType == "string"; } case reflection_info_1.ScalarType.BOOL: return argType == 'boolean'; case reflection_info_1.ScalarType.STRING: return argType == 'string'; case reflection_info_1.ScalarType.BYTES: return arg instanceof Uint8Array; case reflection_info_1.ScalarType.DOUBLE: case reflection_info_1.ScalarType.FLOAT: return argType == 'number' && !isNaN(arg); default: // case ScalarType.UINT32: // case ScalarType.FIXED32: // case ScalarType.INT32: // case ScalarType.SINT32: // case ScalarType.SFIXED32: return argType == 'number' && Number.isInteger(arg); } } scalars(arg, type, depth, longType) { if (!Array.isArray(arg)) return false; if (depth < 2) return true; if (Array.isArray(arg)) for (let i = 0; i < arg.length && i < depth; i++) if (!this.scalar(arg[i], type, longType)) return false; return true; } mapKeys(map, type, depth) { let keys = Object.keys(map); switch (type) { case reflection_info_1.ScalarType.INT32: case reflection_info_1.ScalarType.FIXED32: case reflection_info_1.ScalarType.SFIXED32: case reflection_info_1.ScalarType.SINT32: case reflection_info_1.ScalarType.UINT32: return this.scalars(keys.slice(0, depth).map(k => parseInt(k)), type, depth); case reflection_info_1.ScalarType.BOOL: return this.scalars(keys.slice(0, depth).map(k => k == 'true' ? true : k == 'false' ? false : k), type, depth); default: return this.scalars(keys, type, depth, reflection_info_1.LongType.STRING); } } } exports.ReflectionTypeCheck = ReflectionTypeCheck; /***/ }), /***/ 53098: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { CONFIG_USE_DUALSTACK_ENDPOINT: () => CONFIG_USE_DUALSTACK_ENDPOINT, CONFIG_USE_FIPS_ENDPOINT: () => CONFIG_USE_FIPS_ENDPOINT, DEFAULT_USE_DUALSTACK_ENDPOINT: () => DEFAULT_USE_DUALSTACK_ENDPOINT, DEFAULT_USE_FIPS_ENDPOINT: () => DEFAULT_USE_FIPS_ENDPOINT, ENV_USE_DUALSTACK_ENDPOINT: () => ENV_USE_DUALSTACK_ENDPOINT, ENV_USE_FIPS_ENDPOINT: () => ENV_USE_FIPS_ENDPOINT, NODE_REGION_CONFIG_FILE_OPTIONS: () => NODE_REGION_CONFIG_FILE_OPTIONS, NODE_REGION_CONFIG_OPTIONS: () => NODE_REGION_CONFIG_OPTIONS, NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS: () => NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS: () => NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, REGION_ENV_NAME: () => REGION_ENV_NAME, REGION_INI_NAME: () => REGION_INI_NAME, getRegionInfo: () => getRegionInfo, resolveCustomEndpointsConfig: () => resolveCustomEndpointsConfig, resolveEndpointsConfig: () => resolveEndpointsConfig, resolveRegionConfig: () => resolveRegionConfig }); module.exports = __toCommonJS(src_exports); // src/endpointsConfig/NodeUseDualstackEndpointConfigOptions.ts var import_util_config_provider = __nccwpck_require__(83375); var ENV_USE_DUALSTACK_ENDPOINT = "AWS_USE_DUALSTACK_ENDPOINT"; var CONFIG_USE_DUALSTACK_ENDPOINT = "use_dualstack_endpoint"; var DEFAULT_USE_DUALSTACK_ENDPOINT = false; var NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS = { environmentVariableSelector: (env) => (0, import_util_config_provider.booleanSelector)(env, ENV_USE_DUALSTACK_ENDPOINT, import_util_config_provider.SelectorType.ENV), configFileSelector: (profile) => (0, import_util_config_provider.booleanSelector)(profile, CONFIG_USE_DUALSTACK_ENDPOINT, import_util_config_provider.SelectorType.CONFIG), default: false }; // src/endpointsConfig/NodeUseFipsEndpointConfigOptions.ts var ENV_USE_FIPS_ENDPOINT = "AWS_USE_FIPS_ENDPOINT"; var CONFIG_USE_FIPS_ENDPOINT = "use_fips_endpoint"; var DEFAULT_USE_FIPS_ENDPOINT = false; var NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS = { environmentVariableSelector: (env) => (0, import_util_config_provider.booleanSelector)(env, ENV_USE_FIPS_ENDPOINT, import_util_config_provider.SelectorType.ENV), configFileSelector: (profile) => (0, import_util_config_provider.booleanSelector)(profile, CONFIG_USE_FIPS_ENDPOINT, import_util_config_provider.SelectorType.CONFIG), default: false }; // src/endpointsConfig/resolveCustomEndpointsConfig.ts var import_util_middleware = __nccwpck_require__(2390); var resolveCustomEndpointsConfig = /* @__PURE__ */ __name((input) => { const { tls, endpoint, urlParser, useDualstackEndpoint } = input; return Object.assign(input, { tls: tls ?? true, endpoint: (0, import_util_middleware.normalizeProvider)(typeof endpoint === "string" ? urlParser(endpoint) : endpoint), isCustomEndpoint: true, useDualstackEndpoint: (0, import_util_middleware.normalizeProvider)(useDualstackEndpoint ?? false) }); }, "resolveCustomEndpointsConfig"); // src/endpointsConfig/resolveEndpointsConfig.ts // src/endpointsConfig/utils/getEndpointFromRegion.ts var getEndpointFromRegion = /* @__PURE__ */ __name(async (input) => { const { tls = true } = input; const region = await input.region(); const dnsHostRegex = new RegExp(/^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9])$/); if (!dnsHostRegex.test(region)) { throw new Error("Invalid region in client config"); } const useDualstackEndpoint = await input.useDualstackEndpoint(); const useFipsEndpoint = await input.useFipsEndpoint(); const { hostname } = await input.regionInfoProvider(region, { useDualstackEndpoint, useFipsEndpoint }) ?? {}; if (!hostname) { throw new Error("Cannot resolve hostname from client config"); } return input.urlParser(`${tls ? "https:" : "http:"}//${hostname}`); }, "getEndpointFromRegion"); // src/endpointsConfig/resolveEndpointsConfig.ts var resolveEndpointsConfig = /* @__PURE__ */ __name((input) => { const useDualstackEndpoint = (0, import_util_middleware.normalizeProvider)(input.useDualstackEndpoint ?? false); const { endpoint, useFipsEndpoint, urlParser, tls } = input; return Object.assign(input, { tls: tls ?? true, endpoint: endpoint ? (0, import_util_middleware.normalizeProvider)(typeof endpoint === "string" ? urlParser(endpoint) : endpoint) : () => getEndpointFromRegion({ ...input, useDualstackEndpoint, useFipsEndpoint }), isCustomEndpoint: !!endpoint, useDualstackEndpoint }); }, "resolveEndpointsConfig"); // src/regionConfig/config.ts var REGION_ENV_NAME = "AWS_REGION"; var REGION_INI_NAME = "region"; var NODE_REGION_CONFIG_OPTIONS = { environmentVariableSelector: (env) => env[REGION_ENV_NAME], configFileSelector: (profile) => profile[REGION_INI_NAME], default: () => { throw new Error("Region is missing"); } }; var NODE_REGION_CONFIG_FILE_OPTIONS = { preferredFile: "credentials" }; // src/regionConfig/isFipsRegion.ts var isFipsRegion = /* @__PURE__ */ __name((region) => typeof region === "string" && (region.startsWith("fips-") || region.endsWith("-fips")), "isFipsRegion"); // src/regionConfig/getRealRegion.ts var getRealRegion = /* @__PURE__ */ __name((region) => isFipsRegion(region) ? ["fips-aws-global", "aws-fips"].includes(region) ? "us-east-1" : region.replace(/fips-(dkr-|prod-)?|-fips/, "") : region, "getRealRegion"); // src/regionConfig/resolveRegionConfig.ts var resolveRegionConfig = /* @__PURE__ */ __name((input) => { const { region, useFipsEndpoint } = input; if (!region) { throw new Error("Region is missing"); } return Object.assign(input, { region: async () => { if (typeof region === "string") { return getRealRegion(region); } const providedRegion = await region(); return getRealRegion(providedRegion); }, useFipsEndpoint: async () => { const providedRegion = typeof region === "string" ? region : await region(); if (isFipsRegion(providedRegion)) { return true; } return typeof useFipsEndpoint !== "function" ? Promise.resolve(!!useFipsEndpoint) : useFipsEndpoint(); } }); }, "resolveRegionConfig"); // src/regionInfo/getHostnameFromVariants.ts var getHostnameFromVariants = /* @__PURE__ */ __name((variants = [], { useFipsEndpoint, useDualstackEndpoint }) => variants.find( ({ tags }) => useFipsEndpoint === tags.includes("fips") && useDualstackEndpoint === tags.includes("dualstack") )?.hostname, "getHostnameFromVariants"); // src/regionInfo/getResolvedHostname.ts var getResolvedHostname = /* @__PURE__ */ __name((resolvedRegion, { regionHostname, partitionHostname }) => regionHostname ? regionHostname : partitionHostname ? partitionHostname.replace("{region}", resolvedRegion) : void 0, "getResolvedHostname"); // src/regionInfo/getResolvedPartition.ts var getResolvedPartition = /* @__PURE__ */ __name((region, { partitionHash }) => Object.keys(partitionHash || {}).find((key) => partitionHash[key].regions.includes(region)) ?? "aws", "getResolvedPartition"); // src/regionInfo/getResolvedSigningRegion.ts var getResolvedSigningRegion = /* @__PURE__ */ __name((hostname, { signingRegion, regionRegex, useFipsEndpoint }) => { if (signingRegion) { return signingRegion; } else if (useFipsEndpoint) { const regionRegexJs = regionRegex.replace("\\\\", "\\").replace(/^\^/g, "\\.").replace(/\$$/g, "\\."); const regionRegexmatchArray = hostname.match(regionRegexJs); if (regionRegexmatchArray) { return regionRegexmatchArray[0].slice(1, -1); } } }, "getResolvedSigningRegion"); // src/regionInfo/getRegionInfo.ts var getRegionInfo = /* @__PURE__ */ __name((region, { useFipsEndpoint = false, useDualstackEndpoint = false, signingService, regionHash, partitionHash }) => { const partition = getResolvedPartition(region, { partitionHash }); const resolvedRegion = region in regionHash ? region : partitionHash[partition]?.endpoint ?? region; const hostnameOptions = { useFipsEndpoint, useDualstackEndpoint }; const regionHostname = getHostnameFromVariants(regionHash[resolvedRegion]?.variants, hostnameOptions); const partitionHostname = getHostnameFromVariants(partitionHash[partition]?.variants, hostnameOptions); const hostname = getResolvedHostname(resolvedRegion, { regionHostname, partitionHostname }); if (hostname === void 0) { throw new Error(`Endpoint resolution failed for: ${{ resolvedRegion, useFipsEndpoint, useDualstackEndpoint }}`); } const signingRegion = getResolvedSigningRegion(hostname, { signingRegion: regionHash[resolvedRegion]?.signingRegion, regionRegex: partitionHash[partition].regionRegex, useFipsEndpoint }); return { partition, signingService, hostname, ...signingRegion && { signingRegion }, ...regionHash[resolvedRegion]?.signingService && { signingService: regionHash[resolvedRegion].signingService } }; }, "getRegionInfo"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); /***/ }), /***/ 55829: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { DefaultIdentityProviderConfig: () => DefaultIdentityProviderConfig, EXPIRATION_MS: () => EXPIRATION_MS, HttpApiKeyAuthSigner: () => HttpApiKeyAuthSigner, HttpBearerAuthSigner: () => HttpBearerAuthSigner, NoAuthSigner: () => NoAuthSigner, createIsIdentityExpiredFunction: () => createIsIdentityExpiredFunction, createPaginator: () => createPaginator, doesIdentityRequireRefresh: () => doesIdentityRequireRefresh, getHttpAuthSchemeEndpointRuleSetPlugin: () => getHttpAuthSchemeEndpointRuleSetPlugin, getHttpAuthSchemePlugin: () => getHttpAuthSchemePlugin, getHttpSigningPlugin: () => getHttpSigningPlugin, getSmithyContext: () => getSmithyContext, httpAuthSchemeEndpointRuleSetMiddlewareOptions: () => httpAuthSchemeEndpointRuleSetMiddlewareOptions, httpAuthSchemeMiddleware: () => httpAuthSchemeMiddleware, httpAuthSchemeMiddlewareOptions: () => httpAuthSchemeMiddlewareOptions, httpSigningMiddleware: () => httpSigningMiddleware, httpSigningMiddlewareOptions: () => httpSigningMiddlewareOptions, isIdentityExpired: () => isIdentityExpired, memoizeIdentityProvider: () => memoizeIdentityProvider, normalizeProvider: () => normalizeProvider, requestBuilder: () => import_protocols.requestBuilder, setFeature: () => setFeature }); module.exports = __toCommonJS(src_exports); // src/getSmithyContext.ts var import_types = __nccwpck_require__(55756); var getSmithyContext = /* @__PURE__ */ __name((context) => context[import_types.SMITHY_CONTEXT_KEY] || (context[import_types.SMITHY_CONTEXT_KEY] = {}), "getSmithyContext"); // src/middleware-http-auth-scheme/httpAuthSchemeMiddleware.ts var import_util_middleware = __nccwpck_require__(2390); // src/middleware-http-auth-scheme/resolveAuthOptions.ts var resolveAuthOptions = /* @__PURE__ */ __name((candidateAuthOptions, authSchemePreference) => { if (!authSchemePreference || authSchemePreference.length === 0) { return candidateAuthOptions; } const preferredAuthOptions = []; for (const preferredSchemeName of authSchemePreference) { for (const candidateAuthOption of candidateAuthOptions) { const candidateAuthSchemeName = candidateAuthOption.schemeId.split("#")[1]; if (candidateAuthSchemeName === preferredSchemeName) { preferredAuthOptions.push(candidateAuthOption); } } } for (const candidateAuthOption of candidateAuthOptions) { if (!preferredAuthOptions.find(({ schemeId }) => schemeId === candidateAuthOption.schemeId)) { preferredAuthOptions.push(candidateAuthOption); } } return preferredAuthOptions; }, "resolveAuthOptions"); // src/middleware-http-auth-scheme/httpAuthSchemeMiddleware.ts function convertHttpAuthSchemesToMap(httpAuthSchemes) { const map = /* @__PURE__ */ new Map(); for (const scheme of httpAuthSchemes) { map.set(scheme.schemeId, scheme); } return map; } __name(convertHttpAuthSchemesToMap, "convertHttpAuthSchemesToMap"); var httpAuthSchemeMiddleware = /* @__PURE__ */ __name((config, mwOptions) => (next, context) => async (args) => { const options = config.httpAuthSchemeProvider( await mwOptions.httpAuthSchemeParametersProvider(config, context, args.input) ); const authSchemePreference = config.authSchemePreference ? await config.authSchemePreference() : []; const resolvedOptions = resolveAuthOptions(options, authSchemePreference); const authSchemes = convertHttpAuthSchemesToMap(config.httpAuthSchemes); const smithyContext = (0, import_util_middleware.getSmithyContext)(context); const failureReasons = []; for (const option of resolvedOptions) { const scheme = authSchemes.get(option.schemeId); if (!scheme) { failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` was not enabled for this service.`); continue; } const identityProvider = scheme.identityProvider(await mwOptions.identityProviderConfigProvider(config)); if (!identityProvider) { failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` did not have an IdentityProvider configured.`); continue; } const { identityProperties = {}, signingProperties = {} } = option.propertiesExtractor?.(config, context) || {}; option.identityProperties = Object.assign(option.identityProperties || {}, identityProperties); option.signingProperties = Object.assign(option.signingProperties || {}, signingProperties); smithyContext.selectedHttpAuthScheme = { httpAuthOption: option, identity: await identityProvider(option.identityProperties), signer: scheme.signer }; break; } if (!smithyContext.selectedHttpAuthScheme) { throw new Error(failureReasons.join("\n")); } return next(args); }, "httpAuthSchemeMiddleware"); // src/middleware-http-auth-scheme/getHttpAuthSchemeEndpointRuleSetPlugin.ts var httpAuthSchemeEndpointRuleSetMiddlewareOptions = { step: "serialize", tags: ["HTTP_AUTH_SCHEME"], name: "httpAuthSchemeMiddleware", override: true, relation: "before", toMiddleware: "endpointV2Middleware" }; var getHttpAuthSchemeEndpointRuleSetPlugin = /* @__PURE__ */ __name((config, { httpAuthSchemeParametersProvider, identityProviderConfigProvider }) => ({ applyToStack: (clientStack) => { clientStack.addRelativeTo( httpAuthSchemeMiddleware(config, { httpAuthSchemeParametersProvider, identityProviderConfigProvider }), httpAuthSchemeEndpointRuleSetMiddlewareOptions ); } }), "getHttpAuthSchemeEndpointRuleSetPlugin"); // src/middleware-http-auth-scheme/getHttpAuthSchemePlugin.ts var import_middleware_serde = __nccwpck_require__(81238); var httpAuthSchemeMiddlewareOptions = { step: "serialize", tags: ["HTTP_AUTH_SCHEME"], name: "httpAuthSchemeMiddleware", override: true, relation: "before", toMiddleware: import_middleware_serde.serializerMiddlewareOption.name }; var getHttpAuthSchemePlugin = /* @__PURE__ */ __name((config, { httpAuthSchemeParametersProvider, identityProviderConfigProvider }) => ({ applyToStack: (clientStack) => { clientStack.addRelativeTo( httpAuthSchemeMiddleware(config, { httpAuthSchemeParametersProvider, identityProviderConfigProvider }), httpAuthSchemeMiddlewareOptions ); } }), "getHttpAuthSchemePlugin"); // src/middleware-http-signing/httpSigningMiddleware.ts var import_protocol_http = __nccwpck_require__(64418); var defaultErrorHandler = /* @__PURE__ */ __name((signingProperties) => (error) => { throw error; }, "defaultErrorHandler"); var defaultSuccessHandler = /* @__PURE__ */ __name((httpResponse, signingProperties) => { }, "defaultSuccessHandler"); var httpSigningMiddleware = /* @__PURE__ */ __name((config) => (next, context) => async (args) => { if (!import_protocol_http.HttpRequest.isInstance(args.request)) { return next(args); } const smithyContext = (0, import_util_middleware.getSmithyContext)(context); const scheme = smithyContext.selectedHttpAuthScheme; if (!scheme) { throw new Error(`No HttpAuthScheme was selected: unable to sign request`); } const { httpAuthOption: { signingProperties = {} }, identity, signer } = scheme; const output = await next({ ...args, request: await signer.sign(args.request, identity, signingProperties) }).catch((signer.errorHandler || defaultErrorHandler)(signingProperties)); (signer.successHandler || defaultSuccessHandler)(output.response, signingProperties); return output; }, "httpSigningMiddleware"); // src/middleware-http-signing/getHttpSigningMiddleware.ts var httpSigningMiddlewareOptions = { step: "finalizeRequest", tags: ["HTTP_SIGNING"], name: "httpSigningMiddleware", aliases: ["apiKeyMiddleware", "tokenMiddleware", "awsAuthMiddleware"], override: true, relation: "after", toMiddleware: "retryMiddleware" }; var getHttpSigningPlugin = /* @__PURE__ */ __name((config) => ({ applyToStack: (clientStack) => { clientStack.addRelativeTo(httpSigningMiddleware(config), httpSigningMiddlewareOptions); } }), "getHttpSigningPlugin"); // src/normalizeProvider.ts var normalizeProvider = /* @__PURE__ */ __name((input) => { if (typeof input === "function") return input; const promisified = Promise.resolve(input); return () => promisified; }, "normalizeProvider"); // src/pagination/createPaginator.ts var makePagedClientRequest = /* @__PURE__ */ __name(async (CommandCtor, client, input, withCommand = (_) => _, ...args) => { let command = new CommandCtor(input); command = withCommand(command) ?? command; return await client.send(command, ...args); }, "makePagedClientRequest"); function createPaginator(ClientCtor, CommandCtor, inputTokenName, outputTokenName, pageSizeTokenName) { return /* @__PURE__ */ __name(async function* paginateOperation(config, input, ...additionalArguments) { const _input = input; let token = config.startingToken ?? _input[inputTokenName]; let hasNext = true; let page; while (hasNext) { _input[inputTokenName] = token; if (pageSizeTokenName) { _input[pageSizeTokenName] = _input[pageSizeTokenName] ?? config.pageSize; } if (config.client instanceof ClientCtor) { page = await makePagedClientRequest( CommandCtor, config.client, input, config.withCommand, ...additionalArguments ); } else { throw new Error(`Invalid client, expected instance of ${ClientCtor.name}`); } yield page; const prevToken = token; token = get(page, outputTokenName); hasNext = !!(token && (!config.stopOnSameToken || token !== prevToken)); } return void 0; }, "paginateOperation"); } __name(createPaginator, "createPaginator"); var get = /* @__PURE__ */ __name((fromObject, path) => { let cursor = fromObject; const pathComponents = path.split("."); for (const step of pathComponents) { if (!cursor || typeof cursor !== "object") { return void 0; } cursor = cursor[step]; } return cursor; }, "get"); // src/protocols/requestBuilder.ts var import_protocols = __nccwpck_require__(2241); // src/setFeature.ts function setFeature(context, feature, value) { if (!context.__smithy_context) { context.__smithy_context = { features: {} }; } else if (!context.__smithy_context.features) { context.__smithy_context.features = {}; } context.__smithy_context.features[feature] = value; } __name(setFeature, "setFeature"); // src/util-identity-and-auth/DefaultIdentityProviderConfig.ts var DefaultIdentityProviderConfig = class { /** * Creates an IdentityProviderConfig with a record of scheme IDs to identity providers. * * @param config scheme IDs and identity providers to configure */ constructor(config) { this.authSchemes = /* @__PURE__ */ new Map(); for (const [key, value] of Object.entries(config)) { if (value !== void 0) { this.authSchemes.set(key, value); } } } static { __name(this, "DefaultIdentityProviderConfig"); } getIdentityProvider(schemeId) { return this.authSchemes.get(schemeId); } }; // src/util-identity-and-auth/httpAuthSchemes/httpApiKeyAuth.ts var HttpApiKeyAuthSigner = class { static { __name(this, "HttpApiKeyAuthSigner"); } async sign(httpRequest, identity, signingProperties) { if (!signingProperties) { throw new Error( "request could not be signed with `apiKey` since the `name` and `in` signer properties are missing" ); } if (!signingProperties.name) { throw new Error("request could not be signed with `apiKey` since the `name` signer property is missing"); } if (!signingProperties.in) { throw new Error("request could not be signed with `apiKey` since the `in` signer property is missing"); } if (!identity.apiKey) { throw new Error("request could not be signed with `apiKey` since the `apiKey` is not defined"); } const clonedRequest = import_protocol_http.HttpRequest.clone(httpRequest); if (signingProperties.in === import_types.HttpApiKeyAuthLocation.QUERY) { clonedRequest.query[signingProperties.name] = identity.apiKey; } else if (signingProperties.in === import_types.HttpApiKeyAuthLocation.HEADER) { clonedRequest.headers[signingProperties.name] = signingProperties.scheme ? `${signingProperties.scheme} ${identity.apiKey}` : identity.apiKey; } else { throw new Error( "request can only be signed with `apiKey` locations `query` or `header`, but found: `" + signingProperties.in + "`" ); } return clonedRequest; } }; // src/util-identity-and-auth/httpAuthSchemes/httpBearerAuth.ts var HttpBearerAuthSigner = class { static { __name(this, "HttpBearerAuthSigner"); } async sign(httpRequest, identity, signingProperties) { const clonedRequest = import_protocol_http.HttpRequest.clone(httpRequest); if (!identity.token) { throw new Error("request could not be signed with `token` since the `token` is not defined"); } clonedRequest.headers["Authorization"] = `Bearer ${identity.token}`; return clonedRequest; } }; // src/util-identity-and-auth/httpAuthSchemes/noAuth.ts var NoAuthSigner = class { static { __name(this, "NoAuthSigner"); } async sign(httpRequest, identity, signingProperties) { return httpRequest; } }; // src/util-identity-and-auth/memoizeIdentityProvider.ts var createIsIdentityExpiredFunction = /* @__PURE__ */ __name((expirationMs) => (identity) => doesIdentityRequireRefresh(identity) && identity.expiration.getTime() - Date.now() < expirationMs, "createIsIdentityExpiredFunction"); var EXPIRATION_MS = 3e5; var isIdentityExpired = createIsIdentityExpiredFunction(EXPIRATION_MS); var doesIdentityRequireRefresh = /* @__PURE__ */ __name((identity) => identity.expiration !== void 0, "doesIdentityRequireRefresh"); var memoizeIdentityProvider = /* @__PURE__ */ __name((provider, isExpired, requiresRefresh) => { if (provider === void 0) { return void 0; } const normalizedProvider = typeof provider !== "function" ? async () => Promise.resolve(provider) : provider; let resolved; let pending; let hasResult; let isConstant = false; const coalesceProvider = /* @__PURE__ */ __name(async (options) => { if (!pending) { pending = normalizedProvider(options); } try { resolved = await pending; hasResult = true; isConstant = false; } finally { pending = void 0; } return resolved; }, "coalesceProvider"); if (isExpired === void 0) { return async (options) => { if (!hasResult || options?.forceRefresh) { resolved = await coalesceProvider(options); } return resolved; }; } return async (options) => { if (!hasResult || options?.forceRefresh) { resolved = await coalesceProvider(options); } if (isConstant) { return resolved; } if (!requiresRefresh(resolved)) { isConstant = true; return resolved; } if (isExpired(resolved)) { await coalesceProvider(options); return resolved; } return resolved; }; }, "memoizeIdentityProvider"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); /***/ }), /***/ 2241: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/submodules/protocols/index.ts var protocols_exports = {}; __export(protocols_exports, { FromStringShapeDeserializer: () => FromStringShapeDeserializer, HttpBindingProtocol: () => HttpBindingProtocol, HttpInterceptingShapeDeserializer: () => HttpInterceptingShapeDeserializer, HttpInterceptingShapeSerializer: () => HttpInterceptingShapeSerializer, RequestBuilder: () => RequestBuilder, RpcProtocol: () => RpcProtocol, ToStringShapeSerializer: () => ToStringShapeSerializer, collectBody: () => collectBody, determineTimestampFormat: () => determineTimestampFormat, extendedEncodeURIComponent: () => extendedEncodeURIComponent, requestBuilder: () => requestBuilder, resolvedPath: () => resolvedPath }); module.exports = __toCommonJS(protocols_exports); // src/submodules/protocols/collect-stream-body.ts var import_util_stream = __nccwpck_require__(96607); var collectBody = async (streamBody = new Uint8Array(), context) => { if (streamBody instanceof Uint8Array) { return import_util_stream.Uint8ArrayBlobAdapter.mutate(streamBody); } if (!streamBody) { return import_util_stream.Uint8ArrayBlobAdapter.mutate(new Uint8Array()); } const fromContext = context.streamCollector(streamBody); return import_util_stream.Uint8ArrayBlobAdapter.mutate(await fromContext); }; // src/submodules/protocols/extended-encode-uri-component.ts function extendedEncodeURIComponent(str) { return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { return "%" + c.charCodeAt(0).toString(16).toUpperCase(); }); } // src/submodules/protocols/HttpBindingProtocol.ts var import_schema2 = __nccwpck_require__(19826); var import_protocol_http2 = __nccwpck_require__(64418); // src/submodules/protocols/HttpProtocol.ts var import_schema = __nccwpck_require__(19826); var import_serde = __nccwpck_require__(27669); var import_protocol_http = __nccwpck_require__(64418); var import_util_stream2 = __nccwpck_require__(96607); var HttpProtocol = class { constructor(options) { this.options = options; } getRequestType() { return import_protocol_http.HttpRequest; } getResponseType() { return import_protocol_http.HttpResponse; } setSerdeContext(serdeContext) { this.serdeContext = serdeContext; this.serializer.setSerdeContext(serdeContext); this.deserializer.setSerdeContext(serdeContext); if (this.getPayloadCodec()) { this.getPayloadCodec().setSerdeContext(serdeContext); } } updateServiceEndpoint(request, endpoint) { if ("url" in endpoint) { request.protocol = endpoint.url.protocol; request.hostname = endpoint.url.hostname; request.port = endpoint.url.port ? Number(endpoint.url.port) : void 0; request.path = endpoint.url.pathname; request.fragment = endpoint.url.hash || void 0; request.username = endpoint.url.username || void 0; request.password = endpoint.url.password || void 0; for (const [k, v] of endpoint.url.searchParams.entries()) { if (!request.query) { request.query = {}; } request.query[k] = v; } return request; } else { request.protocol = endpoint.protocol; request.hostname = endpoint.hostname; request.port = endpoint.port ? Number(endpoint.port) : void 0; request.path = endpoint.path; request.query = { ...endpoint.query }; return request; } } setHostPrefix(request, operationSchema, input) { const operationNs = import_schema.NormalizedSchema.of(operationSchema); const inputNs = import_schema.NormalizedSchema.of(operationSchema.input); if (operationNs.getMergedTraits().endpoint) { let hostPrefix = operationNs.getMergedTraits().endpoint?.[0]; if (typeof hostPrefix === "string") { const hostLabelInputs = [...inputNs.structIterator()].filter( ([, member]) => member.getMergedTraits().hostLabel ); for (const [name] of hostLabelInputs) { const replacement = input[name]; if (typeof replacement !== "string") { throw new Error(`@smithy/core/schema - ${name} in input must be a string as hostLabel.`); } hostPrefix = hostPrefix.replace(`{${name}}`, replacement); } request.hostname = hostPrefix + request.hostname; } } } deserializeMetadata(output) { return { httpStatusCode: output.statusCode, requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"], extendedRequestId: output.headers["x-amz-id-2"], cfId: output.headers["x-amz-cf-id"] }; } async deserializeHttpMessage(schema, context, response, arg4, arg5) { let dataObject; if (arg4 instanceof Set) { dataObject = arg5; } else { dataObject = arg4; } const deserializer = this.deserializer; const ns = import_schema.NormalizedSchema.of(schema); const nonHttpBindingMembers = []; for (const [memberName, memberSchema] of ns.structIterator()) { const memberTraits = memberSchema.getMemberTraits(); if (memberTraits.httpPayload) { const isStreaming = memberSchema.isStreaming(); if (isStreaming) { const isEventStream = memberSchema.isStructSchema(); if (isEventStream) { const context2 = this.serdeContext; if (!context2.eventStreamMarshaller) { throw new Error("@smithy/core - HttpProtocol: eventStreamMarshaller missing in serdeContext."); } const memberSchemas = memberSchema.getMemberSchemas(); dataObject[memberName] = context2.eventStreamMarshaller.deserialize(response.body, async (event) => { const unionMember = Object.keys(event).find((key) => { return key !== "__type"; }) ?? ""; if (unionMember in memberSchemas) { const eventStreamSchema = memberSchemas[unionMember]; return { [unionMember]: await deserializer.read(eventStreamSchema, event[unionMember].body) }; } else { return { $unknown: event }; } }); } else { dataObject[memberName] = (0, import_util_stream2.sdkStreamMixin)(response.body); } } else if (response.body) { const bytes = await collectBody(response.body, context); if (bytes.byteLength > 0) { dataObject[memberName] = await deserializer.read(memberSchema, bytes); } } } else if (memberTraits.httpHeader) { const key = String(memberTraits.httpHeader).toLowerCase(); const value = response.headers[key]; if (null != value) { if (memberSchema.isListSchema()) { const headerListValueSchema = memberSchema.getValueSchema(); let sections; if (headerListValueSchema.isTimestampSchema() && headerListValueSchema.getSchema() === import_schema.SCHEMA.TIMESTAMP_DEFAULT) { sections = (0, import_serde.splitEvery)(value, ",", 2); } else { sections = (0, import_serde.splitHeader)(value); } const list = []; for (const section of sections) { list.push(await deserializer.read([headerListValueSchema, { httpHeader: key }], section.trim())); } dataObject[memberName] = list; } else { dataObject[memberName] = await deserializer.read(memberSchema, value); } } } else if (memberTraits.httpPrefixHeaders !== void 0) { dataObject[memberName] = {}; for (const [header, value] of Object.entries(response.headers)) { if (header.startsWith(memberTraits.httpPrefixHeaders)) { dataObject[memberName][header.slice(memberTraits.httpPrefixHeaders.length)] = await deserializer.read( [memberSchema.getValueSchema(), { httpHeader: header }], value ); } } } else if (memberTraits.httpResponseCode) { dataObject[memberName] = response.statusCode; } else { nonHttpBindingMembers.push(memberName); } } return nonHttpBindingMembers; } }; // src/submodules/protocols/HttpBindingProtocol.ts var HttpBindingProtocol = class extends HttpProtocol { async serializeRequest(operationSchema, input, context) { const serializer = this.serializer; const query = {}; const headers = {}; const endpoint = await context.endpoint(); const ns = import_schema2.NormalizedSchema.of(operationSchema?.input); const schema = ns.getSchema(); let hasNonHttpBindingMember = false; let payload; const request = new import_protocol_http2.HttpRequest({ protocol: "", hostname: "", port: void 0, path: "", fragment: void 0, query, headers, body: void 0 }); if (endpoint) { this.updateServiceEndpoint(request, endpoint); this.setHostPrefix(request, operationSchema, input); const opTraits = import_schema2.NormalizedSchema.translateTraits(operationSchema.traits); if (opTraits.http) { request.method = opTraits.http[0]; const [path, search] = opTraits.http[1].split("?"); if (request.path == "/") { request.path = path; } else { request.path += path; } const traitSearchParams = new URLSearchParams(search ?? ""); Object.assign(query, Object.fromEntries(traitSearchParams)); } } const _input = { ...input }; for (const memberName of Object.keys(_input)) { const memberNs = ns.getMemberSchema(memberName); if (memberNs === void 0) { continue; } const memberTraits = memberNs.getMergedTraits(); const inputMember = _input[memberName]; if (memberTraits.httpPayload) { const isStreaming = memberNs.isStreaming(); if (isStreaming) { const isEventStream = memberNs.isStructSchema(); if (isEventStream) { throw new Error("serialization of event streams is not yet implemented"); } else { payload = inputMember; } } else { serializer.write(memberNs, inputMember); payload = serializer.flush(); } } else if (memberTraits.httpLabel) { serializer.write(memberNs, inputMember); const replacement = serializer.flush(); if (request.path.includes(`{${memberName}+}`)) { request.path = request.path.replace( `{${memberName}+}`, replacement.split("/").map(extendedEncodeURIComponent).join("/") ); } else if (request.path.includes(`{${memberName}}`)) { request.path = request.path.replace(`{${memberName}}`, extendedEncodeURIComponent(replacement)); } delete _input[memberName]; } else if (memberTraits.httpHeader) { serializer.write(memberNs, inputMember); headers[memberTraits.httpHeader.toLowerCase()] = String(serializer.flush()); delete _input[memberName]; } else if (typeof memberTraits.httpPrefixHeaders === "string") { for (const [key, val] of Object.entries(inputMember)) { const amalgam = memberTraits.httpPrefixHeaders + key; serializer.write([memberNs.getValueSchema(), { httpHeader: amalgam }], val); headers[amalgam.toLowerCase()] = serializer.flush(); } delete _input[memberName]; } else if (memberTraits.httpQuery || memberTraits.httpQueryParams) { this.serializeQuery(memberNs, inputMember, query); delete _input[memberName]; } else { hasNonHttpBindingMember = true; } } if (hasNonHttpBindingMember && input) { serializer.write(schema, _input); payload = serializer.flush(); } request.headers = headers; request.query = query; request.body = payload; return request; } serializeQuery(ns, data, query) { const serializer = this.serializer; const traits = ns.getMergedTraits(); if (traits.httpQueryParams) { for (const [key, val] of Object.entries(data)) { if (!(key in query)) { this.serializeQuery( import_schema2.NormalizedSchema.of([ ns.getValueSchema(), { // We pass on the traits to the sub-schema // because we are still in the process of serializing the map itself. ...traits, httpQuery: key, httpQueryParams: void 0 } ]), val, query ); } } return; } if (ns.isListSchema()) { const sparse = !!ns.getMergedTraits().sparse; const buffer = []; for (const item of data) { serializer.write([ns.getValueSchema(), traits], item); const serializable = serializer.flush(); if (sparse || serializable !== void 0) { buffer.push(serializable); } } query[traits.httpQuery] = buffer; } else { serializer.write([ns, traits], data); query[traits.httpQuery] = serializer.flush(); } } async deserializeResponse(operationSchema, context, response) { const deserializer = this.deserializer; const ns = import_schema2.NormalizedSchema.of(operationSchema.output); const dataObject = {}; if (response.statusCode >= 300) { const bytes = await collectBody(response.body, context); if (bytes.byteLength > 0) { Object.assign(dataObject, await deserializer.read(import_schema2.SCHEMA.DOCUMENT, bytes)); } await this.handleError(operationSchema, context, response, dataObject, this.deserializeMetadata(response)); throw new Error("@smithy/core/protocols - HTTP Protocol error handler failed to throw."); } for (const header in response.headers) { const value = response.headers[header]; delete response.headers[header]; response.headers[header.toLowerCase()] = value; } const nonHttpBindingMembers = await this.deserializeHttpMessage(ns, context, response, dataObject); if (nonHttpBindingMembers.length) { const bytes = await collectBody(response.body, context); if (bytes.byteLength > 0) { const dataFromBody = await deserializer.read(ns, bytes); for (const member of nonHttpBindingMembers) { dataObject[member] = dataFromBody[member]; } } } const output = { $metadata: this.deserializeMetadata(response), ...dataObject }; return output; } }; // src/submodules/protocols/RpcProtocol.ts var import_schema3 = __nccwpck_require__(19826); var import_protocol_http3 = __nccwpck_require__(64418); var RpcProtocol = class extends HttpProtocol { async serializeRequest(operationSchema, input, context) { const serializer = this.serializer; const query = {}; const headers = {}; const endpoint = await context.endpoint(); const ns = import_schema3.NormalizedSchema.of(operationSchema?.input); const schema = ns.getSchema(); let payload; const request = new import_protocol_http3.HttpRequest({ protocol: "", hostname: "", port: void 0, path: "/", fragment: void 0, query, headers, body: void 0 }); if (endpoint) { this.updateServiceEndpoint(request, endpoint); this.setHostPrefix(request, operationSchema, input); } const _input = { ...input }; if (input) { serializer.write(schema, _input); payload = serializer.flush(); } request.headers = headers; request.query = query; request.body = payload; request.method = "POST"; return request; } async deserializeResponse(operationSchema, context, response) { const deserializer = this.deserializer; const ns = import_schema3.NormalizedSchema.of(operationSchema.output); const dataObject = {}; if (response.statusCode >= 300) { const bytes2 = await collectBody(response.body, context); if (bytes2.byteLength > 0) { Object.assign(dataObject, await deserializer.read(import_schema3.SCHEMA.DOCUMENT, bytes2)); } await this.handleError(operationSchema, context, response, dataObject, this.deserializeMetadata(response)); throw new Error("@smithy/core/protocols - RPC Protocol error handler failed to throw."); } for (const header in response.headers) { const value = response.headers[header]; delete response.headers[header]; response.headers[header.toLowerCase()] = value; } const bytes = await collectBody(response.body, context); if (bytes.byteLength > 0) { Object.assign(dataObject, await deserializer.read(ns, bytes)); } const output = { $metadata: this.deserializeMetadata(response), ...dataObject }; return output; } }; // src/submodules/protocols/requestBuilder.ts var import_protocol_http4 = __nccwpck_require__(64418); // src/submodules/protocols/resolve-path.ts var resolvedPath = (resolvedPath2, input, memberName, labelValueProvider, uriLabel, isGreedyLabel) => { if (input != null && input[memberName] !== void 0) { const labelValue = labelValueProvider(); if (labelValue.length <= 0) { throw new Error("Empty value provided for input HTTP label: " + memberName + "."); } resolvedPath2 = resolvedPath2.replace( uriLabel, isGreedyLabel ? labelValue.split("/").map((segment) => extendedEncodeURIComponent(segment)).join("/") : extendedEncodeURIComponent(labelValue) ); } else { throw new Error("No value provided for input HTTP label: " + memberName + "."); } return resolvedPath2; }; // src/submodules/protocols/requestBuilder.ts function requestBuilder(input, context) { return new RequestBuilder(input, context); } var RequestBuilder = class { constructor(input, context) { this.input = input; this.context = context; this.query = {}; this.method = ""; this.headers = {}; this.path = ""; this.body = null; this.hostname = ""; this.resolvePathStack = []; } async build() { const { hostname, protocol = "https", port, path: basePath } = await this.context.endpoint(); this.path = basePath; for (const resolvePath of this.resolvePathStack) { resolvePath(this.path); } return new import_protocol_http4.HttpRequest({ protocol, hostname: this.hostname || hostname, port, method: this.method, path: this.path, query: this.query, body: this.body, headers: this.headers }); } /** * Brevity setter for "hostname". */ hn(hostname) { this.hostname = hostname; return this; } /** * Brevity initial builder for "basepath". */ bp(uriLabel) { this.resolvePathStack.push((basePath) => { this.path = `${basePath?.endsWith("/") ? basePath.slice(0, -1) : basePath || ""}` + uriLabel; }); return this; } /** * Brevity incremental builder for "path". */ p(memberName, labelValueProvider, uriLabel, isGreedyLabel) { this.resolvePathStack.push((path) => { this.path = resolvedPath(path, this.input, memberName, labelValueProvider, uriLabel, isGreedyLabel); }); return this; } /** * Brevity setter for "headers". */ h(headers) { this.headers = headers; return this; } /** * Brevity setter for "query". */ q(query) { this.query = query; return this; } /** * Brevity setter for "body". */ b(body) { this.body = body; return this; } /** * Brevity setter for "method". */ m(method) { this.method = method; return this; } }; // src/submodules/protocols/serde/FromStringShapeDeserializer.ts var import_schema5 = __nccwpck_require__(19826); var import_serde2 = __nccwpck_require__(27669); var import_util_base64 = __nccwpck_require__(75600); var import_util_utf8 = __nccwpck_require__(41895); // src/submodules/protocols/serde/determineTimestampFormat.ts var import_schema4 = __nccwpck_require__(19826); function determineTimestampFormat(ns, settings) { if (settings.timestampFormat.useTrait) { if (ns.isTimestampSchema() && (ns.getSchema() === import_schema4.SCHEMA.TIMESTAMP_DATE_TIME || ns.getSchema() === import_schema4.SCHEMA.TIMESTAMP_HTTP_DATE || ns.getSchema() === import_schema4.SCHEMA.TIMESTAMP_EPOCH_SECONDS)) { return ns.getSchema(); } } const { httpLabel, httpPrefixHeaders, httpHeader, httpQuery } = ns.getMergedTraits(); const bindingFormat = settings.httpBindings ? typeof httpPrefixHeaders === "string" || Boolean(httpHeader) ? import_schema4.SCHEMA.TIMESTAMP_HTTP_DATE : Boolean(httpQuery) || Boolean(httpLabel) ? import_schema4.SCHEMA.TIMESTAMP_DATE_TIME : void 0 : void 0; return bindingFormat ?? settings.timestampFormat.default; } // src/submodules/protocols/serde/FromStringShapeDeserializer.ts var FromStringShapeDeserializer = class { constructor(settings) { this.settings = settings; } setSerdeContext(serdeContext) { this.serdeContext = serdeContext; } read(_schema, data) { const ns = import_schema5.NormalizedSchema.of(_schema); if (ns.isListSchema()) { return (0, import_serde2.splitHeader)(data).map((item) => this.read(ns.getValueSchema(), item)); } if (ns.isBlobSchema()) { return (this.serdeContext?.base64Decoder ?? import_util_base64.fromBase64)(data); } if (ns.isTimestampSchema()) { const format = determineTimestampFormat(ns, this.settings); switch (format) { case import_schema5.SCHEMA.TIMESTAMP_DATE_TIME: return (0, import_serde2.parseRfc3339DateTimeWithOffset)(data); case import_schema5.SCHEMA.TIMESTAMP_HTTP_DATE: return (0, import_serde2.parseRfc7231DateTime)(data); case import_schema5.SCHEMA.TIMESTAMP_EPOCH_SECONDS: return (0, import_serde2.parseEpochTimestamp)(data); default: console.warn("Missing timestamp format, parsing value with Date constructor:", data); return new Date(data); } } if (ns.isStringSchema()) { const mediaType = ns.getMergedTraits().mediaType; let intermediateValue = data; if (mediaType) { if (ns.getMergedTraits().httpHeader) { intermediateValue = this.base64ToUtf8(intermediateValue); } const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); if (isJson) { intermediateValue = import_serde2.LazyJsonString.from(intermediateValue); } return intermediateValue; } } switch (true) { case ns.isNumericSchema(): return Number(data); case ns.isBigIntegerSchema(): return BigInt(data); case ns.isBigDecimalSchema(): return new import_serde2.NumericValue(data, "bigDecimal"); case ns.isBooleanSchema(): return String(data).toLowerCase() === "true"; } return data; } base64ToUtf8(base64String) { return (this.serdeContext?.utf8Encoder ?? import_util_utf8.toUtf8)((this.serdeContext?.base64Decoder ?? import_util_base64.fromBase64)(base64String)); } }; // src/submodules/protocols/serde/HttpInterceptingShapeDeserializer.ts var import_schema6 = __nccwpck_require__(19826); var import_util_utf82 = __nccwpck_require__(41895); var HttpInterceptingShapeDeserializer = class { constructor(codecDeserializer, codecSettings) { this.codecDeserializer = codecDeserializer; this.stringDeserializer = new FromStringShapeDeserializer(codecSettings); } setSerdeContext(serdeContext) { this.stringDeserializer.setSerdeContext(serdeContext); this.codecDeserializer.setSerdeContext(serdeContext); this.serdeContext = serdeContext; } read(schema, data) { const ns = import_schema6.NormalizedSchema.of(schema); const traits = ns.getMergedTraits(); const toString = this.serdeContext?.utf8Encoder ?? import_util_utf82.toUtf8; if (traits.httpHeader || traits.httpResponseCode) { return this.stringDeserializer.read(ns, toString(data)); } if (traits.httpPayload) { if (ns.isBlobSchema()) { const toBytes = this.serdeContext?.utf8Decoder ?? import_util_utf82.fromUtf8; if (typeof data === "string") { return toBytes(data); } return data; } else if (ns.isStringSchema()) { if ("byteLength" in data) { return toString(data); } return data; } } return this.codecDeserializer.read(ns, data); } }; // src/submodules/protocols/serde/HttpInterceptingShapeSerializer.ts var import_schema8 = __nccwpck_require__(19826); // src/submodules/protocols/serde/ToStringShapeSerializer.ts var import_schema7 = __nccwpck_require__(19826); var import_serde3 = __nccwpck_require__(27669); var import_util_base642 = __nccwpck_require__(75600); var ToStringShapeSerializer = class { constructor(settings) { this.settings = settings; this.stringBuffer = ""; this.serdeContext = void 0; } setSerdeContext(serdeContext) { this.serdeContext = serdeContext; } write(schema, value) { const ns = import_schema7.NormalizedSchema.of(schema); switch (typeof value) { case "object": if (value === null) { this.stringBuffer = "null"; return; } if (ns.isTimestampSchema()) { if (!(value instanceof Date)) { throw new Error( `@smithy/core/protocols - received non-Date value ${value} when schema expected Date in ${ns.getName(true)}` ); } const format = determineTimestampFormat(ns, this.settings); switch (format) { case import_schema7.SCHEMA.TIMESTAMP_DATE_TIME: this.stringBuffer = value.toISOString().replace(".000Z", "Z"); break; case import_schema7.SCHEMA.TIMESTAMP_HTTP_DATE: this.stringBuffer = (0, import_serde3.dateToUtcString)(value); break; case import_schema7.SCHEMA.TIMESTAMP_EPOCH_SECONDS: this.stringBuffer = String(value.getTime() / 1e3); break; default: console.warn("Missing timestamp format, using epoch seconds", value); this.stringBuffer = String(value.getTime() / 1e3); } return; } if (ns.isBlobSchema() && "byteLength" in value) { this.stringBuffer = (this.serdeContext?.base64Encoder ?? import_util_base642.toBase64)(value); return; } if (ns.isListSchema() && Array.isArray(value)) { let buffer = ""; for (const item of value) { this.write([ns.getValueSchema(), ns.getMergedTraits()], item); const headerItem = this.flush(); const serialized = ns.getValueSchema().isTimestampSchema() ? headerItem : (0, import_serde3.quoteHeader)(headerItem); if (buffer !== "") { buffer += ", "; } buffer += serialized; } this.stringBuffer = buffer; return; } this.stringBuffer = JSON.stringify(value, null, 2); break; case "string": const mediaType = ns.getMergedTraits().mediaType; let intermediateValue = value; if (mediaType) { const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); if (isJson) { intermediateValue = import_serde3.LazyJsonString.from(intermediateValue); } if (ns.getMergedTraits().httpHeader) { this.stringBuffer = (this.serdeContext?.base64Encoder ?? import_util_base642.toBase64)(intermediateValue.toString()); return; } } this.stringBuffer = value; break; default: this.stringBuffer = String(value); } } flush() { const buffer = this.stringBuffer; this.stringBuffer = ""; return buffer; } }; // src/submodules/protocols/serde/HttpInterceptingShapeSerializer.ts var HttpInterceptingShapeSerializer = class { constructor(codecSerializer, codecSettings, stringSerializer = new ToStringShapeSerializer(codecSettings)) { this.codecSerializer = codecSerializer; this.stringSerializer = stringSerializer; } setSerdeContext(serdeContext) { this.codecSerializer.setSerdeContext(serdeContext); this.stringSerializer.setSerdeContext(serdeContext); } write(schema, value) { const ns = import_schema8.NormalizedSchema.of(schema); const traits = ns.getMergedTraits(); if (traits.httpHeader || traits.httpLabel || traits.httpQuery) { this.stringSerializer.write(ns, value); this.buffer = this.stringSerializer.flush(); return; } return this.codecSerializer.write(ns, value); } flush() { if (this.buffer !== void 0) { const buffer = this.buffer; this.buffer = void 0; return buffer; } return this.codecSerializer.flush(); } }; // Annotate the CommonJS export names for ESM import in node: 0 && (0); /***/ }), /***/ 19826: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/submodules/schema/index.ts var schema_exports = {}; __export(schema_exports, { ErrorSchema: () => ErrorSchema, ListSchema: () => ListSchema, MapSchema: () => MapSchema, NormalizedSchema: () => NormalizedSchema, OperationSchema: () => OperationSchema, SCHEMA: () => SCHEMA, Schema: () => Schema, SimpleSchema: () => SimpleSchema, StructureSchema: () => StructureSchema, TypeRegistry: () => TypeRegistry, deref: () => deref, deserializerMiddlewareOption: () => deserializerMiddlewareOption, error: () => error, getSchemaSerdePlugin: () => getSchemaSerdePlugin, list: () => list, map: () => map, op: () => op, serializerMiddlewareOption: () => serializerMiddlewareOption, sim: () => sim, struct: () => struct }); module.exports = __toCommonJS(schema_exports); // src/submodules/schema/deref.ts var deref = (schemaRef) => { if (typeof schemaRef === "function") { return schemaRef(); } return schemaRef; }; // src/submodules/schema/middleware/schemaDeserializationMiddleware.ts var import_protocol_http = __nccwpck_require__(64418); var import_util_middleware = __nccwpck_require__(2390); var schemaDeserializationMiddleware = (config) => (next, context) => async (args) => { const { response } = await next(args); const { operationSchema } = (0, import_util_middleware.getSmithyContext)(context); try { const parsed = await config.protocol.deserializeResponse( operationSchema, { ...config, ...context }, response ); return { response, output: parsed }; } catch (error2) { Object.defineProperty(error2, "$response", { value: response }); if (!("$metadata" in error2)) { const hint = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`; try { error2.message += "\n " + hint; } catch (e) { if (!context.logger || context.logger?.constructor?.name === "NoOpLogger") { console.warn(hint); } else { context.logger?.warn?.(hint); } } if (typeof error2.$responseBodyText !== "undefined") { if (error2.$response) { error2.$response.body = error2.$responseBodyText; } } try { if (import_protocol_http.HttpResponse.isInstance(response)) { const { headers = {} } = response; const headerEntries = Object.entries(headers); error2.$metadata = { httpStatusCode: response.statusCode, requestId: findHeader(/^x-[\w-]+-request-?id$/, headerEntries), extendedRequestId: findHeader(/^x-[\w-]+-id-2$/, headerEntries), cfId: findHeader(/^x-[\w-]+-cf-id$/, headerEntries) }; } } catch (e) { } } throw error2; } }; var findHeader = (pattern, headers) => { return (headers.find(([k]) => { return k.match(pattern); }) || [void 0, void 0])[1]; }; // src/submodules/schema/middleware/schemaSerializationMiddleware.ts var import_util_middleware2 = __nccwpck_require__(2390); var schemaSerializationMiddleware = (config) => (next, context) => async (args) => { const { operationSchema } = (0, import_util_middleware2.getSmithyContext)(context); const endpoint = context.endpointV2?.url && config.urlParser ? async () => config.urlParser(context.endpointV2.url) : config.endpoint; const request = await config.protocol.serializeRequest(operationSchema, args.input, { ...config, ...context, endpoint }); return next({ ...args, request }); }; // src/submodules/schema/middleware/getSchemaSerdePlugin.ts var deserializerMiddlewareOption = { name: "deserializerMiddleware", step: "deserialize", tags: ["DESERIALIZER"], override: true }; var serializerMiddlewareOption = { name: "serializerMiddleware", step: "serialize", tags: ["SERIALIZER"], override: true }; function getSchemaSerdePlugin(config) { return { applyToStack: (commandStack) => { commandStack.add(schemaSerializationMiddleware(config), serializerMiddlewareOption); commandStack.add(schemaDeserializationMiddleware(config), deserializerMiddlewareOption); config.protocol.setSerdeContext(config); } }; } // src/submodules/schema/TypeRegistry.ts var TypeRegistry = class _TypeRegistry { constructor(namespace, schemas = /* @__PURE__ */ new Map()) { this.namespace = namespace; this.schemas = schemas; } static { this.registries = /* @__PURE__ */ new Map(); } /** * @param namespace - specifier. * @returns the schema for that namespace, creating it if necessary. */ static for(namespace) { if (!_TypeRegistry.registries.has(namespace)) { _TypeRegistry.registries.set(namespace, new _TypeRegistry(namespace)); } return _TypeRegistry.registries.get(namespace); } /** * Adds the given schema to a type registry with the same namespace. * * @param shapeId - to be registered. * @param schema - to be registered. */ register(shapeId, schema) { const qualifiedName = this.normalizeShapeId(shapeId); const registry = _TypeRegistry.for(this.getNamespace(shapeId)); registry.schemas.set(qualifiedName, schema); } /** * @param shapeId - query. * @returns the schema. */ getSchema(shapeId) { const id = this.normalizeShapeId(shapeId); if (!this.schemas.has(id)) { throw new Error(`@smithy/core/schema - schema not found for ${id}`); } return this.schemas.get(id); } /** * The smithy-typescript code generator generates a synthetic (i.e. unmodeled) base exception, * because generated SDKs before the introduction of schemas have the notion of a ServiceBaseException, which * is unique per service/model. * * This is generated under a unique prefix that is combined with the service namespace, and this * method is used to retrieve it. * * The base exception synthetic schema is used when an error is returned by a service, but we cannot * determine what existing schema to use to deserialize it. * * @returns the synthetic base exception of the service namespace associated with this registry instance. */ getBaseException() { for (const [id, schema] of this.schemas.entries()) { if (id.startsWith("smithy.ts.sdk.synthetic.") && id.endsWith("ServiceException")) { return schema; } } return void 0; } /** * @param predicate - criterion. * @returns a schema in this registry matching the predicate. */ find(predicate) { return [...this.schemas.values()].find(predicate); } /** * Unloads the current TypeRegistry. */ destroy() { _TypeRegistry.registries.delete(this.namespace); this.schemas.clear(); } normalizeShapeId(shapeId) { if (shapeId.includes("#")) { return shapeId; } return this.namespace + "#" + shapeId; } getNamespace(shapeId) { return this.normalizeShapeId(shapeId).split("#")[0]; } }; // src/submodules/schema/schemas/Schema.ts var Schema = class { constructor(name, traits) { this.name = name; this.traits = traits; } }; // src/submodules/schema/schemas/ListSchema.ts var ListSchema = class extends Schema { constructor(name, traits, valueSchema) { super(name, traits); this.name = name; this.traits = traits; this.valueSchema = valueSchema; } }; function list(namespace, name, traits = {}, valueSchema) { const schema = new ListSchema( namespace + "#" + name, traits, typeof valueSchema === "function" ? valueSchema() : valueSchema ); TypeRegistry.for(namespace).register(name, schema); return schema; } // src/submodules/schema/schemas/MapSchema.ts var MapSchema = class extends Schema { constructor(name, traits, keySchema, valueSchema) { super(name, traits); this.name = name; this.traits = traits; this.keySchema = keySchema; this.valueSchema = valueSchema; } }; function map(namespace, name, traits = {}, keySchema, valueSchema) { const schema = new MapSchema( namespace + "#" + name, traits, keySchema, typeof valueSchema === "function" ? valueSchema() : valueSchema ); TypeRegistry.for(namespace).register(name, schema); return schema; } // src/submodules/schema/schemas/OperationSchema.ts var OperationSchema = class extends Schema { constructor(name, traits, input, output) { super(name, traits); this.name = name; this.traits = traits; this.input = input; this.output = output; } }; function op(namespace, name, traits = {}, input, output) { const schema = new OperationSchema(namespace + "#" + name, traits, input, output); TypeRegistry.for(namespace).register(name, schema); return schema; } // src/submodules/schema/schemas/StructureSchema.ts var StructureSchema = class extends Schema { constructor(name, traits, memberNames, memberList) { super(name, traits); this.name = name; this.traits = traits; this.memberNames = memberNames; this.memberList = memberList; this.members = {}; for (let i = 0; i < memberNames.length; ++i) { this.members[memberNames[i]] = Array.isArray(memberList[i]) ? memberList[i] : [memberList[i], 0]; } } }; function struct(namespace, name, traits, memberNames, memberList) { const schema = new StructureSchema(namespace + "#" + name, traits, memberNames, memberList); TypeRegistry.for(namespace).register(name, schema); return schema; } // src/submodules/schema/schemas/ErrorSchema.ts var ErrorSchema = class extends StructureSchema { constructor(name, traits, memberNames, memberList, ctor) { super(name, traits, memberNames, memberList); this.name = name; this.traits = traits; this.memberNames = memberNames; this.memberList = memberList; this.ctor = ctor; } }; function error(namespace, name, traits = {}, memberNames, memberList, ctor) { const schema = new ErrorSchema(namespace + "#" + name, traits, memberNames, memberList, ctor); TypeRegistry.for(namespace).register(name, schema); return schema; } // src/submodules/schema/schemas/sentinels.ts var SCHEMA = { BLOB: 21, // 21 STREAMING_BLOB: 42, // 42 BOOLEAN: 2, // 2 STRING: 0, // 0 NUMERIC: 1, // 1 BIG_INTEGER: 17, // 17 BIG_DECIMAL: 19, // 19 DOCUMENT: 15, // 15 TIMESTAMP_DEFAULT: 4, // 4 TIMESTAMP_DATE_TIME: 5, // 5 TIMESTAMP_HTTP_DATE: 6, // 6 TIMESTAMP_EPOCH_SECONDS: 7, // 7 LIST_MODIFIER: 64, // 64 MAP_MODIFIER: 128 // 128 }; // src/submodules/schema/schemas/SimpleSchema.ts var SimpleSchema = class extends Schema { constructor(name, schemaRef, traits) { super(name, traits); this.name = name; this.schemaRef = schemaRef; this.traits = traits; } }; function sim(namespace, name, schemaRef, traits) { const schema = new SimpleSchema(namespace + "#" + name, schemaRef, traits); TypeRegistry.for(namespace).register(name, schema); return schema; } // src/submodules/schema/schemas/NormalizedSchema.ts var NormalizedSchema = class _NormalizedSchema { /** * @param ref - a polymorphic SchemaRef to be dereferenced/normalized. * @param memberName - optional memberName if this NormalizedSchema should be considered a member schema. */ constructor(ref, memberName) { this.ref = ref; this.memberName = memberName; const traitStack = []; let _ref = ref; let schema = ref; this._isMemberSchema = false; while (Array.isArray(_ref)) { traitStack.push(_ref[1]); _ref = _ref[0]; schema = deref(_ref); this._isMemberSchema = true; } if (traitStack.length > 0) { this.memberTraits = {}; for (let i = traitStack.length - 1; i >= 0; --i) { const traitSet = traitStack[i]; Object.assign(this.memberTraits, _NormalizedSchema.translateTraits(traitSet)); } } else { this.memberTraits = 0; } if (schema instanceof _NormalizedSchema) { this.name = schema.name; this.traits = schema.traits; this._isMemberSchema = schema._isMemberSchema; this.schema = schema.schema; this.memberTraits = Object.assign({}, schema.getMemberTraits(), this.getMemberTraits()); this.normalizedTraits = void 0; this.ref = schema.ref; this.memberName = memberName ?? schema.memberName; return; } this.schema = deref(schema); if (this.schema && typeof this.schema === "object") { this.traits = this.schema?.traits ?? {}; } else { this.traits = 0; } this.name = (typeof this.schema === "object" ? this.schema?.name : void 0) ?? this.memberName ?? this.getSchemaName(); if (this._isMemberSchema && !memberName) { throw new Error( `@smithy/core/schema - NormalizedSchema member schema ${this.getName(true)} must initialize with memberName argument.` ); } } /** * Static constructor that attempts to avoid wrapping a NormalizedSchema within another. */ static of(ref, memberName) { if (ref instanceof _NormalizedSchema) { return ref; } return new _NormalizedSchema(ref, memberName); } /** * @param indicator - numeric indicator for preset trait combination. * @returns equivalent trait object. */ static translateTraits(indicator) { if (typeof indicator === "object") { return indicator; } indicator = indicator | 0; const traits = {}; if ((indicator & 1) === 1) { traits.httpLabel = 1; } if ((indicator >> 1 & 1) === 1) { traits.idempotent = 1; } if ((indicator >> 2 & 1) === 1) { traits.idempotencyToken = 1; } if ((indicator >> 3 & 1) === 1) { traits.sensitive = 1; } if ((indicator >> 4 & 1) === 1) { traits.httpPayload = 1; } if ((indicator >> 5 & 1) === 1) { traits.httpResponseCode = 1; } if ((indicator >> 6 & 1) === 1) { traits.httpQueryParams = 1; } return traits; } /** * Creates a normalized member schema from the given schema and member name. */ static memberFrom(memberSchema, memberName) { if (memberSchema instanceof _NormalizedSchema) { memberSchema.memberName = memberName; memberSchema._isMemberSchema = true; return memberSchema; } return new _NormalizedSchema(memberSchema, memberName); } /** * @returns the underlying non-normalized schema. */ getSchema() { if (this.schema instanceof _NormalizedSchema) { return this.schema = this.schema.getSchema(); } if (this.schema instanceof SimpleSchema) { return deref(this.schema.schemaRef); } return deref(this.schema); } /** * @param withNamespace - qualifies the name. * @returns e.g. `MyShape` or `com.namespace#MyShape`. */ getName(withNamespace = false) { if (!withNamespace) { if (this.name && this.name.includes("#")) { return this.name.split("#")[1]; } } return this.name || void 0; } /** * @returns the member name if the schema is a member schema. * @throws Error when the schema isn't a member schema. */ getMemberName() { if (!this.isMemberSchema()) { throw new Error(`@smithy/core/schema - cannot get member name on non-member schema: ${this.getName(true)}`); } return this.memberName; } isMemberSchema() { return this._isMemberSchema; } isUnitSchema() { return this.getSchema() === "unit"; } /** * boolean methods on this class help control flow in shape serialization and deserialization. */ isListSchema() { const inner = this.getSchema(); if (typeof inner === "number") { return inner >= SCHEMA.LIST_MODIFIER && inner < SCHEMA.MAP_MODIFIER; } return inner instanceof ListSchema; } isMapSchema() { const inner = this.getSchema(); if (typeof inner === "number") { return inner >= SCHEMA.MAP_MODIFIER && inner <= 255; } return inner instanceof MapSchema; } isDocumentSchema() { return this.getSchema() === SCHEMA.DOCUMENT; } isStructSchema() { const inner = this.getSchema(); return inner !== null && typeof inner === "object" && "members" in inner || inner instanceof StructureSchema; } isBlobSchema() { return this.getSchema() === SCHEMA.BLOB || this.getSchema() === SCHEMA.STREAMING_BLOB; } isTimestampSchema() { const schema = this.getSchema(); return typeof schema === "number" && schema >= SCHEMA.TIMESTAMP_DEFAULT && schema <= SCHEMA.TIMESTAMP_EPOCH_SECONDS; } isStringSchema() { return this.getSchema() === SCHEMA.STRING; } isBooleanSchema() { return this.getSchema() === SCHEMA.BOOLEAN; } isNumericSchema() { return this.getSchema() === SCHEMA.NUMERIC; } isBigIntegerSchema() { return this.getSchema() === SCHEMA.BIG_INTEGER; } isBigDecimalSchema() { return this.getSchema() === SCHEMA.BIG_DECIMAL; } isStreaming() { const streaming = !!this.getMergedTraits().streaming; if (streaming) { return true; } return this.getSchema() === SCHEMA.STREAMING_BLOB; } /** * @returns own traits merged with member traits, where member traits of the same trait key take priority. * This method is cached. */ getMergedTraits() { if (this.normalizedTraits) { return this.normalizedTraits; } this.normalizedTraits = { ...this.getOwnTraits(), ...this.getMemberTraits() }; return this.normalizedTraits; } /** * @returns only the member traits. If the schema is not a member, this returns empty. */ getMemberTraits() { return _NormalizedSchema.translateTraits(this.memberTraits); } /** * @returns only the traits inherent to the shape or member target shape if this schema is a member. * If there are any member traits they are excluded. */ getOwnTraits() { return _NormalizedSchema.translateTraits(this.traits); } /** * @returns the map's key's schema. Returns a dummy Document schema if this schema is a Document. * * @throws Error if the schema is not a Map or Document. */ getKeySchema() { if (this.isDocumentSchema()) { return _NormalizedSchema.memberFrom([SCHEMA.DOCUMENT, 0], "key"); } if (!this.isMapSchema()) { throw new Error(`@smithy/core/schema - cannot get key schema for non-map schema: ${this.getName(true)}`); } const schema = this.getSchema(); if (typeof schema === "number") { return _NormalizedSchema.memberFrom([63 & schema, 0], "key"); } return _NormalizedSchema.memberFrom([schema.keySchema, 0], "key"); } /** * @returns the schema of the map's value or list's member. * Returns a dummy Document schema if this schema is a Document. * * @throws Error if the schema is not a Map, List, nor Document. */ getValueSchema() { const schema = this.getSchema(); if (typeof schema === "number") { if (this.isMapSchema()) { return _NormalizedSchema.memberFrom([63 & schema, 0], "value"); } else if (this.isListSchema()) { return _NormalizedSchema.memberFrom([63 & schema, 0], "member"); } } if (schema && typeof schema === "object") { if (this.isStructSchema()) { throw new Error(`cannot call getValueSchema() with StructureSchema ${this.getName(true)}`); } const collection = schema; if ("valueSchema" in collection) { if (this.isMapSchema()) { return _NormalizedSchema.memberFrom([collection.valueSchema, 0], "value"); } else if (this.isListSchema()) { return _NormalizedSchema.memberFrom([collection.valueSchema, 0], "member"); } } } if (this.isDocumentSchema()) { return _NormalizedSchema.memberFrom([SCHEMA.DOCUMENT, 0], "value"); } throw new Error(`@smithy/core/schema - the schema ${this.getName(true)} does not have a value member.`); } /** * @returns the NormalizedSchema for the given member name. The returned instance will return true for `isMemberSchema()` * and will have the member name given. * @param member - which member to retrieve and wrap. * * @throws Error if member does not exist or the schema is neither a document nor structure. * Note that errors are assumed to be structures and unions are considered structures for these purposes. */ getMemberSchema(member) { if (this.isStructSchema()) { const struct2 = this.getSchema(); if (!(member in struct2.members)) { throw new Error( `@smithy/core/schema - the schema ${this.getName(true)} does not have a member with name=${member}.` ); } return _NormalizedSchema.memberFrom(struct2.members[member], member); } if (this.isDocumentSchema()) { return _NormalizedSchema.memberFrom([SCHEMA.DOCUMENT, 0], member); } throw new Error(`@smithy/core/schema - the schema ${this.getName(true)} does not have members.`); } /** * This can be used for checking the members as a hashmap. * Prefer the structIterator method for iteration. * * This does NOT return list and map members, it is only for structures. * * @returns a map of member names to member schemas (normalized). */ getMemberSchemas() { const { schema } = this; const struct2 = schema; if (!struct2 || typeof struct2 !== "object") { return {}; } if ("members" in struct2) { const buffer = {}; for (const member of struct2.memberNames) { buffer[member] = this.getMemberSchema(member); } return buffer; } return {}; } /** * Allows iteration over members of a structure schema. * Each yield is a pair of the member name and member schema. * * This avoids the overhead of calling Object.entries(ns.getMemberSchemas()). */ *structIterator() { if (this.isUnitSchema()) { return; } if (!this.isStructSchema()) { throw new Error("@smithy/core/schema - cannot acquire structIterator on non-struct schema."); } const struct2 = this.getSchema(); for (let i = 0; i < struct2.memberNames.length; ++i) { yield [struct2.memberNames[i], _NormalizedSchema.memberFrom([struct2.memberList[i], 0], struct2.memberNames[i])]; } } /** * @returns a last-resort human-readable name for the schema if it has no other identifiers. */ getSchemaName() { const schema = this.getSchema(); if (typeof schema === "number") { const _schema = 63 & schema; const container = 192 & schema; const type = Object.entries(SCHEMA).find(([, value]) => { return value === _schema; })?.[0] ?? "Unknown"; switch (container) { case SCHEMA.MAP_MODIFIER: return `${type}Map`; case SCHEMA.LIST_MODIFIER: return `${type}List`; case 0: return type; } } return "Unknown"; } }; // Annotate the CommonJS export names for ESM import in node: 0 && (0); /***/ }), /***/ 27669: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/submodules/serde/index.ts var serde_exports = {}; __export(serde_exports, { LazyJsonString: () => LazyJsonString, NumericValue: () => NumericValue, copyDocumentWithTransform: () => copyDocumentWithTransform, dateToUtcString: () => dateToUtcString, expectBoolean: () => expectBoolean, expectByte: () => expectByte, expectFloat32: () => expectFloat32, expectInt: () => expectInt, expectInt32: () => expectInt32, expectLong: () => expectLong, expectNonNull: () => expectNonNull, expectNumber: () => expectNumber, expectObject: () => expectObject, expectShort: () => expectShort, expectString: () => expectString, expectUnion: () => expectUnion, handleFloat: () => handleFloat, limitedParseDouble: () => limitedParseDouble, limitedParseFloat: () => limitedParseFloat, limitedParseFloat32: () => limitedParseFloat32, logger: () => logger, nv: () => nv, parseBoolean: () => parseBoolean, parseEpochTimestamp: () => parseEpochTimestamp, parseRfc3339DateTime: () => parseRfc3339DateTime, parseRfc3339DateTimeWithOffset: () => parseRfc3339DateTimeWithOffset, parseRfc7231DateTime: () => parseRfc7231DateTime, quoteHeader: () => quoteHeader, splitEvery: () => splitEvery, splitHeader: () => splitHeader, strictParseByte: () => strictParseByte, strictParseDouble: () => strictParseDouble, strictParseFloat: () => strictParseFloat, strictParseFloat32: () => strictParseFloat32, strictParseInt: () => strictParseInt, strictParseInt32: () => strictParseInt32, strictParseLong: () => strictParseLong, strictParseShort: () => strictParseShort }); module.exports = __toCommonJS(serde_exports); // src/submodules/serde/copyDocumentWithTransform.ts var import_schema = __nccwpck_require__(19826); var copyDocumentWithTransform = (source, schemaRef, transform = (_) => _) => { const ns = import_schema.NormalizedSchema.of(schemaRef); switch (typeof source) { case "undefined": case "boolean": case "number": case "string": case "bigint": case "symbol": return transform(source, ns); case "function": case "object": if (source === null) { return transform(null, ns); } if (Array.isArray(source)) { const newArray = new Array(source.length); let i = 0; for (const item of source) { newArray[i++] = copyDocumentWithTransform(item, ns.getValueSchema(), transform); } return transform(newArray, ns); } if ("byteLength" in source) { const newBytes = new Uint8Array(source.byteLength); newBytes.set(source, 0); return transform(newBytes, ns); } if (source instanceof Date) { return transform(source, ns); } const newObject = {}; if (ns.isMapSchema()) { for (const key of Object.keys(source)) { newObject[key] = copyDocumentWithTransform(source[key], ns.getValueSchema(), transform); } } else if (ns.isStructSchema()) { for (const [key, memberSchema] of ns.structIterator()) { newObject[key] = copyDocumentWithTransform(source[key], memberSchema, transform); } } else if (ns.isDocumentSchema()) { for (const key of Object.keys(source)) { newObject[key] = copyDocumentWithTransform(source[key], ns.getValueSchema(), transform); } } return transform(newObject, ns); default: return transform(source, ns); } }; // src/submodules/serde/parse-utils.ts var parseBoolean = (value) => { switch (value) { case "true": return true; case "false": return false; default: throw new Error(`Unable to parse boolean value "${value}"`); } }; var expectBoolean = (value) => { if (value === null || value === void 0) { return void 0; } if (typeof value === "number") { if (value === 0 || value === 1) { logger.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`)); } if (value === 0) { return false; } if (value === 1) { return true; } } if (typeof value === "string") { const lower = value.toLowerCase(); if (lower === "false" || lower === "true") { logger.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`)); } if (lower === "false") { return false; } if (lower === "true") { return true; } } if (typeof value === "boolean") { return value; } throw new TypeError(`Expected boolean, got ${typeof value}: ${value}`); }; var expectNumber = (value) => { if (value === null || value === void 0) { return void 0; } if (typeof value === "string") { const parsed = parseFloat(value); if (!Number.isNaN(parsed)) { if (String(parsed) !== String(value)) { logger.warn(stackTraceWarning(`Expected number but observed string: ${value}`)); } return parsed; } } if (typeof value === "number") { return value; } throw new TypeError(`Expected number, got ${typeof value}: ${value}`); }; var MAX_FLOAT = Math.ceil(2 ** 127 * (2 - 2 ** -23)); var expectFloat32 = (value) => { const expected = expectNumber(value); if (expected !== void 0 && !Number.isNaN(expected) && expected !== Infinity && expected !== -Infinity) { if (Math.abs(expected) > MAX_FLOAT) { throw new TypeError(`Expected 32-bit float, got ${value}`); } } return expected; }; var expectLong = (value) => { if (value === null || value === void 0) { return void 0; } if (Number.isInteger(value) && !Number.isNaN(value)) { return value; } throw new TypeError(`Expected integer, got ${typeof value}: ${value}`); }; var expectInt = expectLong; var expectInt32 = (value) => expectSizedInt(value, 32); var expectShort = (value) => expectSizedInt(value, 16); var expectByte = (value) => expectSizedInt(value, 8); var expectSizedInt = (value, size) => { const expected = expectLong(value); if (expected !== void 0 && castInt(expected, size) !== expected) { throw new TypeError(`Expected ${size}-bit integer, got ${value}`); } return expected; }; var castInt = (value, size) => { switch (size) { case 32: return Int32Array.of(value)[0]; case 16: return Int16Array.of(value)[0]; case 8: return Int8Array.of(value)[0]; } }; var expectNonNull = (value, location) => { if (value === null || value === void 0) { if (location) { throw new TypeError(`Expected a non-null value for ${location}`); } throw new TypeError("Expected a non-null value"); } return value; }; var expectObject = (value) => { if (value === null || value === void 0) { return void 0; } if (typeof value === "object" && !Array.isArray(value)) { return value; } const receivedType = Array.isArray(value) ? "array" : typeof value; throw new TypeError(`Expected object, got ${receivedType}: ${value}`); }; var expectString = (value) => { if (value === null || value === void 0) { return void 0; } if (typeof value === "string") { return value; } if (["boolean", "number", "bigint"].includes(typeof value)) { logger.warn(stackTraceWarning(`Expected string, got ${typeof value}: ${value}`)); return String(value); } throw new TypeError(`Expected string, got ${typeof value}: ${value}`); }; var expectUnion = (value) => { if (value === null || value === void 0) { return void 0; } const asObject = expectObject(value); const setKeys = Object.entries(asObject).filter(([, v]) => v != null).map(([k]) => k); if (setKeys.length === 0) { throw new TypeError(`Unions must have exactly one non-null member. None were found.`); } if (setKeys.length > 1) { throw new TypeError(`Unions must have exactly one non-null member. Keys ${setKeys} were not null.`); } return asObject; }; var strictParseDouble = (value) => { if (typeof value == "string") { return expectNumber(parseNumber(value)); } return expectNumber(value); }; var strictParseFloat = strictParseDouble; var strictParseFloat32 = (value) => { if (typeof value == "string") { return expectFloat32(parseNumber(value)); } return expectFloat32(value); }; var NUMBER_REGEX = /(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g; var parseNumber = (value) => { const matches = value.match(NUMBER_REGEX); if (matches === null || matches[0].length !== value.length) { throw new TypeError(`Expected real number, got implicit NaN`); } return parseFloat(value); }; var limitedParseDouble = (value) => { if (typeof value == "string") { return parseFloatString(value); } return expectNumber(value); }; var handleFloat = limitedParseDouble; var limitedParseFloat = limitedParseDouble; var limitedParseFloat32 = (value) => { if (typeof value == "string") { return parseFloatString(value); } return expectFloat32(value); }; var parseFloatString = (value) => { switch (value) { case "NaN": return NaN; case "Infinity": return Infinity; case "-Infinity": return -Infinity; default: throw new Error(`Unable to parse float value: ${value}`); } }; var strictParseLong = (value) => { if (typeof value === "string") { return expectLong(parseNumber(value)); } return expectLong(value); }; var strictParseInt = strictParseLong; var strictParseInt32 = (value) => { if (typeof value === "string") { return expectInt32(parseNumber(value)); } return expectInt32(value); }; var strictParseShort = (value) => { if (typeof value === "string") { return expectShort(parseNumber(value)); } return expectShort(value); }; var strictParseByte = (value) => { if (typeof value === "string") { return expectByte(parseNumber(value)); } return expectByte(value); }; var stackTraceWarning = (message) => { return String(new TypeError(message).stack || message).split("\n").slice(0, 5).filter((s) => !s.includes("stackTraceWarning")).join("\n"); }; var logger = { warn: console.warn }; // src/submodules/serde/date-utils.ts var DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; var MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; function dateToUtcString(date) { const year = date.getUTCFullYear(); const month = date.getUTCMonth(); const dayOfWeek = date.getUTCDay(); const dayOfMonthInt = date.getUTCDate(); const hoursInt = date.getUTCHours(); const minutesInt = date.getUTCMinutes(); const secondsInt = date.getUTCSeconds(); const dayOfMonthString = dayOfMonthInt < 10 ? `0${dayOfMonthInt}` : `${dayOfMonthInt}`; const hoursString = hoursInt < 10 ? `0${hoursInt}` : `${hoursInt}`; const minutesString = minutesInt < 10 ? `0${minutesInt}` : `${minutesInt}`; const secondsString = secondsInt < 10 ? `0${secondsInt}` : `${secondsInt}`; return `${DAYS[dayOfWeek]}, ${dayOfMonthString} ${MONTHS[month]} ${year} ${hoursString}:${minutesString}:${secondsString} GMT`; } var RFC3339 = new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/); var parseRfc3339DateTime = (value) => { if (value === null || value === void 0) { return void 0; } if (typeof value !== "string") { throw new TypeError("RFC-3339 date-times must be expressed as strings"); } const match = RFC3339.exec(value); if (!match) { throw new TypeError("Invalid RFC-3339 date-time value"); } const [_, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds] = match; const year = strictParseShort(stripLeadingZeroes(yearStr)); const month = parseDateValue(monthStr, "month", 1, 12); const day = parseDateValue(dayStr, "day", 1, 31); return buildDate(year, month, day, { hours, minutes, seconds, fractionalMilliseconds }); }; var RFC3339_WITH_OFFSET = new RegExp( /^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/ ); var parseRfc3339DateTimeWithOffset = (value) => { if (value === null || value === void 0) { return void 0; } if (typeof value !== "string") { throw new TypeError("RFC-3339 date-times must be expressed as strings"); } const match = RFC3339_WITH_OFFSET.exec(value); if (!match) { throw new TypeError("Invalid RFC-3339 date-time value"); } const [_, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, offsetStr] = match; const year = strictParseShort(stripLeadingZeroes(yearStr)); const month = parseDateValue(monthStr, "month", 1, 12); const day = parseDateValue(dayStr, "day", 1, 31); const date = buildDate(year, month, day, { hours, minutes, seconds, fractionalMilliseconds }); if (offsetStr.toUpperCase() != "Z") { date.setTime(date.getTime() - parseOffsetToMilliseconds(offsetStr)); } return date; }; var IMF_FIXDATE = new RegExp( /^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/ ); var RFC_850_DATE = new RegExp( /^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/ ); var ASC_TIME = new RegExp( /^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? (\d{4})$/ ); var parseRfc7231DateTime = (value) => { if (value === null || value === void 0) { return void 0; } if (typeof value !== "string") { throw new TypeError("RFC-7231 date-times must be expressed as strings"); } let match = IMF_FIXDATE.exec(value); if (match) { const [_, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match; return buildDate( strictParseShort(stripLeadingZeroes(yearStr)), parseMonthByShortName(monthStr), parseDateValue(dayStr, "day", 1, 31), { hours, minutes, seconds, fractionalMilliseconds } ); } match = RFC_850_DATE.exec(value); if (match) { const [_, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match; return adjustRfc850Year( buildDate(parseTwoDigitYear(yearStr), parseMonthByShortName(monthStr), parseDateValue(dayStr, "day", 1, 31), { hours, minutes, seconds, fractionalMilliseconds }) ); } match = ASC_TIME.exec(value); if (match) { const [_, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, yearStr] = match; return buildDate( strictParseShort(stripLeadingZeroes(yearStr)), parseMonthByShortName(monthStr), parseDateValue(dayStr.trimLeft(), "day", 1, 31), { hours, minutes, seconds, fractionalMilliseconds } ); } throw new TypeError("Invalid RFC-7231 date-time value"); }; var parseEpochTimestamp = (value) => { if (value === null || value === void 0) { return void 0; } let valueAsDouble; if (typeof value === "number") { valueAsDouble = value; } else if (typeof value === "string") { valueAsDouble = strictParseDouble(value); } else if (typeof value === "object" && value.tag === 1) { valueAsDouble = value.value; } else { throw new TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation"); } if (Number.isNaN(valueAsDouble) || valueAsDouble === Infinity || valueAsDouble === -Infinity) { throw new TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics"); } return new Date(Math.round(valueAsDouble * 1e3)); }; var buildDate = (year, month, day, time) => { const adjustedMonth = month - 1; validateDayOfMonth(year, adjustedMonth, day); return new Date( Date.UTC( year, adjustedMonth, day, parseDateValue(time.hours, "hour", 0, 23), parseDateValue(time.minutes, "minute", 0, 59), // seconds can go up to 60 for leap seconds parseDateValue(time.seconds, "seconds", 0, 60), parseMilliseconds(time.fractionalMilliseconds) ) ); }; var parseTwoDigitYear = (value) => { const thisYear = (/* @__PURE__ */ new Date()).getUTCFullYear(); const valueInThisCentury = Math.floor(thisYear / 100) * 100 + strictParseShort(stripLeadingZeroes(value)); if (valueInThisCentury < thisYear) { return valueInThisCentury + 100; } return valueInThisCentury; }; var FIFTY_YEARS_IN_MILLIS = 50 * 365 * 24 * 60 * 60 * 1e3; var adjustRfc850Year = (input) => { if (input.getTime() - (/* @__PURE__ */ new Date()).getTime() > FIFTY_YEARS_IN_MILLIS) { return new Date( Date.UTC( input.getUTCFullYear() - 100, input.getUTCMonth(), input.getUTCDate(), input.getUTCHours(), input.getUTCMinutes(), input.getUTCSeconds(), input.getUTCMilliseconds() ) ); } return input; }; var parseMonthByShortName = (value) => { const monthIdx = MONTHS.indexOf(value); if (monthIdx < 0) { throw new TypeError(`Invalid month: ${value}`); } return monthIdx + 1; }; var DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; var validateDayOfMonth = (year, month, day) => { let maxDays = DAYS_IN_MONTH[month]; if (month === 1 && isLeapYear(year)) { maxDays = 29; } if (day > maxDays) { throw new TypeError(`Invalid day for ${MONTHS[month]} in ${year}: ${day}`); } }; var isLeapYear = (year) => { return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); }; var parseDateValue = (value, type, lower, upper) => { const dateVal = strictParseByte(stripLeadingZeroes(value)); if (dateVal < lower || dateVal > upper) { throw new TypeError(`${type} must be between ${lower} and ${upper}, inclusive`); } return dateVal; }; var parseMilliseconds = (value) => { if (value === null || value === void 0) { return 0; } return strictParseFloat32("0." + value) * 1e3; }; var parseOffsetToMilliseconds = (value) => { const directionStr = value[0]; let direction = 1; if (directionStr == "+") { direction = 1; } else if (directionStr == "-") { direction = -1; } else { throw new TypeError(`Offset direction, ${directionStr}, must be "+" or "-"`); } const hour = Number(value.substring(1, 3)); const minute = Number(value.substring(4, 6)); return direction * (hour * 60 + minute) * 60 * 1e3; }; var stripLeadingZeroes = (value) => { let idx = 0; while (idx < value.length - 1 && value.charAt(idx) === "0") { idx++; } if (idx === 0) { return value; } return value.slice(idx); }; // src/submodules/serde/lazy-json.ts var LazyJsonString = function LazyJsonString2(val) { const str = Object.assign(new String(val), { deserializeJSON() { return JSON.parse(String(val)); }, toString() { return String(val); }, toJSON() { return String(val); } }); return str; }; LazyJsonString.from = (object) => { if (object && typeof object === "object" && (object instanceof LazyJsonString || "deserializeJSON" in object)) { return object; } else if (typeof object === "string" || Object.getPrototypeOf(object) === String.prototype) { return LazyJsonString(String(object)); } return LazyJsonString(JSON.stringify(object)); }; LazyJsonString.fromObject = LazyJsonString.from; // src/submodules/serde/quote-header.ts function quoteHeader(part) { if (part.includes(",") || part.includes('"')) { part = `"${part.replace(/"/g, '\\"')}"`; } return part; } // src/submodules/serde/split-every.ts function splitEvery(value, delimiter, numDelimiters) { if (numDelimiters <= 0 || !Number.isInteger(numDelimiters)) { throw new Error("Invalid number of delimiters (" + numDelimiters + ") for splitEvery."); } const segments = value.split(delimiter); if (numDelimiters === 1) { return segments; } const compoundSegments = []; let currentSegment = ""; for (let i = 0; i < segments.length; i++) { if (currentSegment === "") { currentSegment = segments[i]; } else { currentSegment += delimiter + segments[i]; } if ((i + 1) % numDelimiters === 0) { compoundSegments.push(currentSegment); currentSegment = ""; } } if (currentSegment !== "") { compoundSegments.push(currentSegment); } return compoundSegments; } // src/submodules/serde/split-header.ts var splitHeader = (value) => { const z = value.length; const values = []; let withinQuotes = false; let prevChar = void 0; let anchor = 0; for (let i = 0; i < z; ++i) { const char = value[i]; switch (char) { case `"`: if (prevChar !== "\\") { withinQuotes = !withinQuotes; } break; case ",": if (!withinQuotes) { values.push(value.slice(anchor, i)); anchor = i + 1; } break; default: } prevChar = char; } values.push(value.slice(anchor)); return values.map((v) => { v = v.trim(); const z2 = v.length; if (z2 < 2) { return v; } if (v[0] === `"` && v[z2 - 1] === `"`) { v = v.slice(1, z2 - 1); } return v.replace(/\\"/g, '"'); }); }; // src/submodules/serde/value/NumericValue.ts var NumericValue = class { constructor(string, type) { this.string = string; this.type = type; } }; function nv(string) { return new NumericValue(string, "bigDecimal"); } // Annotate the CommonJS export names for ESM import in node: 0 && (0); /***/ }), /***/ 7477: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { DEFAULT_MAX_RETRIES: () => DEFAULT_MAX_RETRIES, DEFAULT_TIMEOUT: () => DEFAULT_TIMEOUT, ENV_CMDS_AUTH_TOKEN: () => ENV_CMDS_AUTH_TOKEN, ENV_CMDS_FULL_URI: () => ENV_CMDS_FULL_URI, ENV_CMDS_RELATIVE_URI: () => ENV_CMDS_RELATIVE_URI, Endpoint: () => Endpoint, fromContainerMetadata: () => fromContainerMetadata, fromInstanceMetadata: () => fromInstanceMetadata, getInstanceMetadataEndpoint: () => getInstanceMetadataEndpoint, httpRequest: () => httpRequest, providerConfigFromInit: () => providerConfigFromInit }); module.exports = __toCommonJS(src_exports); // src/fromContainerMetadata.ts var import_url = __nccwpck_require__(57310); // src/remoteProvider/httpRequest.ts var import_property_provider = __nccwpck_require__(79721); var import_buffer = __nccwpck_require__(14300); var import_http = __nccwpck_require__(13685); function httpRequest(options) { return new Promise((resolve, reject) => { const req = (0, import_http.request)({ method: "GET", ...options, // Node.js http module doesn't accept hostname with square brackets // Refs: https://github.com/nodejs/node/issues/39738 hostname: options.hostname?.replace(/^\[(.+)\]$/, "$1") }); req.on("error", (err) => { reject(Object.assign(new import_property_provider.ProviderError("Unable to connect to instance metadata service"), err)); req.destroy(); }); req.on("timeout", () => { reject(new import_property_provider.ProviderError("TimeoutError from instance metadata service")); req.destroy(); }); req.on("response", (res) => { const { statusCode = 400 } = res; if (statusCode < 200 || 300 <= statusCode) { reject( Object.assign(new import_property_provider.ProviderError("Error response received from instance metadata service"), { statusCode }) ); req.destroy(); } const chunks = []; res.on("data", (chunk) => { chunks.push(chunk); }); res.on("end", () => { resolve(import_buffer.Buffer.concat(chunks)); req.destroy(); }); }); req.end(); }); } __name(httpRequest, "httpRequest"); // src/remoteProvider/ImdsCredentials.ts var isImdsCredentials = /* @__PURE__ */ __name((arg) => Boolean(arg) && typeof arg === "object" && typeof arg.AccessKeyId === "string" && typeof arg.SecretAccessKey === "string" && typeof arg.Token === "string" && typeof arg.Expiration === "string", "isImdsCredentials"); var fromImdsCredentials = /* @__PURE__ */ __name((creds) => ({ accessKeyId: creds.AccessKeyId, secretAccessKey: creds.SecretAccessKey, sessionToken: creds.Token, expiration: new Date(creds.Expiration), ...creds.AccountId && { accountId: creds.AccountId } }), "fromImdsCredentials"); // src/remoteProvider/RemoteProviderInit.ts var DEFAULT_TIMEOUT = 1e3; var DEFAULT_MAX_RETRIES = 0; var providerConfigFromInit = /* @__PURE__ */ __name(({ maxRetries = DEFAULT_MAX_RETRIES, timeout = DEFAULT_TIMEOUT }) => ({ maxRetries, timeout }), "providerConfigFromInit"); // src/remoteProvider/retry.ts var retry = /* @__PURE__ */ __name((toRetry, maxRetries) => { let promise = toRetry(); for (let i = 0; i < maxRetries; i++) { promise = promise.catch(toRetry); } return promise; }, "retry"); // src/fromContainerMetadata.ts var ENV_CMDS_FULL_URI = "AWS_CONTAINER_CREDENTIALS_FULL_URI"; var ENV_CMDS_RELATIVE_URI = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI"; var ENV_CMDS_AUTH_TOKEN = "AWS_CONTAINER_AUTHORIZATION_TOKEN"; var fromContainerMetadata = /* @__PURE__ */ __name((init = {}) => { const { timeout, maxRetries } = providerConfigFromInit(init); return () => retry(async () => { const requestOptions = await getCmdsUri({ logger: init.logger }); const credsResponse = JSON.parse(await requestFromEcsImds(timeout, requestOptions)); if (!isImdsCredentials(credsResponse)) { throw new import_property_provider.CredentialsProviderError("Invalid response received from instance metadata service.", { logger: init.logger }); } return fromImdsCredentials(credsResponse); }, maxRetries); }, "fromContainerMetadata"); var requestFromEcsImds = /* @__PURE__ */ __name(async (timeout, options) => { if (process.env[ENV_CMDS_AUTH_TOKEN]) { options.headers = { ...options.headers, Authorization: process.env[ENV_CMDS_AUTH_TOKEN] }; } const buffer = await httpRequest({ ...options, timeout }); return buffer.toString(); }, "requestFromEcsImds"); var CMDS_IP = "169.254.170.2"; var GREENGRASS_HOSTS = { localhost: true, "127.0.0.1": true }; var GREENGRASS_PROTOCOLS = { "http:": true, "https:": true }; var getCmdsUri = /* @__PURE__ */ __name(async ({ logger }) => { if (process.env[ENV_CMDS_RELATIVE_URI]) { return { hostname: CMDS_IP, path: process.env[ENV_CMDS_RELATIVE_URI] }; } if (process.env[ENV_CMDS_FULL_URI]) { const parsed = (0, import_url.parse)(process.env[ENV_CMDS_FULL_URI]); if (!parsed.hostname || !(parsed.hostname in GREENGRASS_HOSTS)) { throw new import_property_provider.CredentialsProviderError(`${parsed.hostname} is not a valid container metadata service hostname`, { tryNextLink: false, logger }); } if (!parsed.protocol || !(parsed.protocol in GREENGRASS_PROTOCOLS)) { throw new import_property_provider.CredentialsProviderError(`${parsed.protocol} is not a valid container metadata service protocol`, { tryNextLink: false, logger }); } return { ...parsed, port: parsed.port ? parseInt(parsed.port, 10) : void 0 }; } throw new import_property_provider.CredentialsProviderError( `The container metadata credential provider cannot be used unless the ${ENV_CMDS_RELATIVE_URI} or ${ENV_CMDS_FULL_URI} environment variable is set`, { tryNextLink: false, logger } ); }, "getCmdsUri"); // src/fromInstanceMetadata.ts // src/error/InstanceMetadataV1FallbackError.ts var InstanceMetadataV1FallbackError = class _InstanceMetadataV1FallbackError extends import_property_provider.CredentialsProviderError { constructor(message, tryNextLink = true) { super(message, tryNextLink); this.tryNextLink = tryNextLink; this.name = "InstanceMetadataV1FallbackError"; Object.setPrototypeOf(this, _InstanceMetadataV1FallbackError.prototype); } static { __name(this, "InstanceMetadataV1FallbackError"); } }; // src/utils/getInstanceMetadataEndpoint.ts var import_node_config_provider = __nccwpck_require__(33461); var import_url_parser = __nccwpck_require__(14681); // src/config/Endpoint.ts var Endpoint = /* @__PURE__ */ ((Endpoint2) => { Endpoint2["IPv4"] = "http://169.254.169.254"; Endpoint2["IPv6"] = "http://[fd00:ec2::254]"; return Endpoint2; })(Endpoint || {}); // src/config/EndpointConfigOptions.ts var ENV_ENDPOINT_NAME = "AWS_EC2_METADATA_SERVICE_ENDPOINT"; var CONFIG_ENDPOINT_NAME = "ec2_metadata_service_endpoint"; var ENDPOINT_CONFIG_OPTIONS = { environmentVariableSelector: (env) => env[ENV_ENDPOINT_NAME], configFileSelector: (profile) => profile[CONFIG_ENDPOINT_NAME], default: void 0 }; // src/config/EndpointMode.ts var EndpointMode = /* @__PURE__ */ ((EndpointMode2) => { EndpointMode2["IPv4"] = "IPv4"; EndpointMode2["IPv6"] = "IPv6"; return EndpointMode2; })(EndpointMode || {}); // src/config/EndpointModeConfigOptions.ts var ENV_ENDPOINT_MODE_NAME = "AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE"; var CONFIG_ENDPOINT_MODE_NAME = "ec2_metadata_service_endpoint_mode"; var ENDPOINT_MODE_CONFIG_OPTIONS = { environmentVariableSelector: (env) => env[ENV_ENDPOINT_MODE_NAME], configFileSelector: (profile) => profile[CONFIG_ENDPOINT_MODE_NAME], default: "IPv4" /* IPv4 */ }; // src/utils/getInstanceMetadataEndpoint.ts var getInstanceMetadataEndpoint = /* @__PURE__ */ __name(async () => (0, import_url_parser.parseUrl)(await getFromEndpointConfig() || await getFromEndpointModeConfig()), "getInstanceMetadataEndpoint"); var getFromEndpointConfig = /* @__PURE__ */ __name(async () => (0, import_node_config_provider.loadConfig)(ENDPOINT_CONFIG_OPTIONS)(), "getFromEndpointConfig"); var getFromEndpointModeConfig = /* @__PURE__ */ __name(async () => { const endpointMode = await (0, import_node_config_provider.loadConfig)(ENDPOINT_MODE_CONFIG_OPTIONS)(); switch (endpointMode) { case "IPv4" /* IPv4 */: return "http://169.254.169.254" /* IPv4 */; case "IPv6" /* IPv6 */: return "http://[fd00:ec2::254]" /* IPv6 */; default: throw new Error(`Unsupported endpoint mode: ${endpointMode}. Select from ${Object.values(EndpointMode)}`); } }, "getFromEndpointModeConfig"); // src/utils/getExtendedInstanceMetadataCredentials.ts var STATIC_STABILITY_REFRESH_INTERVAL_SECONDS = 5 * 60; var STATIC_STABILITY_REFRESH_INTERVAL_JITTER_WINDOW_SECONDS = 5 * 60; var STATIC_STABILITY_DOC_URL = "https://docs.aws.amazon.com/sdkref/latest/guide/feature-static-credentials.html"; var getExtendedInstanceMetadataCredentials = /* @__PURE__ */ __name((credentials, logger) => { const refreshInterval = STATIC_STABILITY_REFRESH_INTERVAL_SECONDS + Math.floor(Math.random() * STATIC_STABILITY_REFRESH_INTERVAL_JITTER_WINDOW_SECONDS); const newExpiration = new Date(Date.now() + refreshInterval * 1e3); logger.warn( `Attempting credential expiration extension due to a credential service availability issue. A refresh of these credentials will be attempted after ${new Date(newExpiration)}. For more information, please visit: ` + STATIC_STABILITY_DOC_URL ); const originalExpiration = credentials.originalExpiration ?? credentials.expiration; return { ...credentials, ...originalExpiration ? { originalExpiration } : {}, expiration: newExpiration }; }, "getExtendedInstanceMetadataCredentials"); // src/utils/staticStabilityProvider.ts var staticStabilityProvider = /* @__PURE__ */ __name((provider, options = {}) => { const logger = options?.logger || console; let pastCredentials; return async () => { let credentials; try { credentials = await provider(); if (credentials.expiration && credentials.expiration.getTime() < Date.now()) { credentials = getExtendedInstanceMetadataCredentials(credentials, logger); } } catch (e) { if (pastCredentials) { logger.warn("Credential renew failed: ", e); credentials = getExtendedInstanceMetadataCredentials(pastCredentials, logger); } else { throw e; } } pastCredentials = credentials; return credentials; }; }, "staticStabilityProvider"); // src/fromInstanceMetadata.ts var IMDS_PATH = "/latest/meta-data/iam/security-credentials/"; var IMDS_TOKEN_PATH = "/latest/api/token"; var AWS_EC2_METADATA_V1_DISABLED = "AWS_EC2_METADATA_V1_DISABLED"; var PROFILE_AWS_EC2_METADATA_V1_DISABLED = "ec2_metadata_v1_disabled"; var X_AWS_EC2_METADATA_TOKEN = "x-aws-ec2-metadata-token"; var fromInstanceMetadata = /* @__PURE__ */ __name((init = {}) => staticStabilityProvider(getInstanceMetadataProvider(init), { logger: init.logger }), "fromInstanceMetadata"); var getInstanceMetadataProvider = /* @__PURE__ */ __name((init = {}) => { let disableFetchToken = false; const { logger, profile } = init; const { timeout, maxRetries } = providerConfigFromInit(init); const getCredentials = /* @__PURE__ */ __name(async (maxRetries2, options) => { const isImdsV1Fallback = disableFetchToken || options.headers?.[X_AWS_EC2_METADATA_TOKEN] == null; if (isImdsV1Fallback) { let fallbackBlockedFromProfile = false; let fallbackBlockedFromProcessEnv = false; const configValue = await (0, import_node_config_provider.loadConfig)( { environmentVariableSelector: (env) => { const envValue = env[AWS_EC2_METADATA_V1_DISABLED]; fallbackBlockedFromProcessEnv = !!envValue && envValue !== "false"; if (envValue === void 0) { throw new import_property_provider.CredentialsProviderError( `${AWS_EC2_METADATA_V1_DISABLED} not set in env, checking config file next.`, { logger: init.logger } ); } return fallbackBlockedFromProcessEnv; }, configFileSelector: (profile2) => { const profileValue = profile2[PROFILE_AWS_EC2_METADATA_V1_DISABLED]; fallbackBlockedFromProfile = !!profileValue && profileValue !== "false"; return fallbackBlockedFromProfile; }, default: false }, { profile } )(); if (init.ec2MetadataV1Disabled || configValue) { const causes = []; if (init.ec2MetadataV1Disabled) causes.push("credential provider initialization (runtime option ec2MetadataV1Disabled)"); if (fallbackBlockedFromProfile) causes.push(`config file profile (${PROFILE_AWS_EC2_METADATA_V1_DISABLED})`); if (fallbackBlockedFromProcessEnv) causes.push(`process environment variable (${AWS_EC2_METADATA_V1_DISABLED})`); throw new InstanceMetadataV1FallbackError( `AWS EC2 Metadata v1 fallback has been blocked by AWS SDK configuration in the following: [${causes.join( ", " )}].` ); } } const imdsProfile = (await retry(async () => { let profile2; try { profile2 = await getProfile(options); } catch (err) { if (err.statusCode === 401) { disableFetchToken = false; } throw err; } return profile2; }, maxRetries2)).trim(); return retry(async () => { let creds; try { creds = await getCredentialsFromProfile(imdsProfile, options, init); } catch (err) { if (err.statusCode === 401) { disableFetchToken = false; } throw err; } return creds; }, maxRetries2); }, "getCredentials"); return async () => { const endpoint = await getInstanceMetadataEndpoint(); if (disableFetchToken) { logger?.debug("AWS SDK Instance Metadata", "using v1 fallback (no token fetch)"); return getCredentials(maxRetries, { ...endpoint, timeout }); } else { let token; try { token = (await getMetadataToken({ ...endpoint, timeout })).toString(); } catch (error) { if (error?.statusCode === 400) { throw Object.assign(error, { message: "EC2 Metadata token request returned error" }); } else if (error.message === "TimeoutError" || [403, 404, 405].includes(error.statusCode)) { disableFetchToken = true; } logger?.debug("AWS SDK Instance Metadata", "using v1 fallback (initial)"); return getCredentials(maxRetries, { ...endpoint, timeout }); } return getCredentials(maxRetries, { ...endpoint, headers: { [X_AWS_EC2_METADATA_TOKEN]: token }, timeout }); } }; }, "getInstanceMetadataProvider"); var getMetadataToken = /* @__PURE__ */ __name(async (options) => httpRequest({ ...options, path: IMDS_TOKEN_PATH, method: "PUT", headers: { "x-aws-ec2-metadata-token-ttl-seconds": "21600" } }), "getMetadataToken"); var getProfile = /* @__PURE__ */ __name(async (options) => (await httpRequest({ ...options, path: IMDS_PATH })).toString(), "getProfile"); var getCredentialsFromProfile = /* @__PURE__ */ __name(async (profile, options, init) => { const credentialsResponse = JSON.parse( (await httpRequest({ ...options, path: IMDS_PATH + profile })).toString() ); if (!isImdsCredentials(credentialsResponse)) { throw new import_property_provider.CredentialsProviderError("Invalid response received from instance metadata service.", { logger: init.logger }); } return fromImdsCredentials(credentialsResponse); }, "getCredentialsFromProfile"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); /***/ }), /***/ 56459: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { EventStreamCodec: () => EventStreamCodec, HeaderMarshaller: () => HeaderMarshaller, Int64: () => Int64, MessageDecoderStream: () => MessageDecoderStream, MessageEncoderStream: () => MessageEncoderStream, SmithyMessageDecoderStream: () => SmithyMessageDecoderStream, SmithyMessageEncoderStream: () => SmithyMessageEncoderStream }); module.exports = __toCommonJS(src_exports); // src/EventStreamCodec.ts var import_crc322 = __nccwpck_require__(48408); // src/HeaderMarshaller.ts // src/Int64.ts var import_util_hex_encoding = __nccwpck_require__(45364); var Int64 = class _Int64 { constructor(bytes) { this.bytes = bytes; if (bytes.byteLength !== 8) { throw new Error("Int64 buffers must be exactly 8 bytes"); } } static { __name(this, "Int64"); } static fromNumber(number) { if (number > 9223372036854776e3 || number < -9223372036854776e3) { throw new Error(`${number} is too large (or, if negative, too small) to represent as an Int64`); } const bytes = new Uint8Array(8); for (let i = 7, remaining = Math.abs(Math.round(number)); i > -1 && remaining > 0; i--, remaining /= 256) { bytes[i] = remaining; } if (number < 0) { negate(bytes); } return new _Int64(bytes); } /** * Called implicitly by infix arithmetic operators. */ valueOf() { const bytes = this.bytes.slice(0); const negative = bytes[0] & 128; if (negative) { negate(bytes); } return parseInt((0, import_util_hex_encoding.toHex)(bytes), 16) * (negative ? -1 : 1); } toString() { return String(this.valueOf()); } }; function negate(bytes) { for (let i = 0; i < 8; i++) { bytes[i] ^= 255; } for (let i = 7; i > -1; i--) { bytes[i]++; if (bytes[i] !== 0) break; } } __name(negate, "negate"); // src/HeaderMarshaller.ts var HeaderMarshaller = class { constructor(toUtf8, fromUtf8) { this.toUtf8 = toUtf8; this.fromUtf8 = fromUtf8; } static { __name(this, "HeaderMarshaller"); } format(headers) { const chunks = []; for (const headerName of Object.keys(headers)) { const bytes = this.fromUtf8(headerName); chunks.push(Uint8Array.from([bytes.byteLength]), bytes, this.formatHeaderValue(headers[headerName])); } const out = new Uint8Array(chunks.reduce((carry, bytes) => carry + bytes.byteLength, 0)); let position = 0; for (const chunk of chunks) { out.set(chunk, position); position += chunk.byteLength; } return out; } formatHeaderValue(header) { switch (header.type) { case "boolean": return Uint8Array.from([header.value ? 0 /* boolTrue */ : 1 /* boolFalse */]); case "byte": return Uint8Array.from([2 /* byte */, header.value]); case "short": const shortView = new DataView(new ArrayBuffer(3)); shortView.setUint8(0, 3 /* short */); shortView.setInt16(1, header.value, false); return new Uint8Array(shortView.buffer); case "integer": const intView = new DataView(new ArrayBuffer(5)); intView.setUint8(0, 4 /* integer */); intView.setInt32(1, header.value, false); return new Uint8Array(intView.buffer); case "long": const longBytes = new Uint8Array(9); longBytes[0] = 5 /* long */; longBytes.set(header.value.bytes, 1); return longBytes; case "binary": const binView = new DataView(new ArrayBuffer(3 + header.value.byteLength)); binView.setUint8(0, 6 /* byteArray */); binView.setUint16(1, header.value.byteLength, false); const binBytes = new Uint8Array(binView.buffer); binBytes.set(header.value, 3); return binBytes; case "string": const utf8Bytes = this.fromUtf8(header.value); const strView = new DataView(new ArrayBuffer(3 + utf8Bytes.byteLength)); strView.setUint8(0, 7 /* string */); strView.setUint16(1, utf8Bytes.byteLength, false); const strBytes = new Uint8Array(strView.buffer); strBytes.set(utf8Bytes, 3); return strBytes; case "timestamp": const tsBytes = new Uint8Array(9); tsBytes[0] = 8 /* timestamp */; tsBytes.set(Int64.fromNumber(header.value.valueOf()).bytes, 1); return tsBytes; case "uuid": if (!UUID_PATTERN.test(header.value)) { throw new Error(`Invalid UUID received: ${header.value}`); } const uuidBytes = new Uint8Array(17); uuidBytes[0] = 9 /* uuid */; uuidBytes.set((0, import_util_hex_encoding.fromHex)(header.value.replace(/\-/g, "")), 1); return uuidBytes; } } parse(headers) { const out = {}; let position = 0; while (position < headers.byteLength) { const nameLength = headers.getUint8(position++); const name = this.toUtf8(new Uint8Array(headers.buffer, headers.byteOffset + position, nameLength)); position += nameLength; switch (headers.getUint8(position++)) { case 0 /* boolTrue */: out[name] = { type: BOOLEAN_TAG, value: true }; break; case 1 /* boolFalse */: out[name] = { type: BOOLEAN_TAG, value: false }; break; case 2 /* byte */: out[name] = { type: BYTE_TAG, value: headers.getInt8(position++) }; break; case 3 /* short */: out[name] = { type: SHORT_TAG, value: headers.getInt16(position, false) }; position += 2; break; case 4 /* integer */: out[name] = { type: INT_TAG, value: headers.getInt32(position, false) }; position += 4; break; case 5 /* long */: out[name] = { type: LONG_TAG, value: new Int64(new Uint8Array(headers.buffer, headers.byteOffset + position, 8)) }; position += 8; break; case 6 /* byteArray */: const binaryLength = headers.getUint16(position, false); position += 2; out[name] = { type: BINARY_TAG, value: new Uint8Array(headers.buffer, headers.byteOffset + position, binaryLength) }; position += binaryLength; break; case 7 /* string */: const stringLength = headers.getUint16(position, false); position += 2; out[name] = { type: STRING_TAG, value: this.toUtf8(new Uint8Array(headers.buffer, headers.byteOffset + position, stringLength)) }; position += stringLength; break; case 8 /* timestamp */: out[name] = { type: TIMESTAMP_TAG, value: new Date(new Int64(new Uint8Array(headers.buffer, headers.byteOffset + position, 8)).valueOf()) }; position += 8; break; case 9 /* uuid */: const uuidBytes = new Uint8Array(headers.buffer, headers.byteOffset + position, 16); position += 16; out[name] = { type: UUID_TAG, value: `${(0, import_util_hex_encoding.toHex)(uuidBytes.subarray(0, 4))}-${(0, import_util_hex_encoding.toHex)(uuidBytes.subarray(4, 6))}-${(0, import_util_hex_encoding.toHex)( uuidBytes.subarray(6, 8) )}-${(0, import_util_hex_encoding.toHex)(uuidBytes.subarray(8, 10))}-${(0, import_util_hex_encoding.toHex)(uuidBytes.subarray(10))}` }; break; default: throw new Error(`Unrecognized header type tag`); } } return out; } }; var BOOLEAN_TAG = "boolean"; var BYTE_TAG = "byte"; var SHORT_TAG = "short"; var INT_TAG = "integer"; var LONG_TAG = "long"; var BINARY_TAG = "binary"; var STRING_TAG = "string"; var TIMESTAMP_TAG = "timestamp"; var UUID_TAG = "uuid"; var UUID_PATTERN = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/; // src/splitMessage.ts var import_crc32 = __nccwpck_require__(48408); var PRELUDE_MEMBER_LENGTH = 4; var PRELUDE_LENGTH = PRELUDE_MEMBER_LENGTH * 2; var CHECKSUM_LENGTH = 4; var MINIMUM_MESSAGE_LENGTH = PRELUDE_LENGTH + CHECKSUM_LENGTH * 2; function splitMessage({ byteLength, byteOffset, buffer }) { if (byteLength < MINIMUM_MESSAGE_LENGTH) { throw new Error("Provided message too short to accommodate event stream message overhead"); } const view = new DataView(buffer, byteOffset, byteLength); const messageLength = view.getUint32(0, false); if (byteLength !== messageLength) { throw new Error("Reported message length does not match received message length"); } const headerLength = view.getUint32(PRELUDE_MEMBER_LENGTH, false); const expectedPreludeChecksum = view.getUint32(PRELUDE_LENGTH, false); const expectedMessageChecksum = view.getUint32(byteLength - CHECKSUM_LENGTH, false); const checksummer = new import_crc32.Crc32().update(new Uint8Array(buffer, byteOffset, PRELUDE_LENGTH)); if (expectedPreludeChecksum !== checksummer.digest()) { throw new Error( `The prelude checksum specified in the message (${expectedPreludeChecksum}) does not match the calculated CRC32 checksum (${checksummer.digest()})` ); } checksummer.update( new Uint8Array(buffer, byteOffset + PRELUDE_LENGTH, byteLength - (PRELUDE_LENGTH + CHECKSUM_LENGTH)) ); if (expectedMessageChecksum !== checksummer.digest()) { throw new Error( `The message checksum (${checksummer.digest()}) did not match the expected value of ${expectedMessageChecksum}` ); } return { headers: new DataView(buffer, byteOffset + PRELUDE_LENGTH + CHECKSUM_LENGTH, headerLength), body: new Uint8Array( buffer, byteOffset + PRELUDE_LENGTH + CHECKSUM_LENGTH + headerLength, messageLength - headerLength - (PRELUDE_LENGTH + CHECKSUM_LENGTH + CHECKSUM_LENGTH) ) }; } __name(splitMessage, "splitMessage"); // src/EventStreamCodec.ts var EventStreamCodec = class { static { __name(this, "EventStreamCodec"); } constructor(toUtf8, fromUtf8) { this.headerMarshaller = new HeaderMarshaller(toUtf8, fromUtf8); this.messageBuffer = []; this.isEndOfStream = false; } feed(message) { this.messageBuffer.push(this.decode(message)); } endOfStream() { this.isEndOfStream = true; } getMessage() { const message = this.messageBuffer.pop(); const isEndOfStream = this.isEndOfStream; return { getMessage() { return message; }, isEndOfStream() { return isEndOfStream; } }; } getAvailableMessages() { const messages = this.messageBuffer; this.messageBuffer = []; const isEndOfStream = this.isEndOfStream; return { getMessages() { return messages; }, isEndOfStream() { return isEndOfStream; } }; } /** * Convert a structured JavaScript object with tagged headers into a binary * event stream message. */ encode({ headers: rawHeaders, body }) { const headers = this.headerMarshaller.format(rawHeaders); const length = headers.byteLength + body.byteLength + 16; const out = new Uint8Array(length); const view = new DataView(out.buffer, out.byteOffset, out.byteLength); const checksum = new import_crc322.Crc32(); view.setUint32(0, length, false); view.setUint32(4, headers.byteLength, false); view.setUint32(8, checksum.update(out.subarray(0, 8)).digest(), false); out.set(headers, 12); out.set(body, headers.byteLength + 12); view.setUint32(length - 4, checksum.update(out.subarray(8, length - 4)).digest(), false); return out; } /** * Convert a binary event stream message into a JavaScript object with an * opaque, binary body and tagged, parsed headers. */ decode(message) { const { headers, body } = splitMessage(message); return { headers: this.headerMarshaller.parse(headers), body }; } /** * Convert a structured JavaScript object with tagged headers into a binary * event stream message header. */ formatHeaders(rawHeaders) { return this.headerMarshaller.format(rawHeaders); } }; // src/MessageDecoderStream.ts var MessageDecoderStream = class { constructor(options) { this.options = options; } static { __name(this, "MessageDecoderStream"); } [Symbol.asyncIterator]() { return this.asyncIterator(); } async *asyncIterator() { for await (const bytes of this.options.inputStream) { const decoded = this.options.decoder.decode(bytes); yield decoded; } } }; // src/MessageEncoderStream.ts var MessageEncoderStream = class { constructor(options) { this.options = options; } static { __name(this, "MessageEncoderStream"); } [Symbol.asyncIterator]() { return this.asyncIterator(); } async *asyncIterator() { for await (const msg of this.options.messageStream) { const encoded = this.options.encoder.encode(msg); yield encoded; } if (this.options.includeEndFrame) { yield new Uint8Array(0); } } }; // src/SmithyMessageDecoderStream.ts var SmithyMessageDecoderStream = class { constructor(options) { this.options = options; } static { __name(this, "SmithyMessageDecoderStream"); } [Symbol.asyncIterator]() { return this.asyncIterator(); } async *asyncIterator() { for await (const message of this.options.messageStream) { const deserialized = await this.options.deserializer(message); if (deserialized === void 0) continue; yield deserialized; } } }; // src/SmithyMessageEncoderStream.ts var SmithyMessageEncoderStream = class { constructor(options) { this.options = options; } static { __name(this, "SmithyMessageEncoderStream"); } [Symbol.asyncIterator]() { return this.asyncIterator(); } async *asyncIterator() { for await (const chunk of this.options.inputStream) { const payloadBuf = this.options.serializer(chunk); yield payloadBuf; } } }; // Annotate the CommonJS export names for ESM import in node: 0 && (0); /***/ }), /***/ 16181: /***/ ((module) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { resolveEventStreamSerdeConfig: () => resolveEventStreamSerdeConfig }); module.exports = __toCommonJS(src_exports); // src/EventStreamSerdeConfig.ts var resolveEventStreamSerdeConfig = /* @__PURE__ */ __name((input) => Object.assign(input, { eventStreamMarshaller: input.eventStreamSerdeProvider(input) }), "resolveEventStreamSerdeConfig"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); /***/ }), /***/ 77682: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { EventStreamMarshaller: () => EventStreamMarshaller, eventStreamSerdeProvider: () => eventStreamSerdeProvider }); module.exports = __toCommonJS(src_exports); // src/EventStreamMarshaller.ts var import_eventstream_serde_universal = __nccwpck_require__(66673); var import_stream = __nccwpck_require__(12781); // src/utils.ts async function* readabletoIterable(readStream) { let streamEnded = false; let generationEnded = false; const records = new Array(); readStream.on("error", (err) => { if (!streamEnded) { streamEnded = true; } if (err) { throw err; } }); readStream.on("data", (data) => { records.push(data); }); readStream.on("end", () => { streamEnded = true; }); while (!generationEnded) { const value = await new Promise((resolve) => setTimeout(() => resolve(records.shift()), 0)); if (value) { yield value; } generationEnded = streamEnded && records.length === 0; } } __name(readabletoIterable, "readabletoIterable"); // src/EventStreamMarshaller.ts var EventStreamMarshaller = class { static { __name(this, "EventStreamMarshaller"); } constructor({ utf8Encoder, utf8Decoder }) { this.universalMarshaller = new import_eventstream_serde_universal.EventStreamMarshaller({ utf8Decoder, utf8Encoder }); } deserialize(body, deserializer) { const bodyIterable = typeof body[Symbol.asyncIterator] === "function" ? body : readabletoIterable(body); return this.universalMarshaller.deserialize(bodyIterable, deserializer); } serialize(input, serializer) { return import_stream.Readable.from(this.universalMarshaller.serialize(input, serializer)); } }; // src/provider.ts var eventStreamSerdeProvider = /* @__PURE__ */ __name((options) => new EventStreamMarshaller(options), "eventStreamSerdeProvider"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); /***/ }), /***/ 66673: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { EventStreamMarshaller: () => EventStreamMarshaller, eventStreamSerdeProvider: () => eventStreamSerdeProvider }); module.exports = __toCommonJS(src_exports); // src/EventStreamMarshaller.ts var import_eventstream_codec = __nccwpck_require__(56459); // src/getChunkedStream.ts function getChunkedStream(source) { let currentMessageTotalLength = 0; let currentMessagePendingLength = 0; let currentMessage = null; let messageLengthBuffer = null; const allocateMessage = /* @__PURE__ */ __name((size) => { if (typeof size !== "number") { throw new Error("Attempted to allocate an event message where size was not a number: " + size); } currentMessageTotalLength = size; currentMessagePendingLength = 4; currentMessage = new Uint8Array(size); const currentMessageView = new DataView(currentMessage.buffer); currentMessageView.setUint32(0, size, false); }, "allocateMessage"); const iterator = /* @__PURE__ */ __name(async function* () { const sourceIterator = source[Symbol.asyncIterator](); while (true) { const { value, done } = await sourceIterator.next(); if (done) { if (!currentMessageTotalLength) { return; } else if (currentMessageTotalLength === currentMessagePendingLength) { yield currentMessage; } else { throw new Error("Truncated event message received."); } return; } const chunkLength = value.length; let currentOffset = 0; while (currentOffset < chunkLength) { if (!currentMessage) { const bytesRemaining = chunkLength - currentOffset; if (!messageLengthBuffer) { messageLengthBuffer = new Uint8Array(4); } const numBytesForTotal = Math.min( 4 - currentMessagePendingLength, // remaining bytes to fill the messageLengthBuffer bytesRemaining // bytes left in chunk ); messageLengthBuffer.set( // @ts-ignore error TS2532: Object is possibly 'undefined' for value value.slice(currentOffset, currentOffset + numBytesForTotal), currentMessagePendingLength ); currentMessagePendingLength += numBytesForTotal; currentOffset += numBytesForTotal; if (currentMessagePendingLength < 4) { break; } allocateMessage(new DataView(messageLengthBuffer.buffer).getUint32(0, false)); messageLengthBuffer = null; } const numBytesToWrite = Math.min( currentMessageTotalLength - currentMessagePendingLength, // number of bytes left to complete message chunkLength - currentOffset // number of bytes left in the original chunk ); currentMessage.set( // @ts-ignore error TS2532: Object is possibly 'undefined' for value value.slice(currentOffset, currentOffset + numBytesToWrite), currentMessagePendingLength ); currentMessagePendingLength += numBytesToWrite; currentOffset += numBytesToWrite; if (currentMessageTotalLength && currentMessageTotalLength === currentMessagePendingLength) { yield currentMessage; currentMessage = null; currentMessageTotalLength = 0; currentMessagePendingLength = 0; } } } }, "iterator"); return { [Symbol.asyncIterator]: iterator }; } __name(getChunkedStream, "getChunkedStream"); // src/getUnmarshalledStream.ts function getMessageUnmarshaller(deserializer, toUtf8) { return async function(message) { const { value: messageType } = message.headers[":message-type"]; if (messageType === "error") { const unmodeledError = new Error(message.headers[":error-message"].value || "UnknownError"); unmodeledError.name = message.headers[":error-code"].value; throw unmodeledError; } else if (messageType === "exception") { const code = message.headers[":exception-type"].value; const exception = { [code]: message }; const deserializedException = await deserializer(exception); if (deserializedException.$unknown) { const error = new Error(toUtf8(message.body)); error.name = code; throw error; } throw deserializedException[code]; } else if (messageType === "event") { const event = { [message.headers[":event-type"].value]: message }; const deserialized = await deserializer(event); if (deserialized.$unknown) return; return deserialized; } else { throw Error(`Unrecognizable event type: ${message.headers[":event-type"].value}`); } }; } __name(getMessageUnmarshaller, "getMessageUnmarshaller"); // src/EventStreamMarshaller.ts var EventStreamMarshaller = class { static { __name(this, "EventStreamMarshaller"); } constructor({ utf8Encoder, utf8Decoder }) { this.eventStreamCodec = new import_eventstream_codec.EventStreamCodec(utf8Encoder, utf8Decoder); this.utfEncoder = utf8Encoder; } deserialize(body, deserializer) { const inputStream = getChunkedStream(body); return new import_eventstream_codec.SmithyMessageDecoderStream({ messageStream: new import_eventstream_codec.MessageDecoderStream({ inputStream, decoder: this.eventStreamCodec }), // @ts-expect-error Type 'T' is not assignable to type 'Record' deserializer: getMessageUnmarshaller(deserializer, this.utfEncoder) }); } serialize(inputStream, serializer) { return new import_eventstream_codec.MessageEncoderStream({ messageStream: new import_eventstream_codec.SmithyMessageEncoderStream({ inputStream, serializer }), encoder: this.eventStreamCodec, includeEndFrame: true }); } }; // src/provider.ts var eventStreamSerdeProvider = /* @__PURE__ */ __name((options) => new EventStreamMarshaller(options), "eventStreamSerdeProvider"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); /***/ }), /***/ 82687: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { FetchHttpHandler: () => FetchHttpHandler, keepAliveSupport: () => keepAliveSupport, streamCollector: () => streamCollector }); module.exports = __toCommonJS(src_exports); // src/fetch-http-handler.ts var import_protocol_http = __nccwpck_require__(64418); var import_querystring_builder = __nccwpck_require__(68031); // src/create-request.ts function createRequest(url, requestOptions) { return new Request(url, requestOptions); } __name(createRequest, "createRequest"); // src/request-timeout.ts function requestTimeout(timeoutInMs = 0) { return new Promise((resolve, reject) => { if (timeoutInMs) { setTimeout(() => { const timeoutError = new Error(`Request did not complete within ${timeoutInMs} ms`); timeoutError.name = "TimeoutError"; reject(timeoutError); }, timeoutInMs); } }); } __name(requestTimeout, "requestTimeout"); // src/fetch-http-handler.ts var keepAliveSupport = { supported: void 0 }; var FetchHttpHandler = class _FetchHttpHandler { static { __name(this, "FetchHttpHandler"); } /** * @returns the input if it is an HttpHandler of any class, * or instantiates a new instance of this handler. */ static create(instanceOrOptions) { if (typeof instanceOrOptions?.handle === "function") { return instanceOrOptions; } return new _FetchHttpHandler(instanceOrOptions); } constructor(options) { if (typeof options === "function") { this.configProvider = options().then((opts) => opts || {}); } else { this.config = options ?? {}; this.configProvider = Promise.resolve(this.config); } if (keepAliveSupport.supported === void 0) { keepAliveSupport.supported = Boolean( typeof Request !== "undefined" && "keepalive" in createRequest("https://[::1]") ); } } destroy() { } async handle(request, { abortSignal } = {}) { if (!this.config) { this.config = await this.configProvider; } const requestTimeoutInMs = this.config.requestTimeout; const keepAlive = this.config.keepAlive === true; const credentials = this.config.credentials; if (abortSignal?.aborted) { const abortError = new Error("Request aborted"); abortError.name = "AbortError"; return Promise.reject(abortError); } let path = request.path; const queryString = (0, import_querystring_builder.buildQueryString)(request.query || {}); if (queryString) { path += `?${queryString}`; } if (request.fragment) { path += `#${request.fragment}`; } let auth = ""; if (request.username != null || request.password != null) { const username = request.username ?? ""; const password = request.password ?? ""; auth = `${username}:${password}@`; } const { port, method } = request; const url = `${request.protocol}//${auth}${request.hostname}${port ? `:${port}` : ""}${path}`; const body = method === "GET" || method === "HEAD" ? void 0 : request.body; const requestOptions = { body, headers: new Headers(request.headers), method, credentials }; if (this.config?.cache) { requestOptions.cache = this.config.cache; } if (body) { requestOptions.duplex = "half"; } if (typeof AbortController !== "undefined") { requestOptions.signal = abortSignal; } if (keepAliveSupport.supported) { requestOptions.keepalive = keepAlive; } if (typeof this.config.requestInit === "function") { Object.assign(requestOptions, this.config.requestInit(request)); } let removeSignalEventListener = /* @__PURE__ */ __name(() => { }, "removeSignalEventListener"); const fetchRequest = createRequest(url, requestOptions); const raceOfPromises = [ fetch(fetchRequest).then((response) => { const fetchHeaders = response.headers; const transformedHeaders = {}; for (const pair of fetchHeaders.entries()) { transformedHeaders[pair[0]] = pair[1]; } const hasReadableStream = response.body != void 0; if (!hasReadableStream) { return response.blob().then((body2) => ({ response: new import_protocol_http.HttpResponse({ headers: transformedHeaders, reason: response.statusText, statusCode: response.status, body: body2 }) })); } return { response: new import_protocol_http.HttpResponse({ headers: transformedHeaders, reason: response.statusText, statusCode: response.status, body: response.body }) }; }), requestTimeout(requestTimeoutInMs) ]; if (abortSignal) { raceOfPromises.push( new Promise((resolve, reject) => { const onAbort = /* @__PURE__ */ __name(() => { const abortError = new Error("Request aborted"); abortError.name = "AbortError"; reject(abortError); }, "onAbort"); if (typeof abortSignal.addEventListener === "function") { const signal = abortSignal; signal.addEventListener("abort", onAbort, { once: true }); removeSignalEventListener = /* @__PURE__ */ __name(() => signal.removeEventListener("abort", onAbort), "removeSignalEventListener"); } else { abortSignal.onabort = onAbort; } }) ); } return Promise.race(raceOfPromises).finally(removeSignalEventListener); } updateHttpClientConfig(key, value) { this.config = void 0; this.configProvider = this.configProvider.then((config) => { config[key] = value; return config; }); } httpHandlerConfigs() { return this.config ?? {}; } }; // src/stream-collector.ts var import_util_base64 = __nccwpck_require__(75600); var streamCollector = /* @__PURE__ */ __name(async (stream) => { if (typeof Blob === "function" && stream instanceof Blob || stream.constructor?.name === "Blob") { if (Blob.prototype.arrayBuffer !== void 0) { return new Uint8Array(await stream.arrayBuffer()); } return collectBlob(stream); } return collectStream(stream); }, "streamCollector"); async function collectBlob(blob) { const base64 = await readToBase64(blob); const arrayBuffer = (0, import_util_base64.fromBase64)(base64); return new Uint8Array(arrayBuffer); } __name(collectBlob, "collectBlob"); async function collectStream(stream) { const chunks = []; const reader = stream.getReader(); let isDone = false; let length = 0; while (!isDone) { const { done, value } = await reader.read(); if (value) { chunks.push(value); length += value.length; } isDone = done; } const collected = new Uint8Array(length); let offset = 0; for (const chunk of chunks) { collected.set(chunk, offset); offset += chunk.length; } return collected; } __name(collectStream, "collectStream"); function readToBase64(blob) { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onloadend = () => { if (reader.readyState !== 2) { return reject(new Error("Reader aborted too early")); } const result = reader.result ?? ""; const commaIndex = result.indexOf(","); const dataOffset = commaIndex > -1 ? commaIndex + 1 : result.length; resolve(result.substring(dataOffset)); }; reader.onabort = () => reject(new Error("Read aborted")); reader.onerror = () => reject(reader.error); reader.readAsDataURL(blob); }); } __name(readToBase64, "readToBase64"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); /***/ }), /***/ 3081: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { Hash: () => Hash }); module.exports = __toCommonJS(src_exports); var import_util_buffer_from = __nccwpck_require__(31381); var import_util_utf8 = __nccwpck_require__(41895); var import_buffer = __nccwpck_require__(14300); var import_crypto = __nccwpck_require__(6113); var Hash = class { static { __name(this, "Hash"); } constructor(algorithmIdentifier, secret) { this.algorithmIdentifier = algorithmIdentifier; this.secret = secret; this.reset(); } update(toHash, encoding) { this.hash.update((0, import_util_utf8.toUint8Array)(castSourceData(toHash, encoding))); } digest() { return Promise.resolve(this.hash.digest()); } reset() { this.hash = this.secret ? (0, import_crypto.createHmac)(this.algorithmIdentifier, castSourceData(this.secret)) : (0, import_crypto.createHash)(this.algorithmIdentifier); } }; function castSourceData(toCast, encoding) { if (import_buffer.Buffer.isBuffer(toCast)) { return toCast; } if (typeof toCast === "string") { return (0, import_util_buffer_from.fromString)(toCast, encoding); } if (ArrayBuffer.isView(toCast)) { return (0, import_util_buffer_from.fromArrayBuffer)(toCast.buffer, toCast.byteOffset, toCast.byteLength); } return (0, import_util_buffer_from.fromArrayBuffer)(toCast); } __name(castSourceData, "castSourceData"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); /***/ }), /***/ 48866: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { fileStreamHasher: () => fileStreamHasher, readableStreamHasher: () => readableStreamHasher }); module.exports = __toCommonJS(src_exports); // src/fileStreamHasher.ts var import_fs = __nccwpck_require__(57147); // src/HashCalculator.ts var import_util_utf8 = __nccwpck_require__(41895); var import_stream = __nccwpck_require__(12781); var HashCalculator = class extends import_stream.Writable { constructor(hash, options) { super(options); this.hash = hash; } static { __name(this, "HashCalculator"); } _write(chunk, encoding, callback) { try { this.hash.update((0, import_util_utf8.toUint8Array)(chunk)); } catch (err) { return callback(err); } callback(); } }; // src/fileStreamHasher.ts var fileStreamHasher = /* @__PURE__ */ __name((hashCtor, fileStream) => new Promise((resolve, reject) => { if (!isReadStream(fileStream)) { reject(new Error("Unable to calculate hash for non-file streams.")); return; } const fileStreamTee = (0, import_fs.createReadStream)(fileStream.path, { start: fileStream.start, end: fileStream.end }); const hash = new hashCtor(); const hashCalculator = new HashCalculator(hash); fileStreamTee.pipe(hashCalculator); fileStreamTee.on("error", (err) => { hashCalculator.end(); reject(err); }); hashCalculator.on("error", reject); hashCalculator.on("finish", function() { hash.digest().then(resolve).catch(reject); }); }), "fileStreamHasher"); var isReadStream = /* @__PURE__ */ __name((stream) => typeof stream.path === "string", "isReadStream"); // src/readableStreamHasher.ts var readableStreamHasher = /* @__PURE__ */ __name((hashCtor, readableStream) => { if (readableStream.readableFlowing !== null) { throw new Error("Unable to calculate hash for flowing readable stream"); } const hash = new hashCtor(); const hashCalculator = new HashCalculator(hash); readableStream.pipe(hashCalculator); return new Promise((resolve, reject) => { readableStream.on("error", (err) => { hashCalculator.end(); reject(err); }); hashCalculator.on("error", reject); hashCalculator.on("finish", () => { hash.digest().then(resolve).catch(reject); }); }); }, "readableStreamHasher"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); /***/ }), /***/ 10780: /***/ ((module) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { isArrayBuffer: () => isArrayBuffer }); module.exports = __toCommonJS(src_exports); var isArrayBuffer = /* @__PURE__ */ __name((arg) => typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer || Object.prototype.toString.call(arg) === "[object ArrayBuffer]", "isArrayBuffer"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); /***/ }), /***/ 82800: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { contentLengthMiddleware: () => contentLengthMiddleware, contentLengthMiddlewareOptions: () => contentLengthMiddlewareOptions, getContentLengthPlugin: () => getContentLengthPlugin }); module.exports = __toCommonJS(src_exports); var import_protocol_http = __nccwpck_require__(64418); var CONTENT_LENGTH_HEADER = "content-length"; function contentLengthMiddleware(bodyLengthChecker) { return (next) => async (args) => { const request = args.request; if (import_protocol_http.HttpRequest.isInstance(request)) { const { body, headers } = request; if (body && Object.keys(headers).map((str) => str.toLowerCase()).indexOf(CONTENT_LENGTH_HEADER) === -1) { try { const length = bodyLengthChecker(body); request.headers = { ...request.headers, [CONTENT_LENGTH_HEADER]: String(length) }; } catch (error) { } } } return next({ ...args, request }); }; } __name(contentLengthMiddleware, "contentLengthMiddleware"); var contentLengthMiddlewareOptions = { step: "build", tags: ["SET_CONTENT_LENGTH", "CONTENT_LENGTH"], name: "contentLengthMiddleware", override: true }; var getContentLengthPlugin = /* @__PURE__ */ __name((options) => ({ applyToStack: (clientStack) => { clientStack.add(contentLengthMiddleware(options.bodyLengthChecker), contentLengthMiddlewareOptions); } }), "getContentLengthPlugin"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); /***/ }), /***/ 31518: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getEndpointFromConfig = void 0; const node_config_provider_1 = __nccwpck_require__(33461); const getEndpointUrlConfig_1 = __nccwpck_require__(7574); const getEndpointFromConfig = async (serviceId) => (0, node_config_provider_1.loadConfig)((0, getEndpointUrlConfig_1.getEndpointUrlConfig)(serviceId !== null && serviceId !== void 0 ? serviceId : ""))(); exports.getEndpointFromConfig = getEndpointFromConfig; /***/ }), /***/ 7574: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getEndpointUrlConfig = void 0; const shared_ini_file_loader_1 = __nccwpck_require__(43507); const ENV_ENDPOINT_URL = "AWS_ENDPOINT_URL"; const CONFIG_ENDPOINT_URL = "endpoint_url"; const getEndpointUrlConfig = (serviceId) => ({ environmentVariableSelector: (env) => { const serviceSuffixParts = serviceId.split(" ").map((w) => w.toUpperCase()); const serviceEndpointUrl = env[[ENV_ENDPOINT_URL, ...serviceSuffixParts].join("_")]; if (serviceEndpointUrl) return serviceEndpointUrl; const endpointUrl = env[ENV_ENDPOINT_URL]; if (endpointUrl) return endpointUrl; return undefined; }, configFileSelector: (profile, config) => { if (config && profile.services) { const servicesSection = config[["services", profile.services].join(shared_ini_file_loader_1.CONFIG_PREFIX_SEPARATOR)]; if (servicesSection) { const servicePrefixParts = serviceId.split(" ").map((w) => w.toLowerCase()); const endpointUrl = servicesSection[[servicePrefixParts.join("_"), CONFIG_ENDPOINT_URL].join(shared_ini_file_loader_1.CONFIG_PREFIX_SEPARATOR)]; if (endpointUrl) return endpointUrl; } } const endpointUrl = profile[CONFIG_ENDPOINT_URL]; if (endpointUrl) return endpointUrl; return undefined; }, default: undefined, }); exports.getEndpointUrlConfig = getEndpointUrlConfig; /***/ }), /***/ 82918: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { endpointMiddleware: () => endpointMiddleware, endpointMiddlewareOptions: () => endpointMiddlewareOptions, getEndpointFromInstructions: () => getEndpointFromInstructions, getEndpointPlugin: () => getEndpointPlugin, resolveEndpointConfig: () => resolveEndpointConfig, resolveParams: () => resolveParams, toEndpointV1: () => toEndpointV1 }); module.exports = __toCommonJS(src_exports); // src/service-customizations/s3.ts var resolveParamsForS3 = /* @__PURE__ */ __name(async (endpointParams) => { const bucket = endpointParams?.Bucket || ""; if (typeof endpointParams.Bucket === "string") { endpointParams.Bucket = bucket.replace(/#/g, encodeURIComponent("#")).replace(/\?/g, encodeURIComponent("?")); } if (isArnBucketName(bucket)) { if (endpointParams.ForcePathStyle === true) { throw new Error("Path-style addressing cannot be used with ARN buckets"); } } else if (!isDnsCompatibleBucketName(bucket) || bucket.indexOf(".") !== -1 && !String(endpointParams.Endpoint).startsWith("http:") || bucket.toLowerCase() !== bucket || bucket.length < 3) { endpointParams.ForcePathStyle = true; } if (endpointParams.DisableMultiRegionAccessPoints) { endpointParams.disableMultiRegionAccessPoints = true; endpointParams.DisableMRAP = true; } return endpointParams; }, "resolveParamsForS3"); var DOMAIN_PATTERN = /^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/; var IP_ADDRESS_PATTERN = /(\d+\.){3}\d+/; var DOTS_PATTERN = /\.\./; var isDnsCompatibleBucketName = /* @__PURE__ */ __name((bucketName) => DOMAIN_PATTERN.test(bucketName) && !IP_ADDRESS_PATTERN.test(bucketName) && !DOTS_PATTERN.test(bucketName), "isDnsCompatibleBucketName"); var isArnBucketName = /* @__PURE__ */ __name((bucketName) => { const [arn, partition, service, , , bucket] = bucketName.split(":"); const isArn = arn === "arn" && bucketName.split(":").length >= 6; const isValidArn = Boolean(isArn && partition && service && bucket); if (isArn && !isValidArn) { throw new Error(`Invalid ARN: ${bucketName} was an invalid ARN.`); } return isValidArn; }, "isArnBucketName"); // src/adaptors/createConfigValueProvider.ts var createConfigValueProvider = /* @__PURE__ */ __name((configKey, canonicalEndpointParamKey, config) => { const configProvider = /* @__PURE__ */ __name(async () => { const configValue = config[configKey] ?? config[canonicalEndpointParamKey]; if (typeof configValue === "function") { return configValue(); } return configValue; }, "configProvider"); if (configKey === "credentialScope" || canonicalEndpointParamKey === "CredentialScope") { return async () => { const credentials = typeof config.credentials === "function" ? await config.credentials() : config.credentials; const configValue = credentials?.credentialScope ?? credentials?.CredentialScope; return configValue; }; } if (configKey === "accountId" || canonicalEndpointParamKey === "AccountId") { return async () => { const credentials = typeof config.credentials === "function" ? await config.credentials() : config.credentials; const configValue = credentials?.accountId ?? credentials?.AccountId; return configValue; }; } if (configKey === "endpoint" || canonicalEndpointParamKey === "endpoint") { return async () => { const endpoint = await configProvider(); if (endpoint && typeof endpoint === "object") { if ("url" in endpoint) { return endpoint.url.href; } if ("hostname" in endpoint) { const { protocol, hostname, port, path } = endpoint; return `${protocol}//${hostname}${port ? ":" + port : ""}${path}`; } } return endpoint; }; } return configProvider; }, "createConfigValueProvider"); // src/adaptors/getEndpointFromInstructions.ts var import_getEndpointFromConfig = __nccwpck_require__(31518); // src/adaptors/toEndpointV1.ts var import_url_parser = __nccwpck_require__(14681); var toEndpointV1 = /* @__PURE__ */ __name((endpoint) => { if (typeof endpoint === "object") { if ("url" in endpoint) { return (0, import_url_parser.parseUrl)(endpoint.url); } return endpoint; } return (0, import_url_parser.parseUrl)(endpoint); }, "toEndpointV1"); // src/adaptors/getEndpointFromInstructions.ts var getEndpointFromInstructions = /* @__PURE__ */ __name(async (commandInput, instructionsSupplier, clientConfig, context) => { if (!clientConfig.endpoint) { let endpointFromConfig; if (clientConfig.serviceConfiguredEndpoint) { endpointFromConfig = await clientConfig.serviceConfiguredEndpoint(); } else { endpointFromConfig = await (0, import_getEndpointFromConfig.getEndpointFromConfig)(clientConfig.serviceId); } if (endpointFromConfig) { clientConfig.endpoint = () => Promise.resolve(toEndpointV1(endpointFromConfig)); } } const endpointParams = await resolveParams(commandInput, instructionsSupplier, clientConfig); if (typeof clientConfig.endpointProvider !== "function") { throw new Error("config.endpointProvider is not set."); } const endpoint = clientConfig.endpointProvider(endpointParams, context); return endpoint; }, "getEndpointFromInstructions"); var resolveParams = /* @__PURE__ */ __name(async (commandInput, instructionsSupplier, clientConfig) => { const endpointParams = {}; const instructions = instructionsSupplier?.getEndpointParameterInstructions?.() || {}; for (const [name, instruction] of Object.entries(instructions)) { switch (instruction.type) { case "staticContextParams": endpointParams[name] = instruction.value; break; case "contextParams": endpointParams[name] = commandInput[instruction.name]; break; case "clientContextParams": case "builtInParams": endpointParams[name] = await createConfigValueProvider(instruction.name, name, clientConfig)(); break; case "operationContextParams": endpointParams[name] = instruction.get(commandInput); break; default: throw new Error("Unrecognized endpoint parameter instruction: " + JSON.stringify(instruction)); } } if (Object.keys(instructions).length === 0) { Object.assign(endpointParams, clientConfig); } if (String(clientConfig.serviceId).toLowerCase() === "s3") { await resolveParamsForS3(endpointParams); } return endpointParams; }, "resolveParams"); // src/endpointMiddleware.ts var import_core = __nccwpck_require__(55829); var import_util_middleware = __nccwpck_require__(2390); var endpointMiddleware = /* @__PURE__ */ __name(({ config, instructions }) => { return (next, context) => async (args) => { if (config.endpoint) { (0, import_core.setFeature)(context, "ENDPOINT_OVERRIDE", "N"); } const endpoint = await getEndpointFromInstructions( args.input, { getEndpointParameterInstructions() { return instructions; } }, { ...config }, context ); context.endpointV2 = endpoint; context.authSchemes = endpoint.properties?.authSchemes; const authScheme = context.authSchemes?.[0]; if (authScheme) { context["signing_region"] = authScheme.signingRegion; context["signing_service"] = authScheme.signingName; const smithyContext = (0, import_util_middleware.getSmithyContext)(context); const httpAuthOption = smithyContext?.selectedHttpAuthScheme?.httpAuthOption; if (httpAuthOption) { httpAuthOption.signingProperties = Object.assign( httpAuthOption.signingProperties || {}, { signing_region: authScheme.signingRegion, signingRegion: authScheme.signingRegion, signing_service: authScheme.signingName, signingName: authScheme.signingName, signingRegionSet: authScheme.signingRegionSet }, authScheme.properties ); } } return next({ ...args }); }; }, "endpointMiddleware"); // src/getEndpointPlugin.ts var import_middleware_serde = __nccwpck_require__(81238); var endpointMiddlewareOptions = { step: "serialize", tags: ["ENDPOINT_PARAMETERS", "ENDPOINT_V2", "ENDPOINT"], name: "endpointV2Middleware", override: true, relation: "before", toMiddleware: import_middleware_serde.serializerMiddlewareOption.name }; var getEndpointPlugin = /* @__PURE__ */ __name((config, instructions) => ({ applyToStack: (clientStack) => { clientStack.addRelativeTo( endpointMiddleware({ config, instructions }), endpointMiddlewareOptions ); } }), "getEndpointPlugin"); // src/resolveEndpointConfig.ts var import_getEndpointFromConfig2 = __nccwpck_require__(31518); var resolveEndpointConfig = /* @__PURE__ */ __name((input) => { const tls = input.tls ?? true; const { endpoint, useDualstackEndpoint, useFipsEndpoint } = input; const customEndpointProvider = endpoint != null ? async () => toEndpointV1(await (0, import_util_middleware.normalizeProvider)(endpoint)()) : void 0; const isCustomEndpoint = !!endpoint; const resolvedConfig = Object.assign(input, { endpoint: customEndpointProvider, tls, isCustomEndpoint, useDualstackEndpoint: (0, import_util_middleware.normalizeProvider)(useDualstackEndpoint ?? false), useFipsEndpoint: (0, import_util_middleware.normalizeProvider)(useFipsEndpoint ?? false) }); let configuredEndpointPromise = void 0; resolvedConfig.serviceConfiguredEndpoint = async () => { if (input.serviceId && !configuredEndpointPromise) { configuredEndpointPromise = (0, import_getEndpointFromConfig2.getEndpointFromConfig)(input.serviceId); } return configuredEndpointPromise; }; return resolvedConfig; }, "resolveEndpointConfig"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); /***/ }), /***/ 96039: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { AdaptiveRetryStrategy: () => AdaptiveRetryStrategy, CONFIG_MAX_ATTEMPTS: () => CONFIG_MAX_ATTEMPTS, CONFIG_RETRY_MODE: () => CONFIG_RETRY_MODE, ENV_MAX_ATTEMPTS: () => ENV_MAX_ATTEMPTS, ENV_RETRY_MODE: () => ENV_RETRY_MODE, NODE_MAX_ATTEMPT_CONFIG_OPTIONS: () => NODE_MAX_ATTEMPT_CONFIG_OPTIONS, NODE_RETRY_MODE_CONFIG_OPTIONS: () => NODE_RETRY_MODE_CONFIG_OPTIONS, StandardRetryStrategy: () => StandardRetryStrategy, defaultDelayDecider: () => defaultDelayDecider, defaultRetryDecider: () => defaultRetryDecider, getOmitRetryHeadersPlugin: () => getOmitRetryHeadersPlugin, getRetryAfterHint: () => getRetryAfterHint, getRetryPlugin: () => getRetryPlugin, omitRetryHeadersMiddleware: () => omitRetryHeadersMiddleware, omitRetryHeadersMiddlewareOptions: () => omitRetryHeadersMiddlewareOptions, resolveRetryConfig: () => resolveRetryConfig, retryMiddleware: () => retryMiddleware, retryMiddlewareOptions: () => retryMiddlewareOptions }); module.exports = __toCommonJS(src_exports); // src/AdaptiveRetryStrategy.ts // src/StandardRetryStrategy.ts var import_protocol_http = __nccwpck_require__(64418); var import_uuid = __nccwpck_require__(7761); // src/defaultRetryQuota.ts var import_util_retry = __nccwpck_require__(84902); var getDefaultRetryQuota = /* @__PURE__ */ __name((initialRetryTokens, options) => { const MAX_CAPACITY = initialRetryTokens; const noRetryIncrement = options?.noRetryIncrement ?? import_util_retry.NO_RETRY_INCREMENT; const retryCost = options?.retryCost ?? import_util_retry.RETRY_COST; const timeoutRetryCost = options?.timeoutRetryCost ?? import_util_retry.TIMEOUT_RETRY_COST; let availableCapacity = initialRetryTokens; const getCapacityAmount = /* @__PURE__ */ __name((error) => error.name === "TimeoutError" ? timeoutRetryCost : retryCost, "getCapacityAmount"); const hasRetryTokens = /* @__PURE__ */ __name((error) => getCapacityAmount(error) <= availableCapacity, "hasRetryTokens"); const retrieveRetryTokens = /* @__PURE__ */ __name((error) => { if (!hasRetryTokens(error)) { throw new Error("No retry token available"); } const capacityAmount = getCapacityAmount(error); availableCapacity -= capacityAmount; return capacityAmount; }, "retrieveRetryTokens"); const releaseRetryTokens = /* @__PURE__ */ __name((capacityReleaseAmount) => { availableCapacity += capacityReleaseAmount ?? noRetryIncrement; availableCapacity = Math.min(availableCapacity, MAX_CAPACITY); }, "releaseRetryTokens"); return Object.freeze({ hasRetryTokens, retrieveRetryTokens, releaseRetryTokens }); }, "getDefaultRetryQuota"); // src/delayDecider.ts var defaultDelayDecider = /* @__PURE__ */ __name((delayBase, attempts) => Math.floor(Math.min(import_util_retry.MAXIMUM_RETRY_DELAY, Math.random() * 2 ** attempts * delayBase)), "defaultDelayDecider"); // src/retryDecider.ts var import_service_error_classification = __nccwpck_require__(6375); var defaultRetryDecider = /* @__PURE__ */ __name((error) => { if (!error) { return false; } return (0, import_service_error_classification.isRetryableByTrait)(error) || (0, import_service_error_classification.isClockSkewError)(error) || (0, import_service_error_classification.isThrottlingError)(error) || (0, import_service_error_classification.isTransientError)(error); }, "defaultRetryDecider"); // src/util.ts var asSdkError = /* @__PURE__ */ __name((error) => { if (error instanceof Error) return error; if (error instanceof Object) return Object.assign(new Error(), error); if (typeof error === "string") return new Error(error); return new Error(`AWS SDK error wrapper for ${error}`); }, "asSdkError"); // src/StandardRetryStrategy.ts var StandardRetryStrategy = class { constructor(maxAttemptsProvider, options) { this.maxAttemptsProvider = maxAttemptsProvider; this.mode = import_util_retry.RETRY_MODES.STANDARD; this.retryDecider = options?.retryDecider ?? defaultRetryDecider; this.delayDecider = options?.delayDecider ?? defaultDelayDecider; this.retryQuota = options?.retryQuota ?? getDefaultRetryQuota(import_util_retry.INITIAL_RETRY_TOKENS); } static { __name(this, "StandardRetryStrategy"); } shouldRetry(error, attempts, maxAttempts) { return attempts < maxAttempts && this.retryDecider(error) && this.retryQuota.hasRetryTokens(error); } async getMaxAttempts() { let maxAttempts; try { maxAttempts = await this.maxAttemptsProvider(); } catch (error) { maxAttempts = import_util_retry.DEFAULT_MAX_ATTEMPTS; } return maxAttempts; } async retry(next, args, options) { let retryTokenAmount; let attempts = 0; let totalDelay = 0; const maxAttempts = await this.getMaxAttempts(); const { request } = args; if (import_protocol_http.HttpRequest.isInstance(request)) { request.headers[import_util_retry.INVOCATION_ID_HEADER] = (0, import_uuid.v4)(); } while (true) { try { if (import_protocol_http.HttpRequest.isInstance(request)) { request.headers[import_util_retry.REQUEST_HEADER] = `attempt=${attempts + 1}; max=${maxAttempts}`; } if (options?.beforeRequest) { await options.beforeRequest(); } const { response, output } = await next(args); if (options?.afterRequest) { options.afterRequest(response); } this.retryQuota.releaseRetryTokens(retryTokenAmount); output.$metadata.attempts = attempts + 1; output.$metadata.totalRetryDelay = totalDelay; return { response, output }; } catch (e) { const err = asSdkError(e); attempts++; if (this.shouldRetry(err, attempts, maxAttempts)) { retryTokenAmount = this.retryQuota.retrieveRetryTokens(err); const delayFromDecider = this.delayDecider( (0, import_service_error_classification.isThrottlingError)(err) ? import_util_retry.THROTTLING_RETRY_DELAY_BASE : import_util_retry.DEFAULT_RETRY_DELAY_BASE, attempts ); const delayFromResponse = getDelayFromRetryAfterHeader(err.$response); const delay = Math.max(delayFromResponse || 0, delayFromDecider); totalDelay += delay; await new Promise((resolve) => setTimeout(resolve, delay)); continue; } if (!err.$metadata) { err.$metadata = {}; } err.$metadata.attempts = attempts; err.$metadata.totalRetryDelay = totalDelay; throw err; } } } }; var getDelayFromRetryAfterHeader = /* @__PURE__ */ __name((response) => { if (!import_protocol_http.HttpResponse.isInstance(response)) return; const retryAfterHeaderName = Object.keys(response.headers).find((key) => key.toLowerCase() === "retry-after"); if (!retryAfterHeaderName) return; const retryAfter = response.headers[retryAfterHeaderName]; const retryAfterSeconds = Number(retryAfter); if (!Number.isNaN(retryAfterSeconds)) return retryAfterSeconds * 1e3; const retryAfterDate = new Date(retryAfter); return retryAfterDate.getTime() - Date.now(); }, "getDelayFromRetryAfterHeader"); // src/AdaptiveRetryStrategy.ts var AdaptiveRetryStrategy = class extends StandardRetryStrategy { static { __name(this, "AdaptiveRetryStrategy"); } constructor(maxAttemptsProvider, options) { const { rateLimiter, ...superOptions } = options ?? {}; super(maxAttemptsProvider, superOptions); this.rateLimiter = rateLimiter ?? new import_util_retry.DefaultRateLimiter(); this.mode = import_util_retry.RETRY_MODES.ADAPTIVE; } async retry(next, args) { return super.retry(next, args, { beforeRequest: async () => { return this.rateLimiter.getSendToken(); }, afterRequest: (response) => { this.rateLimiter.updateClientSendingRate(response); } }); } }; // src/configurations.ts var import_util_middleware = __nccwpck_require__(2390); var ENV_MAX_ATTEMPTS = "AWS_MAX_ATTEMPTS"; var CONFIG_MAX_ATTEMPTS = "max_attempts"; var NODE_MAX_ATTEMPT_CONFIG_OPTIONS = { environmentVariableSelector: (env) => { const value = env[ENV_MAX_ATTEMPTS]; if (!value) return void 0; const maxAttempt = parseInt(value); if (Number.isNaN(maxAttempt)) { throw new Error(`Environment variable ${ENV_MAX_ATTEMPTS} mast be a number, got "${value}"`); } return maxAttempt; }, configFileSelector: (profile) => { const value = profile[CONFIG_MAX_ATTEMPTS]; if (!value) return void 0; const maxAttempt = parseInt(value); if (Number.isNaN(maxAttempt)) { throw new Error(`Shared config file entry ${CONFIG_MAX_ATTEMPTS} mast be a number, got "${value}"`); } return maxAttempt; }, default: import_util_retry.DEFAULT_MAX_ATTEMPTS }; var resolveRetryConfig = /* @__PURE__ */ __name((input) => { const { retryStrategy, retryMode: _retryMode, maxAttempts: _maxAttempts } = input; const maxAttempts = (0, import_util_middleware.normalizeProvider)(_maxAttempts ?? import_util_retry.DEFAULT_MAX_ATTEMPTS); return Object.assign(input, { maxAttempts, retryStrategy: async () => { if (retryStrategy) { return retryStrategy; } const retryMode = await (0, import_util_middleware.normalizeProvider)(_retryMode)(); if (retryMode === import_util_retry.RETRY_MODES.ADAPTIVE) { return new import_util_retry.AdaptiveRetryStrategy(maxAttempts); } return new import_util_retry.StandardRetryStrategy(maxAttempts); } }); }, "resolveRetryConfig"); var ENV_RETRY_MODE = "AWS_RETRY_MODE"; var CONFIG_RETRY_MODE = "retry_mode"; var NODE_RETRY_MODE_CONFIG_OPTIONS = { environmentVariableSelector: (env) => env[ENV_RETRY_MODE], configFileSelector: (profile) => profile[CONFIG_RETRY_MODE], default: import_util_retry.DEFAULT_RETRY_MODE }; // src/omitRetryHeadersMiddleware.ts var omitRetryHeadersMiddleware = /* @__PURE__ */ __name(() => (next) => async (args) => { const { request } = args; if (import_protocol_http.HttpRequest.isInstance(request)) { delete request.headers[import_util_retry.INVOCATION_ID_HEADER]; delete request.headers[import_util_retry.REQUEST_HEADER]; } return next(args); }, "omitRetryHeadersMiddleware"); var omitRetryHeadersMiddlewareOptions = { name: "omitRetryHeadersMiddleware", tags: ["RETRY", "HEADERS", "OMIT_RETRY_HEADERS"], relation: "before", toMiddleware: "awsAuthMiddleware", override: true }; var getOmitRetryHeadersPlugin = /* @__PURE__ */ __name((options) => ({ applyToStack: (clientStack) => { clientStack.addRelativeTo(omitRetryHeadersMiddleware(), omitRetryHeadersMiddlewareOptions); } }), "getOmitRetryHeadersPlugin"); // src/retryMiddleware.ts var import_smithy_client = __nccwpck_require__(63570); var import_isStreamingPayload = __nccwpck_require__(18977); var retryMiddleware = /* @__PURE__ */ __name((options) => (next, context) => async (args) => { let retryStrategy = await options.retryStrategy(); const maxAttempts = await options.maxAttempts(); if (isRetryStrategyV2(retryStrategy)) { retryStrategy = retryStrategy; let retryToken = await retryStrategy.acquireInitialRetryToken(context["partition_id"]); let lastError = new Error(); let attempts = 0; let totalRetryDelay = 0; const { request } = args; const isRequest = import_protocol_http.HttpRequest.isInstance(request); if (isRequest) { request.headers[import_util_retry.INVOCATION_ID_HEADER] = (0, import_uuid.v4)(); } while (true) { try { if (isRequest) { request.headers[import_util_retry.REQUEST_HEADER] = `attempt=${attempts + 1}; max=${maxAttempts}`; } const { response, output } = await next(args); retryStrategy.recordSuccess(retryToken); output.$metadata.attempts = attempts + 1; output.$metadata.totalRetryDelay = totalRetryDelay; return { response, output }; } catch (e) { const retryErrorInfo = getRetryErrorInfo(e); lastError = asSdkError(e); if (isRequest && (0, import_isStreamingPayload.isStreamingPayload)(request)) { (context.logger instanceof import_smithy_client.NoOpLogger ? console : context.logger)?.warn( "An error was encountered in a non-retryable streaming request." ); throw lastError; } try { retryToken = await retryStrategy.refreshRetryTokenForRetry(retryToken, retryErrorInfo); } catch (refreshError) { if (!lastError.$metadata) { lastError.$metadata = {}; } lastError.$metadata.attempts = attempts + 1; lastError.$metadata.totalRetryDelay = totalRetryDelay; throw lastError; } attempts = retryToken.getRetryCount(); const delay = retryToken.getRetryDelay(); totalRetryDelay += delay; await new Promise((resolve) => setTimeout(resolve, delay)); } } } else { retryStrategy = retryStrategy; if (retryStrategy?.mode) context.userAgent = [...context.userAgent || [], ["cfg/retry-mode", retryStrategy.mode]]; return retryStrategy.retry(next, args); } }, "retryMiddleware"); var isRetryStrategyV2 = /* @__PURE__ */ __name((retryStrategy) => typeof retryStrategy.acquireInitialRetryToken !== "undefined" && typeof retryStrategy.refreshRetryTokenForRetry !== "undefined" && typeof retryStrategy.recordSuccess !== "undefined", "isRetryStrategyV2"); var getRetryErrorInfo = /* @__PURE__ */ __name((error) => { const errorInfo = { error, errorType: getRetryErrorType(error) }; const retryAfterHint = getRetryAfterHint(error.$response); if (retryAfterHint) { errorInfo.retryAfterHint = retryAfterHint; } return errorInfo; }, "getRetryErrorInfo"); var getRetryErrorType = /* @__PURE__ */ __name((error) => { if ((0, import_service_error_classification.isThrottlingError)(error)) return "THROTTLING"; if ((0, import_service_error_classification.isTransientError)(error)) return "TRANSIENT"; if ((0, import_service_error_classification.isServerError)(error)) return "SERVER_ERROR"; return "CLIENT_ERROR"; }, "getRetryErrorType"); var retryMiddlewareOptions = { name: "retryMiddleware", tags: ["RETRY"], step: "finalizeRequest", priority: "high", override: true }; var getRetryPlugin = /* @__PURE__ */ __name((options) => ({ applyToStack: (clientStack) => { clientStack.add(retryMiddleware(options), retryMiddlewareOptions); } }), "getRetryPlugin"); var getRetryAfterHint = /* @__PURE__ */ __name((response) => { if (!import_protocol_http.HttpResponse.isInstance(response)) return; const retryAfterHeaderName = Object.keys(response.headers).find((key) => key.toLowerCase() === "retry-after"); if (!retryAfterHeaderName) return; const retryAfter = response.headers[retryAfterHeaderName]; const retryAfterSeconds = Number(retryAfter); if (!Number.isNaN(retryAfterSeconds)) return new Date(retryAfterSeconds * 1e3); const retryAfterDate = new Date(retryAfter); return retryAfterDate; }, "getRetryAfterHint"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); /***/ }), /***/ 18977: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isStreamingPayload = void 0; const stream_1 = __nccwpck_require__(12781); const isStreamingPayload = (request) => (request === null || request === void 0 ? void 0 : request.body) instanceof stream_1.Readable || (typeof ReadableStream !== "undefined" && (request === null || request === void 0 ? void 0 : request.body) instanceof ReadableStream); exports.isStreamingPayload = isStreamingPayload; /***/ }), /***/ 7761: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); Object.defineProperty(exports, "NIL", ({ enumerable: true, get: function () { return _nil.default; } })); Object.defineProperty(exports, "parse", ({ enumerable: true, get: function () { return _parse.default; } })); Object.defineProperty(exports, "stringify", ({ enumerable: true, get: function () { return _stringify.default; } })); Object.defineProperty(exports, "v1", ({ enumerable: true, get: function () { return _v.default; } })); Object.defineProperty(exports, "v3", ({ enumerable: true, get: function () { return _v2.default; } })); Object.defineProperty(exports, "v4", ({ enumerable: true, get: function () { return _v3.default; } })); Object.defineProperty(exports, "v5", ({ enumerable: true, get: function () { return _v4.default; } })); Object.defineProperty(exports, "validate", ({ enumerable: true, get: function () { return _validate.default; } })); Object.defineProperty(exports, "version", ({ enumerable: true, get: function () { return _version.default; } })); var _v = _interopRequireDefault(__nccwpck_require__(36310)); var _v2 = _interopRequireDefault(__nccwpck_require__(9465)); var _v3 = _interopRequireDefault(__nccwpck_require__(86001)); var _v4 = _interopRequireDefault(__nccwpck_require__(38310)); var _nil = _interopRequireDefault(__nccwpck_require__(3436)); var _version = _interopRequireDefault(__nccwpck_require__(17780)); var _validate = _interopRequireDefault(__nccwpck_require__(66992)); var _stringify = _interopRequireDefault(__nccwpck_require__(79618)); var _parse = _interopRequireDefault(__nccwpck_require__(40086)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /***/ }), /***/ 11380: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = void 0; var _crypto = _interopRequireDefault(__nccwpck_require__(6113)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function md5(bytes) { if (Array.isArray(bytes)) { bytes = Buffer.from(bytes); } else if (typeof bytes === 'string') { bytes = Buffer.from(bytes, 'utf8'); } return _crypto.default.createHash('md5').update(bytes).digest(); } var _default = md5; exports["default"] = _default; /***/ }), /***/ 34672: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = void 0; var _crypto = _interopRequireDefault(__nccwpck_require__(6113)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var _default = { randomUUID: _crypto.default.randomUUID }; exports["default"] = _default; /***/ }), /***/ 3436: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = void 0; var _default = '00000000-0000-0000-0000-000000000000'; exports["default"] = _default; /***/ }), /***/ 40086: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = void 0; var _validate = _interopRequireDefault(__nccwpck_require__(66992)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function parse(uuid) { if (!(0, _validate.default)(uuid)) { throw TypeError('Invalid UUID'); } let v; const arr = new Uint8Array(16); // Parse ########-....-....-....-............ arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24; arr[1] = v >>> 16 & 0xff; arr[2] = v >>> 8 & 0xff; arr[3] = v & 0xff; // Parse ........-####-....-....-............ arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; arr[5] = v & 0xff; // Parse ........-....-####-....-............ arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; arr[7] = v & 0xff; // Parse ........-....-....-####-............ arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8; arr[9] = v & 0xff; // Parse ........-....-....-....-############ // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes) arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff; arr[11] = v / 0x100000000 & 0xff; arr[12] = v >>> 24 & 0xff; arr[13] = v >>> 16 & 0xff; arr[14] = v >>> 8 & 0xff; arr[15] = v & 0xff; return arr; } var _default = parse; exports["default"] = _default; /***/ }), /***/ 3194: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = void 0; var _default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i; exports["default"] = _default; /***/ }), /***/ 68136: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = rng; var _crypto = _interopRequireDefault(__nccwpck_require__(6113)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate let poolPtr = rnds8Pool.length; function rng() { if (poolPtr > rnds8Pool.length - 16) { _crypto.default.randomFillSync(rnds8Pool); poolPtr = 0; } return rnds8Pool.slice(poolPtr, poolPtr += 16); } /***/ }), /***/ 46679: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = void 0; var _crypto = _interopRequireDefault(__nccwpck_require__(6113)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function sha1(bytes) { if (Array.isArray(bytes)) { bytes = Buffer.from(bytes); } else if (typeof bytes === 'string') { bytes = Buffer.from(bytes, 'utf8'); } return _crypto.default.createHash('sha1').update(bytes).digest(); } var _default = sha1; exports["default"] = _default; /***/ }), /***/ 79618: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = void 0; exports.unsafeStringify = unsafeStringify; var _validate = _interopRequireDefault(__nccwpck_require__(66992)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Convert array of 16 byte values to UUID string format of the form: * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX */ const byteToHex = []; for (let i = 0; i < 256; ++i) { byteToHex.push((i + 0x100).toString(16).slice(1)); } function unsafeStringify(arr, offset = 0) { // Note: Be careful editing this code! It's been tuned for performance // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]; } function stringify(arr, offset = 0) { const uuid = unsafeStringify(arr, offset); // Consistency check for valid UUID. If this throws, it's likely due to one // of the following: // - One or more input array values don't map to a hex octet (leading to // "undefined" in the uuid) // - Invalid input values for the RFC `version` or `variant` fields if (!(0, _validate.default)(uuid)) { throw TypeError('Stringified UUID is invalid'); } return uuid; } var _default = stringify; exports["default"] = _default; /***/ }), /***/ 36310: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = void 0; var _rng = _interopRequireDefault(__nccwpck_require__(68136)); var _stringify = __nccwpck_require__(79618); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // **`v1()` - Generate time-based UUID** // // Inspired by https://github.com/LiosK/UUID.js // and http://docs.python.org/library/uuid.html let _nodeId; let _clockseq; // Previous uuid creation time let _lastMSecs = 0; let _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details function v1(options, buf, offset) { let i = buf && offset || 0; const b = buf || new Array(16); options = options || {}; let node = options.node || _nodeId; let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not // specified. We do this lazily to minimize issues related to insufficient // system entropy. See #189 if (node == null || clockseq == null) { const seedBytes = options.random || (options.rng || _rng.default)(); if (node == null) { // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; } if (clockseq == null) { // Per 4.2.2, randomize (14 bit) clockseq clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; } } // UUID timestamps are 100 nano-second units since the Gregorian epoch, // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock // cycle to simulate higher resolution clock let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression if (dt < 0 && options.clockseq === undefined) { clockseq = clockseq + 1 & 0x3fff; } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new // time interval if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { nsecs = 0; } // Per 4.2.1.2 Throw error if too many uuids are requested if (nsecs >= 10000) { throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); } _lastMSecs = msecs; _lastNSecs = nsecs; _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch msecs += 12219292800000; // `time_low` const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; b[i++] = tl >>> 24 & 0xff; b[i++] = tl >>> 16 & 0xff; b[i++] = tl >>> 8 & 0xff; b[i++] = tl & 0xff; // `time_mid` const tmh = msecs / 0x100000000 * 10000 & 0xfffffff; b[i++] = tmh >>> 8 & 0xff; b[i++] = tmh & 0xff; // `time_high_and_version` b[i++] = tmh >>> 24 & 0xf | 0x10; // include version b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` b[i++] = clockseq & 0xff; // `node` for (let n = 0; n < 6; ++n) { b[i + n] = node[n]; } return buf || (0, _stringify.unsafeStringify)(b); } var _default = v1; exports["default"] = _default; /***/ }), /***/ 9465: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = void 0; var _v = _interopRequireDefault(__nccwpck_require__(2568)); var _md = _interopRequireDefault(__nccwpck_require__(11380)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const v3 = (0, _v.default)('v3', 0x30, _md.default); var _default = v3; exports["default"] = _default; /***/ }), /***/ 2568: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.URL = exports.DNS = void 0; exports["default"] = v35; var _stringify = __nccwpck_require__(79618); var _parse = _interopRequireDefault(__nccwpck_require__(40086)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function stringToBytes(str) { str = unescape(encodeURIComponent(str)); // UTF8 escape const bytes = []; for (let i = 0; i < str.length; ++i) { bytes.push(str.charCodeAt(i)); } return bytes; } const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; exports.DNS = DNS; const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; exports.URL = URL; function v35(name, version, hashfunc) { function generateUUID(value, namespace, buf, offset) { var _namespace; if (typeof value === 'string') { value = stringToBytes(value); } if (typeof namespace === 'string') { namespace = (0, _parse.default)(namespace); } if (((_namespace = namespace) === null || _namespace === void 0 ? void 0 : _namespace.length) !== 16) { throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)'); } // Compute hash of namespace and value, Per 4.3 // Future: Use spread syntax when supported on all platforms, e.g. `bytes = // hashfunc([...namespace, ... value])` let bytes = new Uint8Array(16 + value.length); bytes.set(namespace); bytes.set(value, namespace.length); bytes = hashfunc(bytes); bytes[6] = bytes[6] & 0x0f | version; bytes[8] = bytes[8] & 0x3f | 0x80; if (buf) { offset = offset || 0; for (let i = 0; i < 16; ++i) { buf[offset + i] = bytes[i]; } return buf; } return (0, _stringify.unsafeStringify)(bytes); } // Function#name is not settable on some platforms (#270) try { generateUUID.name = name; // eslint-disable-next-line no-empty } catch (err) {} // For CommonJS default export support generateUUID.DNS = DNS; generateUUID.URL = URL; return generateUUID; } /***/ }), /***/ 86001: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = void 0; var _native = _interopRequireDefault(__nccwpck_require__(34672)); var _rng = _interopRequireDefault(__nccwpck_require__(68136)); var _stringify = __nccwpck_require__(79618); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function v4(options, buf, offset) { if (_native.default.randomUUID && !buf && !options) { return _native.default.randomUUID(); } options = options || {}; const rnds = options.random || (options.rng || _rng.default)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` rnds[6] = rnds[6] & 0x0f | 0x40; rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided if (buf) { offset = offset || 0; for (let i = 0; i < 16; ++i) { buf[offset + i] = rnds[i]; } return buf; } return (0, _stringify.unsafeStringify)(rnds); } var _default = v4; exports["default"] = _default; /***/ }), /***/ 38310: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = void 0; var _v = _interopRequireDefault(__nccwpck_require__(2568)); var _sha = _interopRequireDefault(__nccwpck_require__(46679)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const v5 = (0, _v.default)('v5', 0x50, _sha.default); var _default = v5; exports["default"] = _default; /***/ }), /***/ 66992: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = void 0; var _regex = _interopRequireDefault(__nccwpck_require__(3194)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function validate(uuid) { return typeof uuid === 'string' && _regex.default.test(uuid); } var _default = validate; exports["default"] = _default; /***/ }), /***/ 17780: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = void 0; var _validate = _interopRequireDefault(__nccwpck_require__(66992)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function version(uuid) { if (!(0, _validate.default)(uuid)) { throw TypeError('Invalid UUID'); } return parseInt(uuid.slice(14, 15), 16); } var _default = version; exports["default"] = _default; /***/ }), /***/ 81238: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { deserializerMiddleware: () => deserializerMiddleware, deserializerMiddlewareOption: () => deserializerMiddlewareOption, getSerdePlugin: () => getSerdePlugin, serializerMiddleware: () => serializerMiddleware, serializerMiddlewareOption: () => serializerMiddlewareOption }); module.exports = __toCommonJS(src_exports); // src/deserializerMiddleware.ts var import_protocol_http = __nccwpck_require__(64418); var deserializerMiddleware = /* @__PURE__ */ __name((options, deserializer) => (next, context) => async (args) => { const { response } = await next(args); try { const parsed = await deserializer(response, options); return { response, output: parsed }; } catch (error) { Object.defineProperty(error, "$response", { value: response }); if (!("$metadata" in error)) { const hint = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`; try { error.message += "\n " + hint; } catch (e) { if (!context.logger || context.logger?.constructor?.name === "NoOpLogger") { console.warn(hint); } else { context.logger?.warn?.(hint); } } if (typeof error.$responseBodyText !== "undefined") { if (error.$response) { error.$response.body = error.$responseBodyText; } } try { if (import_protocol_http.HttpResponse.isInstance(response)) { const { headers = {} } = response; const headerEntries = Object.entries(headers); error.$metadata = { httpStatusCode: response.statusCode, requestId: findHeader(/^x-[\w-]+-request-?id$/, headerEntries), extendedRequestId: findHeader(/^x-[\w-]+-id-2$/, headerEntries), cfId: findHeader(/^x-[\w-]+-cf-id$/, headerEntries) }; } } catch (e) { } } throw error; } }, "deserializerMiddleware"); var findHeader = /* @__PURE__ */ __name((pattern, headers) => { return (headers.find(([k]) => { return k.match(pattern); }) || [void 0, void 0])[1]; }, "findHeader"); // src/serializerMiddleware.ts var serializerMiddleware = /* @__PURE__ */ __name((options, serializer) => (next, context) => async (args) => { const endpointConfig = options; const endpoint = context.endpointV2?.url && endpointConfig.urlParser ? async () => endpointConfig.urlParser(context.endpointV2.url) : endpointConfig.endpoint; if (!endpoint) { throw new Error("No valid endpoint provider available."); } const request = await serializer(args.input, { ...options, endpoint }); return next({ ...args, request }); }, "serializerMiddleware"); // src/serdePlugin.ts var deserializerMiddlewareOption = { name: "deserializerMiddleware", step: "deserialize", tags: ["DESERIALIZER"], override: true }; var serializerMiddlewareOption = { name: "serializerMiddleware", step: "serialize", tags: ["SERIALIZER"], override: true }; function getSerdePlugin(config, serializer, deserializer) { return { applyToStack: (commandStack) => { commandStack.add(deserializerMiddleware(config, deserializer), deserializerMiddlewareOption); commandStack.add(serializerMiddleware(config, serializer), serializerMiddlewareOption); } }; } __name(getSerdePlugin, "getSerdePlugin"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); /***/ }), /***/ 97911: /***/ ((module) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { constructStack: () => constructStack }); module.exports = __toCommonJS(src_exports); // src/MiddlewareStack.ts var getAllAliases = /* @__PURE__ */ __name((name, aliases) => { const _aliases = []; if (name) { _aliases.push(name); } if (aliases) { for (const alias of aliases) { _aliases.push(alias); } } return _aliases; }, "getAllAliases"); var getMiddlewareNameWithAliases = /* @__PURE__ */ __name((name, aliases) => { return `${name || "anonymous"}${aliases && aliases.length > 0 ? ` (a.k.a. ${aliases.join(",")})` : ""}`; }, "getMiddlewareNameWithAliases"); var constructStack = /* @__PURE__ */ __name(() => { let absoluteEntries = []; let relativeEntries = []; let identifyOnResolve = false; const entriesNameSet = /* @__PURE__ */ new Set(); const sort = /* @__PURE__ */ __name((entries) => entries.sort( (a, b) => stepWeights[b.step] - stepWeights[a.step] || priorityWeights[b.priority || "normal"] - priorityWeights[a.priority || "normal"] ), "sort"); const removeByName = /* @__PURE__ */ __name((toRemove) => { let isRemoved = false; const filterCb = /* @__PURE__ */ __name((entry) => { const aliases = getAllAliases(entry.name, entry.aliases); if (aliases.includes(toRemove)) { isRemoved = true; for (const alias of aliases) { entriesNameSet.delete(alias); } return false; } return true; }, "filterCb"); absoluteEntries = absoluteEntries.filter(filterCb); relativeEntries = relativeEntries.filter(filterCb); return isRemoved; }, "removeByName"); const removeByReference = /* @__PURE__ */ __name((toRemove) => { let isRemoved = false; const filterCb = /* @__PURE__ */ __name((entry) => { if (entry.middleware === toRemove) { isRemoved = true; for (const alias of getAllAliases(entry.name, entry.aliases)) { entriesNameSet.delete(alias); } return false; } return true; }, "filterCb"); absoluteEntries = absoluteEntries.filter(filterCb); relativeEntries = relativeEntries.filter(filterCb); return isRemoved; }, "removeByReference"); const cloneTo = /* @__PURE__ */ __name((toStack) => { absoluteEntries.forEach((entry) => { toStack.add(entry.middleware, { ...entry }); }); relativeEntries.forEach((entry) => { toStack.addRelativeTo(entry.middleware, { ...entry }); }); toStack.identifyOnResolve?.(stack.identifyOnResolve()); return toStack; }, "cloneTo"); const expandRelativeMiddlewareList = /* @__PURE__ */ __name((from) => { const expandedMiddlewareList = []; from.before.forEach((entry) => { if (entry.before.length === 0 && entry.after.length === 0) { expandedMiddlewareList.push(entry); } else { expandedMiddlewareList.push(...expandRelativeMiddlewareList(entry)); } }); expandedMiddlewareList.push(from); from.after.reverse().forEach((entry) => { if (entry.before.length === 0 && entry.after.length === 0) { expandedMiddlewareList.push(entry); } else { expandedMiddlewareList.push(...expandRelativeMiddlewareList(entry)); } }); return expandedMiddlewareList; }, "expandRelativeMiddlewareList"); const getMiddlewareList = /* @__PURE__ */ __name((debug = false) => { const normalizedAbsoluteEntries = []; const normalizedRelativeEntries = []; const normalizedEntriesNameMap = {}; absoluteEntries.forEach((entry) => { const normalizedEntry = { ...entry, before: [], after: [] }; for (const alias of getAllAliases(normalizedEntry.name, normalizedEntry.aliases)) { normalizedEntriesNameMap[alias] = normalizedEntry; } normalizedAbsoluteEntries.push(normalizedEntry); }); relativeEntries.forEach((entry) => { const normalizedEntry = { ...entry, before: [], after: [] }; for (const alias of getAllAliases(normalizedEntry.name, normalizedEntry.aliases)) { normalizedEntriesNameMap[alias] = normalizedEntry; } normalizedRelativeEntries.push(normalizedEntry); }); normalizedRelativeEntries.forEach((entry) => { if (entry.toMiddleware) { const toMiddleware = normalizedEntriesNameMap[entry.toMiddleware]; if (toMiddleware === void 0) { if (debug) { return; } throw new Error( `${entry.toMiddleware} is not found when adding ${getMiddlewareNameWithAliases(entry.name, entry.aliases)} middleware ${entry.relation} ${entry.toMiddleware}` ); } if (entry.relation === "after") { toMiddleware.after.push(entry); } if (entry.relation === "before") { toMiddleware.before.push(entry); } } }); const mainChain = sort(normalizedAbsoluteEntries).map(expandRelativeMiddlewareList).reduce( (wholeList, expandedMiddlewareList) => { wholeList.push(...expandedMiddlewareList); return wholeList; }, [] ); return mainChain; }, "getMiddlewareList"); const stack = { add: (middleware, options = {}) => { const { name, override, aliases: _aliases } = options; const entry = { step: "initialize", priority: "normal", middleware, ...options }; const aliases = getAllAliases(name, _aliases); if (aliases.length > 0) { if (aliases.some((alias) => entriesNameSet.has(alias))) { if (!override) throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(name, _aliases)}'`); for (const alias of aliases) { const toOverrideIndex = absoluteEntries.findIndex( (entry2) => entry2.name === alias || entry2.aliases?.some((a) => a === alias) ); if (toOverrideIndex === -1) { continue; } const toOverride = absoluteEntries[toOverrideIndex]; if (toOverride.step !== entry.step || entry.priority !== toOverride.priority) { throw new Error( `"${getMiddlewareNameWithAliases(toOverride.name, toOverride.aliases)}" middleware with ${toOverride.priority} priority in ${toOverride.step} step cannot be overridden by "${getMiddlewareNameWithAliases(name, _aliases)}" middleware with ${entry.priority} priority in ${entry.step} step.` ); } absoluteEntries.splice(toOverrideIndex, 1); } } for (const alias of aliases) { entriesNameSet.add(alias); } } absoluteEntries.push(entry); }, addRelativeTo: (middleware, options) => { const { name, override, aliases: _aliases } = options; const entry = { middleware, ...options }; const aliases = getAllAliases(name, _aliases); if (aliases.length > 0) { if (aliases.some((alias) => entriesNameSet.has(alias))) { if (!override) throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(name, _aliases)}'`); for (const alias of aliases) { const toOverrideIndex = relativeEntries.findIndex( (entry2) => entry2.name === alias || entry2.aliases?.some((a) => a === alias) ); if (toOverrideIndex === -1) { continue; } const toOverride = relativeEntries[toOverrideIndex]; if (toOverride.toMiddleware !== entry.toMiddleware || toOverride.relation !== entry.relation) { throw new Error( `"${getMiddlewareNameWithAliases(toOverride.name, toOverride.aliases)}" middleware ${toOverride.relation} "${toOverride.toMiddleware}" middleware cannot be overridden by "${getMiddlewareNameWithAliases(name, _aliases)}" middleware ${entry.relation} "${entry.toMiddleware}" middleware.` ); } relativeEntries.splice(toOverrideIndex, 1); } } for (const alias of aliases) { entriesNameSet.add(alias); } } relativeEntries.push(entry); }, clone: () => cloneTo(constructStack()), use: (plugin) => { plugin.applyToStack(stack); }, remove: (toRemove) => { if (typeof toRemove === "string") return removeByName(toRemove); else return removeByReference(toRemove); }, removeByTag: (toRemove) => { let isRemoved = false; const filterCb = /* @__PURE__ */ __name((entry) => { const { tags, name, aliases: _aliases } = entry; if (tags && tags.includes(toRemove)) { const aliases = getAllAliases(name, _aliases); for (const alias of aliases) { entriesNameSet.delete(alias); } isRemoved = true; return false; } return true; }, "filterCb"); absoluteEntries = absoluteEntries.filter(filterCb); relativeEntries = relativeEntries.filter(filterCb); return isRemoved; }, concat: (from) => { const cloned = cloneTo(constructStack()); cloned.use(from); cloned.identifyOnResolve( identifyOnResolve || cloned.identifyOnResolve() || (from.identifyOnResolve?.() ?? false) ); return cloned; }, applyToStack: cloneTo, identify: () => { return getMiddlewareList(true).map((mw) => { const step = mw.step ?? mw.relation + " " + mw.toMiddleware; return getMiddlewareNameWithAliases(mw.name, mw.aliases) + " - " + step; }); }, identifyOnResolve(toggle) { if (typeof toggle === "boolean") identifyOnResolve = toggle; return identifyOnResolve; }, resolve: (handler, context) => { for (const middleware of getMiddlewareList().map((entry) => entry.middleware).reverse()) { handler = middleware(handler, context); } if (identifyOnResolve) { console.log(stack.identify()); } return handler; } }; return stack; }, "constructStack"); var stepWeights = { initialize: 5, serialize: 4, build: 3, finalizeRequest: 2, deserialize: 1 }; var priorityWeights = { high: 3, normal: 2, low: 1 }; // Annotate the CommonJS export names for ESM import in node: 0 && (0); /***/ }), /***/ 33461: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { loadConfig: () => loadConfig }); module.exports = __toCommonJS(src_exports); // src/configLoader.ts // src/fromEnv.ts var import_property_provider = __nccwpck_require__(79721); // src/getSelectorName.ts function getSelectorName(functionString) { try { const constants = new Set(Array.from(functionString.match(/([A-Z_]){3,}/g) ?? [])); constants.delete("CONFIG"); constants.delete("CONFIG_PREFIX_SEPARATOR"); constants.delete("ENV"); return [...constants].join(", "); } catch (e) { return functionString; } } __name(getSelectorName, "getSelectorName"); // src/fromEnv.ts var fromEnv = /* @__PURE__ */ __name((envVarSelector, options) => async () => { try { const config = envVarSelector(process.env, options); if (config === void 0) { throw new Error(); } return config; } catch (e) { throw new import_property_provider.CredentialsProviderError( e.message || `Not found in ENV: ${getSelectorName(envVarSelector.toString())}`, { logger: options?.logger } ); } }, "fromEnv"); // src/fromSharedConfigFiles.ts var import_shared_ini_file_loader = __nccwpck_require__(43507); var fromSharedConfigFiles = /* @__PURE__ */ __name((configSelector, { preferredFile = "config", ...init } = {}) => async () => { const profile = (0, import_shared_ini_file_loader.getProfileName)(init); const { configFile, credentialsFile } = await (0, import_shared_ini_file_loader.loadSharedConfigFiles)(init); const profileFromCredentials = credentialsFile[profile] || {}; const profileFromConfig = configFile[profile] || {}; const mergedProfile = preferredFile === "config" ? { ...profileFromCredentials, ...profileFromConfig } : { ...profileFromConfig, ...profileFromCredentials }; try { const cfgFile = preferredFile === "config" ? configFile : credentialsFile; const configValue = configSelector(mergedProfile, cfgFile); if (configValue === void 0) { throw new Error(); } return configValue; } catch (e) { throw new import_property_provider.CredentialsProviderError( e.message || `Not found in config files w/ profile [${profile}]: ${getSelectorName(configSelector.toString())}`, { logger: init.logger } ); } }, "fromSharedConfigFiles"); // src/fromStatic.ts var isFunction = /* @__PURE__ */ __name((func) => typeof func === "function", "isFunction"); var fromStatic = /* @__PURE__ */ __name((defaultValue) => isFunction(defaultValue) ? async () => await defaultValue() : (0, import_property_provider.fromStatic)(defaultValue), "fromStatic"); // src/configLoader.ts var loadConfig = /* @__PURE__ */ __name(({ environmentVariableSelector, configFileSelector, default: defaultValue }, configuration = {}) => { const { signingName, logger } = configuration; const envOptions = { signingName, logger }; return (0, import_property_provider.memoize)( (0, import_property_provider.chain)( fromEnv(environmentVariableSelector, envOptions), fromSharedConfigFiles(configFileSelector, configuration), fromStatic(defaultValue) ) ); }, "loadConfig"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); /***/ }), /***/ 20258: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { DEFAULT_REQUEST_TIMEOUT: () => DEFAULT_REQUEST_TIMEOUT, NodeHttp2Handler: () => NodeHttp2Handler, NodeHttpHandler: () => NodeHttpHandler, streamCollector: () => streamCollector }); module.exports = __toCommonJS(src_exports); // src/node-http-handler.ts var import_protocol_http = __nccwpck_require__(64418); var import_querystring_builder = __nccwpck_require__(68031); var import_http = __nccwpck_require__(13685); var import_https = __nccwpck_require__(95687); // src/constants.ts var NODEJS_TIMEOUT_ERROR_CODES = ["ECONNRESET", "EPIPE", "ETIMEDOUT"]; // src/get-transformed-headers.ts var getTransformedHeaders = /* @__PURE__ */ __name((headers) => { const transformedHeaders = {}; for (const name of Object.keys(headers)) { const headerValues = headers[name]; transformedHeaders[name] = Array.isArray(headerValues) ? headerValues.join(",") : headerValues; } return transformedHeaders; }, "getTransformedHeaders"); // src/timing.ts var timing = { setTimeout: (cb, ms) => setTimeout(cb, ms), clearTimeout: (timeoutId) => clearTimeout(timeoutId) }; // src/set-connection-timeout.ts var DEFER_EVENT_LISTENER_TIME = 1e3; var setConnectionTimeout = /* @__PURE__ */ __name((request, reject, timeoutInMs = 0) => { if (!timeoutInMs) { return -1; } const registerTimeout = /* @__PURE__ */ __name((offset) => { const timeoutId = timing.setTimeout(() => { request.destroy(); reject( Object.assign(new Error(`Socket timed out without establishing a connection within ${timeoutInMs} ms`), { name: "TimeoutError" }) ); }, timeoutInMs - offset); const doWithSocket = /* @__PURE__ */ __name((socket) => { if (socket?.connecting) { socket.on("connect", () => { timing.clearTimeout(timeoutId); }); } else { timing.clearTimeout(timeoutId); } }, "doWithSocket"); if (request.socket) { doWithSocket(request.socket); } else { request.on("socket", doWithSocket); } }, "registerTimeout"); if (timeoutInMs < 2e3) { registerTimeout(0); return 0; } return timing.setTimeout(registerTimeout.bind(null, DEFER_EVENT_LISTENER_TIME), DEFER_EVENT_LISTENER_TIME); }, "setConnectionTimeout"); // src/set-socket-keep-alive.ts var DEFER_EVENT_LISTENER_TIME2 = 3e3; var setSocketKeepAlive = /* @__PURE__ */ __name((request, { keepAlive, keepAliveMsecs }, deferTimeMs = DEFER_EVENT_LISTENER_TIME2) => { if (keepAlive !== true) { return -1; } const registerListener = /* @__PURE__ */ __name(() => { if (request.socket) { request.socket.setKeepAlive(keepAlive, keepAliveMsecs || 0); } else { request.on("socket", (socket) => { socket.setKeepAlive(keepAlive, keepAliveMsecs || 0); }); } }, "registerListener"); if (deferTimeMs === 0) { registerListener(); return 0; } return timing.setTimeout(registerListener, deferTimeMs); }, "setSocketKeepAlive"); // src/set-socket-timeout.ts var DEFER_EVENT_LISTENER_TIME3 = 3e3; var setSocketTimeout = /* @__PURE__ */ __name((request, reject, timeoutInMs = DEFAULT_REQUEST_TIMEOUT) => { const registerTimeout = /* @__PURE__ */ __name((offset) => { const timeout = timeoutInMs - offset; const onTimeout = /* @__PURE__ */ __name(() => { request.destroy(); reject(Object.assign(new Error(`Connection timed out after ${timeoutInMs} ms`), { name: "TimeoutError" })); }, "onTimeout"); if (request.socket) { request.socket.setTimeout(timeout, onTimeout); request.on("close", () => request.socket?.removeListener("timeout", onTimeout)); } else { request.setTimeout(timeout, onTimeout); } }, "registerTimeout"); if (0 < timeoutInMs && timeoutInMs < 6e3) { registerTimeout(0); return 0; } return timing.setTimeout( registerTimeout.bind(null, timeoutInMs === 0 ? 0 : DEFER_EVENT_LISTENER_TIME3), DEFER_EVENT_LISTENER_TIME3 ); }, "setSocketTimeout"); // src/write-request-body.ts var import_stream = __nccwpck_require__(12781); var MIN_WAIT_TIME = 6e3; async function writeRequestBody(httpRequest, request, maxContinueTimeoutMs = MIN_WAIT_TIME) { const headers = request.headers ?? {}; const expect = headers["Expect"] || headers["expect"]; let timeoutId = -1; let sendBody = true; if (expect === "100-continue") { sendBody = await Promise.race([ new Promise((resolve) => { timeoutId = Number(timing.setTimeout(() => resolve(true), Math.max(MIN_WAIT_TIME, maxContinueTimeoutMs))); }), new Promise((resolve) => { httpRequest.on("continue", () => { timing.clearTimeout(timeoutId); resolve(true); }); httpRequest.on("response", () => { timing.clearTimeout(timeoutId); resolve(false); }); httpRequest.on("error", () => { timing.clearTimeout(timeoutId); resolve(false); }); }) ]); } if (sendBody) { writeBody(httpRequest, request.body); } } __name(writeRequestBody, "writeRequestBody"); function writeBody(httpRequest, body) { if (body instanceof import_stream.Readable) { body.pipe(httpRequest); return; } if (body) { if (Buffer.isBuffer(body) || typeof body === "string") { httpRequest.end(body); return; } const uint8 = body; if (typeof uint8 === "object" && uint8.buffer && typeof uint8.byteOffset === "number" && typeof uint8.byteLength === "number") { httpRequest.end(Buffer.from(uint8.buffer, uint8.byteOffset, uint8.byteLength)); return; } httpRequest.end(Buffer.from(body)); return; } httpRequest.end(); } __name(writeBody, "writeBody"); // src/node-http-handler.ts var DEFAULT_REQUEST_TIMEOUT = 0; var NodeHttpHandler = class _NodeHttpHandler { constructor(options) { this.socketWarningTimestamp = 0; // Node http handler is hard-coded to http/1.1: https://github.com/nodejs/node/blob/ff5664b83b89c55e4ab5d5f60068fb457f1f5872/lib/_http_server.js#L286 this.metadata = { handlerProtocol: "http/1.1" }; this.configProvider = new Promise((resolve, reject) => { if (typeof options === "function") { options().then((_options) => { resolve(this.resolveDefaultConfig(_options)); }).catch(reject); } else { resolve(this.resolveDefaultConfig(options)); } }); } static { __name(this, "NodeHttpHandler"); } /** * @returns the input if it is an HttpHandler of any class, * or instantiates a new instance of this handler. */ static create(instanceOrOptions) { if (typeof instanceOrOptions?.handle === "function") { return instanceOrOptions; } return new _NodeHttpHandler(instanceOrOptions); } /** * @internal * * @param agent - http(s) agent in use by the NodeHttpHandler instance. * @param socketWarningTimestamp - last socket usage check timestamp. * @param logger - channel for the warning. * @returns timestamp of last emitted warning. */ static checkSocketUsage(agent, socketWarningTimestamp, logger = console) { const { sockets, requests, maxSockets } = agent; if (typeof maxSockets !== "number" || maxSockets === Infinity) { return socketWarningTimestamp; } const interval = 15e3; if (Date.now() - interval < socketWarningTimestamp) { return socketWarningTimestamp; } if (sockets && requests) { for (const origin in sockets) { const socketsInUse = sockets[origin]?.length ?? 0; const requestsEnqueued = requests[origin]?.length ?? 0; if (socketsInUse >= maxSockets && requestsEnqueued >= 2 * maxSockets) { logger?.warn?.( `@smithy/node-http-handler:WARN - socket usage at capacity=${socketsInUse} and ${requestsEnqueued} additional requests are enqueued. See https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/node-configuring-maxsockets.html or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler config.` ); return Date.now(); } } } return socketWarningTimestamp; } resolveDefaultConfig(options) { const { requestTimeout, connectionTimeout, socketTimeout, socketAcquisitionWarningTimeout, httpAgent, httpsAgent } = options || {}; const keepAlive = true; const maxSockets = 50; return { connectionTimeout, requestTimeout: requestTimeout ?? socketTimeout, socketAcquisitionWarningTimeout, httpAgent: (() => { if (httpAgent instanceof import_http.Agent || typeof httpAgent?.destroy === "function") { return httpAgent; } return new import_http.Agent({ keepAlive, maxSockets, ...httpAgent }); })(), httpsAgent: (() => { if (httpsAgent instanceof import_https.Agent || typeof httpsAgent?.destroy === "function") { return httpsAgent; } return new import_https.Agent({ keepAlive, maxSockets, ...httpsAgent }); })(), logger: console }; } destroy() { this.config?.httpAgent?.destroy(); this.config?.httpsAgent?.destroy(); } async handle(request, { abortSignal } = {}) { if (!this.config) { this.config = await this.configProvider; } return new Promise((_resolve, _reject) => { let writeRequestBodyPromise = void 0; const timeouts = []; const resolve = /* @__PURE__ */ __name(async (arg) => { await writeRequestBodyPromise; timeouts.forEach(timing.clearTimeout); _resolve(arg); }, "resolve"); const reject = /* @__PURE__ */ __name(async (arg) => { await writeRequestBodyPromise; timeouts.forEach(timing.clearTimeout); _reject(arg); }, "reject"); if (!this.config) { throw new Error("Node HTTP request handler config is not resolved"); } if (abortSignal?.aborted) { const abortError = new Error("Request aborted"); abortError.name = "AbortError"; reject(abortError); return; } const isSSL = request.protocol === "https:"; const agent = isSSL ? this.config.httpsAgent : this.config.httpAgent; timeouts.push( timing.setTimeout( () => { this.socketWarningTimestamp = _NodeHttpHandler.checkSocketUsage( agent, this.socketWarningTimestamp, this.config.logger ); }, this.config.socketAcquisitionWarningTimeout ?? (this.config.requestTimeout ?? 2e3) + (this.config.connectionTimeout ?? 1e3) ) ); const queryString = (0, import_querystring_builder.buildQueryString)(request.query || {}); let auth = void 0; if (request.username != null || request.password != null) { const username = request.username ?? ""; const password = request.password ?? ""; auth = `${username}:${password}`; } let path = request.path; if (queryString) { path += `?${queryString}`; } if (request.fragment) { path += `#${request.fragment}`; } let hostname = request.hostname ?? ""; if (hostname[0] === "[" && hostname.endsWith("]")) { hostname = request.hostname.slice(1, -1); } else { hostname = request.hostname; } const nodeHttpsOptions = { headers: request.headers, host: hostname, method: request.method, path, port: request.port, agent, auth }; const requestFunc = isSSL ? import_https.request : import_http.request; const req = requestFunc(nodeHttpsOptions, (res) => { const httpResponse = new import_protocol_http.HttpResponse({ statusCode: res.statusCode || -1, reason: res.statusMessage, headers: getTransformedHeaders(res.headers), body: res }); resolve({ response: httpResponse }); }); req.on("error", (err) => { if (NODEJS_TIMEOUT_ERROR_CODES.includes(err.code)) { reject(Object.assign(err, { name: "TimeoutError" })); } else { reject(err); } }); if (abortSignal) { const onAbort = /* @__PURE__ */ __name(() => { req.destroy(); const abortError = new Error("Request aborted"); abortError.name = "AbortError"; reject(abortError); }, "onAbort"); if (typeof abortSignal.addEventListener === "function") { const signal = abortSignal; signal.addEventListener("abort", onAbort, { once: true }); req.once("close", () => signal.removeEventListener("abort", onAbort)); } else { abortSignal.onabort = onAbort; } } timeouts.push(setConnectionTimeout(req, reject, this.config.connectionTimeout)); timeouts.push(setSocketTimeout(req, reject, this.config.requestTimeout)); const httpAgent = nodeHttpsOptions.agent; if (typeof httpAgent === "object" && "keepAlive" in httpAgent) { timeouts.push( setSocketKeepAlive(req, { // @ts-expect-error keepAlive is not public on httpAgent. keepAlive: httpAgent.keepAlive, // @ts-expect-error keepAliveMsecs is not public on httpAgent. keepAliveMsecs: httpAgent.keepAliveMsecs }) ); } writeRequestBodyPromise = writeRequestBody(req, request, this.config.requestTimeout).catch((e) => { timeouts.forEach(timing.clearTimeout); return _reject(e); }); }); } updateHttpClientConfig(key, value) { this.config = void 0; this.configProvider = this.configProvider.then((config) => { return { ...config, [key]: value }; }); } httpHandlerConfigs() { return this.config ?? {}; } }; // src/node-http2-handler.ts var import_http22 = __nccwpck_require__(85158); // src/node-http2-connection-manager.ts var import_http2 = __toESM(__nccwpck_require__(85158)); // src/node-http2-connection-pool.ts var NodeHttp2ConnectionPool = class { constructor(sessions) { this.sessions = []; this.sessions = sessions ?? []; } static { __name(this, "NodeHttp2ConnectionPool"); } poll() { if (this.sessions.length > 0) { return this.sessions.shift(); } } offerLast(session) { this.sessions.push(session); } contains(session) { return this.sessions.includes(session); } remove(session) { this.sessions = this.sessions.filter((s) => s !== session); } [Symbol.iterator]() { return this.sessions[Symbol.iterator](); } destroy(connection) { for (const session of this.sessions) { if (session === connection) { if (!session.destroyed) { session.destroy(); } } } } }; // src/node-http2-connection-manager.ts var NodeHttp2ConnectionManager = class { constructor(config) { this.sessionCache = /* @__PURE__ */ new Map(); this.config = config; if (this.config.maxConcurrency && this.config.maxConcurrency <= 0) { throw new RangeError("maxConcurrency must be greater than zero."); } } static { __name(this, "NodeHttp2ConnectionManager"); } lease(requestContext, connectionConfiguration) { const url = this.getUrlString(requestContext); const existingPool = this.sessionCache.get(url); if (existingPool) { const existingSession = existingPool.poll(); if (existingSession && !this.config.disableConcurrency) { return existingSession; } } const session = import_http2.default.connect(url); if (this.config.maxConcurrency) { session.settings({ maxConcurrentStreams: this.config.maxConcurrency }, (err) => { if (err) { throw new Error( "Fail to set maxConcurrentStreams to " + this.config.maxConcurrency + "when creating new session for " + requestContext.destination.toString() ); } }); } session.unref(); const destroySessionCb = /* @__PURE__ */ __name(() => { session.destroy(); this.deleteSession(url, session); }, "destroySessionCb"); session.on("goaway", destroySessionCb); session.on("error", destroySessionCb); session.on("frameError", destroySessionCb); session.on("close", () => this.deleteSession(url, session)); if (connectionConfiguration.requestTimeout) { session.setTimeout(connectionConfiguration.requestTimeout, destroySessionCb); } const connectionPool = this.sessionCache.get(url) || new NodeHttp2ConnectionPool(); connectionPool.offerLast(session); this.sessionCache.set(url, connectionPool); return session; } /** * Delete a session from the connection pool. * @param authority The authority of the session to delete. * @param session The session to delete. */ deleteSession(authority, session) { const existingConnectionPool = this.sessionCache.get(authority); if (!existingConnectionPool) { return; } if (!existingConnectionPool.contains(session)) { return; } existingConnectionPool.remove(session); this.sessionCache.set(authority, existingConnectionPool); } release(requestContext, session) { const cacheKey = this.getUrlString(requestContext); this.sessionCache.get(cacheKey)?.offerLast(session); } destroy() { for (const [key, connectionPool] of this.sessionCache) { for (const session of connectionPool) { if (!session.destroyed) { session.destroy(); } connectionPool.remove(session); } this.sessionCache.delete(key); } } setMaxConcurrentStreams(maxConcurrentStreams) { if (maxConcurrentStreams && maxConcurrentStreams <= 0) { throw new RangeError("maxConcurrentStreams must be greater than zero."); } this.config.maxConcurrency = maxConcurrentStreams; } setDisableConcurrentStreams(disableConcurrentStreams) { this.config.disableConcurrency = disableConcurrentStreams; } getUrlString(request) { return request.destination.toString(); } }; // src/node-http2-handler.ts var NodeHttp2Handler = class _NodeHttp2Handler { constructor(options) { this.metadata = { handlerProtocol: "h2" }; this.connectionManager = new NodeHttp2ConnectionManager({}); this.configProvider = new Promise((resolve, reject) => { if (typeof options === "function") { options().then((opts) => { resolve(opts || {}); }).catch(reject); } else { resolve(options || {}); } }); } static { __name(this, "NodeHttp2Handler"); } /** * @returns the input if it is an HttpHandler of any class, * or instantiates a new instance of this handler. */ static create(instanceOrOptions) { if (typeof instanceOrOptions?.handle === "function") { return instanceOrOptions; } return new _NodeHttp2Handler(instanceOrOptions); } destroy() { this.connectionManager.destroy(); } async handle(request, { abortSignal } = {}) { if (!this.config) { this.config = await this.configProvider; this.connectionManager.setDisableConcurrentStreams(this.config.disableConcurrentStreams || false); if (this.config.maxConcurrentStreams) { this.connectionManager.setMaxConcurrentStreams(this.config.maxConcurrentStreams); } } const { requestTimeout, disableConcurrentStreams } = this.config; return new Promise((_resolve, _reject) => { let fulfilled = false; let writeRequestBodyPromise = void 0; const resolve = /* @__PURE__ */ __name(async (arg) => { await writeRequestBodyPromise; _resolve(arg); }, "resolve"); const reject = /* @__PURE__ */ __name(async (arg) => { await writeRequestBodyPromise; _reject(arg); }, "reject"); if (abortSignal?.aborted) { fulfilled = true; const abortError = new Error("Request aborted"); abortError.name = "AbortError"; reject(abortError); return; } const { hostname, method, port, protocol, query } = request; let auth = ""; if (request.username != null || request.password != null) { const username = request.username ?? ""; const password = request.password ?? ""; auth = `${username}:${password}@`; } const authority = `${protocol}//${auth}${hostname}${port ? `:${port}` : ""}`; const requestContext = { destination: new URL(authority) }; const session = this.connectionManager.lease(requestContext, { requestTimeout: this.config?.sessionTimeout, disableConcurrentStreams: disableConcurrentStreams || false }); const rejectWithDestroy = /* @__PURE__ */ __name((err) => { if (disableConcurrentStreams) { this.destroySession(session); } fulfilled = true; reject(err); }, "rejectWithDestroy"); const queryString = (0, import_querystring_builder.buildQueryString)(query || {}); let path = request.path; if (queryString) { path += `?${queryString}`; } if (request.fragment) { path += `#${request.fragment}`; } const req = session.request({ ...request.headers, [import_http22.constants.HTTP2_HEADER_PATH]: path, [import_http22.constants.HTTP2_HEADER_METHOD]: method }); session.ref(); req.on("response", (headers) => { const httpResponse = new import_protocol_http.HttpResponse({ statusCode: headers[":status"] || -1, headers: getTransformedHeaders(headers), body: req }); fulfilled = true; resolve({ response: httpResponse }); if (disableConcurrentStreams) { session.close(); this.connectionManager.deleteSession(authority, session); } }); if (requestTimeout) { req.setTimeout(requestTimeout, () => { req.close(); const timeoutError = new Error(`Stream timed out because of no activity for ${requestTimeout} ms`); timeoutError.name = "TimeoutError"; rejectWithDestroy(timeoutError); }); } if (abortSignal) { const onAbort = /* @__PURE__ */ __name(() => { req.close(); const abortError = new Error("Request aborted"); abortError.name = "AbortError"; rejectWithDestroy(abortError); }, "onAbort"); if (typeof abortSignal.addEventListener === "function") { const signal = abortSignal; signal.addEventListener("abort", onAbort, { once: true }); req.once("close", () => signal.removeEventListener("abort", onAbort)); } else { abortSignal.onabort = onAbort; } } req.on("frameError", (type, code, id) => { rejectWithDestroy(new Error(`Frame type id ${type} in stream id ${id} has failed with code ${code}.`)); }); req.on("error", rejectWithDestroy); req.on("aborted", () => { rejectWithDestroy( new Error(`HTTP/2 stream is abnormally aborted in mid-communication with result code ${req.rstCode}.`) ); }); req.on("close", () => { session.unref(); if (disableConcurrentStreams) { session.destroy(); } if (!fulfilled) { rejectWithDestroy(new Error("Unexpected error: http2 request did not get a response")); } }); writeRequestBodyPromise = writeRequestBody(req, request, requestTimeout); }); } updateHttpClientConfig(key, value) { this.config = void 0; this.configProvider = this.configProvider.then((config) => { return { ...config, [key]: value }; }); } httpHandlerConfigs() { return this.config ?? {}; } /** * Destroys a session. * @param session - the session to destroy. */ destroySession(session) { if (!session.destroyed) { session.destroy(); } } }; // src/stream-collector/collector.ts var Collector = class extends import_stream.Writable { constructor() { super(...arguments); this.bufferedBytes = []; } static { __name(this, "Collector"); } _write(chunk, encoding, callback) { this.bufferedBytes.push(chunk); callback(); } }; // src/stream-collector/index.ts var streamCollector = /* @__PURE__ */ __name((stream) => { if (isReadableStreamInstance(stream)) { return collectReadableStream(stream); } return new Promise((resolve, reject) => { const collector = new Collector(); stream.pipe(collector); stream.on("error", (err) => { collector.end(); reject(err); }); collector.on("error", reject); collector.on("finish", function() { const bytes = new Uint8Array(Buffer.concat(this.bufferedBytes)); resolve(bytes); }); }); }, "streamCollector"); var isReadableStreamInstance = /* @__PURE__ */ __name((stream) => typeof ReadableStream === "function" && stream instanceof ReadableStream, "isReadableStreamInstance"); async function collectReadableStream(stream) { const chunks = []; const reader = stream.getReader(); let isDone = false; let length = 0; while (!isDone) { const { done, value } = await reader.read(); if (value) { chunks.push(value); length += value.length; } isDone = done; } const collected = new Uint8Array(length); let offset = 0; for (const chunk of chunks) { collected.set(chunk, offset); offset += chunk.length; } return collected; } __name(collectReadableStream, "collectReadableStream"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); /***/ }), /***/ 79721: /***/ ((module) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { CredentialsProviderError: () => CredentialsProviderError, ProviderError: () => ProviderError, TokenProviderError: () => TokenProviderError, chain: () => chain, fromStatic: () => fromStatic, memoize: () => memoize }); module.exports = __toCommonJS(src_exports); // src/ProviderError.ts var ProviderError = class _ProviderError extends Error { constructor(message, options = true) { let logger; let tryNextLink = true; if (typeof options === "boolean") { logger = void 0; tryNextLink = options; } else if (options != null && typeof options === "object") { logger = options.logger; tryNextLink = options.tryNextLink ?? true; } super(message); this.name = "ProviderError"; this.tryNextLink = tryNextLink; Object.setPrototypeOf(this, _ProviderError.prototype); logger?.debug?.(`@smithy/property-provider ${tryNextLink ? "->" : "(!)"} ${message}`); } static { __name(this, "ProviderError"); } /** * @deprecated use new operator. */ static from(error, options = true) { return Object.assign(new this(error.message, options), error); } }; // src/CredentialsProviderError.ts var CredentialsProviderError = class _CredentialsProviderError extends ProviderError { /** * @override */ constructor(message, options = true) { super(message, options); this.name = "CredentialsProviderError"; Object.setPrototypeOf(this, _CredentialsProviderError.prototype); } static { __name(this, "CredentialsProviderError"); } }; // src/TokenProviderError.ts var TokenProviderError = class _TokenProviderError extends ProviderError { /** * @override */ constructor(message, options = true) { super(message, options); this.name = "TokenProviderError"; Object.setPrototypeOf(this, _TokenProviderError.prototype); } static { __name(this, "TokenProviderError"); } }; // src/chain.ts var chain = /* @__PURE__ */ __name((...providers) => async () => { if (providers.length === 0) { throw new ProviderError("No providers in chain"); } let lastProviderError; for (const provider of providers) { try { const credentials = await provider(); return credentials; } catch (err) { lastProviderError = err; if (err?.tryNextLink) { continue; } throw err; } } throw lastProviderError; }, "chain"); // src/fromStatic.ts var fromStatic = /* @__PURE__ */ __name((staticValue) => () => Promise.resolve(staticValue), "fromStatic"); // src/memoize.ts var memoize = /* @__PURE__ */ __name((provider, isExpired, requiresRefresh) => { let resolved; let pending; let hasResult; let isConstant = false; const coalesceProvider = /* @__PURE__ */ __name(async () => { if (!pending) { pending = provider(); } try { resolved = await pending; hasResult = true; isConstant = false; } finally { pending = void 0; } return resolved; }, "coalesceProvider"); if (isExpired === void 0) { return async (options) => { if (!hasResult || options?.forceRefresh) { resolved = await coalesceProvider(); } return resolved; }; } return async (options) => { if (!hasResult || options?.forceRefresh) { resolved = await coalesceProvider(); } if (isConstant) { return resolved; } if (requiresRefresh && !requiresRefresh(resolved)) { isConstant = true; return resolved; } if (isExpired(resolved)) { await coalesceProvider(); return resolved; } return resolved; }; }, "memoize"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); /***/ }), /***/ 64418: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { Field: () => Field, Fields: () => Fields, HttpRequest: () => HttpRequest, HttpResponse: () => HttpResponse, IHttpRequest: () => import_types.HttpRequest, getHttpHandlerExtensionConfiguration: () => getHttpHandlerExtensionConfiguration, isValidHostname: () => isValidHostname, resolveHttpHandlerRuntimeConfig: () => resolveHttpHandlerRuntimeConfig }); module.exports = __toCommonJS(src_exports); // src/extensions/httpExtensionConfiguration.ts var getHttpHandlerExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { return { setHttpHandler(handler) { runtimeConfig.httpHandler = handler; }, httpHandler() { return runtimeConfig.httpHandler; }, updateHttpClientConfig(key, value) { runtimeConfig.httpHandler?.updateHttpClientConfig(key, value); }, httpHandlerConfigs() { return runtimeConfig.httpHandler.httpHandlerConfigs(); } }; }, "getHttpHandlerExtensionConfiguration"); var resolveHttpHandlerRuntimeConfig = /* @__PURE__ */ __name((httpHandlerExtensionConfiguration) => { return { httpHandler: httpHandlerExtensionConfiguration.httpHandler() }; }, "resolveHttpHandlerRuntimeConfig"); // src/Field.ts var import_types = __nccwpck_require__(55756); var Field = class { static { __name(this, "Field"); } constructor({ name, kind = import_types.FieldPosition.HEADER, values = [] }) { this.name = name; this.kind = kind; this.values = values; } /** * Appends a value to the field. * * @param value The value to append. */ add(value) { this.values.push(value); } /** * Overwrite existing field values. * * @param values The new field values. */ set(values) { this.values = values; } /** * Remove all matching entries from list. * * @param value Value to remove. */ remove(value) { this.values = this.values.filter((v) => v !== value); } /** * Get comma-delimited string. * * @returns String representation of {@link Field}. */ toString() { return this.values.map((v) => v.includes(",") || v.includes(" ") ? `"${v}"` : v).join(", "); } /** * Get string values as a list * * @returns Values in {@link Field} as a list. */ get() { return this.values; } }; // src/Fields.ts var Fields = class { constructor({ fields = [], encoding = "utf-8" }) { this.entries = {}; fields.forEach(this.setField.bind(this)); this.encoding = encoding; } static { __name(this, "Fields"); } /** * Set entry for a {@link Field} name. The `name` * attribute will be used to key the collection. * * @param field The {@link Field} to set. */ setField(field) { this.entries[field.name.toLowerCase()] = field; } /** * Retrieve {@link Field} entry by name. * * @param name The name of the {@link Field} entry * to retrieve * @returns The {@link Field} if it exists. */ getField(name) { return this.entries[name.toLowerCase()]; } /** * Delete entry from collection. * * @param name Name of the entry to delete. */ removeField(name) { delete this.entries[name.toLowerCase()]; } /** * Helper function for retrieving specific types of fields. * Used to grab all headers or all trailers. * * @param kind {@link FieldPosition} of entries to retrieve. * @returns The {@link Field} entries with the specified * {@link FieldPosition}. */ getByType(kind) { return Object.values(this.entries).filter((field) => field.kind === kind); } }; // src/httpRequest.ts var HttpRequest = class _HttpRequest { static { __name(this, "HttpRequest"); } constructor(options) { this.method = options.method || "GET"; this.hostname = options.hostname || "localhost"; this.port = options.port; this.query = options.query || {}; this.headers = options.headers || {}; this.body = options.body; this.protocol = options.protocol ? options.protocol.slice(-1) !== ":" ? `${options.protocol}:` : options.protocol : "https:"; this.path = options.path ? options.path.charAt(0) !== "/" ? `/${options.path}` : options.path : "/"; this.username = options.username; this.password = options.password; this.fragment = options.fragment; } /** * Note: this does not deep-clone the body. */ static clone(request) { const cloned = new _HttpRequest({ ...request, headers: { ...request.headers } }); if (cloned.query) { cloned.query = cloneQuery(cloned.query); } return cloned; } /** * This method only actually asserts that request is the interface {@link IHttpRequest}, * and not necessarily this concrete class. Left in place for API stability. * * Do not call instance methods on the input of this function, and * do not assume it has the HttpRequest prototype. */ static isInstance(request) { if (!request) { return false; } const req = request; return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object"; } /** * @deprecated use static HttpRequest.clone(request) instead. It's not safe to call * this method because {@link HttpRequest.isInstance} incorrectly * asserts that IHttpRequest (interface) objects are of type HttpRequest (class). */ clone() { return _HttpRequest.clone(this); } }; function cloneQuery(query) { return Object.keys(query).reduce((carry, paramName) => { const param = query[paramName]; return { ...carry, [paramName]: Array.isArray(param) ? [...param] : param }; }, {}); } __name(cloneQuery, "cloneQuery"); // src/httpResponse.ts var HttpResponse = class { static { __name(this, "HttpResponse"); } constructor(options) { this.statusCode = options.statusCode; this.reason = options.reason; this.headers = options.headers || {}; this.body = options.body; } static isInstance(response) { if (!response) return false; const resp = response; return typeof resp.statusCode === "number" && typeof resp.headers === "object"; } }; // src/isValidHostname.ts function isValidHostname(hostname) { const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/; return hostPattern.test(hostname); } __name(isValidHostname, "isValidHostname"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); /***/ }), /***/ 68031: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { buildQueryString: () => buildQueryString }); module.exports = __toCommonJS(src_exports); var import_util_uri_escape = __nccwpck_require__(54197); function buildQueryString(query) { const parts = []; for (let key of Object.keys(query).sort()) { const value = query[key]; key = (0, import_util_uri_escape.escapeUri)(key); if (Array.isArray(value)) { for (let i = 0, iLen = value.length; i < iLen; i++) { parts.push(`${key}=${(0, import_util_uri_escape.escapeUri)(value[i])}`); } } else { let qsEntry = key; if (value || typeof value === "string") { qsEntry += `=${(0, import_util_uri_escape.escapeUri)(value)}`; } parts.push(qsEntry); } } return parts.join("&"); } __name(buildQueryString, "buildQueryString"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); /***/ }), /***/ 4769: /***/ ((module) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { parseQueryString: () => parseQueryString }); module.exports = __toCommonJS(src_exports); function parseQueryString(querystring) { const query = {}; querystring = querystring.replace(/^\?/, ""); if (querystring) { for (const pair of querystring.split("&")) { let [key, value = null] = pair.split("="); key = decodeURIComponent(key); if (value) { value = decodeURIComponent(value); } if (!(key in query)) { query[key] = value; } else if (Array.isArray(query[key])) { query[key].push(value); } else { query[key] = [query[key], value]; } } } return query; } __name(parseQueryString, "parseQueryString"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); /***/ }), /***/ 6375: /***/ ((module) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { isBrowserNetworkError: () => isBrowserNetworkError, isClockSkewCorrectedError: () => isClockSkewCorrectedError, isClockSkewError: () => isClockSkewError, isRetryableByTrait: () => isRetryableByTrait, isServerError: () => isServerError, isThrottlingError: () => isThrottlingError, isTransientError: () => isTransientError }); module.exports = __toCommonJS(src_exports); // src/constants.ts var CLOCK_SKEW_ERROR_CODES = [ "AuthFailure", "InvalidSignatureException", "RequestExpired", "RequestInTheFuture", "RequestTimeTooSkewed", "SignatureDoesNotMatch" ]; var THROTTLING_ERROR_CODES = [ "BandwidthLimitExceeded", "EC2ThrottledException", "LimitExceededException", "PriorRequestNotComplete", "ProvisionedThroughputExceededException", "RequestLimitExceeded", "RequestThrottled", "RequestThrottledException", "SlowDown", "ThrottledException", "Throttling", "ThrottlingException", "TooManyRequestsException", "TransactionInProgressException" // DynamoDB ]; var TRANSIENT_ERROR_CODES = ["TimeoutError", "RequestTimeout", "RequestTimeoutException"]; var TRANSIENT_ERROR_STATUS_CODES = [500, 502, 503, 504]; var NODEJS_TIMEOUT_ERROR_CODES = ["ECONNRESET", "ECONNREFUSED", "EPIPE", "ETIMEDOUT"]; // src/index.ts var isRetryableByTrait = /* @__PURE__ */ __name((error) => error.$retryable !== void 0, "isRetryableByTrait"); var isClockSkewError = /* @__PURE__ */ __name((error) => CLOCK_SKEW_ERROR_CODES.includes(error.name), "isClockSkewError"); var isClockSkewCorrectedError = /* @__PURE__ */ __name((error) => error.$metadata?.clockSkewCorrected, "isClockSkewCorrectedError"); var isBrowserNetworkError = /* @__PURE__ */ __name((error) => { const errorMessages = /* @__PURE__ */ new Set([ "Failed to fetch", // Chrome "NetworkError when attempting to fetch resource", // Firefox "The Internet connection appears to be offline", // Safari 16 "Load failed", // Safari 17+ "Network request failed" // `cross-fetch` ]); const isValid = error && error instanceof TypeError; if (!isValid) { return false; } return errorMessages.has(error.message); }, "isBrowserNetworkError"); var isThrottlingError = /* @__PURE__ */ __name((error) => error.$metadata?.httpStatusCode === 429 || THROTTLING_ERROR_CODES.includes(error.name) || error.$retryable?.throttling == true, "isThrottlingError"); var isTransientError = /* @__PURE__ */ __name((error, depth = 0) => isClockSkewCorrectedError(error) || TRANSIENT_ERROR_CODES.includes(error.name) || NODEJS_TIMEOUT_ERROR_CODES.includes(error?.code || "") || TRANSIENT_ERROR_STATUS_CODES.includes(error.$metadata?.httpStatusCode || 0) || isBrowserNetworkError(error) || error.cause !== void 0 && depth <= 10 && isTransientError(error.cause, depth + 1), "isTransientError"); var isServerError = /* @__PURE__ */ __name((error) => { if (error.$metadata?.httpStatusCode !== void 0) { const statusCode = error.$metadata.httpStatusCode; if (500 <= statusCode && statusCode <= 599 && !isTransientError(error)) { return true; } return false; } return false; }, "isServerError"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); /***/ }), /***/ 68340: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getHomeDir = void 0; const os_1 = __nccwpck_require__(22037); const path_1 = __nccwpck_require__(71017); const homeDirCache = {}; const getHomeDirCacheKey = () => { if (process && process.geteuid) { return `${process.geteuid()}`; } return "DEFAULT"; }; const getHomeDir = () => { const { HOME, USERPROFILE, HOMEPATH, HOMEDRIVE = `C:${path_1.sep}` } = process.env; if (HOME) return HOME; if (USERPROFILE) return USERPROFILE; if (HOMEPATH) return `${HOMEDRIVE}${HOMEPATH}`; const homeDirCacheKey = getHomeDirCacheKey(); if (!homeDirCache[homeDirCacheKey]) homeDirCache[homeDirCacheKey] = (0, os_1.homedir)(); return homeDirCache[homeDirCacheKey]; }; exports.getHomeDir = getHomeDir; /***/ }), /***/ 24740: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getSSOTokenFilepath = void 0; const crypto_1 = __nccwpck_require__(6113); const path_1 = __nccwpck_require__(71017); const getHomeDir_1 = __nccwpck_require__(68340); const getSSOTokenFilepath = (id) => { const hasher = (0, crypto_1.createHash)("sha1"); const cacheName = hasher.update(id).digest("hex"); return (0, path_1.join)((0, getHomeDir_1.getHomeDir)(), ".aws", "sso", "cache", `${cacheName}.json`); }; exports.getSSOTokenFilepath = getSSOTokenFilepath; /***/ }), /***/ 69678: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getSSOTokenFromFile = void 0; const fs_1 = __nccwpck_require__(57147); const getSSOTokenFilepath_1 = __nccwpck_require__(24740); const { readFile } = fs_1.promises; const getSSOTokenFromFile = async (id) => { const ssoTokenFilepath = (0, getSSOTokenFilepath_1.getSSOTokenFilepath)(id); const ssoTokenText = await readFile(ssoTokenFilepath, "utf8"); return JSON.parse(ssoTokenText); }; exports.getSSOTokenFromFile = getSSOTokenFromFile; /***/ }), /***/ 43507: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { CONFIG_PREFIX_SEPARATOR: () => CONFIG_PREFIX_SEPARATOR, DEFAULT_PROFILE: () => DEFAULT_PROFILE, ENV_PROFILE: () => ENV_PROFILE, getProfileName: () => getProfileName, loadSharedConfigFiles: () => loadSharedConfigFiles, loadSsoSessionData: () => loadSsoSessionData, parseKnownFiles: () => parseKnownFiles }); module.exports = __toCommonJS(src_exports); __reExport(src_exports, __nccwpck_require__(68340), module.exports); // src/getProfileName.ts var ENV_PROFILE = "AWS_PROFILE"; var DEFAULT_PROFILE = "default"; var getProfileName = /* @__PURE__ */ __name((init) => init.profile || process.env[ENV_PROFILE] || DEFAULT_PROFILE, "getProfileName"); // src/index.ts __reExport(src_exports, __nccwpck_require__(24740), module.exports); __reExport(src_exports, __nccwpck_require__(69678), module.exports); // src/loadSharedConfigFiles.ts // src/getConfigData.ts var import_types = __nccwpck_require__(55756); var getConfigData = /* @__PURE__ */ __name((data) => Object.entries(data).filter(([key]) => { const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); if (indexOfSeparator === -1) { return false; } return Object.values(import_types.IniSectionType).includes(key.substring(0, indexOfSeparator)); }).reduce( (acc, [key, value]) => { const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); const updatedKey = key.substring(0, indexOfSeparator) === import_types.IniSectionType.PROFILE ? key.substring(indexOfSeparator + 1) : key; acc[updatedKey] = value; return acc; }, { // Populate default profile, if present. ...data.default && { default: data.default } } ), "getConfigData"); // src/getConfigFilepath.ts var import_path = __nccwpck_require__(71017); var import_getHomeDir = __nccwpck_require__(68340); var ENV_CONFIG_PATH = "AWS_CONFIG_FILE"; var getConfigFilepath = /* @__PURE__ */ __name(() => process.env[ENV_CONFIG_PATH] || (0, import_path.join)((0, import_getHomeDir.getHomeDir)(), ".aws", "config"), "getConfigFilepath"); // src/getCredentialsFilepath.ts var import_getHomeDir2 = __nccwpck_require__(68340); var ENV_CREDENTIALS_PATH = "AWS_SHARED_CREDENTIALS_FILE"; var getCredentialsFilepath = /* @__PURE__ */ __name(() => process.env[ENV_CREDENTIALS_PATH] || (0, import_path.join)((0, import_getHomeDir2.getHomeDir)(), ".aws", "credentials"), "getCredentialsFilepath"); // src/loadSharedConfigFiles.ts var import_getHomeDir3 = __nccwpck_require__(68340); // src/parseIni.ts var prefixKeyRegex = /^([\w-]+)\s(["'])?([\w-@\+\.%:/]+)\2$/; var profileNameBlockList = ["__proto__", "profile __proto__"]; var parseIni = /* @__PURE__ */ __name((iniData) => { const map = {}; let currentSection; let currentSubSection; for (const iniLine of iniData.split(/\r?\n/)) { const trimmedLine = iniLine.split(/(^|\s)[;#]/)[0].trim(); const isSection = trimmedLine[0] === "[" && trimmedLine[trimmedLine.length - 1] === "]"; if (isSection) { currentSection = void 0; currentSubSection = void 0; const sectionName = trimmedLine.substring(1, trimmedLine.length - 1); const matches = prefixKeyRegex.exec(sectionName); if (matches) { const [, prefix, , name] = matches; if (Object.values(import_types.IniSectionType).includes(prefix)) { currentSection = [prefix, name].join(CONFIG_PREFIX_SEPARATOR); } } else { currentSection = sectionName; } if (profileNameBlockList.includes(sectionName)) { throw new Error(`Found invalid profile name "${sectionName}"`); } } else if (currentSection) { const indexOfEqualsSign = trimmedLine.indexOf("="); if (![0, -1].includes(indexOfEqualsSign)) { const [name, value] = [ trimmedLine.substring(0, indexOfEqualsSign).trim(), trimmedLine.substring(indexOfEqualsSign + 1).trim() ]; if (value === "") { currentSubSection = name; } else { if (currentSubSection && iniLine.trimStart() === iniLine) { currentSubSection = void 0; } map[currentSection] = map[currentSection] || {}; const key = currentSubSection ? [currentSubSection, name].join(CONFIG_PREFIX_SEPARATOR) : name; map[currentSection][key] = value; } } } } return map; }, "parseIni"); // src/loadSharedConfigFiles.ts var import_slurpFile = __nccwpck_require__(19155); var swallowError = /* @__PURE__ */ __name(() => ({}), "swallowError"); var CONFIG_PREFIX_SEPARATOR = "."; var loadSharedConfigFiles = /* @__PURE__ */ __name(async (init = {}) => { const { filepath = getCredentialsFilepath(), configFilepath = getConfigFilepath() } = init; const homeDir = (0, import_getHomeDir3.getHomeDir)(); const relativeHomeDirPrefix = "~/"; let resolvedFilepath = filepath; if (filepath.startsWith(relativeHomeDirPrefix)) { resolvedFilepath = (0, import_path.join)(homeDir, filepath.slice(2)); } let resolvedConfigFilepath = configFilepath; if (configFilepath.startsWith(relativeHomeDirPrefix)) { resolvedConfigFilepath = (0, import_path.join)(homeDir, configFilepath.slice(2)); } const parsedFiles = await Promise.all([ (0, import_slurpFile.slurpFile)(resolvedConfigFilepath, { ignoreCache: init.ignoreCache }).then(parseIni).then(getConfigData).catch(swallowError), (0, import_slurpFile.slurpFile)(resolvedFilepath, { ignoreCache: init.ignoreCache }).then(parseIni).catch(swallowError) ]); return { configFile: parsedFiles[0], credentialsFile: parsedFiles[1] }; }, "loadSharedConfigFiles"); // src/getSsoSessionData.ts var getSsoSessionData = /* @__PURE__ */ __name((data) => Object.entries(data).filter(([key]) => key.startsWith(import_types.IniSectionType.SSO_SESSION + CONFIG_PREFIX_SEPARATOR)).reduce((acc, [key, value]) => ({ ...acc, [key.substring(key.indexOf(CONFIG_PREFIX_SEPARATOR) + 1)]: value }), {}), "getSsoSessionData"); // src/loadSsoSessionData.ts var import_slurpFile2 = __nccwpck_require__(19155); var swallowError2 = /* @__PURE__ */ __name(() => ({}), "swallowError"); var loadSsoSessionData = /* @__PURE__ */ __name(async (init = {}) => (0, import_slurpFile2.slurpFile)(init.configFilepath ?? getConfigFilepath()).then(parseIni).then(getSsoSessionData).catch(swallowError2), "loadSsoSessionData"); // src/mergeConfigFiles.ts var mergeConfigFiles = /* @__PURE__ */ __name((...files) => { const merged = {}; for (const file of files) { for (const [key, values] of Object.entries(file)) { if (merged[key] !== void 0) { Object.assign(merged[key], values); } else { merged[key] = values; } } } return merged; }, "mergeConfigFiles"); // src/parseKnownFiles.ts var parseKnownFiles = /* @__PURE__ */ __name(async (init) => { const parsedFiles = await loadSharedConfigFiles(init); return mergeConfigFiles(parsedFiles.configFile, parsedFiles.credentialsFile); }, "parseKnownFiles"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); /***/ }), /***/ 19155: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.slurpFile = void 0; const fs_1 = __nccwpck_require__(57147); const { readFile } = fs_1.promises; const filePromisesHash = {}; const slurpFile = (path, options) => { if (!filePromisesHash[path] || (options === null || options === void 0 ? void 0 : options.ignoreCache)) { filePromisesHash[path] = readFile(path, "utf8"); } return filePromisesHash[path]; }; exports.slurpFile = slurpFile; /***/ }), /***/ 11528: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { ALGORITHM_IDENTIFIER: () => ALGORITHM_IDENTIFIER, ALGORITHM_IDENTIFIER_V4A: () => ALGORITHM_IDENTIFIER_V4A, ALGORITHM_QUERY_PARAM: () => ALGORITHM_QUERY_PARAM, ALWAYS_UNSIGNABLE_HEADERS: () => ALWAYS_UNSIGNABLE_HEADERS, AMZ_DATE_HEADER: () => AMZ_DATE_HEADER, AMZ_DATE_QUERY_PARAM: () => AMZ_DATE_QUERY_PARAM, AUTH_HEADER: () => AUTH_HEADER, CREDENTIAL_QUERY_PARAM: () => CREDENTIAL_QUERY_PARAM, DATE_HEADER: () => DATE_HEADER, EVENT_ALGORITHM_IDENTIFIER: () => EVENT_ALGORITHM_IDENTIFIER, EXPIRES_QUERY_PARAM: () => EXPIRES_QUERY_PARAM, GENERATED_HEADERS: () => GENERATED_HEADERS, HOST_HEADER: () => HOST_HEADER, KEY_TYPE_IDENTIFIER: () => KEY_TYPE_IDENTIFIER, MAX_CACHE_SIZE: () => MAX_CACHE_SIZE, MAX_PRESIGNED_TTL: () => MAX_PRESIGNED_TTL, PROXY_HEADER_PATTERN: () => PROXY_HEADER_PATTERN, REGION_SET_PARAM: () => REGION_SET_PARAM, SEC_HEADER_PATTERN: () => SEC_HEADER_PATTERN, SHA256_HEADER: () => SHA256_HEADER, SIGNATURE_HEADER: () => SIGNATURE_HEADER, SIGNATURE_QUERY_PARAM: () => SIGNATURE_QUERY_PARAM, SIGNED_HEADERS_QUERY_PARAM: () => SIGNED_HEADERS_QUERY_PARAM, SignatureV4: () => SignatureV4, SignatureV4Base: () => SignatureV4Base, TOKEN_HEADER: () => TOKEN_HEADER, TOKEN_QUERY_PARAM: () => TOKEN_QUERY_PARAM, UNSIGNABLE_PATTERNS: () => UNSIGNABLE_PATTERNS, UNSIGNED_PAYLOAD: () => UNSIGNED_PAYLOAD, clearCredentialCache: () => clearCredentialCache, createScope: () => createScope, getCanonicalHeaders: () => getCanonicalHeaders, getCanonicalQuery: () => getCanonicalQuery, getPayloadHash: () => getPayloadHash, getSigningKey: () => getSigningKey, hasHeader: () => hasHeader, moveHeadersToQuery: () => moveHeadersToQuery, prepareRequest: () => prepareRequest, signatureV4aContainer: () => signatureV4aContainer }); module.exports = __toCommonJS(src_exports); // src/SignatureV4.ts var import_util_utf85 = __nccwpck_require__(41895); // src/constants.ts var ALGORITHM_QUERY_PARAM = "X-Amz-Algorithm"; var CREDENTIAL_QUERY_PARAM = "X-Amz-Credential"; var AMZ_DATE_QUERY_PARAM = "X-Amz-Date"; var SIGNED_HEADERS_QUERY_PARAM = "X-Amz-SignedHeaders"; var EXPIRES_QUERY_PARAM = "X-Amz-Expires"; var SIGNATURE_QUERY_PARAM = "X-Amz-Signature"; var TOKEN_QUERY_PARAM = "X-Amz-Security-Token"; var REGION_SET_PARAM = "X-Amz-Region-Set"; var AUTH_HEADER = "authorization"; var AMZ_DATE_HEADER = AMZ_DATE_QUERY_PARAM.toLowerCase(); var DATE_HEADER = "date"; var GENERATED_HEADERS = [AUTH_HEADER, AMZ_DATE_HEADER, DATE_HEADER]; var SIGNATURE_HEADER = SIGNATURE_QUERY_PARAM.toLowerCase(); var SHA256_HEADER = "x-amz-content-sha256"; var TOKEN_HEADER = TOKEN_QUERY_PARAM.toLowerCase(); var HOST_HEADER = "host"; var ALWAYS_UNSIGNABLE_HEADERS = { authorization: true, "cache-control": true, connection: true, expect: true, from: true, "keep-alive": true, "max-forwards": true, pragma: true, referer: true, te: true, trailer: true, "transfer-encoding": true, upgrade: true, "user-agent": true, "x-amzn-trace-id": true }; var PROXY_HEADER_PATTERN = /^proxy-/; var SEC_HEADER_PATTERN = /^sec-/; var UNSIGNABLE_PATTERNS = [/^proxy-/i, /^sec-/i]; var ALGORITHM_IDENTIFIER = "AWS4-HMAC-SHA256"; var ALGORITHM_IDENTIFIER_V4A = "AWS4-ECDSA-P256-SHA256"; var EVENT_ALGORITHM_IDENTIFIER = "AWS4-HMAC-SHA256-PAYLOAD"; var UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD"; var MAX_CACHE_SIZE = 50; var KEY_TYPE_IDENTIFIER = "aws4_request"; var MAX_PRESIGNED_TTL = 60 * 60 * 24 * 7; // src/credentialDerivation.ts var import_util_hex_encoding = __nccwpck_require__(45364); var import_util_utf8 = __nccwpck_require__(41895); var signingKeyCache = {}; var cacheQueue = []; var createScope = /* @__PURE__ */ __name((shortDate, region, service) => `${shortDate}/${region}/${service}/${KEY_TYPE_IDENTIFIER}`, "createScope"); var getSigningKey = /* @__PURE__ */ __name(async (sha256Constructor, credentials, shortDate, region, service) => { const credsHash = await hmac(sha256Constructor, credentials.secretAccessKey, credentials.accessKeyId); const cacheKey = `${shortDate}:${region}:${service}:${(0, import_util_hex_encoding.toHex)(credsHash)}:${credentials.sessionToken}`; if (cacheKey in signingKeyCache) { return signingKeyCache[cacheKey]; } cacheQueue.push(cacheKey); while (cacheQueue.length > MAX_CACHE_SIZE) { delete signingKeyCache[cacheQueue.shift()]; } let key = `AWS4${credentials.secretAccessKey}`; for (const signable of [shortDate, region, service, KEY_TYPE_IDENTIFIER]) { key = await hmac(sha256Constructor, key, signable); } return signingKeyCache[cacheKey] = key; }, "getSigningKey"); var clearCredentialCache = /* @__PURE__ */ __name(() => { cacheQueue.length = 0; Object.keys(signingKeyCache).forEach((cacheKey) => { delete signingKeyCache[cacheKey]; }); }, "clearCredentialCache"); var hmac = /* @__PURE__ */ __name((ctor, secret, data) => { const hash = new ctor(secret); hash.update((0, import_util_utf8.toUint8Array)(data)); return hash.digest(); }, "hmac"); // src/getCanonicalHeaders.ts var getCanonicalHeaders = /* @__PURE__ */ __name(({ headers }, unsignableHeaders, signableHeaders) => { const canonical = {}; for (const headerName of Object.keys(headers).sort()) { if (headers[headerName] == void 0) { continue; } const canonicalHeaderName = headerName.toLowerCase(); if (canonicalHeaderName in ALWAYS_UNSIGNABLE_HEADERS || unsignableHeaders?.has(canonicalHeaderName) || PROXY_HEADER_PATTERN.test(canonicalHeaderName) || SEC_HEADER_PATTERN.test(canonicalHeaderName)) { if (!signableHeaders || signableHeaders && !signableHeaders.has(canonicalHeaderName)) { continue; } } canonical[canonicalHeaderName] = headers[headerName].trim().replace(/\s+/g, " "); } return canonical; }, "getCanonicalHeaders"); // src/getPayloadHash.ts var import_is_array_buffer = __nccwpck_require__(10780); var import_util_utf82 = __nccwpck_require__(41895); var getPayloadHash = /* @__PURE__ */ __name(async ({ headers, body }, hashConstructor) => { for (const headerName of Object.keys(headers)) { if (headerName.toLowerCase() === SHA256_HEADER) { return headers[headerName]; } } if (body == void 0) { return "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; } else if (typeof body === "string" || ArrayBuffer.isView(body) || (0, import_is_array_buffer.isArrayBuffer)(body)) { const hashCtor = new hashConstructor(); hashCtor.update((0, import_util_utf82.toUint8Array)(body)); return (0, import_util_hex_encoding.toHex)(await hashCtor.digest()); } return UNSIGNED_PAYLOAD; }, "getPayloadHash"); // src/HeaderFormatter.ts var import_util_utf83 = __nccwpck_require__(41895); var HeaderFormatter = class { static { __name(this, "HeaderFormatter"); } format(headers) { const chunks = []; for (const headerName of Object.keys(headers)) { const bytes = (0, import_util_utf83.fromUtf8)(headerName); chunks.push(Uint8Array.from([bytes.byteLength]), bytes, this.formatHeaderValue(headers[headerName])); } const out = new Uint8Array(chunks.reduce((carry, bytes) => carry + bytes.byteLength, 0)); let position = 0; for (const chunk of chunks) { out.set(chunk, position); position += chunk.byteLength; } return out; } formatHeaderValue(header) { switch (header.type) { case "boolean": return Uint8Array.from([header.value ? 0 /* boolTrue */ : 1 /* boolFalse */]); case "byte": return Uint8Array.from([2 /* byte */, header.value]); case "short": const shortView = new DataView(new ArrayBuffer(3)); shortView.setUint8(0, 3 /* short */); shortView.setInt16(1, header.value, false); return new Uint8Array(shortView.buffer); case "integer": const intView = new DataView(new ArrayBuffer(5)); intView.setUint8(0, 4 /* integer */); intView.setInt32(1, header.value, false); return new Uint8Array(intView.buffer); case "long": const longBytes = new Uint8Array(9); longBytes[0] = 5 /* long */; longBytes.set(header.value.bytes, 1); return longBytes; case "binary": const binView = new DataView(new ArrayBuffer(3 + header.value.byteLength)); binView.setUint8(0, 6 /* byteArray */); binView.setUint16(1, header.value.byteLength, false); const binBytes = new Uint8Array(binView.buffer); binBytes.set(header.value, 3); return binBytes; case "string": const utf8Bytes = (0, import_util_utf83.fromUtf8)(header.value); const strView = new DataView(new ArrayBuffer(3 + utf8Bytes.byteLength)); strView.setUint8(0, 7 /* string */); strView.setUint16(1, utf8Bytes.byteLength, false); const strBytes = new Uint8Array(strView.buffer); strBytes.set(utf8Bytes, 3); return strBytes; case "timestamp": const tsBytes = new Uint8Array(9); tsBytes[0] = 8 /* timestamp */; tsBytes.set(Int64.fromNumber(header.value.valueOf()).bytes, 1); return tsBytes; case "uuid": if (!UUID_PATTERN.test(header.value)) { throw new Error(`Invalid UUID received: ${header.value}`); } const uuidBytes = new Uint8Array(17); uuidBytes[0] = 9 /* uuid */; uuidBytes.set((0, import_util_hex_encoding.fromHex)(header.value.replace(/\-/g, "")), 1); return uuidBytes; } } }; var UUID_PATTERN = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/; var Int64 = class _Int64 { constructor(bytes) { this.bytes = bytes; if (bytes.byteLength !== 8) { throw new Error("Int64 buffers must be exactly 8 bytes"); } } static { __name(this, "Int64"); } static fromNumber(number) { if (number > 9223372036854776e3 || number < -9223372036854776e3) { throw new Error(`${number} is too large (or, if negative, too small) to represent as an Int64`); } const bytes = new Uint8Array(8); for (let i = 7, remaining = Math.abs(Math.round(number)); i > -1 && remaining > 0; i--, remaining /= 256) { bytes[i] = remaining; } if (number < 0) { negate(bytes); } return new _Int64(bytes); } /** * Called implicitly by infix arithmetic operators. */ valueOf() { const bytes = this.bytes.slice(0); const negative = bytes[0] & 128; if (negative) { negate(bytes); } return parseInt((0, import_util_hex_encoding.toHex)(bytes), 16) * (negative ? -1 : 1); } toString() { return String(this.valueOf()); } }; function negate(bytes) { for (let i = 0; i < 8; i++) { bytes[i] ^= 255; } for (let i = 7; i > -1; i--) { bytes[i]++; if (bytes[i] !== 0) break; } } __name(negate, "negate"); // src/headerUtil.ts var hasHeader = /* @__PURE__ */ __name((soughtHeader, headers) => { soughtHeader = soughtHeader.toLowerCase(); for (const headerName of Object.keys(headers)) { if (soughtHeader === headerName.toLowerCase()) { return true; } } return false; }, "hasHeader"); // src/moveHeadersToQuery.ts var import_protocol_http = __nccwpck_require__(64418); var moveHeadersToQuery = /* @__PURE__ */ __name((request, options = {}) => { const { headers, query = {} } = import_protocol_http.HttpRequest.clone(request); for (const name of Object.keys(headers)) { const lname = name.toLowerCase(); if (lname.slice(0, 6) === "x-amz-" && !options.unhoistableHeaders?.has(lname) || options.hoistableHeaders?.has(lname)) { query[name] = headers[name]; delete headers[name]; } } return { ...request, headers, query }; }, "moveHeadersToQuery"); // src/prepareRequest.ts var prepareRequest = /* @__PURE__ */ __name((request) => { request = import_protocol_http.HttpRequest.clone(request); for (const headerName of Object.keys(request.headers)) { if (GENERATED_HEADERS.indexOf(headerName.toLowerCase()) > -1) { delete request.headers[headerName]; } } return request; }, "prepareRequest"); // src/SignatureV4Base.ts var import_util_middleware = __nccwpck_require__(2390); var import_util_utf84 = __nccwpck_require__(41895); // src/getCanonicalQuery.ts var import_util_uri_escape = __nccwpck_require__(54197); var getCanonicalQuery = /* @__PURE__ */ __name(({ query = {} }) => { const keys = []; const serialized = {}; for (const key of Object.keys(query)) { if (key.toLowerCase() === SIGNATURE_HEADER) { continue; } const encodedKey = (0, import_util_uri_escape.escapeUri)(key); keys.push(encodedKey); const value = query[key]; if (typeof value === "string") { serialized[encodedKey] = `${encodedKey}=${(0, import_util_uri_escape.escapeUri)(value)}`; } else if (Array.isArray(value)) { serialized[encodedKey] = value.slice(0).reduce((encoded, value2) => encoded.concat([`${encodedKey}=${(0, import_util_uri_escape.escapeUri)(value2)}`]), []).sort().join("&"); } } return keys.sort().map((key) => serialized[key]).filter((serialized2) => serialized2).join("&"); }, "getCanonicalQuery"); // src/utilDate.ts var iso8601 = /* @__PURE__ */ __name((time) => toDate(time).toISOString().replace(/\.\d{3}Z$/, "Z"), "iso8601"); var toDate = /* @__PURE__ */ __name((time) => { if (typeof time === "number") { return new Date(time * 1e3); } if (typeof time === "string") { if (Number(time)) { return new Date(Number(time) * 1e3); } return new Date(time); } return time; }, "toDate"); // src/SignatureV4Base.ts var SignatureV4Base = class { static { __name(this, "SignatureV4Base"); } constructor({ applyChecksum, credentials, region, service, sha256, uriEscapePath = true }) { this.service = service; this.sha256 = sha256; this.uriEscapePath = uriEscapePath; this.applyChecksum = typeof applyChecksum === "boolean" ? applyChecksum : true; this.regionProvider = (0, import_util_middleware.normalizeProvider)(region); this.credentialProvider = (0, import_util_middleware.normalizeProvider)(credentials); } createCanonicalRequest(request, canonicalHeaders, payloadHash) { const sortedHeaders = Object.keys(canonicalHeaders).sort(); return `${request.method} ${this.getCanonicalPath(request)} ${getCanonicalQuery(request)} ${sortedHeaders.map((name) => `${name}:${canonicalHeaders[name]}`).join("\n")} ${sortedHeaders.join(";")} ${payloadHash}`; } async createStringToSign(longDate, credentialScope, canonicalRequest, algorithmIdentifier) { const hash = new this.sha256(); hash.update((0, import_util_utf84.toUint8Array)(canonicalRequest)); const hashedRequest = await hash.digest(); return `${algorithmIdentifier} ${longDate} ${credentialScope} ${(0, import_util_hex_encoding.toHex)(hashedRequest)}`; } getCanonicalPath({ path }) { if (this.uriEscapePath) { const normalizedPathSegments = []; for (const pathSegment of path.split("/")) { if (pathSegment?.length === 0) continue; if (pathSegment === ".") continue; if (pathSegment === "..") { normalizedPathSegments.pop(); } else { normalizedPathSegments.push(pathSegment); } } const normalizedPath = `${path?.startsWith("/") ? "/" : ""}${normalizedPathSegments.join("/")}${normalizedPathSegments.length > 0 && path?.endsWith("/") ? "/" : ""}`; const doubleEncoded = (0, import_util_uri_escape.escapeUri)(normalizedPath); return doubleEncoded.replace(/%2F/g, "/"); } return path; } validateResolvedCredentials(credentials) { if (typeof credentials !== "object" || // @ts-expect-error: Property 'accessKeyId' does not exist on type 'object'.ts(2339) typeof credentials.accessKeyId !== "string" || // @ts-expect-error: Property 'secretAccessKey' does not exist on type 'object'.ts(2339) typeof credentials.secretAccessKey !== "string") { throw new Error("Resolved credential object is not valid"); } } formatDate(now) { const longDate = iso8601(now).replace(/[\-:]/g, ""); return { longDate, shortDate: longDate.slice(0, 8) }; } getCanonicalHeaderList(headers) { return Object.keys(headers).sort().join(";"); } }; // src/SignatureV4.ts var SignatureV4 = class extends SignatureV4Base { constructor({ applyChecksum, credentials, region, service, sha256, uriEscapePath = true }) { super({ applyChecksum, credentials, region, service, sha256, uriEscapePath }); this.headerFormatter = new HeaderFormatter(); } static { __name(this, "SignatureV4"); } async presign(originalRequest, options = {}) { const { signingDate = /* @__PURE__ */ new Date(), expiresIn = 3600, unsignableHeaders, unhoistableHeaders, signableHeaders, hoistableHeaders, signingRegion, signingService } = options; const credentials = await this.credentialProvider(); this.validateResolvedCredentials(credentials); const region = signingRegion ?? await this.regionProvider(); const { longDate, shortDate } = this.formatDate(signingDate); if (expiresIn > MAX_PRESIGNED_TTL) { return Promise.reject( "Signature version 4 presigned URLs must have an expiration date less than one week in the future" ); } const scope = createScope(shortDate, region, signingService ?? this.service); const request = moveHeadersToQuery(prepareRequest(originalRequest), { unhoistableHeaders, hoistableHeaders }); if (credentials.sessionToken) { request.query[TOKEN_QUERY_PARAM] = credentials.sessionToken; } request.query[ALGORITHM_QUERY_PARAM] = ALGORITHM_IDENTIFIER; request.query[CREDENTIAL_QUERY_PARAM] = `${credentials.accessKeyId}/${scope}`; request.query[AMZ_DATE_QUERY_PARAM] = longDate; request.query[EXPIRES_QUERY_PARAM] = expiresIn.toString(10); const canonicalHeaders = getCanonicalHeaders(request, unsignableHeaders, signableHeaders); request.query[SIGNED_HEADERS_QUERY_PARAM] = this.getCanonicalHeaderList(canonicalHeaders); request.query[SIGNATURE_QUERY_PARAM] = await this.getSignature( longDate, scope, this.getSigningKey(credentials, region, shortDate, signingService), this.createCanonicalRequest(request, canonicalHeaders, await getPayloadHash(originalRequest, this.sha256)) ); return request; } async sign(toSign, options) { if (typeof toSign === "string") { return this.signString(toSign, options); } else if (toSign.headers && toSign.payload) { return this.signEvent(toSign, options); } else if (toSign.message) { return this.signMessage(toSign, options); } else { return this.signRequest(toSign, options); } } async signEvent({ headers, payload }, { signingDate = /* @__PURE__ */ new Date(), priorSignature, signingRegion, signingService }) { const region = signingRegion ?? await this.regionProvider(); const { shortDate, longDate } = this.formatDate(signingDate); const scope = createScope(shortDate, region, signingService ?? this.service); const hashedPayload = await getPayloadHash({ headers: {}, body: payload }, this.sha256); const hash = new this.sha256(); hash.update(headers); const hashedHeaders = (0, import_util_hex_encoding.toHex)(await hash.digest()); const stringToSign = [ EVENT_ALGORITHM_IDENTIFIER, longDate, scope, priorSignature, hashedHeaders, hashedPayload ].join("\n"); return this.signString(stringToSign, { signingDate, signingRegion: region, signingService }); } async signMessage(signableMessage, { signingDate = /* @__PURE__ */ new Date(), signingRegion, signingService }) { const promise = this.signEvent( { headers: this.headerFormatter.format(signableMessage.message.headers), payload: signableMessage.message.body }, { signingDate, signingRegion, signingService, priorSignature: signableMessage.priorSignature } ); return promise.then((signature) => { return { message: signableMessage.message, signature }; }); } async signString(stringToSign, { signingDate = /* @__PURE__ */ new Date(), signingRegion, signingService } = {}) { const credentials = await this.credentialProvider(); this.validateResolvedCredentials(credentials); const region = signingRegion ?? await this.regionProvider(); const { shortDate } = this.formatDate(signingDate); const hash = new this.sha256(await this.getSigningKey(credentials, region, shortDate, signingService)); hash.update((0, import_util_utf85.toUint8Array)(stringToSign)); return (0, import_util_hex_encoding.toHex)(await hash.digest()); } async signRequest(requestToSign, { signingDate = /* @__PURE__ */ new Date(), signableHeaders, unsignableHeaders, signingRegion, signingService } = {}) { const credentials = await this.credentialProvider(); this.validateResolvedCredentials(credentials); const region = signingRegion ?? await this.regionProvider(); const request = prepareRequest(requestToSign); const { longDate, shortDate } = this.formatDate(signingDate); const scope = createScope(shortDate, region, signingService ?? this.service); request.headers[AMZ_DATE_HEADER] = longDate; if (credentials.sessionToken) { request.headers[TOKEN_HEADER] = credentials.sessionToken; } const payloadHash = await getPayloadHash(request, this.sha256); if (!hasHeader(SHA256_HEADER, request.headers) && this.applyChecksum) { request.headers[SHA256_HEADER] = payloadHash; } const canonicalHeaders = getCanonicalHeaders(request, unsignableHeaders, signableHeaders); const signature = await this.getSignature( longDate, scope, this.getSigningKey(credentials, region, shortDate, signingService), this.createCanonicalRequest(request, canonicalHeaders, payloadHash) ); request.headers[AUTH_HEADER] = `${ALGORITHM_IDENTIFIER} Credential=${credentials.accessKeyId}/${scope}, SignedHeaders=${this.getCanonicalHeaderList(canonicalHeaders)}, Signature=${signature}`; return request; } async getSignature(longDate, credentialScope, keyPromise, canonicalRequest) { const stringToSign = await this.createStringToSign( longDate, credentialScope, canonicalRequest, ALGORITHM_IDENTIFIER ); const hash = new this.sha256(await keyPromise); hash.update((0, import_util_utf85.toUint8Array)(stringToSign)); return (0, import_util_hex_encoding.toHex)(await hash.digest()); } getSigningKey(credentials, region, shortDate, service) { return getSigningKey(this.sha256, credentials, shortDate, region, service || this.service); } }; // src/signature-v4a-container.ts var signatureV4aContainer = { SignatureV4a: null }; // Annotate the CommonJS export names for ESM import in node: 0 && (0); /***/ }), /***/ 63570: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { Client: () => Client, Command: () => Command, NoOpLogger: () => NoOpLogger, SENSITIVE_STRING: () => SENSITIVE_STRING, ServiceException: () => ServiceException, _json: () => _json, collectBody: () => import_protocols.collectBody, convertMap: () => convertMap, createAggregatedClient: () => createAggregatedClient, decorateServiceException: () => decorateServiceException, emitWarningIfUnsupportedVersion: () => emitWarningIfUnsupportedVersion, extendedEncodeURIComponent: () => import_protocols.extendedEncodeURIComponent, getArrayIfSingleItem: () => getArrayIfSingleItem, getDefaultClientConfiguration: () => getDefaultClientConfiguration, getDefaultExtensionConfiguration: () => getDefaultExtensionConfiguration, getValueFromTextNode: () => getValueFromTextNode, isSerializableHeaderValue: () => isSerializableHeaderValue, loadConfigsForDefaultMode: () => loadConfigsForDefaultMode, map: () => map, resolveDefaultRuntimeConfig: () => resolveDefaultRuntimeConfig, resolvedPath: () => import_protocols.resolvedPath, serializeDateTime: () => serializeDateTime, serializeFloat: () => serializeFloat, take: () => take, throwDefaultError: () => throwDefaultError, withBaseException: () => withBaseException }); module.exports = __toCommonJS(src_exports); // src/client.ts var import_middleware_stack = __nccwpck_require__(97911); var Client = class { constructor(config) { this.config = config; this.middlewareStack = (0, import_middleware_stack.constructStack)(); } static { __name(this, "Client"); } send(command, optionsOrCb, cb) { const options = typeof optionsOrCb !== "function" ? optionsOrCb : void 0; const callback = typeof optionsOrCb === "function" ? optionsOrCb : cb; const useHandlerCache = options === void 0 && this.config.cacheMiddleware === true; let handler; if (useHandlerCache) { if (!this.handlers) { this.handlers = /* @__PURE__ */ new WeakMap(); } const handlers = this.handlers; if (handlers.has(command.constructor)) { handler = handlers.get(command.constructor); } else { handler = command.resolveMiddleware(this.middlewareStack, this.config, options); handlers.set(command.constructor, handler); } } else { delete this.handlers; handler = command.resolveMiddleware(this.middlewareStack, this.config, options); } if (callback) { handler(command).then( (result) => callback(null, result.output), (err) => callback(err) ).catch( // prevent any errors thrown in the callback from triggering an // unhandled promise rejection () => { } ); } else { return handler(command).then((result) => result.output); } } destroy() { this.config?.requestHandler?.destroy?.(); delete this.handlers; } }; // src/collect-stream-body.ts var import_protocols = __nccwpck_require__(2241); // src/command.ts var import_types = __nccwpck_require__(55756); var Command = class { constructor() { this.middlewareStack = (0, import_middleware_stack.constructStack)(); } static { __name(this, "Command"); } /** * Factory for Command ClassBuilder. * @internal */ static classBuilder() { return new ClassBuilder(); } /** * @internal */ resolveMiddlewareWithContext(clientStack, configuration, options, { middlewareFn, clientName, commandName, inputFilterSensitiveLog, outputFilterSensitiveLog, smithyContext, additionalContext, CommandCtor }) { for (const mw of middlewareFn.bind(this)(CommandCtor, clientStack, configuration, options)) { this.middlewareStack.use(mw); } const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog, outputFilterSensitiveLog, [import_types.SMITHY_CONTEXT_KEY]: { commandInstance: this, ...smithyContext }, ...additionalContext }; const { requestHandler } = configuration; return stack.resolve( (request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext ); } }; var ClassBuilder = class { constructor() { this._init = () => { }; this._ep = {}; this._middlewareFn = () => []; this._commandName = ""; this._clientName = ""; this._additionalContext = {}; this._smithyContext = {}; this._inputFilterSensitiveLog = (_) => _; this._outputFilterSensitiveLog = (_) => _; this._serializer = null; this._deserializer = null; } static { __name(this, "ClassBuilder"); } /** * Optional init callback. */ init(cb) { this._init = cb; } /** * Set the endpoint parameter instructions. */ ep(endpointParameterInstructions) { this._ep = endpointParameterInstructions; return this; } /** * Add any number of middleware. */ m(middlewareSupplier) { this._middlewareFn = middlewareSupplier; return this; } /** * Set the initial handler execution context Smithy field. */ s(service, operation, smithyContext = {}) { this._smithyContext = { service, operation, ...smithyContext }; return this; } /** * Set the initial handler execution context. */ c(additionalContext = {}) { this._additionalContext = additionalContext; return this; } /** * Set constant string identifiers for the operation. */ n(clientName, commandName) { this._clientName = clientName; this._commandName = commandName; return this; } /** * Set the input and output sensistive log filters. */ f(inputFilter = (_) => _, outputFilter = (_) => _) { this._inputFilterSensitiveLog = inputFilter; this._outputFilterSensitiveLog = outputFilter; return this; } /** * Sets the serializer. */ ser(serializer) { this._serializer = serializer; return this; } /** * Sets the deserializer. */ de(deserializer) { this._deserializer = deserializer; return this; } /** * Sets input/output schema for the operation. */ sc(operation) { this._operationSchema = operation; this._smithyContext.operationSchema = operation; return this; } /** * @returns a Command class with the classBuilder properties. */ build() { const closure = this; let CommandRef; return CommandRef = class extends Command { /** * @public */ constructor(...[input]) { super(); /** * @internal */ // @ts-ignore used in middlewareFn closure. this.serialize = closure._serializer; /** * @internal */ // @ts-ignore used in middlewareFn closure. this.deserialize = closure._deserializer; this.input = input ?? {}; closure._init(this); this.schema = closure._operationSchema; } static { __name(this, "CommandRef"); } /** * @public */ static getEndpointParameterInstructions() { return closure._ep; } /** * @internal */ resolveMiddleware(stack, configuration, options) { return this.resolveMiddlewareWithContext(stack, configuration, options, { CommandCtor: CommandRef, middlewareFn: closure._middlewareFn, clientName: closure._clientName, commandName: closure._commandName, inputFilterSensitiveLog: closure._inputFilterSensitiveLog, outputFilterSensitiveLog: closure._outputFilterSensitiveLog, smithyContext: closure._smithyContext, additionalContext: closure._additionalContext }); } }; } }; // src/constants.ts var SENSITIVE_STRING = "***SensitiveInformation***"; // src/create-aggregated-client.ts var createAggregatedClient = /* @__PURE__ */ __name((commands, Client2) => { for (const command of Object.keys(commands)) { const CommandCtor = commands[command]; const methodImpl = /* @__PURE__ */ __name(async function(args, optionsOrCb, cb) { const command2 = new CommandCtor(args); if (typeof optionsOrCb === "function") { this.send(command2, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expected http options but got ${typeof optionsOrCb}`); this.send(command2, optionsOrCb || {}, cb); } else { return this.send(command2, optionsOrCb); } }, "methodImpl"); const methodName = (command[0].toLowerCase() + command.slice(1)).replace(/Command$/, ""); Client2.prototype[methodName] = methodImpl; } }, "createAggregatedClient"); // src/exceptions.ts var ServiceException = class _ServiceException extends Error { static { __name(this, "ServiceException"); } constructor(options) { super(options.message); Object.setPrototypeOf(this, Object.getPrototypeOf(this).constructor.prototype); this.name = options.name; this.$fault = options.$fault; this.$metadata = options.$metadata; } /** * Checks if a value is an instance of ServiceException (duck typed) */ static isInstance(value) { if (!value) return false; const candidate = value; return _ServiceException.prototype.isPrototypeOf(candidate) || Boolean(candidate.$fault) && Boolean(candidate.$metadata) && (candidate.$fault === "client" || candidate.$fault === "server"); } /** * Custom instanceof check to support the operator for ServiceException base class */ static [Symbol.hasInstance](instance) { if (!instance) return false; const candidate = instance; if (this === _ServiceException) { return _ServiceException.isInstance(instance); } if (_ServiceException.isInstance(instance)) { if (candidate.name && this.name) { return this.prototype.isPrototypeOf(instance) || candidate.name === this.name; } return this.prototype.isPrototypeOf(instance); } return false; } }; var decorateServiceException = /* @__PURE__ */ __name((exception, additions = {}) => { Object.entries(additions).filter(([, v]) => v !== void 0).forEach(([k, v]) => { if (exception[k] == void 0 || exception[k] === "") { exception[k] = v; } }); const message = exception.message || exception.Message || "UnknownError"; exception.message = message; delete exception.Message; return exception; }, "decorateServiceException"); // src/default-error-handler.ts var throwDefaultError = /* @__PURE__ */ __name(({ output, parsedBody, exceptionCtor, errorCode }) => { const $metadata = deserializeMetadata(output); const statusCode = $metadata.httpStatusCode ? $metadata.httpStatusCode + "" : void 0; const response = new exceptionCtor({ name: parsedBody?.code || parsedBody?.Code || errorCode || statusCode || "UnknownError", $fault: "client", $metadata }); throw decorateServiceException(response, parsedBody); }, "throwDefaultError"); var withBaseException = /* @__PURE__ */ __name((ExceptionCtor) => { return ({ output, parsedBody, errorCode }) => { throwDefaultError({ output, parsedBody, exceptionCtor: ExceptionCtor, errorCode }); }; }, "withBaseException"); var deserializeMetadata = /* @__PURE__ */ __name((output) => ({ httpStatusCode: output.statusCode, requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"], extendedRequestId: output.headers["x-amz-id-2"], cfId: output.headers["x-amz-cf-id"] }), "deserializeMetadata"); // src/defaults-mode.ts var loadConfigsForDefaultMode = /* @__PURE__ */ __name((mode) => { switch (mode) { case "standard": return { retryMode: "standard", connectionTimeout: 3100 }; case "in-region": return { retryMode: "standard", connectionTimeout: 1100 }; case "cross-region": return { retryMode: "standard", connectionTimeout: 3100 }; case "mobile": return { retryMode: "standard", connectionTimeout: 3e4 }; default: return {}; } }, "loadConfigsForDefaultMode"); // src/emitWarningIfUnsupportedVersion.ts var warningEmitted = false; var emitWarningIfUnsupportedVersion = /* @__PURE__ */ __name((version) => { if (version && !warningEmitted && parseInt(version.substring(1, version.indexOf("."))) < 16) { warningEmitted = true; } }, "emitWarningIfUnsupportedVersion"); // src/extended-encode-uri-component.ts // src/extensions/checksum.ts var getChecksumConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { const checksumAlgorithms = []; for (const id in import_types.AlgorithmId) { const algorithmId = import_types.AlgorithmId[id]; if (runtimeConfig[algorithmId] === void 0) { continue; } checksumAlgorithms.push({ algorithmId: () => algorithmId, checksumConstructor: () => runtimeConfig[algorithmId] }); } return { addChecksumAlgorithm(algo) { checksumAlgorithms.push(algo); }, checksumAlgorithms() { return checksumAlgorithms; } }; }, "getChecksumConfiguration"); var resolveChecksumRuntimeConfig = /* @__PURE__ */ __name((clientConfig) => { const runtimeConfig = {}; clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); }); return runtimeConfig; }, "resolveChecksumRuntimeConfig"); // src/extensions/retry.ts var getRetryConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { return { setRetryStrategy(retryStrategy) { runtimeConfig.retryStrategy = retryStrategy; }, retryStrategy() { return runtimeConfig.retryStrategy; } }; }, "getRetryConfiguration"); var resolveRetryRuntimeConfig = /* @__PURE__ */ __name((retryStrategyConfiguration) => { const runtimeConfig = {}; runtimeConfig.retryStrategy = retryStrategyConfiguration.retryStrategy(); return runtimeConfig; }, "resolveRetryRuntimeConfig"); // src/extensions/defaultExtensionConfiguration.ts var getDefaultExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { return Object.assign(getChecksumConfiguration(runtimeConfig), getRetryConfiguration(runtimeConfig)); }, "getDefaultExtensionConfiguration"); var getDefaultClientConfiguration = getDefaultExtensionConfiguration; var resolveDefaultRuntimeConfig = /* @__PURE__ */ __name((config) => { return Object.assign(resolveChecksumRuntimeConfig(config), resolveRetryRuntimeConfig(config)); }, "resolveDefaultRuntimeConfig"); // src/get-array-if-single-item.ts var getArrayIfSingleItem = /* @__PURE__ */ __name((mayBeArray) => Array.isArray(mayBeArray) ? mayBeArray : [mayBeArray], "getArrayIfSingleItem"); // src/get-value-from-text-node.ts var getValueFromTextNode = /* @__PURE__ */ __name((obj) => { const textNodeName = "#text"; for (const key in obj) { if (obj.hasOwnProperty(key) && obj[key][textNodeName] !== void 0) { obj[key] = obj[key][textNodeName]; } else if (typeof obj[key] === "object" && obj[key] !== null) { obj[key] = getValueFromTextNode(obj[key]); } } return obj; }, "getValueFromTextNode"); // src/is-serializable-header-value.ts var isSerializableHeaderValue = /* @__PURE__ */ __name((value) => { return value != null; }, "isSerializableHeaderValue"); // src/NoOpLogger.ts var NoOpLogger = class { static { __name(this, "NoOpLogger"); } trace() { } debug() { } info() { } warn() { } error() { } }; // src/object-mapping.ts function map(arg0, arg1, arg2) { let target; let filter; let instructions; if (typeof arg1 === "undefined" && typeof arg2 === "undefined") { target = {}; instructions = arg0; } else { target = arg0; if (typeof arg1 === "function") { filter = arg1; instructions = arg2; return mapWithFilter(target, filter, instructions); } else { instructions = arg1; } } for (const key of Object.keys(instructions)) { if (!Array.isArray(instructions[key])) { target[key] = instructions[key]; continue; } applyInstruction(target, null, instructions, key); } return target; } __name(map, "map"); var convertMap = /* @__PURE__ */ __name((target) => { const output = {}; for (const [k, v] of Object.entries(target || {})) { output[k] = [, v]; } return output; }, "convertMap"); var take = /* @__PURE__ */ __name((source, instructions) => { const out = {}; for (const key in instructions) { applyInstruction(out, source, instructions, key); } return out; }, "take"); var mapWithFilter = /* @__PURE__ */ __name((target, filter, instructions) => { return map( target, Object.entries(instructions).reduce( (_instructions, [key, value]) => { if (Array.isArray(value)) { _instructions[key] = value; } else { if (typeof value === "function") { _instructions[key] = [filter, value()]; } else { _instructions[key] = [filter, value]; } } return _instructions; }, {} ) ); }, "mapWithFilter"); var applyInstruction = /* @__PURE__ */ __name((target, source, instructions, targetKey) => { if (source !== null) { let instruction = instructions[targetKey]; if (typeof instruction === "function") { instruction = [, instruction]; } const [filter2 = nonNullish, valueFn = pass, sourceKey = targetKey] = instruction; if (typeof filter2 === "function" && filter2(source[sourceKey]) || typeof filter2 !== "function" && !!filter2) { target[targetKey] = valueFn(source[sourceKey]); } return; } let [filter, value] = instructions[targetKey]; if (typeof value === "function") { let _value; const defaultFilterPassed = filter === void 0 && (_value = value()) != null; const customFilterPassed = typeof filter === "function" && !!filter(void 0) || typeof filter !== "function" && !!filter; if (defaultFilterPassed) { target[targetKey] = _value; } else if (customFilterPassed) { target[targetKey] = value(); } } else { const defaultFilterPassed = filter === void 0 && value != null; const customFilterPassed = typeof filter === "function" && !!filter(value) || typeof filter !== "function" && !!filter; if (defaultFilterPassed || customFilterPassed) { target[targetKey] = value; } } }, "applyInstruction"); var nonNullish = /* @__PURE__ */ __name((_) => _ != null, "nonNullish"); var pass = /* @__PURE__ */ __name((_) => _, "pass"); // src/resolve-path.ts // src/ser-utils.ts var serializeFloat = /* @__PURE__ */ __name((value) => { if (value !== value) { return "NaN"; } switch (value) { case Infinity: return "Infinity"; case -Infinity: return "-Infinity"; default: return value; } }, "serializeFloat"); var serializeDateTime = /* @__PURE__ */ __name((date) => date.toISOString().replace(".000Z", "Z"), "serializeDateTime"); // src/serde-json.ts var _json = /* @__PURE__ */ __name((obj) => { if (obj == null) { return {}; } if (Array.isArray(obj)) { return obj.filter((_) => _ != null).map(_json); } if (typeof obj === "object") { const target = {}; for (const key of Object.keys(obj)) { if (obj[key] == null) { continue; } target[key] = _json(obj[key]); } return target; } return obj; }, "_json"); // src/index.ts __reExport(src_exports, __nccwpck_require__(27669), module.exports); // Annotate the CommonJS export names for ESM import in node: 0 && (0); /***/ }), /***/ 55756: /***/ ((module) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { AlgorithmId: () => AlgorithmId, EndpointURLScheme: () => EndpointURLScheme, FieldPosition: () => FieldPosition, HttpApiKeyAuthLocation: () => HttpApiKeyAuthLocation, HttpAuthLocation: () => HttpAuthLocation, IniSectionType: () => IniSectionType, RequestHandlerProtocol: () => RequestHandlerProtocol, SMITHY_CONTEXT_KEY: () => SMITHY_CONTEXT_KEY, getDefaultClientConfiguration: () => getDefaultClientConfiguration, resolveDefaultRuntimeConfig: () => resolveDefaultRuntimeConfig }); module.exports = __toCommonJS(src_exports); // src/auth/auth.ts var HttpAuthLocation = /* @__PURE__ */ ((HttpAuthLocation2) => { HttpAuthLocation2["HEADER"] = "header"; HttpAuthLocation2["QUERY"] = "query"; return HttpAuthLocation2; })(HttpAuthLocation || {}); // src/auth/HttpApiKeyAuth.ts var HttpApiKeyAuthLocation = /* @__PURE__ */ ((HttpApiKeyAuthLocation2) => { HttpApiKeyAuthLocation2["HEADER"] = "header"; HttpApiKeyAuthLocation2["QUERY"] = "query"; return HttpApiKeyAuthLocation2; })(HttpApiKeyAuthLocation || {}); // src/endpoint.ts var EndpointURLScheme = /* @__PURE__ */ ((EndpointURLScheme2) => { EndpointURLScheme2["HTTP"] = "http"; EndpointURLScheme2["HTTPS"] = "https"; return EndpointURLScheme2; })(EndpointURLScheme || {}); // src/extensions/checksum.ts var AlgorithmId = /* @__PURE__ */ ((AlgorithmId2) => { AlgorithmId2["MD5"] = "md5"; AlgorithmId2["CRC32"] = "crc32"; AlgorithmId2["CRC32C"] = "crc32c"; AlgorithmId2["SHA1"] = "sha1"; AlgorithmId2["SHA256"] = "sha256"; return AlgorithmId2; })(AlgorithmId || {}); var getChecksumConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { const checksumAlgorithms = []; if (runtimeConfig.sha256 !== void 0) { checksumAlgorithms.push({ algorithmId: () => "sha256" /* SHA256 */, checksumConstructor: () => runtimeConfig.sha256 }); } if (runtimeConfig.md5 != void 0) { checksumAlgorithms.push({ algorithmId: () => "md5" /* MD5 */, checksumConstructor: () => runtimeConfig.md5 }); } return { addChecksumAlgorithm(algo) { checksumAlgorithms.push(algo); }, checksumAlgorithms() { return checksumAlgorithms; } }; }, "getChecksumConfiguration"); var resolveChecksumRuntimeConfig = /* @__PURE__ */ __name((clientConfig) => { const runtimeConfig = {}; clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); }); return runtimeConfig; }, "resolveChecksumRuntimeConfig"); // src/extensions/defaultClientConfiguration.ts var getDefaultClientConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { return getChecksumConfiguration(runtimeConfig); }, "getDefaultClientConfiguration"); var resolveDefaultRuntimeConfig = /* @__PURE__ */ __name((config) => { return resolveChecksumRuntimeConfig(config); }, "resolveDefaultRuntimeConfig"); // src/http.ts var FieldPosition = /* @__PURE__ */ ((FieldPosition2) => { FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER"; FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER"; return FieldPosition2; })(FieldPosition || {}); // src/middleware.ts var SMITHY_CONTEXT_KEY = "__smithy_context"; // src/profile.ts var IniSectionType = /* @__PURE__ */ ((IniSectionType2) => { IniSectionType2["PROFILE"] = "profile"; IniSectionType2["SSO_SESSION"] = "sso-session"; IniSectionType2["SERVICES"] = "services"; return IniSectionType2; })(IniSectionType || {}); // src/transfer.ts var RequestHandlerProtocol = /* @__PURE__ */ ((RequestHandlerProtocol2) => { RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9"; RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0"; RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0"; return RequestHandlerProtocol2; })(RequestHandlerProtocol || {}); // Annotate the CommonJS export names for ESM import in node: 0 && (0); /***/ }), /***/ 14681: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { parseUrl: () => parseUrl }); module.exports = __toCommonJS(src_exports); var import_querystring_parser = __nccwpck_require__(4769); var parseUrl = /* @__PURE__ */ __name((url) => { if (typeof url === "string") { return parseUrl(new URL(url)); } const { hostname, pathname, port, protocol, search } = url; let query; if (search) { query = (0, import_querystring_parser.parseQueryString)(search); } return { hostname, port: port ? parseInt(port) : void 0, protocol, path: pathname, query }; }, "parseUrl"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); /***/ }), /***/ 30305: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.fromBase64 = void 0; const util_buffer_from_1 = __nccwpck_require__(31381); const BASE64_REGEX = /^[A-Za-z0-9+/]*={0,2}$/; const fromBase64 = (input) => { if ((input.length * 3) % 4 !== 0) { throw new TypeError(`Incorrect padding on base64 string.`); } if (!BASE64_REGEX.exec(input)) { throw new TypeError(`Invalid base64 string.`); } const buffer = (0, util_buffer_from_1.fromString)(input, "base64"); return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength); }; exports.fromBase64 = fromBase64; /***/ }), /***/ 75600: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; module.exports = __toCommonJS(src_exports); __reExport(src_exports, __nccwpck_require__(30305), module.exports); __reExport(src_exports, __nccwpck_require__(74730), module.exports); // Annotate the CommonJS export names for ESM import in node: 0 && (0); /***/ }), /***/ 74730: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.toBase64 = void 0; const util_buffer_from_1 = __nccwpck_require__(31381); const util_utf8_1 = __nccwpck_require__(41895); const toBase64 = (_input) => { let input; if (typeof _input === "string") { input = (0, util_utf8_1.fromUtf8)(_input); } else { input = _input; } if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array."); } return (0, util_buffer_from_1.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("base64"); }; exports.toBase64 = toBase64; /***/ }), /***/ 30713: /***/ ((module) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { calculateBodyLength: () => calculateBodyLength }); module.exports = __toCommonJS(src_exports); // src/calculateBodyLength.ts var TEXT_ENCODER = typeof TextEncoder == "function" ? new TextEncoder() : null; var calculateBodyLength = /* @__PURE__ */ __name((body) => { if (typeof body === "string") { if (TEXT_ENCODER) { return TEXT_ENCODER.encode(body).byteLength; } let len = body.length; for (let i = len - 1; i >= 0; i--) { const code = body.charCodeAt(i); if (code > 127 && code <= 2047) len++; else if (code > 2047 && code <= 65535) len += 2; if (code >= 56320 && code <= 57343) i--; } return len; } else if (typeof body.byteLength === "number") { return body.byteLength; } else if (typeof body.size === "number") { return body.size; } throw new Error(`Body Length computation failed for ${body}`); }, "calculateBodyLength"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); /***/ }), /***/ 68075: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { calculateBodyLength: () => calculateBodyLength }); module.exports = __toCommonJS(src_exports); // src/calculateBodyLength.ts var import_fs = __nccwpck_require__(57147); var calculateBodyLength = /* @__PURE__ */ __name((body) => { if (!body) { return 0; } if (typeof body === "string") { return Buffer.byteLength(body); } else if (typeof body.byteLength === "number") { return body.byteLength; } else if (typeof body.size === "number") { return body.size; } else if (typeof body.start === "number" && typeof body.end === "number") { return body.end + 1 - body.start; } else if (typeof body.path === "string" || Buffer.isBuffer(body.path)) { return (0, import_fs.lstatSync)(body.path).size; } else if (typeof body.fd === "number") { return (0, import_fs.fstatSync)(body.fd).size; } throw new Error(`Body Length computation failed for ${body}`); }, "calculateBodyLength"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); /***/ }), /***/ 31381: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { fromArrayBuffer: () => fromArrayBuffer, fromString: () => fromString }); module.exports = __toCommonJS(src_exports); var import_is_array_buffer = __nccwpck_require__(10780); var import_buffer = __nccwpck_require__(14300); var fromArrayBuffer = /* @__PURE__ */ __name((input, offset = 0, length = input.byteLength - offset) => { if (!(0, import_is_array_buffer.isArrayBuffer)(input)) { throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`); } return import_buffer.Buffer.from(input, offset, length); }, "fromArrayBuffer"); var fromString = /* @__PURE__ */ __name((input, encoding) => { if (typeof input !== "string") { throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`); } return encoding ? import_buffer.Buffer.from(input, encoding) : import_buffer.Buffer.from(input); }, "fromString"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); /***/ }), /***/ 83375: /***/ ((module) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { SelectorType: () => SelectorType, booleanSelector: () => booleanSelector, numberSelector: () => numberSelector }); module.exports = __toCommonJS(src_exports); // src/booleanSelector.ts var booleanSelector = /* @__PURE__ */ __name((obj, key, type) => { if (!(key in obj)) return void 0; if (obj[key] === "true") return true; if (obj[key] === "false") return false; throw new Error(`Cannot load ${type} "${key}". Expected "true" or "false", got ${obj[key]}.`); }, "booleanSelector"); // src/numberSelector.ts var numberSelector = /* @__PURE__ */ __name((obj, key, type) => { if (!(key in obj)) return void 0; const numberValue = parseInt(obj[key], 10); if (Number.isNaN(numberValue)) { throw new TypeError(`Cannot load ${type} '${key}'. Expected number, got '${obj[key]}'.`); } return numberValue; }, "numberSelector"); // src/types.ts var SelectorType = /* @__PURE__ */ ((SelectorType2) => { SelectorType2["ENV"] = "env"; SelectorType2["CONFIG"] = "shared config entry"; return SelectorType2; })(SelectorType || {}); // Annotate the CommonJS export names for ESM import in node: 0 && (0); /***/ }), /***/ 72429: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { resolveDefaultsModeConfig: () => resolveDefaultsModeConfig }); module.exports = __toCommonJS(src_exports); // src/resolveDefaultsModeConfig.ts var import_config_resolver = __nccwpck_require__(53098); var import_node_config_provider = __nccwpck_require__(33461); var import_property_provider = __nccwpck_require__(79721); // src/constants.ts var AWS_EXECUTION_ENV = "AWS_EXECUTION_ENV"; var AWS_REGION_ENV = "AWS_REGION"; var AWS_DEFAULT_REGION_ENV = "AWS_DEFAULT_REGION"; var ENV_IMDS_DISABLED = "AWS_EC2_METADATA_DISABLED"; var DEFAULTS_MODE_OPTIONS = ["in-region", "cross-region", "mobile", "standard", "legacy"]; var IMDS_REGION_PATH = "/latest/meta-data/placement/region"; // src/defaultsModeConfig.ts var AWS_DEFAULTS_MODE_ENV = "AWS_DEFAULTS_MODE"; var AWS_DEFAULTS_MODE_CONFIG = "defaults_mode"; var NODE_DEFAULTS_MODE_CONFIG_OPTIONS = { environmentVariableSelector: (env) => { return env[AWS_DEFAULTS_MODE_ENV]; }, configFileSelector: (profile) => { return profile[AWS_DEFAULTS_MODE_CONFIG]; }, default: "legacy" }; // src/resolveDefaultsModeConfig.ts var resolveDefaultsModeConfig = /* @__PURE__ */ __name(({ region = (0, import_node_config_provider.loadConfig)(import_config_resolver.NODE_REGION_CONFIG_OPTIONS), defaultsMode = (0, import_node_config_provider.loadConfig)(NODE_DEFAULTS_MODE_CONFIG_OPTIONS) } = {}) => (0, import_property_provider.memoize)(async () => { const mode = typeof defaultsMode === "function" ? await defaultsMode() : defaultsMode; switch (mode?.toLowerCase()) { case "auto": return resolveNodeDefaultsModeAuto(region); case "in-region": case "cross-region": case "mobile": case "standard": case "legacy": return Promise.resolve(mode?.toLocaleLowerCase()); case void 0: return Promise.resolve("legacy"); default: throw new Error( `Invalid parameter for "defaultsMode", expect ${DEFAULTS_MODE_OPTIONS.join(", ")}, got ${mode}` ); } }), "resolveDefaultsModeConfig"); var resolveNodeDefaultsModeAuto = /* @__PURE__ */ __name(async (clientRegion) => { if (clientRegion) { const resolvedRegion = typeof clientRegion === "function" ? await clientRegion() : clientRegion; const inferredRegion = await inferPhysicalRegion(); if (!inferredRegion) { return "standard"; } if (resolvedRegion === inferredRegion) { return "in-region"; } else { return "cross-region"; } } return "standard"; }, "resolveNodeDefaultsModeAuto"); var inferPhysicalRegion = /* @__PURE__ */ __name(async () => { if (process.env[AWS_EXECUTION_ENV] && (process.env[AWS_REGION_ENV] || process.env[AWS_DEFAULT_REGION_ENV])) { return process.env[AWS_REGION_ENV] ?? process.env[AWS_DEFAULT_REGION_ENV]; } if (!process.env[ENV_IMDS_DISABLED]) { try { const { getInstanceMetadataEndpoint, httpRequest } = await Promise.resolve().then(() => __toESM(__nccwpck_require__(7477))); const endpoint = await getInstanceMetadataEndpoint(); return (await httpRequest({ ...endpoint, path: IMDS_REGION_PATH })).toString(); } catch (e) { } } }, "inferPhysicalRegion"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); /***/ }), /***/ 45473: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { EndpointCache: () => EndpointCache, EndpointError: () => EndpointError, customEndpointFunctions: () => customEndpointFunctions, isIpAddress: () => isIpAddress, isValidHostLabel: () => isValidHostLabel, resolveEndpoint: () => resolveEndpoint }); module.exports = __toCommonJS(src_exports); // src/cache/EndpointCache.ts var EndpointCache = class { /** * @param [size] - desired average maximum capacity. A buffer of 10 additional keys will be allowed * before keys are dropped. * @param [params] - list of params to consider as part of the cache key. * * If the params list is not populated, no caching will happen. * This may be out of order depending on how the object is created and arrives to this class. */ constructor({ size, params }) { this.data = /* @__PURE__ */ new Map(); this.parameters = []; this.capacity = size ?? 50; if (params) { this.parameters = params; } } static { __name(this, "EndpointCache"); } /** * @param endpointParams - query for endpoint. * @param resolver - provider of the value if not present. * @returns endpoint corresponding to the query. */ get(endpointParams, resolver) { const key = this.hash(endpointParams); if (key === false) { return resolver(); } if (!this.data.has(key)) { if (this.data.size > this.capacity + 10) { const keys = this.data.keys(); let i = 0; while (true) { const { value, done } = keys.next(); this.data.delete(value); if (done || ++i > 10) { break; } } } this.data.set(key, resolver()); } return this.data.get(key); } size() { return this.data.size; } /** * @returns cache key or false if not cachable. */ hash(endpointParams) { let buffer = ""; const { parameters } = this; if (parameters.length === 0) { return false; } for (const param of parameters) { const val = String(endpointParams[param] ?? ""); if (val.includes("|;")) { return false; } buffer += val + "|;"; } return buffer; } }; // src/lib/isIpAddress.ts var IP_V4_REGEX = new RegExp( `^(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}$` ); var isIpAddress = /* @__PURE__ */ __name((value) => IP_V4_REGEX.test(value) || value.startsWith("[") && value.endsWith("]"), "isIpAddress"); // src/lib/isValidHostLabel.ts var VALID_HOST_LABEL_REGEX = new RegExp(`^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$`); var isValidHostLabel = /* @__PURE__ */ __name((value, allowSubDomains = false) => { if (!allowSubDomains) { return VALID_HOST_LABEL_REGEX.test(value); } const labels = value.split("."); for (const label of labels) { if (!isValidHostLabel(label)) { return false; } } return true; }, "isValidHostLabel"); // src/utils/customEndpointFunctions.ts var customEndpointFunctions = {}; // src/debug/debugId.ts var debugId = "endpoints"; // src/debug/toDebugString.ts function toDebugString(input) { if (typeof input !== "object" || input == null) { return input; } if ("ref" in input) { return `$${toDebugString(input.ref)}`; } if ("fn" in input) { return `${input.fn}(${(input.argv || []).map(toDebugString).join(", ")})`; } return JSON.stringify(input, null, 2); } __name(toDebugString, "toDebugString"); // src/types/EndpointError.ts var EndpointError = class extends Error { static { __name(this, "EndpointError"); } constructor(message) { super(message); this.name = "EndpointError"; } }; // src/lib/booleanEquals.ts var booleanEquals = /* @__PURE__ */ __name((value1, value2) => value1 === value2, "booleanEquals"); // src/lib/getAttrPathList.ts var getAttrPathList = /* @__PURE__ */ __name((path) => { const parts = path.split("."); const pathList = []; for (const part of parts) { const squareBracketIndex = part.indexOf("["); if (squareBracketIndex !== -1) { if (part.indexOf("]") !== part.length - 1) { throw new EndpointError(`Path: '${path}' does not end with ']'`); } const arrayIndex = part.slice(squareBracketIndex + 1, -1); if (Number.isNaN(parseInt(arrayIndex))) { throw new EndpointError(`Invalid array index: '${arrayIndex}' in path: '${path}'`); } if (squareBracketIndex !== 0) { pathList.push(part.slice(0, squareBracketIndex)); } pathList.push(arrayIndex); } else { pathList.push(part); } } return pathList; }, "getAttrPathList"); // src/lib/getAttr.ts var getAttr = /* @__PURE__ */ __name((value, path) => getAttrPathList(path).reduce((acc, index) => { if (typeof acc !== "object") { throw new EndpointError(`Index '${index}' in '${path}' not found in '${JSON.stringify(value)}'`); } else if (Array.isArray(acc)) { return acc[parseInt(index)]; } return acc[index]; }, value), "getAttr"); // src/lib/isSet.ts var isSet = /* @__PURE__ */ __name((value) => value != null, "isSet"); // src/lib/not.ts var not = /* @__PURE__ */ __name((value) => !value, "not"); // src/lib/parseURL.ts var import_types3 = __nccwpck_require__(55756); var DEFAULT_PORTS = { [import_types3.EndpointURLScheme.HTTP]: 80, [import_types3.EndpointURLScheme.HTTPS]: 443 }; var parseURL = /* @__PURE__ */ __name((value) => { const whatwgURL = (() => { try { if (value instanceof URL) { return value; } if (typeof value === "object" && "hostname" in value) { const { hostname: hostname2, port, protocol: protocol2 = "", path = "", query = {} } = value; const url = new URL(`${protocol2}//${hostname2}${port ? `:${port}` : ""}${path}`); url.search = Object.entries(query).map(([k, v]) => `${k}=${v}`).join("&"); return url; } return new URL(value); } catch (error) { return null; } })(); if (!whatwgURL) { console.error(`Unable to parse ${JSON.stringify(value)} as a whatwg URL.`); return null; } const urlString = whatwgURL.href; const { host, hostname, pathname, protocol, search } = whatwgURL; if (search) { return null; } const scheme = protocol.slice(0, -1); if (!Object.values(import_types3.EndpointURLScheme).includes(scheme)) { return null; } const isIp = isIpAddress(hostname); const inputContainsDefaultPort = urlString.includes(`${host}:${DEFAULT_PORTS[scheme]}`) || typeof value === "string" && value.includes(`${host}:${DEFAULT_PORTS[scheme]}`); const authority = `${host}${inputContainsDefaultPort ? `:${DEFAULT_PORTS[scheme]}` : ``}`; return { scheme, authority, path: pathname, normalizedPath: pathname.endsWith("/") ? pathname : `${pathname}/`, isIp }; }, "parseURL"); // src/lib/stringEquals.ts var stringEquals = /* @__PURE__ */ __name((value1, value2) => value1 === value2, "stringEquals"); // src/lib/substring.ts var substring = /* @__PURE__ */ __name((input, start, stop, reverse) => { if (start >= stop || input.length < stop) { return null; } if (!reverse) { return input.substring(start, stop); } return input.substring(input.length - stop, input.length - start); }, "substring"); // src/lib/uriEncode.ts var uriEncode = /* @__PURE__ */ __name((value) => encodeURIComponent(value).replace(/[!*'()]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`), "uriEncode"); // src/utils/endpointFunctions.ts var endpointFunctions = { booleanEquals, getAttr, isSet, isValidHostLabel, not, parseURL, stringEquals, substring, uriEncode }; // src/utils/evaluateTemplate.ts var evaluateTemplate = /* @__PURE__ */ __name((template, options) => { const evaluatedTemplateArr = []; const templateContext = { ...options.endpointParams, ...options.referenceRecord }; let currentIndex = 0; while (currentIndex < template.length) { const openingBraceIndex = template.indexOf("{", currentIndex); if (openingBraceIndex === -1) { evaluatedTemplateArr.push(template.slice(currentIndex)); break; } evaluatedTemplateArr.push(template.slice(currentIndex, openingBraceIndex)); const closingBraceIndex = template.indexOf("}", openingBraceIndex); if (closingBraceIndex === -1) { evaluatedTemplateArr.push(template.slice(openingBraceIndex)); break; } if (template[openingBraceIndex + 1] === "{" && template[closingBraceIndex + 1] === "}") { evaluatedTemplateArr.push(template.slice(openingBraceIndex + 1, closingBraceIndex)); currentIndex = closingBraceIndex + 2; } const parameterName = template.substring(openingBraceIndex + 1, closingBraceIndex); if (parameterName.includes("#")) { const [refName, attrName] = parameterName.split("#"); evaluatedTemplateArr.push(getAttr(templateContext[refName], attrName)); } else { evaluatedTemplateArr.push(templateContext[parameterName]); } currentIndex = closingBraceIndex + 1; } return evaluatedTemplateArr.join(""); }, "evaluateTemplate"); // src/utils/getReferenceValue.ts var getReferenceValue = /* @__PURE__ */ __name(({ ref }, options) => { const referenceRecord = { ...options.endpointParams, ...options.referenceRecord }; return referenceRecord[ref]; }, "getReferenceValue"); // src/utils/evaluateExpression.ts var evaluateExpression = /* @__PURE__ */ __name((obj, keyName, options) => { if (typeof obj === "string") { return evaluateTemplate(obj, options); } else if (obj["fn"]) { return callFunction(obj, options); } else if (obj["ref"]) { return getReferenceValue(obj, options); } throw new EndpointError(`'${keyName}': ${String(obj)} is not a string, function or reference.`); }, "evaluateExpression"); // src/utils/callFunction.ts var callFunction = /* @__PURE__ */ __name(({ fn, argv }, options) => { const evaluatedArgs = argv.map( (arg) => ["boolean", "number"].includes(typeof arg) ? arg : evaluateExpression(arg, "arg", options) ); const fnSegments = fn.split("."); if (fnSegments[0] in customEndpointFunctions && fnSegments[1] != null) { return customEndpointFunctions[fnSegments[0]][fnSegments[1]](...evaluatedArgs); } return endpointFunctions[fn](...evaluatedArgs); }, "callFunction"); // src/utils/evaluateCondition.ts var evaluateCondition = /* @__PURE__ */ __name(({ assign, ...fnArgs }, options) => { if (assign && assign in options.referenceRecord) { throw new EndpointError(`'${assign}' is already defined in Reference Record.`); } const value = callFunction(fnArgs, options); options.logger?.debug?.(`${debugId} evaluateCondition: ${toDebugString(fnArgs)} = ${toDebugString(value)}`); return { result: value === "" ? true : !!value, ...assign != null && { toAssign: { name: assign, value } } }; }, "evaluateCondition"); // src/utils/evaluateConditions.ts var evaluateConditions = /* @__PURE__ */ __name((conditions = [], options) => { const conditionsReferenceRecord = {}; for (const condition of conditions) { const { result, toAssign } = evaluateCondition(condition, { ...options, referenceRecord: { ...options.referenceRecord, ...conditionsReferenceRecord } }); if (!result) { return { result }; } if (toAssign) { conditionsReferenceRecord[toAssign.name] = toAssign.value; options.logger?.debug?.(`${debugId} assign: ${toAssign.name} := ${toDebugString(toAssign.value)}`); } } return { result: true, referenceRecord: conditionsReferenceRecord }; }, "evaluateConditions"); // src/utils/getEndpointHeaders.ts var getEndpointHeaders = /* @__PURE__ */ __name((headers, options) => Object.entries(headers).reduce( (acc, [headerKey, headerVal]) => ({ ...acc, [headerKey]: headerVal.map((headerValEntry) => { const processedExpr = evaluateExpression(headerValEntry, "Header value entry", options); if (typeof processedExpr !== "string") { throw new EndpointError(`Header '${headerKey}' value '${processedExpr}' is not a string`); } return processedExpr; }) }), {} ), "getEndpointHeaders"); // src/utils/getEndpointProperty.ts var getEndpointProperty = /* @__PURE__ */ __name((property, options) => { if (Array.isArray(property)) { return property.map((propertyEntry) => getEndpointProperty(propertyEntry, options)); } switch (typeof property) { case "string": return evaluateTemplate(property, options); case "object": if (property === null) { throw new EndpointError(`Unexpected endpoint property: ${property}`); } return getEndpointProperties(property, options); case "boolean": return property; default: throw new EndpointError(`Unexpected endpoint property type: ${typeof property}`); } }, "getEndpointProperty"); // src/utils/getEndpointProperties.ts var getEndpointProperties = /* @__PURE__ */ __name((properties, options) => Object.entries(properties).reduce( (acc, [propertyKey, propertyVal]) => ({ ...acc, [propertyKey]: getEndpointProperty(propertyVal, options) }), {} ), "getEndpointProperties"); // src/utils/getEndpointUrl.ts var getEndpointUrl = /* @__PURE__ */ __name((endpointUrl, options) => { const expression = evaluateExpression(endpointUrl, "Endpoint URL", options); if (typeof expression === "string") { try { return new URL(expression); } catch (error) { console.error(`Failed to construct URL with ${expression}`, error); throw error; } } throw new EndpointError(`Endpoint URL must be a string, got ${typeof expression}`); }, "getEndpointUrl"); // src/utils/evaluateEndpointRule.ts var evaluateEndpointRule = /* @__PURE__ */ __name((endpointRule, options) => { const { conditions, endpoint } = endpointRule; const { result, referenceRecord } = evaluateConditions(conditions, options); if (!result) { return; } const endpointRuleOptions = { ...options, referenceRecord: { ...options.referenceRecord, ...referenceRecord } }; const { url, properties, headers } = endpoint; options.logger?.debug?.(`${debugId} Resolving endpoint from template: ${toDebugString(endpoint)}`); return { ...headers != void 0 && { headers: getEndpointHeaders(headers, endpointRuleOptions) }, ...properties != void 0 && { properties: getEndpointProperties(properties, endpointRuleOptions) }, url: getEndpointUrl(url, endpointRuleOptions) }; }, "evaluateEndpointRule"); // src/utils/evaluateErrorRule.ts var evaluateErrorRule = /* @__PURE__ */ __name((errorRule, options) => { const { conditions, error } = errorRule; const { result, referenceRecord } = evaluateConditions(conditions, options); if (!result) { return; } throw new EndpointError( evaluateExpression(error, "Error", { ...options, referenceRecord: { ...options.referenceRecord, ...referenceRecord } }) ); }, "evaluateErrorRule"); // src/utils/evaluateTreeRule.ts var evaluateTreeRule = /* @__PURE__ */ __name((treeRule, options) => { const { conditions, rules } = treeRule; const { result, referenceRecord } = evaluateConditions(conditions, options); if (!result) { return; } return evaluateRules(rules, { ...options, referenceRecord: { ...options.referenceRecord, ...referenceRecord } }); }, "evaluateTreeRule"); // src/utils/evaluateRules.ts var evaluateRules = /* @__PURE__ */ __name((rules, options) => { for (const rule of rules) { if (rule.type === "endpoint") { const endpointOrUndefined = evaluateEndpointRule(rule, options); if (endpointOrUndefined) { return endpointOrUndefined; } } else if (rule.type === "error") { evaluateErrorRule(rule, options); } else if (rule.type === "tree") { const endpointOrUndefined = evaluateTreeRule(rule, options); if (endpointOrUndefined) { return endpointOrUndefined; } } else { throw new EndpointError(`Unknown endpoint rule: ${rule}`); } } throw new EndpointError(`Rules evaluation failed`); }, "evaluateRules"); // src/resolveEndpoint.ts var resolveEndpoint = /* @__PURE__ */ __name((ruleSetObject, options) => { const { endpointParams, logger } = options; const { parameters, rules } = ruleSetObject; options.logger?.debug?.(`${debugId} Initial EndpointParams: ${toDebugString(endpointParams)}`); const paramsWithDefault = Object.entries(parameters).filter(([, v]) => v.default != null).map(([k, v]) => [k, v.default]); if (paramsWithDefault.length > 0) { for (const [paramKey, paramDefaultValue] of paramsWithDefault) { endpointParams[paramKey] = endpointParams[paramKey] ?? paramDefaultValue; } } const requiredParams = Object.entries(parameters).filter(([, v]) => v.required).map(([k]) => k); for (const requiredParam of requiredParams) { if (endpointParams[requiredParam] == null) { throw new EndpointError(`Missing required parameter: '${requiredParam}'`); } } const endpoint = evaluateRules(rules, { endpointParams, logger, referenceRecord: {} }); options.logger?.debug?.(`${debugId} Resolved endpoint: ${toDebugString(endpoint)}`); return endpoint; }, "resolveEndpoint"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); /***/ }), /***/ 45364: /***/ ((module) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { fromHex: () => fromHex, toHex: () => toHex }); module.exports = __toCommonJS(src_exports); var SHORT_TO_HEX = {}; var HEX_TO_SHORT = {}; for (let i = 0; i < 256; i++) { let encodedByte = i.toString(16).toLowerCase(); if (encodedByte.length === 1) { encodedByte = `0${encodedByte}`; } SHORT_TO_HEX[i] = encodedByte; HEX_TO_SHORT[encodedByte] = i; } function fromHex(encoded) { if (encoded.length % 2 !== 0) { throw new Error("Hex encoded strings must have an even number length"); } const out = new Uint8Array(encoded.length / 2); for (let i = 0; i < encoded.length; i += 2) { const encodedByte = encoded.slice(i, i + 2).toLowerCase(); if (encodedByte in HEX_TO_SHORT) { out[i / 2] = HEX_TO_SHORT[encodedByte]; } else { throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`); } } return out; } __name(fromHex, "fromHex"); function toHex(bytes) { let out = ""; for (let i = 0; i < bytes.byteLength; i++) { out += SHORT_TO_HEX[bytes[i]]; } return out; } __name(toHex, "toHex"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); /***/ }), /***/ 2390: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { getSmithyContext: () => getSmithyContext, normalizeProvider: () => normalizeProvider }); module.exports = __toCommonJS(src_exports); // src/getSmithyContext.ts var import_types = __nccwpck_require__(55756); var getSmithyContext = /* @__PURE__ */ __name((context) => context[import_types.SMITHY_CONTEXT_KEY] || (context[import_types.SMITHY_CONTEXT_KEY] = {}), "getSmithyContext"); // src/normalizeProvider.ts var normalizeProvider = /* @__PURE__ */ __name((input) => { if (typeof input === "function") return input; const promisified = Promise.resolve(input); return () => promisified; }, "normalizeProvider"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); /***/ }), /***/ 84902: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { AdaptiveRetryStrategy: () => AdaptiveRetryStrategy, ConfiguredRetryStrategy: () => ConfiguredRetryStrategy, DEFAULT_MAX_ATTEMPTS: () => DEFAULT_MAX_ATTEMPTS, DEFAULT_RETRY_DELAY_BASE: () => DEFAULT_RETRY_DELAY_BASE, DEFAULT_RETRY_MODE: () => DEFAULT_RETRY_MODE, DefaultRateLimiter: () => DefaultRateLimiter, INITIAL_RETRY_TOKENS: () => INITIAL_RETRY_TOKENS, INVOCATION_ID_HEADER: () => INVOCATION_ID_HEADER, MAXIMUM_RETRY_DELAY: () => MAXIMUM_RETRY_DELAY, NO_RETRY_INCREMENT: () => NO_RETRY_INCREMENT, REQUEST_HEADER: () => REQUEST_HEADER, RETRY_COST: () => RETRY_COST, RETRY_MODES: () => RETRY_MODES, StandardRetryStrategy: () => StandardRetryStrategy, THROTTLING_RETRY_DELAY_BASE: () => THROTTLING_RETRY_DELAY_BASE, TIMEOUT_RETRY_COST: () => TIMEOUT_RETRY_COST }); module.exports = __toCommonJS(src_exports); // src/config.ts var RETRY_MODES = /* @__PURE__ */ ((RETRY_MODES2) => { RETRY_MODES2["STANDARD"] = "standard"; RETRY_MODES2["ADAPTIVE"] = "adaptive"; return RETRY_MODES2; })(RETRY_MODES || {}); var DEFAULT_MAX_ATTEMPTS = 3; var DEFAULT_RETRY_MODE = "standard" /* STANDARD */; // src/DefaultRateLimiter.ts var import_service_error_classification = __nccwpck_require__(6375); var DefaultRateLimiter = class _DefaultRateLimiter { constructor(options) { // Pre-set state variables this.currentCapacity = 0; this.enabled = false; this.lastMaxRate = 0; this.measuredTxRate = 0; this.requestCount = 0; this.lastTimestamp = 0; this.timeWindow = 0; this.beta = options?.beta ?? 0.7; this.minCapacity = options?.minCapacity ?? 1; this.minFillRate = options?.minFillRate ?? 0.5; this.scaleConstant = options?.scaleConstant ?? 0.4; this.smooth = options?.smooth ?? 0.8; const currentTimeInSeconds = this.getCurrentTimeInSeconds(); this.lastThrottleTime = currentTimeInSeconds; this.lastTxRateBucket = Math.floor(this.getCurrentTimeInSeconds()); this.fillRate = this.minFillRate; this.maxCapacity = this.minCapacity; } static { __name(this, "DefaultRateLimiter"); } static { /** * Only used in testing. */ this.setTimeoutFn = setTimeout; } getCurrentTimeInSeconds() { return Date.now() / 1e3; } async getSendToken() { return this.acquireTokenBucket(1); } async acquireTokenBucket(amount) { if (!this.enabled) { return; } this.refillTokenBucket(); if (amount > this.currentCapacity) { const delay = (amount - this.currentCapacity) / this.fillRate * 1e3; await new Promise((resolve) => _DefaultRateLimiter.setTimeoutFn(resolve, delay)); } this.currentCapacity = this.currentCapacity - amount; } refillTokenBucket() { const timestamp = this.getCurrentTimeInSeconds(); if (!this.lastTimestamp) { this.lastTimestamp = timestamp; return; } const fillAmount = (timestamp - this.lastTimestamp) * this.fillRate; this.currentCapacity = Math.min(this.maxCapacity, this.currentCapacity + fillAmount); this.lastTimestamp = timestamp; } updateClientSendingRate(response) { let calculatedRate; this.updateMeasuredRate(); if ((0, import_service_error_classification.isThrottlingError)(response)) { const rateToUse = !this.enabled ? this.measuredTxRate : Math.min(this.measuredTxRate, this.fillRate); this.lastMaxRate = rateToUse; this.calculateTimeWindow(); this.lastThrottleTime = this.getCurrentTimeInSeconds(); calculatedRate = this.cubicThrottle(rateToUse); this.enableTokenBucket(); } else { this.calculateTimeWindow(); calculatedRate = this.cubicSuccess(this.getCurrentTimeInSeconds()); } const newRate = Math.min(calculatedRate, 2 * this.measuredTxRate); this.updateTokenBucketRate(newRate); } calculateTimeWindow() { this.timeWindow = this.getPrecise(Math.pow(this.lastMaxRate * (1 - this.beta) / this.scaleConstant, 1 / 3)); } cubicThrottle(rateToUse) { return this.getPrecise(rateToUse * this.beta); } cubicSuccess(timestamp) { return this.getPrecise( this.scaleConstant * Math.pow(timestamp - this.lastThrottleTime - this.timeWindow, 3) + this.lastMaxRate ); } enableTokenBucket() { this.enabled = true; } updateTokenBucketRate(newRate) { this.refillTokenBucket(); this.fillRate = Math.max(newRate, this.minFillRate); this.maxCapacity = Math.max(newRate, this.minCapacity); this.currentCapacity = Math.min(this.currentCapacity, this.maxCapacity); } updateMeasuredRate() { const t = this.getCurrentTimeInSeconds(); const timeBucket = Math.floor(t * 2) / 2; this.requestCount++; if (timeBucket > this.lastTxRateBucket) { const currentRate = this.requestCount / (timeBucket - this.lastTxRateBucket); this.measuredTxRate = this.getPrecise(currentRate * this.smooth + this.measuredTxRate * (1 - this.smooth)); this.requestCount = 0; this.lastTxRateBucket = timeBucket; } } getPrecise(num) { return parseFloat(num.toFixed(8)); } }; // src/constants.ts var DEFAULT_RETRY_DELAY_BASE = 100; var MAXIMUM_RETRY_DELAY = 20 * 1e3; var THROTTLING_RETRY_DELAY_BASE = 500; var INITIAL_RETRY_TOKENS = 500; var RETRY_COST = 5; var TIMEOUT_RETRY_COST = 10; var NO_RETRY_INCREMENT = 1; var INVOCATION_ID_HEADER = "amz-sdk-invocation-id"; var REQUEST_HEADER = "amz-sdk-request"; // src/defaultRetryBackoffStrategy.ts var getDefaultRetryBackoffStrategy = /* @__PURE__ */ __name(() => { let delayBase = DEFAULT_RETRY_DELAY_BASE; const computeNextBackoffDelay = /* @__PURE__ */ __name((attempts) => { return Math.floor(Math.min(MAXIMUM_RETRY_DELAY, Math.random() * 2 ** attempts * delayBase)); }, "computeNextBackoffDelay"); const setDelayBase = /* @__PURE__ */ __name((delay) => { delayBase = delay; }, "setDelayBase"); return { computeNextBackoffDelay, setDelayBase }; }, "getDefaultRetryBackoffStrategy"); // src/defaultRetryToken.ts var createDefaultRetryToken = /* @__PURE__ */ __name(({ retryDelay, retryCount, retryCost }) => { const getRetryCount = /* @__PURE__ */ __name(() => retryCount, "getRetryCount"); const getRetryDelay = /* @__PURE__ */ __name(() => Math.min(MAXIMUM_RETRY_DELAY, retryDelay), "getRetryDelay"); const getRetryCost = /* @__PURE__ */ __name(() => retryCost, "getRetryCost"); return { getRetryCount, getRetryDelay, getRetryCost }; }, "createDefaultRetryToken"); // src/StandardRetryStrategy.ts var StandardRetryStrategy = class { constructor(maxAttempts) { this.maxAttempts = maxAttempts; this.mode = "standard" /* STANDARD */; this.capacity = INITIAL_RETRY_TOKENS; this.retryBackoffStrategy = getDefaultRetryBackoffStrategy(); this.maxAttemptsProvider = typeof maxAttempts === "function" ? maxAttempts : async () => maxAttempts; } static { __name(this, "StandardRetryStrategy"); } // eslint-disable-next-line @typescript-eslint/no-unused-vars async acquireInitialRetryToken(retryTokenScope) { return createDefaultRetryToken({ retryDelay: DEFAULT_RETRY_DELAY_BASE, retryCount: 0 }); } async refreshRetryTokenForRetry(token, errorInfo) { const maxAttempts = await this.getMaxAttempts(); if (this.shouldRetry(token, errorInfo, maxAttempts)) { const errorType = errorInfo.errorType; this.retryBackoffStrategy.setDelayBase( errorType === "THROTTLING" ? THROTTLING_RETRY_DELAY_BASE : DEFAULT_RETRY_DELAY_BASE ); const delayFromErrorType = this.retryBackoffStrategy.computeNextBackoffDelay(token.getRetryCount()); const retryDelay = errorInfo.retryAfterHint ? Math.max(errorInfo.retryAfterHint.getTime() - Date.now() || 0, delayFromErrorType) : delayFromErrorType; const capacityCost = this.getCapacityCost(errorType); this.capacity -= capacityCost; return createDefaultRetryToken({ retryDelay, retryCount: token.getRetryCount() + 1, retryCost: capacityCost }); } throw new Error("No retry token available"); } recordSuccess(token) { this.capacity = Math.max(INITIAL_RETRY_TOKENS, this.capacity + (token.getRetryCost() ?? NO_RETRY_INCREMENT)); } /** * @returns the current available retry capacity. * * This number decreases when retries are executed and refills when requests or retries succeed. */ getCapacity() { return this.capacity; } async getMaxAttempts() { try { return await this.maxAttemptsProvider(); } catch (error) { console.warn(`Max attempts provider could not resolve. Using default of ${DEFAULT_MAX_ATTEMPTS}`); return DEFAULT_MAX_ATTEMPTS; } } shouldRetry(tokenToRenew, errorInfo, maxAttempts) { const attempts = tokenToRenew.getRetryCount() + 1; return attempts < maxAttempts && this.capacity >= this.getCapacityCost(errorInfo.errorType) && this.isRetryableError(errorInfo.errorType); } getCapacityCost(errorType) { return errorType === "TRANSIENT" ? TIMEOUT_RETRY_COST : RETRY_COST; } isRetryableError(errorType) { return errorType === "THROTTLING" || errorType === "TRANSIENT"; } }; // src/AdaptiveRetryStrategy.ts var AdaptiveRetryStrategy = class { constructor(maxAttemptsProvider, options) { this.maxAttemptsProvider = maxAttemptsProvider; this.mode = "adaptive" /* ADAPTIVE */; const { rateLimiter } = options ?? {}; this.rateLimiter = rateLimiter ?? new DefaultRateLimiter(); this.standardRetryStrategy = new StandardRetryStrategy(maxAttemptsProvider); } static { __name(this, "AdaptiveRetryStrategy"); } async acquireInitialRetryToken(retryTokenScope) { await this.rateLimiter.getSendToken(); return this.standardRetryStrategy.acquireInitialRetryToken(retryTokenScope); } async refreshRetryTokenForRetry(tokenToRenew, errorInfo) { this.rateLimiter.updateClientSendingRate(errorInfo); return this.standardRetryStrategy.refreshRetryTokenForRetry(tokenToRenew, errorInfo); } recordSuccess(token) { this.rateLimiter.updateClientSendingRate({}); this.standardRetryStrategy.recordSuccess(token); } }; // src/ConfiguredRetryStrategy.ts var ConfiguredRetryStrategy = class extends StandardRetryStrategy { static { __name(this, "ConfiguredRetryStrategy"); } /** * @param maxAttempts - the maximum number of retry attempts allowed. * e.g., if set to 3, then 4 total requests are possible. * @param computeNextBackoffDelay - a millisecond delay for each retry or a function that takes the retry attempt * and returns the delay. * * @example exponential backoff. * ```js * new Client({ * retryStrategy: new ConfiguredRetryStrategy(3, (attempt) => attempt ** 2) * }); * ``` * @example constant delay. * ```js * new Client({ * retryStrategy: new ConfiguredRetryStrategy(3, 2000) * }); * ``` */ constructor(maxAttempts, computeNextBackoffDelay = DEFAULT_RETRY_DELAY_BASE) { super(typeof maxAttempts === "function" ? maxAttempts : async () => maxAttempts); if (typeof computeNextBackoffDelay === "number") { this.computeNextBackoffDelay = () => computeNextBackoffDelay; } else { this.computeNextBackoffDelay = computeNextBackoffDelay; } } async refreshRetryTokenForRetry(tokenToRenew, errorInfo) { const token = await super.refreshRetryTokenForRetry(tokenToRenew, errorInfo); token.getRetryDelay = () => this.computeNextBackoffDelay(token.getRetryCount()); return token; } }; // Annotate the CommonJS export names for ESM import in node: 0 && (0); /***/ }), /***/ 39361: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ByteArrayCollector = void 0; class ByteArrayCollector { constructor(allocByteArray) { this.allocByteArray = allocByteArray; this.byteLength = 0; this.byteArrays = []; } push(byteArray) { this.byteArrays.push(byteArray); this.byteLength += byteArray.byteLength; } flush() { if (this.byteArrays.length === 1) { const bytes = this.byteArrays[0]; this.reset(); return bytes; } const aggregation = this.allocByteArray(this.byteLength); let cursor = 0; for (let i = 0; i < this.byteArrays.length; ++i) { const bytes = this.byteArrays[i]; aggregation.set(bytes, cursor); cursor += bytes.byteLength; } this.reset(); return aggregation; } reset() { this.byteArrays = []; this.byteLength = 0; } } exports.ByteArrayCollector = ByteArrayCollector; /***/ }), /***/ 78551: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ChecksumStream = void 0; const ReadableStreamRef = typeof ReadableStream === "function" ? ReadableStream : function () { }; class ChecksumStream extends ReadableStreamRef { } exports.ChecksumStream = ChecksumStream; /***/ }), /***/ 6982: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ChecksumStream = void 0; const util_base64_1 = __nccwpck_require__(75600); const stream_1 = __nccwpck_require__(12781); class ChecksumStream extends stream_1.Duplex { constructor({ expectedChecksum, checksum, source, checksumSourceLocation, base64Encoder, }) { var _a, _b; super(); if (typeof source.pipe === "function") { this.source = source; } else { throw new Error(`@smithy/util-stream: unsupported source type ${(_b = (_a = source === null || source === void 0 ? void 0 : source.constructor) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : source} in ChecksumStream.`); } this.base64Encoder = base64Encoder !== null && base64Encoder !== void 0 ? base64Encoder : util_base64_1.toBase64; this.expectedChecksum = expectedChecksum; this.checksum = checksum; this.checksumSourceLocation = checksumSourceLocation; this.source.pipe(this); } _read(size) { } _write(chunk, encoding, callback) { try { this.checksum.update(chunk); this.push(chunk); } catch (e) { return callback(e); } return callback(); } async _final(callback) { try { const digest = await this.checksum.digest(); const received = this.base64Encoder(digest); if (this.expectedChecksum !== received) { return callback(new Error(`Checksum mismatch: expected "${this.expectedChecksum}" but received "${received}"` + ` in response header "${this.checksumSourceLocation}".`)); } } catch (e) { return callback(e); } this.push(null); return callback(); } } exports.ChecksumStream = ChecksumStream; /***/ }), /***/ 72313: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createChecksumStream = void 0; const util_base64_1 = __nccwpck_require__(75600); const stream_type_check_1 = __nccwpck_require__(57578); const ChecksumStream_browser_1 = __nccwpck_require__(78551); const createChecksumStream = ({ expectedChecksum, checksum, source, checksumSourceLocation, base64Encoder, }) => { var _a, _b; if (!(0, stream_type_check_1.isReadableStream)(source)) { throw new Error(`@smithy/util-stream: unsupported source type ${(_b = (_a = source === null || source === void 0 ? void 0 : source.constructor) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : source} in ChecksumStream.`); } const encoder = base64Encoder !== null && base64Encoder !== void 0 ? base64Encoder : util_base64_1.toBase64; if (typeof TransformStream !== "function") { throw new Error("@smithy/util-stream: unable to instantiate ChecksumStream because API unavailable: ReadableStream/TransformStream."); } const transform = new TransformStream({ start() { }, async transform(chunk, controller) { checksum.update(chunk); controller.enqueue(chunk); }, async flush(controller) { const digest = await checksum.digest(); const received = encoder(digest); if (expectedChecksum !== received) { const error = new Error(`Checksum mismatch: expected "${expectedChecksum}" but received "${received}"` + ` in response header "${checksumSourceLocation}".`); controller.error(error); } else { controller.terminate(); } }, }); source.pipeThrough(transform); const readable = transform.readable; Object.setPrototypeOf(readable, ChecksumStream_browser_1.ChecksumStream.prototype); return readable; }; exports.createChecksumStream = createChecksumStream; /***/ }), /***/ 21927: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createChecksumStream = createChecksumStream; const stream_type_check_1 = __nccwpck_require__(57578); const ChecksumStream_1 = __nccwpck_require__(6982); const createChecksumStream_browser_1 = __nccwpck_require__(72313); function createChecksumStream(init) { if (typeof ReadableStream === "function" && (0, stream_type_check_1.isReadableStream)(init.source)) { return (0, createChecksumStream_browser_1.createChecksumStream)(init); } return new ChecksumStream_1.ChecksumStream(init); } /***/ }), /***/ 33259: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createBufferedReadable = createBufferedReadable; const node_stream_1 = __nccwpck_require__(84492); const ByteArrayCollector_1 = __nccwpck_require__(39361); const createBufferedReadableStream_1 = __nccwpck_require__(92558); const stream_type_check_1 = __nccwpck_require__(57578); function createBufferedReadable(upstream, size, logger) { if ((0, stream_type_check_1.isReadableStream)(upstream)) { return (0, createBufferedReadableStream_1.createBufferedReadableStream)(upstream, size, logger); } const downstream = new node_stream_1.Readable({ read() { } }); let streamBufferingLoggedWarning = false; let bytesSeen = 0; const buffers = [ "", new ByteArrayCollector_1.ByteArrayCollector((size) => new Uint8Array(size)), new ByteArrayCollector_1.ByteArrayCollector((size) => Buffer.from(new Uint8Array(size))), ]; let mode = -1; upstream.on("data", (chunk) => { const chunkMode = (0, createBufferedReadableStream_1.modeOf)(chunk, true); if (mode !== chunkMode) { if (mode >= 0) { downstream.push((0, createBufferedReadableStream_1.flush)(buffers, mode)); } mode = chunkMode; } if (mode === -1) { downstream.push(chunk); return; } const chunkSize = (0, createBufferedReadableStream_1.sizeOf)(chunk); bytesSeen += chunkSize; const bufferSize = (0, createBufferedReadableStream_1.sizeOf)(buffers[mode]); if (chunkSize >= size && bufferSize === 0) { downstream.push(chunk); } else { const newSize = (0, createBufferedReadableStream_1.merge)(buffers, mode, chunk); if (!streamBufferingLoggedWarning && bytesSeen > size * 2) { streamBufferingLoggedWarning = true; logger === null || logger === void 0 ? void 0 : logger.warn(`@smithy/util-stream - stream chunk size ${chunkSize} is below threshold of ${size}, automatically buffering.`); } if (newSize >= size) { downstream.push((0, createBufferedReadableStream_1.flush)(buffers, mode)); } } }); upstream.on("end", () => { if (mode !== -1) { const remainder = (0, createBufferedReadableStream_1.flush)(buffers, mode); if ((0, createBufferedReadableStream_1.sizeOf)(remainder) > 0) { downstream.push(remainder); } } downstream.push(null); }); return downstream; } /***/ }), /***/ 92558: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createBufferedReadable = void 0; exports.createBufferedReadableStream = createBufferedReadableStream; exports.merge = merge; exports.flush = flush; exports.sizeOf = sizeOf; exports.modeOf = modeOf; const ByteArrayCollector_1 = __nccwpck_require__(39361); function createBufferedReadableStream(upstream, size, logger) { const reader = upstream.getReader(); let streamBufferingLoggedWarning = false; let bytesSeen = 0; const buffers = ["", new ByteArrayCollector_1.ByteArrayCollector((size) => new Uint8Array(size))]; let mode = -1; const pull = async (controller) => { const { value, done } = await reader.read(); const chunk = value; if (done) { if (mode !== -1) { const remainder = flush(buffers, mode); if (sizeOf(remainder) > 0) { controller.enqueue(remainder); } } controller.close(); } else { const chunkMode = modeOf(chunk, false); if (mode !== chunkMode) { if (mode >= 0) { controller.enqueue(flush(buffers, mode)); } mode = chunkMode; } if (mode === -1) { controller.enqueue(chunk); return; } const chunkSize = sizeOf(chunk); bytesSeen += chunkSize; const bufferSize = sizeOf(buffers[mode]); if (chunkSize >= size && bufferSize === 0) { controller.enqueue(chunk); } else { const newSize = merge(buffers, mode, chunk); if (!streamBufferingLoggedWarning && bytesSeen > size * 2) { streamBufferingLoggedWarning = true; logger === null || logger === void 0 ? void 0 : logger.warn(`@smithy/util-stream - stream chunk size ${chunkSize} is below threshold of ${size}, automatically buffering.`); } if (newSize >= size) { controller.enqueue(flush(buffers, mode)); } else { await pull(controller); } } } }; return new ReadableStream({ pull, }); } exports.createBufferedReadable = createBufferedReadableStream; function merge(buffers, mode, chunk) { switch (mode) { case 0: buffers[0] += chunk; return sizeOf(buffers[0]); case 1: case 2: buffers[mode].push(chunk); return sizeOf(buffers[mode]); } } function flush(buffers, mode) { switch (mode) { case 0: const s = buffers[0]; buffers[0] = ""; return s; case 1: case 2: return buffers[mode].flush(); } throw new Error(`@smithy/util-stream - invalid index ${mode} given to flush()`); } function sizeOf(chunk) { var _a, _b; return (_b = (_a = chunk === null || chunk === void 0 ? void 0 : chunk.byteLength) !== null && _a !== void 0 ? _a : chunk === null || chunk === void 0 ? void 0 : chunk.length) !== null && _b !== void 0 ? _b : 0; } function modeOf(chunk, allowBuffer = true) { if (allowBuffer && typeof Buffer !== "undefined" && chunk instanceof Buffer) { return 2; } if (chunk instanceof Uint8Array) { return 1; } if (typeof chunk === "string") { return 0; } return -1; } /***/ }), /***/ 23636: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getAwsChunkedEncodingStream = void 0; const stream_1 = __nccwpck_require__(12781); const getAwsChunkedEncodingStream = (readableStream, options) => { const { base64Encoder, bodyLengthChecker, checksumAlgorithmFn, checksumLocationName, streamHasher } = options; const checksumRequired = base64Encoder !== undefined && checksumAlgorithmFn !== undefined && checksumLocationName !== undefined && streamHasher !== undefined; const digest = checksumRequired ? streamHasher(checksumAlgorithmFn, readableStream) : undefined; const awsChunkedEncodingStream = new stream_1.Readable({ read: () => { } }); readableStream.on("data", (data) => { const length = bodyLengthChecker(data) || 0; awsChunkedEncodingStream.push(`${length.toString(16)}\r\n`); awsChunkedEncodingStream.push(data); awsChunkedEncodingStream.push("\r\n"); }); readableStream.on("end", async () => { awsChunkedEncodingStream.push(`0\r\n`); if (checksumRequired) { const checksum = base64Encoder(await digest); awsChunkedEncodingStream.push(`${checksumLocationName}:${checksum}\r\n`); awsChunkedEncodingStream.push(`\r\n`); } awsChunkedEncodingStream.push(null); }); return awsChunkedEncodingStream; }; exports.getAwsChunkedEncodingStream = getAwsChunkedEncodingStream; /***/ }), /***/ 56711: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.headStream = headStream; async function headStream(stream, bytes) { var _a; let byteLengthCounter = 0; const chunks = []; const reader = stream.getReader(); let isDone = false; while (!isDone) { const { done, value } = await reader.read(); if (value) { chunks.push(value); byteLengthCounter += (_a = value === null || value === void 0 ? void 0 : value.byteLength) !== null && _a !== void 0 ? _a : 0; } if (byteLengthCounter >= bytes) { break; } isDone = done; } reader.releaseLock(); const collected = new Uint8Array(Math.min(bytes, byteLengthCounter)); let offset = 0; for (const chunk of chunks) { if (chunk.byteLength > collected.byteLength - offset) { collected.set(chunk.subarray(0, collected.byteLength - offset), offset); break; } else { collected.set(chunk, offset); } offset += chunk.length; } return collected; } /***/ }), /***/ 6708: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.headStream = void 0; const stream_1 = __nccwpck_require__(12781); const headStream_browser_1 = __nccwpck_require__(56711); const stream_type_check_1 = __nccwpck_require__(57578); const headStream = (stream, bytes) => { if ((0, stream_type_check_1.isReadableStream)(stream)) { return (0, headStream_browser_1.headStream)(stream, bytes); } return new Promise((resolve, reject) => { const collector = new Collector(); collector.limit = bytes; stream.pipe(collector); stream.on("error", (err) => { collector.end(); reject(err); }); collector.on("error", reject); collector.on("finish", function () { const bytes = new Uint8Array(Buffer.concat(this.buffers)); resolve(bytes); }); }); }; exports.headStream = headStream; class Collector extends stream_1.Writable { constructor() { super(...arguments); this.buffers = []; this.limit = Infinity; this.bytesBuffered = 0; } _write(chunk, encoding, callback) { var _a; this.buffers.push(chunk); this.bytesBuffered += (_a = chunk.byteLength) !== null && _a !== void 0 ? _a : 0; if (this.bytesBuffered >= this.limit) { const excess = this.bytesBuffered - this.limit; const tailBuffer = this.buffers[this.buffers.length - 1]; this.buffers[this.buffers.length - 1] = tailBuffer.subarray(0, tailBuffer.byteLength - excess); this.emit("finish"); } callback(); } } /***/ }), /***/ 96607: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { Uint8ArrayBlobAdapter: () => Uint8ArrayBlobAdapter }); module.exports = __toCommonJS(src_exports); // src/blob/transforms.ts var import_util_base64 = __nccwpck_require__(75600); var import_util_utf8 = __nccwpck_require__(41895); function transformToString(payload, encoding = "utf-8") { if (encoding === "base64") { return (0, import_util_base64.toBase64)(payload); } return (0, import_util_utf8.toUtf8)(payload); } __name(transformToString, "transformToString"); function transformFromString(str, encoding) { if (encoding === "base64") { return Uint8ArrayBlobAdapter.mutate((0, import_util_base64.fromBase64)(str)); } return Uint8ArrayBlobAdapter.mutate((0, import_util_utf8.fromUtf8)(str)); } __name(transformFromString, "transformFromString"); // src/blob/Uint8ArrayBlobAdapter.ts var Uint8ArrayBlobAdapter = class _Uint8ArrayBlobAdapter extends Uint8Array { static { __name(this, "Uint8ArrayBlobAdapter"); } /** * @param source - such as a string or Stream. * @returns a new Uint8ArrayBlobAdapter extending Uint8Array. */ static fromString(source, encoding = "utf-8") { switch (typeof source) { case "string": return transformFromString(source, encoding); default: throw new Error(`Unsupported conversion from ${typeof source} to Uint8ArrayBlobAdapter.`); } } /** * @param source - Uint8Array to be mutated. * @returns the same Uint8Array but with prototype switched to Uint8ArrayBlobAdapter. */ static mutate(source) { Object.setPrototypeOf(source, _Uint8ArrayBlobAdapter.prototype); return source; } /** * @param encoding - default 'utf-8'. * @returns the blob as string. */ transformToString(encoding = "utf-8") { return transformToString(this, encoding); } }; // src/index.ts __reExport(src_exports, __nccwpck_require__(6982), module.exports); __reExport(src_exports, __nccwpck_require__(21927), module.exports); __reExport(src_exports, __nccwpck_require__(33259), module.exports); __reExport(src_exports, __nccwpck_require__(23636), module.exports); __reExport(src_exports, __nccwpck_require__(6708), module.exports); __reExport(src_exports, __nccwpck_require__(4515), module.exports); __reExport(src_exports, __nccwpck_require__(88321), module.exports); __reExport(src_exports, __nccwpck_require__(57578), module.exports); // Annotate the CommonJS export names for ESM import in node: 0 && (0); /***/ }), /***/ 12942: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.sdkStreamMixin = void 0; const fetch_http_handler_1 = __nccwpck_require__(82687); const util_base64_1 = __nccwpck_require__(75600); const util_hex_encoding_1 = __nccwpck_require__(45364); const util_utf8_1 = __nccwpck_require__(41895); const stream_type_check_1 = __nccwpck_require__(57578); const ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = "The stream has already been transformed."; const sdkStreamMixin = (stream) => { var _a, _b; if (!isBlobInstance(stream) && !(0, stream_type_check_1.isReadableStream)(stream)) { const name = ((_b = (_a = stream === null || stream === void 0 ? void 0 : stream.__proto__) === null || _a === void 0 ? void 0 : _a.constructor) === null || _b === void 0 ? void 0 : _b.name) || stream; throw new Error(`Unexpected stream implementation, expect Blob or ReadableStream, got ${name}`); } let transformed = false; const transformToByteArray = async () => { if (transformed) { throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); } transformed = true; return await (0, fetch_http_handler_1.streamCollector)(stream); }; const blobToWebStream = (blob) => { if (typeof blob.stream !== "function") { throw new Error("Cannot transform payload Blob to web stream. Please make sure the Blob.stream() is polyfilled.\n" + "If you are using React Native, this API is not yet supported, see: https://react-native.canny.io/feature-requests/p/fetch-streaming-body"); } return blob.stream(); }; return Object.assign(stream, { transformToByteArray: transformToByteArray, transformToString: async (encoding) => { const buf = await transformToByteArray(); if (encoding === "base64") { return (0, util_base64_1.toBase64)(buf); } else if (encoding === "hex") { return (0, util_hex_encoding_1.toHex)(buf); } else if (encoding === undefined || encoding === "utf8" || encoding === "utf-8") { return (0, util_utf8_1.toUtf8)(buf); } else if (typeof TextDecoder === "function") { return new TextDecoder(encoding).decode(buf); } else { throw new Error("TextDecoder is not available, please make sure polyfill is provided."); } }, transformToWebStream: () => { if (transformed) { throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); } transformed = true; if (isBlobInstance(stream)) { return blobToWebStream(stream); } else if ((0, stream_type_check_1.isReadableStream)(stream)) { return stream; } else { throw new Error(`Cannot transform payload to web stream, got ${stream}`); } }, }); }; exports.sdkStreamMixin = sdkStreamMixin; const isBlobInstance = (stream) => typeof Blob === "function" && stream instanceof Blob; /***/ }), /***/ 4515: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.sdkStreamMixin = void 0; const node_http_handler_1 = __nccwpck_require__(20258); const util_buffer_from_1 = __nccwpck_require__(31381); const stream_1 = __nccwpck_require__(12781); const sdk_stream_mixin_browser_1 = __nccwpck_require__(12942); const ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = "The stream has already been transformed."; const sdkStreamMixin = (stream) => { var _a, _b; if (!(stream instanceof stream_1.Readable)) { try { return (0, sdk_stream_mixin_browser_1.sdkStreamMixin)(stream); } catch (e) { const name = ((_b = (_a = stream === null || stream === void 0 ? void 0 : stream.__proto__) === null || _a === void 0 ? void 0 : _a.constructor) === null || _b === void 0 ? void 0 : _b.name) || stream; throw new Error(`Unexpected stream implementation, expect Stream.Readable instance, got ${name}`); } } let transformed = false; const transformToByteArray = async () => { if (transformed) { throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); } transformed = true; return await (0, node_http_handler_1.streamCollector)(stream); }; return Object.assign(stream, { transformToByteArray, transformToString: async (encoding) => { const buf = await transformToByteArray(); if (encoding === undefined || Buffer.isEncoding(encoding)) { return (0, util_buffer_from_1.fromArrayBuffer)(buf.buffer, buf.byteOffset, buf.byteLength).toString(encoding); } else { const decoder = new TextDecoder(encoding); return decoder.decode(buf); } }, transformToWebStream: () => { if (transformed) { throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); } if (stream.readableFlowing !== null) { throw new Error("The stream has been consumed by other callbacks."); } if (typeof stream_1.Readable.toWeb !== "function") { throw new Error("Readable.toWeb() is not supported. Please ensure a polyfill is available."); } transformed = true; return stream_1.Readable.toWeb(stream); }, }); }; exports.sdkStreamMixin = sdkStreamMixin; /***/ }), /***/ 64693: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.splitStream = splitStream; async function splitStream(stream) { if (typeof stream.stream === "function") { stream = stream.stream(); } const readableStream = stream; return readableStream.tee(); } /***/ }), /***/ 88321: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.splitStream = splitStream; const stream_1 = __nccwpck_require__(12781); const splitStream_browser_1 = __nccwpck_require__(64693); const stream_type_check_1 = __nccwpck_require__(57578); async function splitStream(stream) { if ((0, stream_type_check_1.isReadableStream)(stream) || (0, stream_type_check_1.isBlob)(stream)) { return (0, splitStream_browser_1.splitStream)(stream); } const stream1 = new stream_1.PassThrough(); const stream2 = new stream_1.PassThrough(); stream.pipe(stream1); stream.pipe(stream2); return [stream1, stream2]; } /***/ }), /***/ 57578: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isBlob = exports.isReadableStream = void 0; const isReadableStream = (stream) => { var _a; return typeof ReadableStream === "function" && (((_a = stream === null || stream === void 0 ? void 0 : stream.constructor) === null || _a === void 0 ? void 0 : _a.name) === ReadableStream.name || stream instanceof ReadableStream); }; exports.isReadableStream = isReadableStream; const isBlob = (blob) => { var _a; return typeof Blob === "function" && (((_a = blob === null || blob === void 0 ? void 0 : blob.constructor) === null || _a === void 0 ? void 0 : _a.name) === Blob.name || blob instanceof Blob); }; exports.isBlob = isBlob; /***/ }), /***/ 54197: /***/ ((module) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { escapeUri: () => escapeUri, escapeUriPath: () => escapeUriPath }); module.exports = __toCommonJS(src_exports); // src/escape-uri.ts var escapeUri = /* @__PURE__ */ __name((uri) => ( // AWS percent-encodes some extra non-standard characters in a URI encodeURIComponent(uri).replace(/[!'()*]/g, hexEncode) ), "escapeUri"); var hexEncode = /* @__PURE__ */ __name((c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`, "hexEncode"); // src/escape-uri-path.ts var escapeUriPath = /* @__PURE__ */ __name((uri) => uri.split("/").map(escapeUri).join("/"), "escapeUriPath"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); /***/ }), /***/ 41895: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { fromUtf8: () => fromUtf8, toUint8Array: () => toUint8Array, toUtf8: () => toUtf8 }); module.exports = __toCommonJS(src_exports); // src/fromUtf8.ts var import_util_buffer_from = __nccwpck_require__(31381); var fromUtf8 = /* @__PURE__ */ __name((input) => { const buf = (0, import_util_buffer_from.fromString)(input, "utf8"); return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT); }, "fromUtf8"); // src/toUint8Array.ts var toUint8Array = /* @__PURE__ */ __name((data) => { if (typeof data === "string") { return fromUtf8(data); } if (ArrayBuffer.isView(data)) { return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT); } return new Uint8Array(data); }, "toUint8Array"); // src/toUtf8.ts var toUtf8 = /* @__PURE__ */ __name((input) => { if (typeof input === "string") { return input; } if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array."); } return (0, import_util_buffer_from.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("utf8"); }, "toUtf8"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); /***/ }), /***/ 78011: /***/ ((module) => { var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { WaiterState: () => WaiterState, checkExceptions: () => checkExceptions, createWaiter: () => createWaiter, waiterServiceDefaults: () => waiterServiceDefaults }); module.exports = __toCommonJS(src_exports); // src/utils/sleep.ts var sleep = /* @__PURE__ */ __name((seconds) => { return new Promise((resolve) => setTimeout(resolve, seconds * 1e3)); }, "sleep"); // src/waiter.ts var waiterServiceDefaults = { minDelay: 2, maxDelay: 120 }; var WaiterState = /* @__PURE__ */ ((WaiterState2) => { WaiterState2["ABORTED"] = "ABORTED"; WaiterState2["FAILURE"] = "FAILURE"; WaiterState2["SUCCESS"] = "SUCCESS"; WaiterState2["RETRY"] = "RETRY"; WaiterState2["TIMEOUT"] = "TIMEOUT"; return WaiterState2; })(WaiterState || {}); var checkExceptions = /* @__PURE__ */ __name((result) => { if (result.state === "ABORTED" /* ABORTED */) { const abortError = new Error( `${JSON.stringify({ ...result, reason: "Request was aborted" })}` ); abortError.name = "AbortError"; throw abortError; } else if (result.state === "TIMEOUT" /* TIMEOUT */) { const timeoutError = new Error( `${JSON.stringify({ ...result, reason: "Waiter has timed out" })}` ); timeoutError.name = "TimeoutError"; throw timeoutError; } else if (result.state !== "SUCCESS" /* SUCCESS */) { throw new Error(`${JSON.stringify(result)}`); } return result; }, "checkExceptions"); // src/poller.ts var exponentialBackoffWithJitter = /* @__PURE__ */ __name((minDelay, maxDelay, attemptCeiling, attempt) => { if (attempt > attemptCeiling) return maxDelay; const delay = minDelay * 2 ** (attempt - 1); return randomInRange(minDelay, delay); }, "exponentialBackoffWithJitter"); var randomInRange = /* @__PURE__ */ __name((min, max) => min + Math.random() * (max - min), "randomInRange"); var runPolling = /* @__PURE__ */ __name(async ({ minDelay, maxDelay, maxWaitTime, abortController, client, abortSignal }, input, acceptorChecks) => { const observedResponses = {}; const { state, reason } = await acceptorChecks(client, input); if (reason) { const message = createMessageFromResponse(reason); observedResponses[message] |= 0; observedResponses[message] += 1; } if (state !== "RETRY" /* RETRY */) { return { state, reason, observedResponses }; } let currentAttempt = 1; const waitUntil = Date.now() + maxWaitTime * 1e3; const attemptCeiling = Math.log(maxDelay / minDelay) / Math.log(2) + 1; while (true) { if (abortController?.signal?.aborted || abortSignal?.aborted) { const message = "AbortController signal aborted."; observedResponses[message] |= 0; observedResponses[message] += 1; return { state: "ABORTED" /* ABORTED */, observedResponses }; } const delay = exponentialBackoffWithJitter(minDelay, maxDelay, attemptCeiling, currentAttempt); if (Date.now() + delay * 1e3 > waitUntil) { return { state: "TIMEOUT" /* TIMEOUT */, observedResponses }; } await sleep(delay); const { state: state2, reason: reason2 } = await acceptorChecks(client, input); if (reason2) { const message = createMessageFromResponse(reason2); observedResponses[message] |= 0; observedResponses[message] += 1; } if (state2 !== "RETRY" /* RETRY */) { return { state: state2, reason: reason2, observedResponses }; } currentAttempt += 1; } }, "runPolling"); var createMessageFromResponse = /* @__PURE__ */ __name((reason) => { if (reason?.$responseBodyText) { return `Deserialization error for body: ${reason.$responseBodyText}`; } if (reason?.$metadata?.httpStatusCode) { if (reason.$response || reason.message) { return `${reason.$response.statusCode ?? reason.$metadata.httpStatusCode ?? "Unknown"}: ${reason.message}`; } return `${reason.$metadata.httpStatusCode}: OK`; } return String(reason?.message ?? JSON.stringify(reason) ?? "Unknown"); }, "createMessageFromResponse"); // src/utils/validate.ts var validateWaiterOptions = /* @__PURE__ */ __name((options) => { if (options.maxWaitTime <= 0) { throw new Error(`WaiterConfiguration.maxWaitTime must be greater than 0`); } else if (options.minDelay <= 0) { throw new Error(`WaiterConfiguration.minDelay must be greater than 0`); } else if (options.maxDelay <= 0) { throw new Error(`WaiterConfiguration.maxDelay must be greater than 0`); } else if (options.maxWaitTime <= options.minDelay) { throw new Error( `WaiterConfiguration.maxWaitTime [${options.maxWaitTime}] must be greater than WaiterConfiguration.minDelay [${options.minDelay}] for this waiter` ); } else if (options.maxDelay < options.minDelay) { throw new Error( `WaiterConfiguration.maxDelay [${options.maxDelay}] must be greater than WaiterConfiguration.minDelay [${options.minDelay}] for this waiter` ); } }, "validateWaiterOptions"); // src/createWaiter.ts var abortTimeout = /* @__PURE__ */ __name(async (abortSignal) => { return new Promise((resolve) => { const onAbort = /* @__PURE__ */ __name(() => resolve({ state: "ABORTED" /* ABORTED */ }), "onAbort"); if (typeof abortSignal.addEventListener === "function") { abortSignal.addEventListener("abort", onAbort); } else { abortSignal.onabort = onAbort; } }); }, "abortTimeout"); var createWaiter = /* @__PURE__ */ __name(async (options, input, acceptorChecks) => { const params = { ...waiterServiceDefaults, ...options }; validateWaiterOptions(params); const exitConditions = [runPolling(params, input, acceptorChecks)]; if (options.abortController) { exitConditions.push(abortTimeout(options.abortController.signal)); } if (options.abortSignal) { exitConditions.push(abortTimeout(options.abortSignal)); } return Promise.race(exitConditions); }, "createWaiter"); // Annotate the CommonJS export names for ESM import in node: 0 && (0); /***/ }), /***/ 61231: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const indentString = __nccwpck_require__(98043); const cleanStack = __nccwpck_require__(27972); const cleanInternalStack = stack => stack.replace(/\s+at .*aggregate-error\/index.js:\d+:\d+\)?/g, ''); class AggregateError extends Error { constructor(errors) { if (!Array.isArray(errors)) { throw new TypeError(`Expected input to be an Array, got ${typeof errors}`); } errors = [...errors].map(error => { if (error instanceof Error) { return error; } if (error !== null && typeof error === 'object') { // Handle plain error objects with message property and/or possibly other metadata return Object.assign(new Error(error.message), error); } return new Error(error); }); let message = errors .map(error => { // The `stack` property is not standardized, so we can't assume it exists return typeof error.stack === 'string' ? cleanInternalStack(cleanStack(error.stack)) : String(error); }) .join('\n'); message = '\n' + indentString(message, 4); super(message); this.name = 'AggregateError'; Object.defineProperty(this, '_errors', {value: errors}); } * [Symbol.iterator]() { for (const error of this._errors) { yield error; } } } module.exports = AggregateError; /***/ }), /***/ 64941: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var compileSchema = __nccwpck_require__(875) , resolve = __nccwpck_require__(63896) , Cache = __nccwpck_require__(93679) , SchemaObject = __nccwpck_require__(37605) , stableStringify = __nccwpck_require__(30969) , formats = __nccwpck_require__(66627) , rules = __nccwpck_require__(68561) , $dataMetaSchema = __nccwpck_require__(21412) , util = __nccwpck_require__(76578); module.exports = Ajv; Ajv.prototype.validate = validate; Ajv.prototype.compile = compile; Ajv.prototype.addSchema = addSchema; Ajv.prototype.addMetaSchema = addMetaSchema; Ajv.prototype.validateSchema = validateSchema; Ajv.prototype.getSchema = getSchema; Ajv.prototype.removeSchema = removeSchema; Ajv.prototype.addFormat = addFormat; Ajv.prototype.errorsText = errorsText; Ajv.prototype._addSchema = _addSchema; Ajv.prototype._compile = _compile; Ajv.prototype.compileAsync = __nccwpck_require__(80890); var customKeyword = __nccwpck_require__(53297); Ajv.prototype.addKeyword = customKeyword.add; Ajv.prototype.getKeyword = customKeyword.get; Ajv.prototype.removeKeyword = customKeyword.remove; Ajv.prototype.validateKeyword = customKeyword.validate; var errorClasses = __nccwpck_require__(25726); Ajv.ValidationError = errorClasses.Validation; Ajv.MissingRefError = errorClasses.MissingRef; Ajv.$dataMetaSchema = $dataMetaSchema; var META_SCHEMA_ID = 'http://json-schema.org/draft-07/schema'; var META_IGNORE_OPTIONS = [ 'removeAdditional', 'useDefaults', 'coerceTypes', 'strictDefaults' ]; var META_SUPPORT_DATA = ['/properties']; /** * Creates validator instance. * Usage: `Ajv(opts)` * @param {Object} opts optional options * @return {Object} ajv instance */ function Ajv(opts) { if (!(this instanceof Ajv)) return new Ajv(opts); opts = this._opts = util.copy(opts) || {}; setLogger(this); this._schemas = {}; this._refs = {}; this._fragments = {}; this._formats = formats(opts.format); this._cache = opts.cache || new Cache; this._loadingSchemas = {}; this._compilations = []; this.RULES = rules(); this._getId = chooseGetId(opts); opts.loopRequired = opts.loopRequired || Infinity; if (opts.errorDataPath == 'property') opts._errorDataPathProperty = true; if (opts.serialize === undefined) opts.serialize = stableStringify; this._metaOpts = getMetaSchemaOptions(this); if (opts.formats) addInitialFormats(this); if (opts.keywords) addInitialKeywords(this); addDefaultMetaSchema(this); if (typeof opts.meta == 'object') this.addMetaSchema(opts.meta); if (opts.nullable) this.addKeyword('nullable', {metaSchema: {type: 'boolean'}}); addInitialSchemas(this); } /** * Validate data using schema * Schema will be compiled and cached (using serialized JSON as key. [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) is used to serialize. * @this Ajv * @param {String|Object} schemaKeyRef key, ref or schema object * @param {Any} data to be validated * @return {Boolean} validation result. Errors from the last validation will be available in `ajv.errors` (and also in compiled schema: `schema.errors`). */ function validate(schemaKeyRef, data) { var v; if (typeof schemaKeyRef == 'string') { v = this.getSchema(schemaKeyRef); if (!v) throw new Error('no schema with key or ref "' + schemaKeyRef + '"'); } else { var schemaObj = this._addSchema(schemaKeyRef); v = schemaObj.validate || this._compile(schemaObj); } var valid = v(data); if (v.$async !== true) this.errors = v.errors; return valid; } /** * Create validating function for passed schema. * @this Ajv * @param {Object} schema schema object * @param {Boolean} _meta true if schema is a meta-schema. Used internally to compile meta schemas of custom keywords. * @return {Function} validating function */ function compile(schema, _meta) { var schemaObj = this._addSchema(schema, undefined, _meta); return schemaObj.validate || this._compile(schemaObj); } /** * Adds schema to the instance. * @this Ajv * @param {Object|Array} schema schema or array of schemas. If array is passed, `key` and other parameters will be ignored. * @param {String} key Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`. * @param {Boolean} _skipValidation true to skip schema validation. Used internally, option validateSchema should be used instead. * @param {Boolean} _meta true if schema is a meta-schema. Used internally, addMetaSchema should be used instead. * @return {Ajv} this for method chaining */ function addSchema(schema, key, _skipValidation, _meta) { if (Array.isArray(schema)){ for (var i=0; i} errors optional array of validation errors, if not passed errors from the instance are used. * @param {Object} options optional options with properties `separator` and `dataVar`. * @return {String} human readable string with all errors descriptions */ function errorsText(errors, options) { errors = errors || this.errors; if (!errors) return 'No errors'; options = options || {}; var separator = options.separator === undefined ? ', ' : options.separator; var dataVar = options.dataVar === undefined ? 'data' : options.dataVar; var text = ''; for (var i=0; i { "use strict"; var Cache = module.exports = function Cache() { this._cache = {}; }; Cache.prototype.put = function Cache_put(key, value) { this._cache[key] = value; }; Cache.prototype.get = function Cache_get(key) { return this._cache[key]; }; Cache.prototype.del = function Cache_del(key) { delete this._cache[key]; }; Cache.prototype.clear = function Cache_clear() { this._cache = {}; }; /***/ }), /***/ 80890: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var MissingRefError = (__nccwpck_require__(25726).MissingRef); module.exports = compileAsync; /** * Creates validating function for passed schema with asynchronous loading of missing schemas. * `loadSchema` option should be a function that accepts schema uri and returns promise that resolves with the schema. * @this Ajv * @param {Object} schema schema object * @param {Boolean} meta optional true to compile meta-schema; this parameter can be skipped * @param {Function} callback an optional node-style callback, it is called with 2 parameters: error (or null) and validating function. * @return {Promise} promise that resolves with a validating function. */ function compileAsync(schema, meta, callback) { /* eslint no-shadow: 0 */ /* global Promise */ /* jshint validthis: true */ var self = this; if (typeof this._opts.loadSchema != 'function') throw new Error('options.loadSchema should be a function'); if (typeof meta == 'function') { callback = meta; meta = undefined; } var p = loadMetaSchemaOf(schema).then(function () { var schemaObj = self._addSchema(schema, undefined, meta); return schemaObj.validate || _compileAsync(schemaObj); }); if (callback) { p.then( function(v) { callback(null, v); }, callback ); } return p; function loadMetaSchemaOf(sch) { var $schema = sch.$schema; return $schema && !self.getSchema($schema) ? compileAsync.call(self, { $ref: $schema }, true) : Promise.resolve(); } function _compileAsync(schemaObj) { try { return self._compile(schemaObj); } catch(e) { if (e instanceof MissingRefError) return loadMissingSchema(e); throw e; } function loadMissingSchema(e) { var ref = e.missingSchema; if (added(ref)) throw new Error('Schema ' + ref + ' is loaded but ' + e.missingRef + ' cannot be resolved'); var schemaPromise = self._loadingSchemas[ref]; if (!schemaPromise) { schemaPromise = self._loadingSchemas[ref] = self._opts.loadSchema(ref); schemaPromise.then(removePromise, removePromise); } return schemaPromise.then(function (sch) { if (!added(ref)) { return loadMetaSchemaOf(sch).then(function () { if (!added(ref)) self.addSchema(sch, ref, undefined, meta); }); } }).then(function() { return _compileAsync(schemaObj); }); function removePromise() { delete self._loadingSchemas[ref]; } function added(ref) { return self._refs[ref] || self._schemas[ref]; } } } } /***/ }), /***/ 25726: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var resolve = __nccwpck_require__(63896); module.exports = { Validation: errorSubclass(ValidationError), MissingRef: errorSubclass(MissingRefError) }; function ValidationError(errors) { this.message = 'validation failed'; this.errors = errors; this.ajv = this.validation = true; } MissingRefError.message = function (baseId, ref) { return 'can\'t resolve reference ' + ref + ' from id ' + baseId; }; function MissingRefError(baseId, ref, message) { this.message = message || MissingRefError.message(baseId, ref); this.missingRef = resolve.url(baseId, ref); this.missingSchema = resolve.normalizeId(resolve.fullPath(this.missingRef)); } function errorSubclass(Subclass) { Subclass.prototype = Object.create(Error.prototype); Subclass.prototype.constructor = Subclass; return Subclass; } /***/ }), /***/ 66627: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var util = __nccwpck_require__(76578); var DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/; var DAYS = [0,31,28,31,30,31,30,31,31,30,31,30,31]; var TIME = /^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i; var HOSTNAME = /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i; var URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; var URIREF = /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; // uri-template: https://tools.ietf.org/html/rfc6570 var URITEMPLATE = /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i; // For the source: https://gist.github.com/dperini/729294 // For test cases: https://mathiasbynens.be/demo/url-regex // @todo Delete current URL in favour of the commented out URL rule when this issue is fixed https://github.com/eslint/eslint/issues/7983. // var URL = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu; var URL = /^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i; var UUID = /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i; var JSON_POINTER = /^(?:\/(?:[^~/]|~0|~1)*)*$/; var JSON_POINTER_URI_FRAGMENT = /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i; var RELATIVE_JSON_POINTER = /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/; module.exports = formats; function formats(mode) { mode = mode == 'full' ? 'full' : 'fast'; return util.copy(formats[mode]); } formats.fast = { // date: http://tools.ietf.org/html/rfc3339#section-5.6 date: /^\d\d\d\d-[0-1]\d-[0-3]\d$/, // date-time: http://tools.ietf.org/html/rfc3339#section-5.6 time: /^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, 'date-time': /^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i, 'uri-reference': /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i, 'uri-template': URITEMPLATE, url: URL, // email (sources from jsen validator): // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363 // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'willful violation') email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i, hostname: HOSTNAME, // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/, // optimized http://stackoverflow.com/questions/53497/regular-expression-that-matches-valid-ipv6-addresses ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i, regex: regex, // uuid: http://tools.ietf.org/html/rfc4122 uuid: UUID, // JSON-pointer: https://tools.ietf.org/html/rfc6901 // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A 'json-pointer': JSON_POINTER, 'json-pointer-uri-fragment': JSON_POINTER_URI_FRAGMENT, // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00 'relative-json-pointer': RELATIVE_JSON_POINTER }; formats.full = { date: date, time: time, 'date-time': date_time, uri: uri, 'uri-reference': URIREF, 'uri-template': URITEMPLATE, url: URL, email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i, hostname: HOSTNAME, ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/, ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i, regex: regex, uuid: UUID, 'json-pointer': JSON_POINTER, 'json-pointer-uri-fragment': JSON_POINTER_URI_FRAGMENT, 'relative-json-pointer': RELATIVE_JSON_POINTER }; function isLeapYear(year) { // https://tools.ietf.org/html/rfc3339#appendix-C return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); } function date(str) { // full-date from http://tools.ietf.org/html/rfc3339#section-5.6 var matches = str.match(DATE); if (!matches) return false; var year = +matches[1]; var month = +matches[2]; var day = +matches[3]; return month >= 1 && month <= 12 && day >= 1 && day <= (month == 2 && isLeapYear(year) ? 29 : DAYS[month]); } function time(str, full) { var matches = str.match(TIME); if (!matches) return false; var hour = matches[1]; var minute = matches[2]; var second = matches[3]; var timeZone = matches[5]; return ((hour <= 23 && minute <= 59 && second <= 59) || (hour == 23 && minute == 59 && second == 60)) && (!full || timeZone); } var DATE_TIME_SEPARATOR = /t|\s/i; function date_time(str) { // http://tools.ietf.org/html/rfc3339#section-5.6 var dateTime = str.split(DATE_TIME_SEPARATOR); return dateTime.length == 2 && date(dateTime[0]) && time(dateTime[1], true); } var NOT_URI_FRAGMENT = /\/|:/; function uri(str) { // http://jmrware.com/articles/2009/uri_regexp/URI_regex.html + optional protocol + required "." return NOT_URI_FRAGMENT.test(str) && URI.test(str); } var Z_ANCHOR = /[^\\]\\Z/; function regex(str) { if (Z_ANCHOR.test(str)) return false; try { new RegExp(str); return true; } catch(e) { return false; } } /***/ }), /***/ 875: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var resolve = __nccwpck_require__(63896) , util = __nccwpck_require__(76578) , errorClasses = __nccwpck_require__(25726) , stableStringify = __nccwpck_require__(30969); var validateGenerator = __nccwpck_require__(49585); /** * Functions below are used inside compiled validations function */ var ucs2length = util.ucs2length; var equal = __nccwpck_require__(28206); // this error is thrown by async schemas to return validation errors via exception var ValidationError = errorClasses.Validation; module.exports = compile; /** * Compiles schema to validation function * @this Ajv * @param {Object} schema schema object * @param {Object} root object with information about the root schema for this schema * @param {Object} localRefs the hash of local references inside the schema (created by resolve.id), used for inline resolution * @param {String} baseId base ID for IDs in the schema * @return {Function} validation function */ function compile(schema, root, localRefs, baseId) { /* jshint validthis: true, evil: true */ /* eslint no-shadow: 0 */ var self = this , opts = this._opts , refVal = [ undefined ] , refs = {} , patterns = [] , patternsHash = {} , defaults = [] , defaultsHash = {} , customRules = []; root = root || { schema: schema, refVal: refVal, refs: refs }; var c = checkCompiling.call(this, schema, root, baseId); var compilation = this._compilations[c.index]; if (c.compiling) return (compilation.callValidate = callValidate); var formats = this._formats; var RULES = this.RULES; try { var v = localCompile(schema, root, localRefs, baseId); compilation.validate = v; var cv = compilation.callValidate; if (cv) { cv.schema = v.schema; cv.errors = null; cv.refs = v.refs; cv.refVal = v.refVal; cv.root = v.root; cv.$async = v.$async; if (opts.sourceCode) cv.source = v.source; } return v; } finally { endCompiling.call(this, schema, root, baseId); } /* @this {*} - custom context, see passContext option */ function callValidate() { /* jshint validthis: true */ var validate = compilation.validate; var result = validate.apply(this, arguments); callValidate.errors = validate.errors; return result; } function localCompile(_schema, _root, localRefs, baseId) { var isRoot = !_root || (_root && _root.schema == _schema); if (_root.schema != root.schema) return compile.call(self, _schema, _root, localRefs, baseId); var $async = _schema.$async === true; var sourceCode = validateGenerator({ isTop: true, schema: _schema, isRoot: isRoot, baseId: baseId, root: _root, schemaPath: '', errSchemaPath: '#', errorPath: '""', MissingRefError: errorClasses.MissingRef, RULES: RULES, validate: validateGenerator, util: util, resolve: resolve, resolveRef: resolveRef, usePattern: usePattern, useDefault: useDefault, useCustomRule: useCustomRule, opts: opts, formats: formats, logger: self.logger, self: self }); sourceCode = vars(refVal, refValCode) + vars(patterns, patternCode) + vars(defaults, defaultCode) + vars(customRules, customRuleCode) + sourceCode; if (opts.processCode) sourceCode = opts.processCode(sourceCode, _schema); // console.log('\n\n\n *** \n', JSON.stringify(sourceCode)); var validate; try { var makeValidate = new Function( 'self', 'RULES', 'formats', 'root', 'refVal', 'defaults', 'customRules', 'equal', 'ucs2length', 'ValidationError', sourceCode ); validate = makeValidate( self, RULES, formats, root, refVal, defaults, customRules, equal, ucs2length, ValidationError ); refVal[0] = validate; } catch(e) { self.logger.error('Error compiling schema, function code:', sourceCode); throw e; } validate.schema = _schema; validate.errors = null; validate.refs = refs; validate.refVal = refVal; validate.root = isRoot ? validate : _root; if ($async) validate.$async = true; if (opts.sourceCode === true) { validate.source = { code: sourceCode, patterns: patterns, defaults: defaults }; } return validate; } function resolveRef(baseId, ref, isRoot) { ref = resolve.url(baseId, ref); var refIndex = refs[ref]; var _refVal, refCode; if (refIndex !== undefined) { _refVal = refVal[refIndex]; refCode = 'refVal[' + refIndex + ']'; return resolvedRef(_refVal, refCode); } if (!isRoot && root.refs) { var rootRefId = root.refs[ref]; if (rootRefId !== undefined) { _refVal = root.refVal[rootRefId]; refCode = addLocalRef(ref, _refVal); return resolvedRef(_refVal, refCode); } } refCode = addLocalRef(ref); var v = resolve.call(self, localCompile, root, ref); if (v === undefined) { var localSchema = localRefs && localRefs[ref]; if (localSchema) { v = resolve.inlineRef(localSchema, opts.inlineRefs) ? localSchema : compile.call(self, localSchema, root, localRefs, baseId); } } if (v === undefined) { removeLocalRef(ref); } else { replaceLocalRef(ref, v); return resolvedRef(v, refCode); } } function addLocalRef(ref, v) { var refId = refVal.length; refVal[refId] = v; refs[ref] = refId; return 'refVal' + refId; } function removeLocalRef(ref) { delete refs[ref]; } function replaceLocalRef(ref, v) { var refId = refs[ref]; refVal[refId] = v; } function resolvedRef(refVal, code) { return typeof refVal == 'object' || typeof refVal == 'boolean' ? { code: code, schema: refVal, inline: true } : { code: code, $async: refVal && !!refVal.$async }; } function usePattern(regexStr) { var index = patternsHash[regexStr]; if (index === undefined) { index = patternsHash[regexStr] = patterns.length; patterns[index] = regexStr; } return 'pattern' + index; } function useDefault(value) { switch (typeof value) { case 'boolean': case 'number': return '' + value; case 'string': return util.toQuotedString(value); case 'object': if (value === null) return 'null'; var valueStr = stableStringify(value); var index = defaultsHash[valueStr]; if (index === undefined) { index = defaultsHash[valueStr] = defaults.length; defaults[index] = value; } return 'default' + index; } } function useCustomRule(rule, schema, parentSchema, it) { if (self._opts.validateSchema !== false) { var deps = rule.definition.dependencies; if (deps && !deps.every(function(keyword) { return Object.prototype.hasOwnProperty.call(parentSchema, keyword); })) throw new Error('parent schema must have all required keywords: ' + deps.join(',')); var validateSchema = rule.definition.validateSchema; if (validateSchema) { var valid = validateSchema(schema); if (!valid) { var message = 'keyword schema is invalid: ' + self.errorsText(validateSchema.errors); if (self._opts.validateSchema == 'log') self.logger.error(message); else throw new Error(message); } } } var compile = rule.definition.compile , inline = rule.definition.inline , macro = rule.definition.macro; var validate; if (compile) { validate = compile.call(self, schema, parentSchema, it); } else if (macro) { validate = macro.call(self, schema, parentSchema, it); if (opts.validateSchema !== false) self.validateSchema(validate, true); } else if (inline) { validate = inline.call(self, it, rule.keyword, schema, parentSchema); } else { validate = rule.definition.validate; if (!validate) return; } if (validate === undefined) throw new Error('custom keyword "' + rule.keyword + '"failed to compile'); var index = customRules.length; customRules[index] = validate; return { code: 'customRule' + index, validate: validate }; } } /** * Checks if the schema is currently compiled * @this Ajv * @param {Object} schema schema to compile * @param {Object} root root object * @param {String} baseId base schema ID * @return {Object} object with properties "index" (compilation index) and "compiling" (boolean) */ function checkCompiling(schema, root, baseId) { /* jshint validthis: true */ var index = compIndex.call(this, schema, root, baseId); if (index >= 0) return { index: index, compiling: true }; index = this._compilations.length; this._compilations[index] = { schema: schema, root: root, baseId: baseId }; return { index: index, compiling: false }; } /** * Removes the schema from the currently compiled list * @this Ajv * @param {Object} schema schema to compile * @param {Object} root root object * @param {String} baseId base schema ID */ function endCompiling(schema, root, baseId) { /* jshint validthis: true */ var i = compIndex.call(this, schema, root, baseId); if (i >= 0) this._compilations.splice(i, 1); } /** * Index of schema compilation in the currently compiled list * @this Ajv * @param {Object} schema schema to compile * @param {Object} root root object * @param {String} baseId base schema ID * @return {Integer} compilation index */ function compIndex(schema, root, baseId) { /* jshint validthis: true */ for (var i=0; i { "use strict"; var URI = __nccwpck_require__(70020) , equal = __nccwpck_require__(28206) , util = __nccwpck_require__(76578) , SchemaObject = __nccwpck_require__(37605) , traverse = __nccwpck_require__(52533); module.exports = resolve; resolve.normalizeId = normalizeId; resolve.fullPath = getFullPath; resolve.url = resolveUrl; resolve.ids = resolveIds; resolve.inlineRef = inlineRef; resolve.schema = resolveSchema; /** * [resolve and compile the references ($ref)] * @this Ajv * @param {Function} compile reference to schema compilation funciton (localCompile) * @param {Object} root object with information about the root schema for the current schema * @param {String} ref reference to resolve * @return {Object|Function} schema object (if the schema can be inlined) or validation function */ function resolve(compile, root, ref) { /* jshint validthis: true */ var refVal = this._refs[ref]; if (typeof refVal == 'string') { if (this._refs[refVal]) refVal = this._refs[refVal]; else return resolve.call(this, compile, root, refVal); } refVal = refVal || this._schemas[ref]; if (refVal instanceof SchemaObject) { return inlineRef(refVal.schema, this._opts.inlineRefs) ? refVal.schema : refVal.validate || this._compile(refVal); } var res = resolveSchema.call(this, root, ref); var schema, v, baseId; if (res) { schema = res.schema; root = res.root; baseId = res.baseId; } if (schema instanceof SchemaObject) { v = schema.validate || compile.call(this, schema.schema, root, undefined, baseId); } else if (schema !== undefined) { v = inlineRef(schema, this._opts.inlineRefs) ? schema : compile.call(this, schema, root, undefined, baseId); } return v; } /** * Resolve schema, its root and baseId * @this Ajv * @param {Object} root root object with properties schema, refVal, refs * @param {String} ref reference to resolve * @return {Object} object with properties schema, root, baseId */ function resolveSchema(root, ref) { /* jshint validthis: true */ var p = URI.parse(ref) , refPath = _getFullPath(p) , baseId = getFullPath(this._getId(root.schema)); if (Object.keys(root.schema).length === 0 || refPath !== baseId) { var id = normalizeId(refPath); var refVal = this._refs[id]; if (typeof refVal == 'string') { return resolveRecursive.call(this, root, refVal, p); } else if (refVal instanceof SchemaObject) { if (!refVal.validate) this._compile(refVal); root = refVal; } else { refVal = this._schemas[id]; if (refVal instanceof SchemaObject) { if (!refVal.validate) this._compile(refVal); if (id == normalizeId(ref)) return { schema: refVal, root: root, baseId: baseId }; root = refVal; } else { return; } } if (!root.schema) return; baseId = getFullPath(this._getId(root.schema)); } return getJsonPointer.call(this, p, baseId, root.schema, root); } /* @this Ajv */ function resolveRecursive(root, ref, parsedRef) { /* jshint validthis: true */ var res = resolveSchema.call(this, root, ref); if (res) { var schema = res.schema; var baseId = res.baseId; root = res.root; var id = this._getId(schema); if (id) baseId = resolveUrl(baseId, id); return getJsonPointer.call(this, parsedRef, baseId, schema, root); } } var PREVENT_SCOPE_CHANGE = util.toHash(['properties', 'patternProperties', 'enum', 'dependencies', 'definitions']); /* @this Ajv */ function getJsonPointer(parsedRef, baseId, schema, root) { /* jshint validthis: true */ parsedRef.fragment = parsedRef.fragment || ''; if (parsedRef.fragment.slice(0,1) != '/') return; var parts = parsedRef.fragment.split('/'); for (var i = 1; i < parts.length; i++) { var part = parts[i]; if (part) { part = util.unescapeFragment(part); schema = schema[part]; if (schema === undefined) break; var id; if (!PREVENT_SCOPE_CHANGE[part]) { id = this._getId(schema); if (id) baseId = resolveUrl(baseId, id); if (schema.$ref) { var $ref = resolveUrl(baseId, schema.$ref); var res = resolveSchema.call(this, root, $ref); if (res) { schema = res.schema; root = res.root; baseId = res.baseId; } } } } } if (schema !== undefined && schema !== root.schema) return { schema: schema, root: root, baseId: baseId }; } var SIMPLE_INLINED = util.toHash([ 'type', 'format', 'pattern', 'maxLength', 'minLength', 'maxProperties', 'minProperties', 'maxItems', 'minItems', 'maximum', 'minimum', 'uniqueItems', 'multipleOf', 'required', 'enum' ]); function inlineRef(schema, limit) { if (limit === false) return false; if (limit === undefined || limit === true) return checkNoRef(schema); else if (limit) return countKeys(schema) <= limit; } function checkNoRef(schema) { var item; if (Array.isArray(schema)) { for (var i=0; i { "use strict"; var ruleModules = __nccwpck_require__(85810) , toHash = (__nccwpck_require__(76578).toHash); module.exports = function rules() { var RULES = [ { type: 'number', rules: [ { 'maximum': ['exclusiveMaximum'] }, { 'minimum': ['exclusiveMinimum'] }, 'multipleOf', 'format'] }, { type: 'string', rules: [ 'maxLength', 'minLength', 'pattern', 'format' ] }, { type: 'array', rules: [ 'maxItems', 'minItems', 'items', 'contains', 'uniqueItems' ] }, { type: 'object', rules: [ 'maxProperties', 'minProperties', 'required', 'dependencies', 'propertyNames', { 'properties': ['additionalProperties', 'patternProperties'] } ] }, { rules: [ '$ref', 'const', 'enum', 'not', 'anyOf', 'oneOf', 'allOf', 'if' ] } ]; var ALL = [ 'type', '$comment' ]; var KEYWORDS = [ '$schema', '$id', 'id', '$data', '$async', 'title', 'description', 'default', 'definitions', 'examples', 'readOnly', 'writeOnly', 'contentMediaType', 'contentEncoding', 'additionalItems', 'then', 'else' ]; var TYPES = [ 'number', 'integer', 'string', 'array', 'object', 'boolean', 'null' ]; RULES.all = toHash(ALL); RULES.types = toHash(TYPES); RULES.forEach(function (group) { group.rules = group.rules.map(function (keyword) { var implKeywords; if (typeof keyword == 'object') { var key = Object.keys(keyword)[0]; implKeywords = keyword[key]; keyword = key; implKeywords.forEach(function (k) { ALL.push(k); RULES.all[k] = true; }); } ALL.push(keyword); var rule = RULES.all[keyword] = { keyword: keyword, code: ruleModules[keyword], implements: implKeywords }; return rule; }); RULES.all.$comment = { keyword: '$comment', code: ruleModules.$comment }; if (group.type) RULES.types[group.type] = group; }); RULES.keywords = toHash(ALL.concat(KEYWORDS)); RULES.custom = {}; return RULES; }; /***/ }), /***/ 37605: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var util = __nccwpck_require__(76578); module.exports = SchemaObject; function SchemaObject(obj) { util.copy(obj, this); } /***/ }), /***/ 64580: /***/ ((module) => { "use strict"; // https://mathiasbynens.be/notes/javascript-encoding // https://github.com/bestiejs/punycode.js - punycode.ucs2.decode module.exports = function ucs2length(str) { var length = 0 , len = str.length , pos = 0 , value; while (pos < len) { length++; value = str.charCodeAt(pos++); if (value >= 0xD800 && value <= 0xDBFF && pos < len) { // high surrogate, and there is a next character value = str.charCodeAt(pos); if ((value & 0xFC00) == 0xDC00) pos++; // low surrogate } } return length; }; /***/ }), /***/ 76578: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; module.exports = { copy: copy, checkDataType: checkDataType, checkDataTypes: checkDataTypes, coerceToTypes: coerceToTypes, toHash: toHash, getProperty: getProperty, escapeQuotes: escapeQuotes, equal: __nccwpck_require__(28206), ucs2length: __nccwpck_require__(64580), varOccurences: varOccurences, varReplace: varReplace, schemaHasRules: schemaHasRules, schemaHasRulesExcept: schemaHasRulesExcept, schemaUnknownRules: schemaUnknownRules, toQuotedString: toQuotedString, getPathExpr: getPathExpr, getPath: getPath, getData: getData, unescapeFragment: unescapeFragment, unescapeJsonPointer: unescapeJsonPointer, escapeFragment: escapeFragment, escapeJsonPointer: escapeJsonPointer }; function copy(o, to) { to = to || {}; for (var key in o) to[key] = o[key]; return to; } function checkDataType(dataType, data, strictNumbers, negate) { var EQUAL = negate ? ' !== ' : ' === ' , AND = negate ? ' || ' : ' && ' , OK = negate ? '!' : '' , NOT = negate ? '' : '!'; switch (dataType) { case 'null': return data + EQUAL + 'null'; case 'array': return OK + 'Array.isArray(' + data + ')'; case 'object': return '(' + OK + data + AND + 'typeof ' + data + EQUAL + '"object"' + AND + NOT + 'Array.isArray(' + data + '))'; case 'integer': return '(typeof ' + data + EQUAL + '"number"' + AND + NOT + '(' + data + ' % 1)' + AND + data + EQUAL + data + (strictNumbers ? (AND + OK + 'isFinite(' + data + ')') : '') + ')'; case 'number': return '(typeof ' + data + EQUAL + '"' + dataType + '"' + (strictNumbers ? (AND + OK + 'isFinite(' + data + ')') : '') + ')'; default: return 'typeof ' + data + EQUAL + '"' + dataType + '"'; } } function checkDataTypes(dataTypes, data, strictNumbers) { switch (dataTypes.length) { case 1: return checkDataType(dataTypes[0], data, strictNumbers, true); default: var code = ''; var types = toHash(dataTypes); if (types.array && types.object) { code = types.null ? '(': '(!' + data + ' || '; code += 'typeof ' + data + ' !== "object")'; delete types.null; delete types.array; delete types.object; } if (types.number) delete types.integer; for (var t in types) code += (code ? ' && ' : '' ) + checkDataType(t, data, strictNumbers, true); return code; } } var COERCE_TO_TYPES = toHash([ 'string', 'number', 'integer', 'boolean', 'null' ]); function coerceToTypes(optionCoerceTypes, dataTypes) { if (Array.isArray(dataTypes)) { var types = []; for (var i=0; i= lvl) throw new Error('Cannot access property/index ' + up + ' levels up, current level is ' + lvl); return paths[lvl - up]; } if (up > lvl) throw new Error('Cannot access data ' + up + ' levels up, current level is ' + lvl); data = 'data' + ((lvl - up) || ''); if (!jsonPointer) return data; } var expr = data; var segments = jsonPointer.split('/'); for (var i=0; i { "use strict"; var KEYWORDS = [ 'multipleOf', 'maximum', 'exclusiveMaximum', 'minimum', 'exclusiveMinimum', 'maxLength', 'minLength', 'pattern', 'additionalItems', 'maxItems', 'minItems', 'uniqueItems', 'maxProperties', 'minProperties', 'required', 'additionalProperties', 'enum', 'format', 'const' ]; module.exports = function (metaSchema, keywordsJsonPointers) { for (var i=0; i { "use strict"; var metaSchema = __nccwpck_require__(6680); module.exports = { $id: 'https://github.com/ajv-validator/ajv/blob/master/lib/definition_schema.js', definitions: { simpleTypes: metaSchema.definitions.simpleTypes }, type: 'object', dependencies: { schema: ['validate'], $data: ['validate'], statements: ['inline'], valid: {not: {required: ['macro']}} }, properties: { type: metaSchema.properties.type, schema: {type: 'boolean'}, statements: {type: 'boolean'}, dependencies: { type: 'array', items: {type: 'string'} }, metaSchema: {type: 'object'}, modifying: {type: 'boolean'}, valid: {type: 'boolean'}, $data: {type: 'boolean'}, async: {type: 'boolean'}, errors: { anyOf: [ {type: 'boolean'}, {const: 'full'} ] } } }; /***/ }), /***/ 7404: /***/ ((module) => { "use strict"; module.exports = function generate__limit(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $errorKeyword; var $data = 'data' + ($dataLvl || ''); var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue; if ($isData) { out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; $schemaValue = 'schema' + $lvl; } else { $schemaValue = $schema; } var $isMax = $keyword == 'maximum', $exclusiveKeyword = $isMax ? 'exclusiveMaximum' : 'exclusiveMinimum', $schemaExcl = it.schema[$exclusiveKeyword], $isDataExcl = it.opts.$data && $schemaExcl && $schemaExcl.$data, $op = $isMax ? '<' : '>', $notOp = $isMax ? '>' : '<', $errorKeyword = undefined; if (!($isData || typeof $schema == 'number' || $schema === undefined)) { throw new Error($keyword + ' must be number'); } if (!($isDataExcl || $schemaExcl === undefined || typeof $schemaExcl == 'number' || typeof $schemaExcl == 'boolean')) { throw new Error($exclusiveKeyword + ' must be number or boolean'); } if ($isDataExcl) { var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr), $exclusive = 'exclusive' + $lvl, $exclType = 'exclType' + $lvl, $exclIsNumber = 'exclIsNumber' + $lvl, $opExpr = 'op' + $lvl, $opStr = '\' + ' + $opExpr + ' + \''; out += ' var schemaExcl' + ($lvl) + ' = ' + ($schemaValueExcl) + '; '; $schemaValueExcl = 'schemaExcl' + $lvl; out += ' var ' + ($exclusive) + '; var ' + ($exclType) + ' = typeof ' + ($schemaValueExcl) + '; if (' + ($exclType) + ' != \'boolean\' && ' + ($exclType) + ' != \'undefined\' && ' + ($exclType) + ' != \'number\') { '; var $errorKeyword = $exclusiveKeyword; var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ($errorKeyword || '_exclusiveLimit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; if (it.opts.messages !== false) { out += ' , message: \'' + ($exclusiveKeyword) + ' should be boolean\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } out += ' } else if ( '; if ($isData) { out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; } out += ' ' + ($exclType) + ' == \'number\' ? ( (' + ($exclusive) + ' = ' + ($schemaValue) + ' === undefined || ' + ($schemaValueExcl) + ' ' + ($op) + '= ' + ($schemaValue) + ') ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaValueExcl) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) : ( (' + ($exclusive) + ' = ' + ($schemaValueExcl) + ' === true) ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaValue) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) || ' + ($data) + ' !== ' + ($data) + ') { var op' + ($lvl) + ' = ' + ($exclusive) + ' ? \'' + ($op) + '\' : \'' + ($op) + '=\'; '; if ($schema === undefined) { $errorKeyword = $exclusiveKeyword; $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword; $schemaValue = $schemaValueExcl; $isData = $isDataExcl; } } else { var $exclIsNumber = typeof $schemaExcl == 'number', $opStr = $op; if ($exclIsNumber && $isData) { var $opExpr = '\'' + $opStr + '\''; out += ' if ( '; if ($isData) { out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; } out += ' ( ' + ($schemaValue) + ' === undefined || ' + ($schemaExcl) + ' ' + ($op) + '= ' + ($schemaValue) + ' ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaExcl) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) || ' + ($data) + ' !== ' + ($data) + ') { '; } else { if ($exclIsNumber && $schema === undefined) { $exclusive = true; $errorKeyword = $exclusiveKeyword; $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword; $schemaValue = $schemaExcl; $notOp += '='; } else { if ($exclIsNumber) $schemaValue = Math[$isMax ? 'min' : 'max']($schemaExcl, $schema); if ($schemaExcl === ($exclIsNumber ? $schemaValue : true)) { $exclusive = true; $errorKeyword = $exclusiveKeyword; $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword; $notOp += '='; } else { $exclusive = false; $opStr += '='; } } var $opExpr = '\'' + $opStr + '\''; out += ' if ( '; if ($isData) { out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; } out += ' ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' || ' + ($data) + ' !== ' + ($data) + ') { '; } } $errorKeyword = $errorKeyword || $keyword; var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ($errorKeyword || '_limit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { comparison: ' + ($opExpr) + ', limit: ' + ($schemaValue) + ', exclusive: ' + ($exclusive) + ' } '; if (it.opts.messages !== false) { out += ' , message: \'should be ' + ($opStr) + ' '; if ($isData) { out += '\' + ' + ($schemaValue); } else { out += '' + ($schemaValue) + '\''; } } if (it.opts.verbose) { out += ' , schema: '; if ($isData) { out += 'validate.schema' + ($schemaPath); } else { out += '' + ($schema); } out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } out += ' } '; if ($breakOnError) { out += ' else { '; } return out; } /***/ }), /***/ 64683: /***/ ((module) => { "use strict"; module.exports = function generate__limitItems(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $errorKeyword; var $data = 'data' + ($dataLvl || ''); var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue; if ($isData) { out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; $schemaValue = 'schema' + $lvl; } else { $schemaValue = $schema; } if (!($isData || typeof $schema == 'number')) { throw new Error($keyword + ' must be number'); } var $op = $keyword == 'maxItems' ? '>' : '<'; out += 'if ( '; if ($isData) { out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; } out += ' ' + ($data) + '.length ' + ($op) + ' ' + ($schemaValue) + ') { '; var $errorKeyword = $keyword; var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ($errorKeyword || '_limitItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } '; if (it.opts.messages !== false) { out += ' , message: \'should NOT have '; if ($keyword == 'maxItems') { out += 'more'; } else { out += 'fewer'; } out += ' than '; if ($isData) { out += '\' + ' + ($schemaValue) + ' + \''; } else { out += '' + ($schema); } out += ' items\' '; } if (it.opts.verbose) { out += ' , schema: '; if ($isData) { out += 'validate.schema' + ($schemaPath); } else { out += '' + ($schema); } out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } out += '} '; if ($breakOnError) { out += ' else { '; } return out; } /***/ }), /***/ 52114: /***/ ((module) => { "use strict"; module.exports = function generate__limitLength(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $errorKeyword; var $data = 'data' + ($dataLvl || ''); var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue; if ($isData) { out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; $schemaValue = 'schema' + $lvl; } else { $schemaValue = $schema; } if (!($isData || typeof $schema == 'number')) { throw new Error($keyword + ' must be number'); } var $op = $keyword == 'maxLength' ? '>' : '<'; out += 'if ( '; if ($isData) { out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; } if (it.opts.unicode === false) { out += ' ' + ($data) + '.length '; } else { out += ' ucs2length(' + ($data) + ') '; } out += ' ' + ($op) + ' ' + ($schemaValue) + ') { '; var $errorKeyword = $keyword; var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ($errorKeyword || '_limitLength') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } '; if (it.opts.messages !== false) { out += ' , message: \'should NOT be '; if ($keyword == 'maxLength') { out += 'longer'; } else { out += 'shorter'; } out += ' than '; if ($isData) { out += '\' + ' + ($schemaValue) + ' + \''; } else { out += '' + ($schema); } out += ' characters\' '; } if (it.opts.verbose) { out += ' , schema: '; if ($isData) { out += 'validate.schema' + ($schemaPath); } else { out += '' + ($schema); } out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } out += '} '; if ($breakOnError) { out += ' else { '; } return out; } /***/ }), /***/ 71142: /***/ ((module) => { "use strict"; module.exports = function generate__limitProperties(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $errorKeyword; var $data = 'data' + ($dataLvl || ''); var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue; if ($isData) { out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; $schemaValue = 'schema' + $lvl; } else { $schemaValue = $schema; } if (!($isData || typeof $schema == 'number')) { throw new Error($keyword + ' must be number'); } var $op = $keyword == 'maxProperties' ? '>' : '<'; out += 'if ( '; if ($isData) { out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; } out += ' Object.keys(' + ($data) + ').length ' + ($op) + ' ' + ($schemaValue) + ') { '; var $errorKeyword = $keyword; var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ($errorKeyword || '_limitProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } '; if (it.opts.messages !== false) { out += ' , message: \'should NOT have '; if ($keyword == 'maxProperties') { out += 'more'; } else { out += 'fewer'; } out += ' than '; if ($isData) { out += '\' + ' + ($schemaValue) + ' + \''; } else { out += '' + ($schema); } out += ' properties\' '; } if (it.opts.verbose) { out += ' , schema: '; if ($isData) { out += 'validate.schema' + ($schemaPath); } else { out += '' + ($schema); } out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } out += '} '; if ($breakOnError) { out += ' else { '; } return out; } /***/ }), /***/ 89443: /***/ ((module) => { "use strict"; module.exports = function generate_allOf(it, $keyword, $ruleType) { var out = ' '; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $it = it.util.copy(it); var $closingBraces = ''; $it.level++; var $nextValid = 'valid' + $it.level; var $currentBaseId = $it.baseId, $allSchemasEmpty = true; var arr1 = $schema; if (arr1) { var $sch, $i = -1, l1 = arr1.length - 1; while ($i < l1) { $sch = arr1[$i += 1]; if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { $allSchemasEmpty = false; $it.schema = $sch; $it.schemaPath = $schemaPath + '[' + $i + ']'; $it.errSchemaPath = $errSchemaPath + '/' + $i; out += ' ' + (it.validate($it)) + ' '; $it.baseId = $currentBaseId; if ($breakOnError) { out += ' if (' + ($nextValid) + ') { '; $closingBraces += '}'; } } } } if ($breakOnError) { if ($allSchemasEmpty) { out += ' if (true) { '; } else { out += ' ' + ($closingBraces.slice(0, -1)) + ' '; } } return out; } /***/ }), /***/ 63093: /***/ ((module) => { "use strict"; module.exports = function generate_anyOf(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $data = 'data' + ($dataLvl || ''); var $valid = 'valid' + $lvl; var $errs = 'errs__' + $lvl; var $it = it.util.copy(it); var $closingBraces = ''; $it.level++; var $nextValid = 'valid' + $it.level; var $noEmptySchema = $schema.every(function($sch) { return (it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all)); }); if ($noEmptySchema) { var $currentBaseId = $it.baseId; out += ' var ' + ($errs) + ' = errors; var ' + ($valid) + ' = false; '; var $wasComposite = it.compositeRule; it.compositeRule = $it.compositeRule = true; var arr1 = $schema; if (arr1) { var $sch, $i = -1, l1 = arr1.length - 1; while ($i < l1) { $sch = arr1[$i += 1]; $it.schema = $sch; $it.schemaPath = $schemaPath + '[' + $i + ']'; $it.errSchemaPath = $errSchemaPath + '/' + $i; out += ' ' + (it.validate($it)) + ' '; $it.baseId = $currentBaseId; out += ' ' + ($valid) + ' = ' + ($valid) + ' || ' + ($nextValid) + '; if (!' + ($valid) + ') { '; $closingBraces += '}'; } } it.compositeRule = $it.compositeRule = $wasComposite; out += ' ' + ($closingBraces) + ' if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('anyOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; if (it.opts.messages !== false) { out += ' , message: \'should match some schema in anyOf\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError(vErrors); '; } else { out += ' validate.errors = vErrors; return false; '; } } out += ' } else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; if (it.opts.allErrors) { out += ' } '; } } else { if ($breakOnError) { out += ' if (true) { '; } } return out; } /***/ }), /***/ 30134: /***/ ((module) => { "use strict"; module.exports = function generate_comment(it, $keyword, $ruleType) { var out = ' '; var $schema = it.schema[$keyword]; var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $comment = it.util.toQuotedString($schema); if (it.opts.$comment === true) { out += ' console.log(' + ($comment) + ');'; } else if (typeof it.opts.$comment == 'function') { out += ' self._opts.$comment(' + ($comment) + ', ' + (it.util.toQuotedString($errSchemaPath)) + ', validate.root.schema);'; } return out; } /***/ }), /***/ 1661: /***/ ((module) => { "use strict"; module.exports = function generate_const(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $data = 'data' + ($dataLvl || ''); var $valid = 'valid' + $lvl; var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue; if ($isData) { out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; $schemaValue = 'schema' + $lvl; } else { $schemaValue = $schema; } if (!$isData) { out += ' var schema' + ($lvl) + ' = validate.schema' + ($schemaPath) + ';'; } out += 'var ' + ($valid) + ' = equal(' + ($data) + ', schema' + ($lvl) + '); if (!' + ($valid) + ') { '; var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('const') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { allowedValue: schema' + ($lvl) + ' } '; if (it.opts.messages !== false) { out += ' , message: \'should be equal to constant\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } out += ' }'; if ($breakOnError) { out += ' else { '; } return out; } /***/ }), /***/ 55964: /***/ ((module) => { "use strict"; module.exports = function generate_contains(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $data = 'data' + ($dataLvl || ''); var $valid = 'valid' + $lvl; var $errs = 'errs__' + $lvl; var $it = it.util.copy(it); var $closingBraces = ''; $it.level++; var $nextValid = 'valid' + $it.level; var $idx = 'i' + $lvl, $dataNxt = $it.dataLevel = it.dataLevel + 1, $nextData = 'data' + $dataNxt, $currentBaseId = it.baseId, $nonEmptySchema = (it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all)); out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';'; if ($nonEmptySchema) { var $wasComposite = it.compositeRule; it.compositeRule = $it.compositeRule = true; $it.schema = $schema; $it.schemaPath = $schemaPath; $it.errSchemaPath = $errSchemaPath; out += ' var ' + ($nextValid) + ' = false; for (var ' + ($idx) + ' = 0; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { '; $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); var $passData = $data + '[' + $idx + ']'; $it.dataPathArr[$dataNxt] = $idx; var $code = it.validate($it); $it.baseId = $currentBaseId; if (it.util.varOccurences($code, $nextData) < 2) { out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; } else { out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; } out += ' if (' + ($nextValid) + ') break; } '; it.compositeRule = $it.compositeRule = $wasComposite; out += ' ' + ($closingBraces) + ' if (!' + ($nextValid) + ') {'; } else { out += ' if (' + ($data) + '.length == 0) {'; } var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('contains') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; if (it.opts.messages !== false) { out += ' , message: \'should contain a valid item\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } out += ' } else { '; if ($nonEmptySchema) { out += ' errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; } if (it.opts.allErrors) { out += ' } '; } return out; } /***/ }), /***/ 5912: /***/ ((module) => { "use strict"; module.exports = function generate_custom(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $errorKeyword; var $data = 'data' + ($dataLvl || ''); var $valid = 'valid' + $lvl; var $errs = 'errs__' + $lvl; var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue; if ($isData) { out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; $schemaValue = 'schema' + $lvl; } else { $schemaValue = $schema; } var $rule = this, $definition = 'definition' + $lvl, $rDef = $rule.definition, $closingBraces = ''; var $compile, $inline, $macro, $ruleValidate, $validateCode; if ($isData && $rDef.$data) { $validateCode = 'keywordValidate' + $lvl; var $validateSchema = $rDef.validateSchema; out += ' var ' + ($definition) + ' = RULES.custom[\'' + ($keyword) + '\'].definition; var ' + ($validateCode) + ' = ' + ($definition) + '.validate;'; } else { $ruleValidate = it.useCustomRule($rule, $schema, it.schema, it); if (!$ruleValidate) return; $schemaValue = 'validate.schema' + $schemaPath; $validateCode = $ruleValidate.code; $compile = $rDef.compile; $inline = $rDef.inline; $macro = $rDef.macro; } var $ruleErrs = $validateCode + '.errors', $i = 'i' + $lvl, $ruleErr = 'ruleErr' + $lvl, $asyncKeyword = $rDef.async; if ($asyncKeyword && !it.async) throw new Error('async keyword in sync schema'); if (!($inline || $macro)) { out += '' + ($ruleErrs) + ' = null;'; } out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';'; if ($isData && $rDef.$data) { $closingBraces += '}'; out += ' if (' + ($schemaValue) + ' === undefined) { ' + ($valid) + ' = true; } else { '; if ($validateSchema) { $closingBraces += '}'; out += ' ' + ($valid) + ' = ' + ($definition) + '.validateSchema(' + ($schemaValue) + '); if (' + ($valid) + ') { '; } } if ($inline) { if ($rDef.statements) { out += ' ' + ($ruleValidate.validate) + ' '; } else { out += ' ' + ($valid) + ' = ' + ($ruleValidate.validate) + '; '; } } else if ($macro) { var $it = it.util.copy(it); var $closingBraces = ''; $it.level++; var $nextValid = 'valid' + $it.level; $it.schema = $ruleValidate.validate; $it.schemaPath = ''; var $wasComposite = it.compositeRule; it.compositeRule = $it.compositeRule = true; var $code = it.validate($it).replace(/validate\.schema/g, $validateCode); it.compositeRule = $it.compositeRule = $wasComposite; out += ' ' + ($code); } else { var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; out += ' ' + ($validateCode) + '.call( '; if (it.opts.passContext) { out += 'this'; } else { out += 'self'; } if ($compile || $rDef.schema === false) { out += ' , ' + ($data) + ' '; } else { out += ' , ' + ($schemaValue) + ' , ' + ($data) + ' , validate.schema' + (it.schemaPath) + ' '; } out += ' , (dataPath || \'\')'; if (it.errorPath != '""') { out += ' + ' + (it.errorPath); } var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData', $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty'; out += ' , ' + ($parentData) + ' , ' + ($parentDataProperty) + ' , rootData ) '; var def_callRuleValidate = out; out = $$outStack.pop(); if ($rDef.errors === false) { out += ' ' + ($valid) + ' = '; if ($asyncKeyword) { out += 'await '; } out += '' + (def_callRuleValidate) + '; '; } else { if ($asyncKeyword) { $ruleErrs = 'customErrors' + $lvl; out += ' var ' + ($ruleErrs) + ' = null; try { ' + ($valid) + ' = await ' + (def_callRuleValidate) + '; } catch (e) { ' + ($valid) + ' = false; if (e instanceof ValidationError) ' + ($ruleErrs) + ' = e.errors; else throw e; } '; } else { out += ' ' + ($ruleErrs) + ' = null; ' + ($valid) + ' = ' + (def_callRuleValidate) + '; '; } } } if ($rDef.modifying) { out += ' if (' + ($parentData) + ') ' + ($data) + ' = ' + ($parentData) + '[' + ($parentDataProperty) + '];'; } out += '' + ($closingBraces); if ($rDef.valid) { if ($breakOnError) { out += ' if (true) { '; } } else { out += ' if ( '; if ($rDef.valid === undefined) { out += ' !'; if ($macro) { out += '' + ($nextValid); } else { out += '' + ($valid); } } else { out += ' ' + (!$rDef.valid) + ' '; } out += ') { '; $errorKeyword = $rule.keyword; var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ($errorKeyword || 'custom') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { keyword: \'' + ($rule.keyword) + '\' } '; if (it.opts.messages !== false) { out += ' , message: \'should pass "' + ($rule.keyword) + '" keyword validation\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } var def_customError = out; out = $$outStack.pop(); if ($inline) { if ($rDef.errors) { if ($rDef.errors != 'full') { out += ' for (var ' + ($i) + '=' + ($errs) + '; ' + ($i) + ' { "use strict"; module.exports = function generate_dependencies(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $data = 'data' + ($dataLvl || ''); var $errs = 'errs__' + $lvl; var $it = it.util.copy(it); var $closingBraces = ''; $it.level++; var $nextValid = 'valid' + $it.level; var $schemaDeps = {}, $propertyDeps = {}, $ownProperties = it.opts.ownProperties; for ($property in $schema) { if ($property == '__proto__') continue; var $sch = $schema[$property]; var $deps = Array.isArray($sch) ? $propertyDeps : $schemaDeps; $deps[$property] = $sch; } out += 'var ' + ($errs) + ' = errors;'; var $currentErrorPath = it.errorPath; out += 'var missing' + ($lvl) + ';'; for (var $property in $propertyDeps) { $deps = $propertyDeps[$property]; if ($deps.length) { out += ' if ( ' + ($data) + (it.util.getProperty($property)) + ' !== undefined '; if ($ownProperties) { out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($property)) + '\') '; } if ($breakOnError) { out += ' && ( '; var arr1 = $deps; if (arr1) { var $propertyKey, $i = -1, l1 = arr1.length - 1; while ($i < l1) { $propertyKey = arr1[$i += 1]; if ($i) { out += ' || '; } var $prop = it.util.getProperty($propertyKey), $useData = $data + $prop; out += ' ( ( ' + ($useData) + ' === undefined '; if ($ownProperties) { out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; } out += ') && (missing' + ($lvl) + ' = ' + (it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop)) + ') ) '; } } out += ')) { '; var $propertyPath = 'missing' + $lvl, $missingProperty = '\' + ' + $propertyPath + ' + \''; if (it.opts._errorDataPathProperty) { it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath; } var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('dependencies') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { property: \'' + (it.util.escapeQuotes($property)) + '\', missingProperty: \'' + ($missingProperty) + '\', depsCount: ' + ($deps.length) + ', deps: \'' + (it.util.escapeQuotes($deps.length == 1 ? $deps[0] : $deps.join(", "))) + '\' } '; if (it.opts.messages !== false) { out += ' , message: \'should have '; if ($deps.length == 1) { out += 'property ' + (it.util.escapeQuotes($deps[0])); } else { out += 'properties ' + (it.util.escapeQuotes($deps.join(", "))); } out += ' when property ' + (it.util.escapeQuotes($property)) + ' is present\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } } else { out += ' ) { '; var arr2 = $deps; if (arr2) { var $propertyKey, i2 = -1, l2 = arr2.length - 1; while (i2 < l2) { $propertyKey = arr2[i2 += 1]; var $prop = it.util.getProperty($propertyKey), $missingProperty = it.util.escapeQuotes($propertyKey), $useData = $data + $prop; if (it.opts._errorDataPathProperty) { it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers); } out += ' if ( ' + ($useData) + ' === undefined '; if ($ownProperties) { out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; } out += ') { var err = '; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('dependencies') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { property: \'' + (it.util.escapeQuotes($property)) + '\', missingProperty: \'' + ($missingProperty) + '\', depsCount: ' + ($deps.length) + ', deps: \'' + (it.util.escapeQuotes($deps.length == 1 ? $deps[0] : $deps.join(", "))) + '\' } '; if (it.opts.messages !== false) { out += ' , message: \'should have '; if ($deps.length == 1) { out += 'property ' + (it.util.escapeQuotes($deps[0])); } else { out += 'properties ' + (it.util.escapeQuotes($deps.join(", "))); } out += ' when property ' + (it.util.escapeQuotes($property)) + ' is present\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } '; } } } out += ' } '; if ($breakOnError) { $closingBraces += '}'; out += ' else { '; } } } it.errorPath = $currentErrorPath; var $currentBaseId = $it.baseId; for (var $property in $schemaDeps) { var $sch = $schemaDeps[$property]; if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { out += ' ' + ($nextValid) + ' = true; if ( ' + ($data) + (it.util.getProperty($property)) + ' !== undefined '; if ($ownProperties) { out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($property)) + '\') '; } out += ') { '; $it.schema = $sch; $it.schemaPath = $schemaPath + it.util.getProperty($property); $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($property); out += ' ' + (it.validate($it)) + ' '; $it.baseId = $currentBaseId; out += ' } '; if ($breakOnError) { out += ' if (' + ($nextValid) + ') { '; $closingBraces += '}'; } } } if ($breakOnError) { out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {'; } return out; } /***/ }), /***/ 10163: /***/ ((module) => { "use strict"; module.exports = function generate_enum(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $data = 'data' + ($dataLvl || ''); var $valid = 'valid' + $lvl; var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue; if ($isData) { out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; $schemaValue = 'schema' + $lvl; } else { $schemaValue = $schema; } var $i = 'i' + $lvl, $vSchema = 'schema' + $lvl; if (!$isData) { out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + ';'; } out += 'var ' + ($valid) + ';'; if ($isData) { out += ' if (schema' + ($lvl) + ' === undefined) ' + ($valid) + ' = true; else if (!Array.isArray(schema' + ($lvl) + ')) ' + ($valid) + ' = false; else {'; } out += '' + ($valid) + ' = false;for (var ' + ($i) + '=0; ' + ($i) + '<' + ($vSchema) + '.length; ' + ($i) + '++) if (equal(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + '])) { ' + ($valid) + ' = true; break; }'; if ($isData) { out += ' } '; } out += ' if (!' + ($valid) + ') { '; var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('enum') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { allowedValues: schema' + ($lvl) + ' } '; if (it.opts.messages !== false) { out += ' , message: \'should be equal to one of the allowed values\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } out += ' }'; if ($breakOnError) { out += ' else { '; } return out; } /***/ }), /***/ 63847: /***/ ((module) => { "use strict"; module.exports = function generate_format(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $data = 'data' + ($dataLvl || ''); if (it.opts.format === false) { if ($breakOnError) { out += ' if (true) { '; } return out; } var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue; if ($isData) { out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; $schemaValue = 'schema' + $lvl; } else { $schemaValue = $schema; } var $unknownFormats = it.opts.unknownFormats, $allowUnknown = Array.isArray($unknownFormats); if ($isData) { var $format = 'format' + $lvl, $isObject = 'isObject' + $lvl, $formatType = 'formatType' + $lvl; out += ' var ' + ($format) + ' = formats[' + ($schemaValue) + ']; var ' + ($isObject) + ' = typeof ' + ($format) + ' == \'object\' && !(' + ($format) + ' instanceof RegExp) && ' + ($format) + '.validate; var ' + ($formatType) + ' = ' + ($isObject) + ' && ' + ($format) + '.type || \'string\'; if (' + ($isObject) + ') { '; if (it.async) { out += ' var async' + ($lvl) + ' = ' + ($format) + '.async; '; } out += ' ' + ($format) + ' = ' + ($format) + '.validate; } if ( '; if ($isData) { out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || '; } out += ' ('; if ($unknownFormats != 'ignore') { out += ' (' + ($schemaValue) + ' && !' + ($format) + ' '; if ($allowUnknown) { out += ' && self._opts.unknownFormats.indexOf(' + ($schemaValue) + ') == -1 '; } out += ') || '; } out += ' (' + ($format) + ' && ' + ($formatType) + ' == \'' + ($ruleType) + '\' && !(typeof ' + ($format) + ' == \'function\' ? '; if (it.async) { out += ' (async' + ($lvl) + ' ? await ' + ($format) + '(' + ($data) + ') : ' + ($format) + '(' + ($data) + ')) '; } else { out += ' ' + ($format) + '(' + ($data) + ') '; } out += ' : ' + ($format) + '.test(' + ($data) + '))))) {'; } else { var $format = it.formats[$schema]; if (!$format) { if ($unknownFormats == 'ignore') { it.logger.warn('unknown format "' + $schema + '" ignored in schema at path "' + it.errSchemaPath + '"'); if ($breakOnError) { out += ' if (true) { '; } return out; } else if ($allowUnknown && $unknownFormats.indexOf($schema) >= 0) { if ($breakOnError) { out += ' if (true) { '; } return out; } else { throw new Error('unknown format "' + $schema + '" is used in schema at path "' + it.errSchemaPath + '"'); } } var $isObject = typeof $format == 'object' && !($format instanceof RegExp) && $format.validate; var $formatType = $isObject && $format.type || 'string'; if ($isObject) { var $async = $format.async === true; $format = $format.validate; } if ($formatType != $ruleType) { if ($breakOnError) { out += ' if (true) { '; } return out; } if ($async) { if (!it.async) throw new Error('async format in sync schema'); var $formatRef = 'formats' + it.util.getProperty($schema) + '.validate'; out += ' if (!(await ' + ($formatRef) + '(' + ($data) + '))) { '; } else { out += ' if (! '; var $formatRef = 'formats' + it.util.getProperty($schema); if ($isObject) $formatRef += '.validate'; if (typeof $format == 'function') { out += ' ' + ($formatRef) + '(' + ($data) + ') '; } else { out += ' ' + ($formatRef) + '.test(' + ($data) + ') '; } out += ') { '; } } var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('format') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { format: '; if ($isData) { out += '' + ($schemaValue); } else { out += '' + (it.util.toQuotedString($schema)); } out += ' } '; if (it.opts.messages !== false) { out += ' , message: \'should match format "'; if ($isData) { out += '\' + ' + ($schemaValue) + ' + \''; } else { out += '' + (it.util.escapeQuotes($schema)); } out += '"\' '; } if (it.opts.verbose) { out += ' , schema: '; if ($isData) { out += 'validate.schema' + ($schemaPath); } else { out += '' + (it.util.toQuotedString($schema)); } out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } out += ' } '; if ($breakOnError) { out += ' else { '; } return out; } /***/ }), /***/ 80862: /***/ ((module) => { "use strict"; module.exports = function generate_if(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $data = 'data' + ($dataLvl || ''); var $valid = 'valid' + $lvl; var $errs = 'errs__' + $lvl; var $it = it.util.copy(it); $it.level++; var $nextValid = 'valid' + $it.level; var $thenSch = it.schema['then'], $elseSch = it.schema['else'], $thenPresent = $thenSch !== undefined && (it.opts.strictKeywords ? (typeof $thenSch == 'object' && Object.keys($thenSch).length > 0) || $thenSch === false : it.util.schemaHasRules($thenSch, it.RULES.all)), $elsePresent = $elseSch !== undefined && (it.opts.strictKeywords ? (typeof $elseSch == 'object' && Object.keys($elseSch).length > 0) || $elseSch === false : it.util.schemaHasRules($elseSch, it.RULES.all)), $currentBaseId = $it.baseId; if ($thenPresent || $elsePresent) { var $ifClause; $it.createErrors = false; $it.schema = $schema; $it.schemaPath = $schemaPath; $it.errSchemaPath = $errSchemaPath; out += ' var ' + ($errs) + ' = errors; var ' + ($valid) + ' = true; '; var $wasComposite = it.compositeRule; it.compositeRule = $it.compositeRule = true; out += ' ' + (it.validate($it)) + ' '; $it.baseId = $currentBaseId; $it.createErrors = true; out += ' errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; it.compositeRule = $it.compositeRule = $wasComposite; if ($thenPresent) { out += ' if (' + ($nextValid) + ') { '; $it.schema = it.schema['then']; $it.schemaPath = it.schemaPath + '.then'; $it.errSchemaPath = it.errSchemaPath + '/then'; out += ' ' + (it.validate($it)) + ' '; $it.baseId = $currentBaseId; out += ' ' + ($valid) + ' = ' + ($nextValid) + '; '; if ($thenPresent && $elsePresent) { $ifClause = 'ifClause' + $lvl; out += ' var ' + ($ifClause) + ' = \'then\'; '; } else { $ifClause = '\'then\''; } out += ' } '; if ($elsePresent) { out += ' else { '; } } else { out += ' if (!' + ($nextValid) + ') { '; } if ($elsePresent) { $it.schema = it.schema['else']; $it.schemaPath = it.schemaPath + '.else'; $it.errSchemaPath = it.errSchemaPath + '/else'; out += ' ' + (it.validate($it)) + ' '; $it.baseId = $currentBaseId; out += ' ' + ($valid) + ' = ' + ($nextValid) + '; '; if ($thenPresent && $elsePresent) { $ifClause = 'ifClause' + $lvl; out += ' var ' + ($ifClause) + ' = \'else\'; '; } else { $ifClause = '\'else\''; } out += ' } '; } out += ' if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('if') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { failingKeyword: ' + ($ifClause) + ' } '; if (it.opts.messages !== false) { out += ' , message: \'should match "\' + ' + ($ifClause) + ' + \'" schema\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError(vErrors); '; } else { out += ' validate.errors = vErrors; return false; '; } } out += ' } '; if ($breakOnError) { out += ' else { '; } } else { if ($breakOnError) { out += ' if (true) { '; } } return out; } /***/ }), /***/ 85810: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; //all requires must be explicit because browserify won't work with dynamic requires module.exports = { '$ref': __nccwpck_require__(42393), allOf: __nccwpck_require__(89443), anyOf: __nccwpck_require__(63093), '$comment': __nccwpck_require__(30134), const: __nccwpck_require__(1661), contains: __nccwpck_require__(55964), dependencies: __nccwpck_require__(2591), 'enum': __nccwpck_require__(10163), format: __nccwpck_require__(63847), 'if': __nccwpck_require__(80862), items: __nccwpck_require__(54408), maximum: __nccwpck_require__(7404), minimum: __nccwpck_require__(7404), maxItems: __nccwpck_require__(64683), minItems: __nccwpck_require__(64683), maxLength: __nccwpck_require__(52114), minLength: __nccwpck_require__(52114), maxProperties: __nccwpck_require__(71142), minProperties: __nccwpck_require__(71142), multipleOf: __nccwpck_require__(39772), not: __nccwpck_require__(60750), oneOf: __nccwpck_require__(6106), pattern: __nccwpck_require__(13912), properties: __nccwpck_require__(52924), propertyNames: __nccwpck_require__(19195), required: __nccwpck_require__(8420), uniqueItems: __nccwpck_require__(24995), validate: __nccwpck_require__(49585) }; /***/ }), /***/ 54408: /***/ ((module) => { "use strict"; module.exports = function generate_items(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $data = 'data' + ($dataLvl || ''); var $valid = 'valid' + $lvl; var $errs = 'errs__' + $lvl; var $it = it.util.copy(it); var $closingBraces = ''; $it.level++; var $nextValid = 'valid' + $it.level; var $idx = 'i' + $lvl, $dataNxt = $it.dataLevel = it.dataLevel + 1, $nextData = 'data' + $dataNxt, $currentBaseId = it.baseId; out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';'; if (Array.isArray($schema)) { var $additionalItems = it.schema.additionalItems; if ($additionalItems === false) { out += ' ' + ($valid) + ' = ' + ($data) + '.length <= ' + ($schema.length) + '; '; var $currErrSchemaPath = $errSchemaPath; $errSchemaPath = it.errSchemaPath + '/additionalItems'; out += ' if (!' + ($valid) + ') { '; var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('additionalItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schema.length) + ' } '; if (it.opts.messages !== false) { out += ' , message: \'should NOT have more than ' + ($schema.length) + ' items\' '; } if (it.opts.verbose) { out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } out += ' } '; $errSchemaPath = $currErrSchemaPath; if ($breakOnError) { $closingBraces += '}'; out += ' else { '; } } var arr1 = $schema; if (arr1) { var $sch, $i = -1, l1 = arr1.length - 1; while ($i < l1) { $sch = arr1[$i += 1]; if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { out += ' ' + ($nextValid) + ' = true; if (' + ($data) + '.length > ' + ($i) + ') { '; var $passData = $data + '[' + $i + ']'; $it.schema = $sch; $it.schemaPath = $schemaPath + '[' + $i + ']'; $it.errSchemaPath = $errSchemaPath + '/' + $i; $it.errorPath = it.util.getPathExpr(it.errorPath, $i, it.opts.jsonPointers, true); $it.dataPathArr[$dataNxt] = $i; var $code = it.validate($it); $it.baseId = $currentBaseId; if (it.util.varOccurences($code, $nextData) < 2) { out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; } else { out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; } out += ' } '; if ($breakOnError) { out += ' if (' + ($nextValid) + ') { '; $closingBraces += '}'; } } } } if (typeof $additionalItems == 'object' && (it.opts.strictKeywords ? (typeof $additionalItems == 'object' && Object.keys($additionalItems).length > 0) || $additionalItems === false : it.util.schemaHasRules($additionalItems, it.RULES.all))) { $it.schema = $additionalItems; $it.schemaPath = it.schemaPath + '.additionalItems'; $it.errSchemaPath = it.errSchemaPath + '/additionalItems'; out += ' ' + ($nextValid) + ' = true; if (' + ($data) + '.length > ' + ($schema.length) + ') { for (var ' + ($idx) + ' = ' + ($schema.length) + '; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { '; $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); var $passData = $data + '[' + $idx + ']'; $it.dataPathArr[$dataNxt] = $idx; var $code = it.validate($it); $it.baseId = $currentBaseId; if (it.util.varOccurences($code, $nextData) < 2) { out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; } else { out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; } if ($breakOnError) { out += ' if (!' + ($nextValid) + ') break; '; } out += ' } } '; if ($breakOnError) { out += ' if (' + ($nextValid) + ') { '; $closingBraces += '}'; } } } else if ((it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all))) { $it.schema = $schema; $it.schemaPath = $schemaPath; $it.errSchemaPath = $errSchemaPath; out += ' for (var ' + ($idx) + ' = ' + (0) + '; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { '; $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); var $passData = $data + '[' + $idx + ']'; $it.dataPathArr[$dataNxt] = $idx; var $code = it.validate($it); $it.baseId = $currentBaseId; if (it.util.varOccurences($code, $nextData) < 2) { out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; } else { out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; } if ($breakOnError) { out += ' if (!' + ($nextValid) + ') break; '; } out += ' }'; } if ($breakOnError) { out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {'; } return out; } /***/ }), /***/ 39772: /***/ ((module) => { "use strict"; module.exports = function generate_multipleOf(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $data = 'data' + ($dataLvl || ''); var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue; if ($isData) { out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; $schemaValue = 'schema' + $lvl; } else { $schemaValue = $schema; } if (!($isData || typeof $schema == 'number')) { throw new Error($keyword + ' must be number'); } out += 'var division' + ($lvl) + ';if ('; if ($isData) { out += ' ' + ($schemaValue) + ' !== undefined && ( typeof ' + ($schemaValue) + ' != \'number\' || '; } out += ' (division' + ($lvl) + ' = ' + ($data) + ' / ' + ($schemaValue) + ', '; if (it.opts.multipleOfPrecision) { out += ' Math.abs(Math.round(division' + ($lvl) + ') - division' + ($lvl) + ') > 1e-' + (it.opts.multipleOfPrecision) + ' '; } else { out += ' division' + ($lvl) + ' !== parseInt(division' + ($lvl) + ') '; } out += ' ) '; if ($isData) { out += ' ) '; } out += ' ) { '; var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('multipleOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { multipleOf: ' + ($schemaValue) + ' } '; if (it.opts.messages !== false) { out += ' , message: \'should be multiple of '; if ($isData) { out += '\' + ' + ($schemaValue); } else { out += '' + ($schemaValue) + '\''; } } if (it.opts.verbose) { out += ' , schema: '; if ($isData) { out += 'validate.schema' + ($schemaPath); } else { out += '' + ($schema); } out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } out += '} '; if ($breakOnError) { out += ' else { '; } return out; } /***/ }), /***/ 60750: /***/ ((module) => { "use strict"; module.exports = function generate_not(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $data = 'data' + ($dataLvl || ''); var $errs = 'errs__' + $lvl; var $it = it.util.copy(it); $it.level++; var $nextValid = 'valid' + $it.level; if ((it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all))) { $it.schema = $schema; $it.schemaPath = $schemaPath; $it.errSchemaPath = $errSchemaPath; out += ' var ' + ($errs) + ' = errors; '; var $wasComposite = it.compositeRule; it.compositeRule = $it.compositeRule = true; $it.createErrors = false; var $allErrorsOption; if ($it.opts.allErrors) { $allErrorsOption = $it.opts.allErrors; $it.opts.allErrors = false; } out += ' ' + (it.validate($it)) + ' '; $it.createErrors = true; if ($allErrorsOption) $it.opts.allErrors = $allErrorsOption; it.compositeRule = $it.compositeRule = $wasComposite; out += ' if (' + ($nextValid) + ') { '; var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('not') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; if (it.opts.messages !== false) { out += ' , message: \'should NOT be valid\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } out += ' } else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; if (it.opts.allErrors) { out += ' } '; } } else { out += ' var err = '; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('not') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; if (it.opts.messages !== false) { out += ' , message: \'should NOT be valid\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; if ($breakOnError) { out += ' if (false) { '; } } return out; } /***/ }), /***/ 6106: /***/ ((module) => { "use strict"; module.exports = function generate_oneOf(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $data = 'data' + ($dataLvl || ''); var $valid = 'valid' + $lvl; var $errs = 'errs__' + $lvl; var $it = it.util.copy(it); var $closingBraces = ''; $it.level++; var $nextValid = 'valid' + $it.level; var $currentBaseId = $it.baseId, $prevValid = 'prevValid' + $lvl, $passingSchemas = 'passingSchemas' + $lvl; out += 'var ' + ($errs) + ' = errors , ' + ($prevValid) + ' = false , ' + ($valid) + ' = false , ' + ($passingSchemas) + ' = null; '; var $wasComposite = it.compositeRule; it.compositeRule = $it.compositeRule = true; var arr1 = $schema; if (arr1) { var $sch, $i = -1, l1 = arr1.length - 1; while ($i < l1) { $sch = arr1[$i += 1]; if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { $it.schema = $sch; $it.schemaPath = $schemaPath + '[' + $i + ']'; $it.errSchemaPath = $errSchemaPath + '/' + $i; out += ' ' + (it.validate($it)) + ' '; $it.baseId = $currentBaseId; } else { out += ' var ' + ($nextValid) + ' = true; '; } if ($i) { out += ' if (' + ($nextValid) + ' && ' + ($prevValid) + ') { ' + ($valid) + ' = false; ' + ($passingSchemas) + ' = [' + ($passingSchemas) + ', ' + ($i) + ']; } else { '; $closingBraces += '}'; } out += ' if (' + ($nextValid) + ') { ' + ($valid) + ' = ' + ($prevValid) + ' = true; ' + ($passingSchemas) + ' = ' + ($i) + '; }'; } } it.compositeRule = $it.compositeRule = $wasComposite; out += '' + ($closingBraces) + 'if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('oneOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { passingSchemas: ' + ($passingSchemas) + ' } '; if (it.opts.messages !== false) { out += ' , message: \'should match exactly one schema in oneOf\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError(vErrors); '; } else { out += ' validate.errors = vErrors; return false; '; } } out += '} else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; }'; if (it.opts.allErrors) { out += ' } '; } return out; } /***/ }), /***/ 13912: /***/ ((module) => { "use strict"; module.exports = function generate_pattern(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $data = 'data' + ($dataLvl || ''); var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue; if ($isData) { out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; $schemaValue = 'schema' + $lvl; } else { $schemaValue = $schema; } var $regexp = $isData ? '(new RegExp(' + $schemaValue + '))' : it.usePattern($schema); out += 'if ( '; if ($isData) { out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || '; } out += ' !' + ($regexp) + '.test(' + ($data) + ') ) { '; var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('pattern') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { pattern: '; if ($isData) { out += '' + ($schemaValue); } else { out += '' + (it.util.toQuotedString($schema)); } out += ' } '; if (it.opts.messages !== false) { out += ' , message: \'should match pattern "'; if ($isData) { out += '\' + ' + ($schemaValue) + ' + \''; } else { out += '' + (it.util.escapeQuotes($schema)); } out += '"\' '; } if (it.opts.verbose) { out += ' , schema: '; if ($isData) { out += 'validate.schema' + ($schemaPath); } else { out += '' + (it.util.toQuotedString($schema)); } out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } out += '} '; if ($breakOnError) { out += ' else { '; } return out; } /***/ }), /***/ 52924: /***/ ((module) => { "use strict"; module.exports = function generate_properties(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $data = 'data' + ($dataLvl || ''); var $errs = 'errs__' + $lvl; var $it = it.util.copy(it); var $closingBraces = ''; $it.level++; var $nextValid = 'valid' + $it.level; var $key = 'key' + $lvl, $idx = 'idx' + $lvl, $dataNxt = $it.dataLevel = it.dataLevel + 1, $nextData = 'data' + $dataNxt, $dataProperties = 'dataProperties' + $lvl; var $schemaKeys = Object.keys($schema || {}).filter(notProto), $pProperties = it.schema.patternProperties || {}, $pPropertyKeys = Object.keys($pProperties).filter(notProto), $aProperties = it.schema.additionalProperties, $someProperties = $schemaKeys.length || $pPropertyKeys.length, $noAdditional = $aProperties === false, $additionalIsSchema = typeof $aProperties == 'object' && Object.keys($aProperties).length, $removeAdditional = it.opts.removeAdditional, $checkAdditional = $noAdditional || $additionalIsSchema || $removeAdditional, $ownProperties = it.opts.ownProperties, $currentBaseId = it.baseId; var $required = it.schema.required; if ($required && !(it.opts.$data && $required.$data) && $required.length < it.opts.loopRequired) { var $requiredHash = it.util.toHash($required); } function notProto(p) { return p !== '__proto__'; } out += 'var ' + ($errs) + ' = errors;var ' + ($nextValid) + ' = true;'; if ($ownProperties) { out += ' var ' + ($dataProperties) + ' = undefined;'; } if ($checkAdditional) { if ($ownProperties) { out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; '; } else { out += ' for (var ' + ($key) + ' in ' + ($data) + ') { '; } if ($someProperties) { out += ' var isAdditional' + ($lvl) + ' = !(false '; if ($schemaKeys.length) { if ($schemaKeys.length > 8) { out += ' || validate.schema' + ($schemaPath) + '.hasOwnProperty(' + ($key) + ') '; } else { var arr1 = $schemaKeys; if (arr1) { var $propertyKey, i1 = -1, l1 = arr1.length - 1; while (i1 < l1) { $propertyKey = arr1[i1 += 1]; out += ' || ' + ($key) + ' == ' + (it.util.toQuotedString($propertyKey)) + ' '; } } } } if ($pPropertyKeys.length) { var arr2 = $pPropertyKeys; if (arr2) { var $pProperty, $i = -1, l2 = arr2.length - 1; while ($i < l2) { $pProperty = arr2[$i += 1]; out += ' || ' + (it.usePattern($pProperty)) + '.test(' + ($key) + ') '; } } } out += ' ); if (isAdditional' + ($lvl) + ') { '; } if ($removeAdditional == 'all') { out += ' delete ' + ($data) + '[' + ($key) + ']; '; } else { var $currentErrorPath = it.errorPath; var $additionalProperty = '\' + ' + $key + ' + \''; if (it.opts._errorDataPathProperty) { it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); } if ($noAdditional) { if ($removeAdditional) { out += ' delete ' + ($data) + '[' + ($key) + ']; '; } else { out += ' ' + ($nextValid) + ' = false; '; var $currErrSchemaPath = $errSchemaPath; $errSchemaPath = it.errSchemaPath + '/additionalProperties'; var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('additionalProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { additionalProperty: \'' + ($additionalProperty) + '\' } '; if (it.opts.messages !== false) { out += ' , message: \''; if (it.opts._errorDataPathProperty) { out += 'is an invalid additional property'; } else { out += 'should NOT have additional properties'; } out += '\' '; } if (it.opts.verbose) { out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } $errSchemaPath = $currErrSchemaPath; if ($breakOnError) { out += ' break; '; } } } else if ($additionalIsSchema) { if ($removeAdditional == 'failing') { out += ' var ' + ($errs) + ' = errors; '; var $wasComposite = it.compositeRule; it.compositeRule = $it.compositeRule = true; $it.schema = $aProperties; $it.schemaPath = it.schemaPath + '.additionalProperties'; $it.errSchemaPath = it.errSchemaPath + '/additionalProperties'; $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); var $passData = $data + '[' + $key + ']'; $it.dataPathArr[$dataNxt] = $key; var $code = it.validate($it); $it.baseId = $currentBaseId; if (it.util.varOccurences($code, $nextData) < 2) { out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; } else { out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; } out += ' if (!' + ($nextValid) + ') { errors = ' + ($errs) + '; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete ' + ($data) + '[' + ($key) + ']; } '; it.compositeRule = $it.compositeRule = $wasComposite; } else { $it.schema = $aProperties; $it.schemaPath = it.schemaPath + '.additionalProperties'; $it.errSchemaPath = it.errSchemaPath + '/additionalProperties'; $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); var $passData = $data + '[' + $key + ']'; $it.dataPathArr[$dataNxt] = $key; var $code = it.validate($it); $it.baseId = $currentBaseId; if (it.util.varOccurences($code, $nextData) < 2) { out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; } else { out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; } if ($breakOnError) { out += ' if (!' + ($nextValid) + ') break; '; } } } it.errorPath = $currentErrorPath; } if ($someProperties) { out += ' } '; } out += ' } '; if ($breakOnError) { out += ' if (' + ($nextValid) + ') { '; $closingBraces += '}'; } } var $useDefaults = it.opts.useDefaults && !it.compositeRule; if ($schemaKeys.length) { var arr3 = $schemaKeys; if (arr3) { var $propertyKey, i3 = -1, l3 = arr3.length - 1; while (i3 < l3) { $propertyKey = arr3[i3 += 1]; var $sch = $schema[$propertyKey]; if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { var $prop = it.util.getProperty($propertyKey), $passData = $data + $prop, $hasDefault = $useDefaults && $sch.default !== undefined; $it.schema = $sch; $it.schemaPath = $schemaPath + $prop; $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($propertyKey); $it.errorPath = it.util.getPath(it.errorPath, $propertyKey, it.opts.jsonPointers); $it.dataPathArr[$dataNxt] = it.util.toQuotedString($propertyKey); var $code = it.validate($it); $it.baseId = $currentBaseId; if (it.util.varOccurences($code, $nextData) < 2) { $code = it.util.varReplace($code, $nextData, $passData); var $useData = $passData; } else { var $useData = $nextData; out += ' var ' + ($nextData) + ' = ' + ($passData) + '; '; } if ($hasDefault) { out += ' ' + ($code) + ' '; } else { if ($requiredHash && $requiredHash[$propertyKey]) { out += ' if ( ' + ($useData) + ' === undefined '; if ($ownProperties) { out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; } out += ') { ' + ($nextValid) + ' = false; '; var $currentErrorPath = it.errorPath, $currErrSchemaPath = $errSchemaPath, $missingProperty = it.util.escapeQuotes($propertyKey); if (it.opts._errorDataPathProperty) { it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers); } $errSchemaPath = it.errSchemaPath + '/required'; var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; if (it.opts.messages !== false) { out += ' , message: \''; if (it.opts._errorDataPathProperty) { out += 'is a required property'; } else { out += 'should have required property \\\'' + ($missingProperty) + '\\\''; } out += '\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } $errSchemaPath = $currErrSchemaPath; it.errorPath = $currentErrorPath; out += ' } else { '; } else { if ($breakOnError) { out += ' if ( ' + ($useData) + ' === undefined '; if ($ownProperties) { out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; } out += ') { ' + ($nextValid) + ' = true; } else { '; } else { out += ' if (' + ($useData) + ' !== undefined '; if ($ownProperties) { out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; } out += ' ) { '; } } out += ' ' + ($code) + ' } '; } } if ($breakOnError) { out += ' if (' + ($nextValid) + ') { '; $closingBraces += '}'; } } } } if ($pPropertyKeys.length) { var arr4 = $pPropertyKeys; if (arr4) { var $pProperty, i4 = -1, l4 = arr4.length - 1; while (i4 < l4) { $pProperty = arr4[i4 += 1]; var $sch = $pProperties[$pProperty]; if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) { $it.schema = $sch; $it.schemaPath = it.schemaPath + '.patternProperties' + it.util.getProperty($pProperty); $it.errSchemaPath = it.errSchemaPath + '/patternProperties/' + it.util.escapeFragment($pProperty); if ($ownProperties) { out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; '; } else { out += ' for (var ' + ($key) + ' in ' + ($data) + ') { '; } out += ' if (' + (it.usePattern($pProperty)) + '.test(' + ($key) + ')) { '; $it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); var $passData = $data + '[' + $key + ']'; $it.dataPathArr[$dataNxt] = $key; var $code = it.validate($it); $it.baseId = $currentBaseId; if (it.util.varOccurences($code, $nextData) < 2) { out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; } else { out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; } if ($breakOnError) { out += ' if (!' + ($nextValid) + ') break; '; } out += ' } '; if ($breakOnError) { out += ' else ' + ($nextValid) + ' = true; '; } out += ' } '; if ($breakOnError) { out += ' if (' + ($nextValid) + ') { '; $closingBraces += '}'; } } } } } if ($breakOnError) { out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {'; } return out; } /***/ }), /***/ 19195: /***/ ((module) => { "use strict"; module.exports = function generate_propertyNames(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $data = 'data' + ($dataLvl || ''); var $errs = 'errs__' + $lvl; var $it = it.util.copy(it); var $closingBraces = ''; $it.level++; var $nextValid = 'valid' + $it.level; out += 'var ' + ($errs) + ' = errors;'; if ((it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all))) { $it.schema = $schema; $it.schemaPath = $schemaPath; $it.errSchemaPath = $errSchemaPath; var $key = 'key' + $lvl, $idx = 'idx' + $lvl, $i = 'i' + $lvl, $invalidName = '\' + ' + $key + ' + \'', $dataNxt = $it.dataLevel = it.dataLevel + 1, $nextData = 'data' + $dataNxt, $dataProperties = 'dataProperties' + $lvl, $ownProperties = it.opts.ownProperties, $currentBaseId = it.baseId; if ($ownProperties) { out += ' var ' + ($dataProperties) + ' = undefined; '; } if ($ownProperties) { out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; '; } else { out += ' for (var ' + ($key) + ' in ' + ($data) + ') { '; } out += ' var startErrs' + ($lvl) + ' = errors; '; var $passData = $key; var $wasComposite = it.compositeRule; it.compositeRule = $it.compositeRule = true; var $code = it.validate($it); $it.baseId = $currentBaseId; if (it.util.varOccurences($code, $nextData) < 2) { out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; } else { out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; } it.compositeRule = $it.compositeRule = $wasComposite; out += ' if (!' + ($nextValid) + ') { for (var ' + ($i) + '=startErrs' + ($lvl) + '; ' + ($i) + ' { "use strict"; module.exports = function generate_ref(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $data = 'data' + ($dataLvl || ''); var $valid = 'valid' + $lvl; var $async, $refCode; if ($schema == '#' || $schema == '#/') { if (it.isRoot) { $async = it.async; $refCode = 'validate'; } else { $async = it.root.schema.$async === true; $refCode = 'root.refVal[0]'; } } else { var $refVal = it.resolveRef(it.baseId, $schema, it.isRoot); if ($refVal === undefined) { var $message = it.MissingRefError.message(it.baseId, $schema); if (it.opts.missingRefs == 'fail') { it.logger.error($message); var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('$ref') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { ref: \'' + (it.util.escapeQuotes($schema)) + '\' } '; if (it.opts.messages !== false) { out += ' , message: \'can\\\'t resolve reference ' + (it.util.escapeQuotes($schema)) + '\' '; } if (it.opts.verbose) { out += ' , schema: ' + (it.util.toQuotedString($schema)) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } if ($breakOnError) { out += ' if (false) { '; } } else if (it.opts.missingRefs == 'ignore') { it.logger.warn($message); if ($breakOnError) { out += ' if (true) { '; } } else { throw new it.MissingRefError(it.baseId, $schema, $message); } } else if ($refVal.inline) { var $it = it.util.copy(it); $it.level++; var $nextValid = 'valid' + $it.level; $it.schema = $refVal.schema; $it.schemaPath = ''; $it.errSchemaPath = $schema; var $code = it.validate($it).replace(/validate\.schema/g, $refVal.code); out += ' ' + ($code) + ' '; if ($breakOnError) { out += ' if (' + ($nextValid) + ') { '; } } else { $async = $refVal.$async === true || (it.async && $refVal.$async !== false); $refCode = $refVal.code; } } if ($refCode) { var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; if (it.opts.passContext) { out += ' ' + ($refCode) + '.call(this, '; } else { out += ' ' + ($refCode) + '( '; } out += ' ' + ($data) + ', (dataPath || \'\')'; if (it.errorPath != '""') { out += ' + ' + (it.errorPath); } var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData', $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty'; out += ' , ' + ($parentData) + ' , ' + ($parentDataProperty) + ', rootData) '; var __callValidate = out; out = $$outStack.pop(); if ($async) { if (!it.async) throw new Error('async schema referenced by sync schema'); if ($breakOnError) { out += ' var ' + ($valid) + '; '; } out += ' try { await ' + (__callValidate) + '; '; if ($breakOnError) { out += ' ' + ($valid) + ' = true; '; } out += ' } catch (e) { if (!(e instanceof ValidationError)) throw e; if (vErrors === null) vErrors = e.errors; else vErrors = vErrors.concat(e.errors); errors = vErrors.length; '; if ($breakOnError) { out += ' ' + ($valid) + ' = false; '; } out += ' } '; if ($breakOnError) { out += ' if (' + ($valid) + ') { '; } } else { out += ' if (!' + (__callValidate) + ') { if (vErrors === null) vErrors = ' + ($refCode) + '.errors; else vErrors = vErrors.concat(' + ($refCode) + '.errors); errors = vErrors.length; } '; if ($breakOnError) { out += ' else { '; } } } return out; } /***/ }), /***/ 8420: /***/ ((module) => { "use strict"; module.exports = function generate_required(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $data = 'data' + ($dataLvl || ''); var $valid = 'valid' + $lvl; var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue; if ($isData) { out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; $schemaValue = 'schema' + $lvl; } else { $schemaValue = $schema; } var $vSchema = 'schema' + $lvl; if (!$isData) { if ($schema.length < it.opts.loopRequired && it.schema.properties && Object.keys(it.schema.properties).length) { var $required = []; var arr1 = $schema; if (arr1) { var $property, i1 = -1, l1 = arr1.length - 1; while (i1 < l1) { $property = arr1[i1 += 1]; var $propertySch = it.schema.properties[$property]; if (!($propertySch && (it.opts.strictKeywords ? (typeof $propertySch == 'object' && Object.keys($propertySch).length > 0) || $propertySch === false : it.util.schemaHasRules($propertySch, it.RULES.all)))) { $required[$required.length] = $property; } } } } else { var $required = $schema; } } if ($isData || $required.length) { var $currentErrorPath = it.errorPath, $loopRequired = $isData || $required.length >= it.opts.loopRequired, $ownProperties = it.opts.ownProperties; if ($breakOnError) { out += ' var missing' + ($lvl) + '; '; if ($loopRequired) { if (!$isData) { out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; '; } var $i = 'i' + $lvl, $propertyPath = 'schema' + $lvl + '[' + $i + ']', $missingProperty = '\' + ' + $propertyPath + ' + \''; if (it.opts._errorDataPathProperty) { it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers); } out += ' var ' + ($valid) + ' = true; '; if ($isData) { out += ' if (schema' + ($lvl) + ' === undefined) ' + ($valid) + ' = true; else if (!Array.isArray(schema' + ($lvl) + ')) ' + ($valid) + ' = false; else {'; } out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { ' + ($valid) + ' = ' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] !== undefined '; if ($ownProperties) { out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + ']) '; } out += '; if (!' + ($valid) + ') break; } '; if ($isData) { out += ' } '; } out += ' if (!' + ($valid) + ') { '; var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; if (it.opts.messages !== false) { out += ' , message: \''; if (it.opts._errorDataPathProperty) { out += 'is a required property'; } else { out += 'should have required property \\\'' + ($missingProperty) + '\\\''; } out += '\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } out += ' } else { '; } else { out += ' if ( '; var arr2 = $required; if (arr2) { var $propertyKey, $i = -1, l2 = arr2.length - 1; while ($i < l2) { $propertyKey = arr2[$i += 1]; if ($i) { out += ' || '; } var $prop = it.util.getProperty($propertyKey), $useData = $data + $prop; out += ' ( ( ' + ($useData) + ' === undefined '; if ($ownProperties) { out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; } out += ') && (missing' + ($lvl) + ' = ' + (it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop)) + ') ) '; } } out += ') { '; var $propertyPath = 'missing' + $lvl, $missingProperty = '\' + ' + $propertyPath + ' + \''; if (it.opts._errorDataPathProperty) { it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath; } var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; if (it.opts.messages !== false) { out += ' , message: \''; if (it.opts._errorDataPathProperty) { out += 'is a required property'; } else { out += 'should have required property \\\'' + ($missingProperty) + '\\\''; } out += '\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } out += ' } else { '; } } else { if ($loopRequired) { if (!$isData) { out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; '; } var $i = 'i' + $lvl, $propertyPath = 'schema' + $lvl + '[' + $i + ']', $missingProperty = '\' + ' + $propertyPath + ' + \''; if (it.opts._errorDataPathProperty) { it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers); } if ($isData) { out += ' if (' + ($vSchema) + ' && !Array.isArray(' + ($vSchema) + ')) { var err = '; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; if (it.opts.messages !== false) { out += ' , message: \''; if (it.opts._errorDataPathProperty) { out += 'is a required property'; } else { out += 'should have required property \\\'' + ($missingProperty) + '\\\''; } out += '\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if (' + ($vSchema) + ' !== undefined) { '; } out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { if (' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] === undefined '; if ($ownProperties) { out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + ']) '; } out += ') { var err = '; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; if (it.opts.messages !== false) { out += ' , message: \''; if (it.opts._errorDataPathProperty) { out += 'is a required property'; } else { out += 'should have required property \\\'' + ($missingProperty) + '\\\''; } out += '\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } '; if ($isData) { out += ' } '; } } else { var arr3 = $required; if (arr3) { var $propertyKey, i3 = -1, l3 = arr3.length - 1; while (i3 < l3) { $propertyKey = arr3[i3 += 1]; var $prop = it.util.getProperty($propertyKey), $missingProperty = it.util.escapeQuotes($propertyKey), $useData = $data + $prop; if (it.opts._errorDataPathProperty) { it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers); } out += ' if ( ' + ($useData) + ' === undefined '; if ($ownProperties) { out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; } out += ') { var err = '; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; if (it.opts.messages !== false) { out += ' , message: \''; if (it.opts._errorDataPathProperty) { out += 'is a required property'; } else { out += 'should have required property \\\'' + ($missingProperty) + '\\\''; } out += '\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } '; } } } } it.errorPath = $currentErrorPath; } else if ($breakOnError) { out += ' if (true) {'; } return out; } /***/ }), /***/ 24995: /***/ ((module) => { "use strict"; module.exports = function generate_uniqueItems(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $data = 'data' + ($dataLvl || ''); var $valid = 'valid' + $lvl; var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue; if ($isData) { out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; $schemaValue = 'schema' + $lvl; } else { $schemaValue = $schema; } if (($schema || $isData) && it.opts.uniqueItems !== false) { if ($isData) { out += ' var ' + ($valid) + '; if (' + ($schemaValue) + ' === false || ' + ($schemaValue) + ' === undefined) ' + ($valid) + ' = true; else if (typeof ' + ($schemaValue) + ' != \'boolean\') ' + ($valid) + ' = false; else { '; } out += ' var i = ' + ($data) + '.length , ' + ($valid) + ' = true , j; if (i > 1) { '; var $itemType = it.schema.items && it.schema.items.type, $typeIsArray = Array.isArray($itemType); if (!$itemType || $itemType == 'object' || $itemType == 'array' || ($typeIsArray && ($itemType.indexOf('object') >= 0 || $itemType.indexOf('array') >= 0))) { out += ' outer: for (;i--;) { for (j = i; j--;) { if (equal(' + ($data) + '[i], ' + ($data) + '[j])) { ' + ($valid) + ' = false; break outer; } } } '; } else { out += ' var itemIndices = {}, item; for (;i--;) { var item = ' + ($data) + '[i]; '; var $method = 'checkDataType' + ($typeIsArray ? 's' : ''); out += ' if (' + (it.util[$method]($itemType, 'item', it.opts.strictNumbers, true)) + ') continue; '; if ($typeIsArray) { out += ' if (typeof item == \'string\') item = \'"\' + item; '; } out += ' if (typeof itemIndices[item] == \'number\') { ' + ($valid) + ' = false; j = itemIndices[item]; break; } itemIndices[item] = i; } '; } out += ' } '; if ($isData) { out += ' } '; } out += ' if (!' + ($valid) + ') { '; var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('uniqueItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { i: i, j: j } '; if (it.opts.messages !== false) { out += ' , message: \'should NOT have duplicate items (items ## \' + j + \' and \' + i + \' are identical)\' '; } if (it.opts.verbose) { out += ' , schema: '; if ($isData) { out += 'validate.schema' + ($schemaPath); } else { out += '' + ($schema); } out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } out += ' } '; if ($breakOnError) { out += ' else { '; } } else { if ($breakOnError) { out += ' if (true) { '; } } return out; } /***/ }), /***/ 49585: /***/ ((module) => { "use strict"; module.exports = function generate_validate(it, $keyword, $ruleType) { var out = ''; var $async = it.schema.$async === true, $refKeywords = it.util.schemaHasRulesExcept(it.schema, it.RULES.all, '$ref'), $id = it.self._getId(it.schema); if (it.opts.strictKeywords) { var $unknownKwd = it.util.schemaUnknownRules(it.schema, it.RULES.keywords); if ($unknownKwd) { var $keywordsMsg = 'unknown keyword: ' + $unknownKwd; if (it.opts.strictKeywords === 'log') it.logger.warn($keywordsMsg); else throw new Error($keywordsMsg); } } if (it.isTop) { out += ' var validate = '; if ($async) { it.async = true; out += 'async '; } out += 'function(data, dataPath, parentData, parentDataProperty, rootData) { \'use strict\'; '; if ($id && (it.opts.sourceCode || it.opts.processCode)) { out += ' ' + ('/\*# sourceURL=' + $id + ' */') + ' '; } } if (typeof it.schema == 'boolean' || !($refKeywords || it.schema.$ref)) { var $keyword = 'false schema'; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $errorKeyword; var $data = 'data' + ($dataLvl || ''); var $valid = 'valid' + $lvl; if (it.schema === false) { if (it.isTop) { $breakOnError = true; } else { out += ' var ' + ($valid) + ' = false; '; } var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ($errorKeyword || 'false schema') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; if (it.opts.messages !== false) { out += ' , message: \'boolean schema is false\' '; } if (it.opts.verbose) { out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } } else { if (it.isTop) { if ($async) { out += ' return data; '; } else { out += ' validate.errors = null; return true; '; } } else { out += ' var ' + ($valid) + ' = true; '; } } if (it.isTop) { out += ' }; return validate; '; } return out; } if (it.isTop) { var $top = it.isTop, $lvl = it.level = 0, $dataLvl = it.dataLevel = 0, $data = 'data'; it.rootId = it.resolve.fullPath(it.self._getId(it.root.schema)); it.baseId = it.baseId || it.rootId; delete it.isTop; it.dataPathArr = [""]; if (it.schema.default !== undefined && it.opts.useDefaults && it.opts.strictDefaults) { var $defaultMsg = 'default is ignored in the schema root'; if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg); else throw new Error($defaultMsg); } out += ' var vErrors = null; '; out += ' var errors = 0; '; out += ' if (rootData === undefined) rootData = data; '; } else { var $lvl = it.level, $dataLvl = it.dataLevel, $data = 'data' + ($dataLvl || ''); if ($id) it.baseId = it.resolve.url(it.baseId, $id); if ($async && !it.async) throw new Error('async schema in sync schema'); out += ' var errs_' + ($lvl) + ' = errors;'; } var $valid = 'valid' + $lvl, $breakOnError = !it.opts.allErrors, $closingBraces1 = '', $closingBraces2 = ''; var $errorKeyword; var $typeSchema = it.schema.type, $typeIsArray = Array.isArray($typeSchema); if ($typeSchema && it.opts.nullable && it.schema.nullable === true) { if ($typeIsArray) { if ($typeSchema.indexOf('null') == -1) $typeSchema = $typeSchema.concat('null'); } else if ($typeSchema != 'null') { $typeSchema = [$typeSchema, 'null']; $typeIsArray = true; } } if ($typeIsArray && $typeSchema.length == 1) { $typeSchema = $typeSchema[0]; $typeIsArray = false; } if (it.schema.$ref && $refKeywords) { if (it.opts.extendRefs == 'fail') { throw new Error('$ref: validation keywords used in schema at path "' + it.errSchemaPath + '" (see option extendRefs)'); } else if (it.opts.extendRefs !== true) { $refKeywords = false; it.logger.warn('$ref: keywords ignored in schema at path "' + it.errSchemaPath + '"'); } } if (it.schema.$comment && it.opts.$comment) { out += ' ' + (it.RULES.all.$comment.code(it, '$comment')); } if ($typeSchema) { if (it.opts.coerceTypes) { var $coerceToTypes = it.util.coerceToTypes(it.opts.coerceTypes, $typeSchema); } var $rulesGroup = it.RULES.types[$typeSchema]; if ($coerceToTypes || $typeIsArray || $rulesGroup === true || ($rulesGroup && !$shouldUseGroup($rulesGroup))) { var $schemaPath = it.schemaPath + '.type', $errSchemaPath = it.errSchemaPath + '/type'; var $schemaPath = it.schemaPath + '.type', $errSchemaPath = it.errSchemaPath + '/type', $method = $typeIsArray ? 'checkDataTypes' : 'checkDataType'; out += ' if (' + (it.util[$method]($typeSchema, $data, it.opts.strictNumbers, true)) + ') { '; if ($coerceToTypes) { var $dataType = 'dataType' + $lvl, $coerced = 'coerced' + $lvl; out += ' var ' + ($dataType) + ' = typeof ' + ($data) + '; var ' + ($coerced) + ' = undefined; '; if (it.opts.coerceTypes == 'array') { out += ' if (' + ($dataType) + ' == \'object\' && Array.isArray(' + ($data) + ') && ' + ($data) + '.length == 1) { ' + ($data) + ' = ' + ($data) + '[0]; ' + ($dataType) + ' = typeof ' + ($data) + '; if (' + (it.util.checkDataType(it.schema.type, $data, it.opts.strictNumbers)) + ') ' + ($coerced) + ' = ' + ($data) + '; } '; } out += ' if (' + ($coerced) + ' !== undefined) ; '; var arr1 = $coerceToTypes; if (arr1) { var $type, $i = -1, l1 = arr1.length - 1; while ($i < l1) { $type = arr1[$i += 1]; if ($type == 'string') { out += ' else if (' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\') ' + ($coerced) + ' = \'\' + ' + ($data) + '; else if (' + ($data) + ' === null) ' + ($coerced) + ' = \'\'; '; } else if ($type == 'number' || $type == 'integer') { out += ' else if (' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' === null || (' + ($dataType) + ' == \'string\' && ' + ($data) + ' && ' + ($data) + ' == +' + ($data) + ' '; if ($type == 'integer') { out += ' && !(' + ($data) + ' % 1)'; } out += ')) ' + ($coerced) + ' = +' + ($data) + '; '; } else if ($type == 'boolean') { out += ' else if (' + ($data) + ' === \'false\' || ' + ($data) + ' === 0 || ' + ($data) + ' === null) ' + ($coerced) + ' = false; else if (' + ($data) + ' === \'true\' || ' + ($data) + ' === 1) ' + ($coerced) + ' = true; '; } else if ($type == 'null') { out += ' else if (' + ($data) + ' === \'\' || ' + ($data) + ' === 0 || ' + ($data) + ' === false) ' + ($coerced) + ' = null; '; } else if (it.opts.coerceTypes == 'array' && $type == 'array') { out += ' else if (' + ($dataType) + ' == \'string\' || ' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' == null) ' + ($coerced) + ' = [' + ($data) + ']; '; } } } out += ' else { '; var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \''; if ($typeIsArray) { out += '' + ($typeSchema.join(",")); } else { out += '' + ($typeSchema); } out += '\' } '; if (it.opts.messages !== false) { out += ' , message: \'should be '; if ($typeIsArray) { out += '' + ($typeSchema.join(",")); } else { out += '' + ($typeSchema); } out += '\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } out += ' } if (' + ($coerced) + ' !== undefined) { '; var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData', $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty'; out += ' ' + ($data) + ' = ' + ($coerced) + '; '; if (!$dataLvl) { out += 'if (' + ($parentData) + ' !== undefined)'; } out += ' ' + ($parentData) + '[' + ($parentDataProperty) + '] = ' + ($coerced) + '; } '; } else { var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \''; if ($typeIsArray) { out += '' + ($typeSchema.join(",")); } else { out += '' + ($typeSchema); } out += '\' } '; if (it.opts.messages !== false) { out += ' , message: \'should be '; if ($typeIsArray) { out += '' + ($typeSchema.join(",")); } else { out += '' + ($typeSchema); } out += '\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } } out += ' } '; } } if (it.schema.$ref && !$refKeywords) { out += ' ' + (it.RULES.all.$ref.code(it, '$ref')) + ' '; if ($breakOnError) { out += ' } if (errors === '; if ($top) { out += '0'; } else { out += 'errs_' + ($lvl); } out += ') { '; $closingBraces2 += '}'; } } else { var arr2 = it.RULES; if (arr2) { var $rulesGroup, i2 = -1, l2 = arr2.length - 1; while (i2 < l2) { $rulesGroup = arr2[i2 += 1]; if ($shouldUseGroup($rulesGroup)) { if ($rulesGroup.type) { out += ' if (' + (it.util.checkDataType($rulesGroup.type, $data, it.opts.strictNumbers)) + ') { '; } if (it.opts.useDefaults) { if ($rulesGroup.type == 'object' && it.schema.properties) { var $schema = it.schema.properties, $schemaKeys = Object.keys($schema); var arr3 = $schemaKeys; if (arr3) { var $propertyKey, i3 = -1, l3 = arr3.length - 1; while (i3 < l3) { $propertyKey = arr3[i3 += 1]; var $sch = $schema[$propertyKey]; if ($sch.default !== undefined) { var $passData = $data + it.util.getProperty($propertyKey); if (it.compositeRule) { if (it.opts.strictDefaults) { var $defaultMsg = 'default is ignored for: ' + $passData; if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg); else throw new Error($defaultMsg); } } else { out += ' if (' + ($passData) + ' === undefined '; if (it.opts.useDefaults == 'empty') { out += ' || ' + ($passData) + ' === null || ' + ($passData) + ' === \'\' '; } out += ' ) ' + ($passData) + ' = '; if (it.opts.useDefaults == 'shared') { out += ' ' + (it.useDefault($sch.default)) + ' '; } else { out += ' ' + (JSON.stringify($sch.default)) + ' '; } out += '; '; } } } } } else if ($rulesGroup.type == 'array' && Array.isArray(it.schema.items)) { var arr4 = it.schema.items; if (arr4) { var $sch, $i = -1, l4 = arr4.length - 1; while ($i < l4) { $sch = arr4[$i += 1]; if ($sch.default !== undefined) { var $passData = $data + '[' + $i + ']'; if (it.compositeRule) { if (it.opts.strictDefaults) { var $defaultMsg = 'default is ignored for: ' + $passData; if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg); else throw new Error($defaultMsg); } } else { out += ' if (' + ($passData) + ' === undefined '; if (it.opts.useDefaults == 'empty') { out += ' || ' + ($passData) + ' === null || ' + ($passData) + ' === \'\' '; } out += ' ) ' + ($passData) + ' = '; if (it.opts.useDefaults == 'shared') { out += ' ' + (it.useDefault($sch.default)) + ' '; } else { out += ' ' + (JSON.stringify($sch.default)) + ' '; } out += '; '; } } } } } } var arr5 = $rulesGroup.rules; if (arr5) { var $rule, i5 = -1, l5 = arr5.length - 1; while (i5 < l5) { $rule = arr5[i5 += 1]; if ($shouldUseRule($rule)) { var $code = $rule.code(it, $rule.keyword, $rulesGroup.type); if ($code) { out += ' ' + ($code) + ' '; if ($breakOnError) { $closingBraces1 += '}'; } } } } } if ($breakOnError) { out += ' ' + ($closingBraces1) + ' '; $closingBraces1 = ''; } if ($rulesGroup.type) { out += ' } '; if ($typeSchema && $typeSchema === $rulesGroup.type && !$coerceToTypes) { out += ' else { '; var $schemaPath = it.schemaPath + '.type', $errSchemaPath = it.errSchemaPath + '/type'; var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \''; if ($typeIsArray) { out += '' + ($typeSchema.join(",")); } else { out += '' + ($typeSchema); } out += '\' } '; if (it.opts.messages !== false) { out += ' , message: \'should be '; if ($typeIsArray) { out += '' + ($typeSchema.join(",")); } else { out += '' + ($typeSchema); } out += '\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } out += ' } '; } } if ($breakOnError) { out += ' if (errors === '; if ($top) { out += '0'; } else { out += 'errs_' + ($lvl); } out += ') { '; $closingBraces2 += '}'; } } } } } if ($breakOnError) { out += ' ' + ($closingBraces2) + ' '; } if ($top) { if ($async) { out += ' if (errors === 0) return data; '; out += ' else throw new ValidationError(vErrors); '; } else { out += ' validate.errors = vErrors; '; out += ' return errors === 0; '; } out += ' }; return validate;'; } else { out += ' var ' + ($valid) + ' = errors === errs_' + ($lvl) + ';'; } function $shouldUseGroup($rulesGroup) { var rules = $rulesGroup.rules; for (var i = 0; i < rules.length; i++) if ($shouldUseRule(rules[i])) return true; } function $shouldUseRule($rule) { return it.schema[$rule.keyword] !== undefined || ($rule.implements && $ruleImplementsSomeKeyword($rule)); } function $ruleImplementsSomeKeyword($rule) { var impl = $rule.implements; for (var i = 0; i < impl.length; i++) if (it.schema[impl[i]] !== undefined) return true; } return out; } /***/ }), /***/ 53297: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var IDENTIFIER = /^[a-z_$][a-z0-9_$-]*$/i; var customRuleCode = __nccwpck_require__(5912); var definitionSchema = __nccwpck_require__(10458); module.exports = { add: addKeyword, get: getKeyword, remove: removeKeyword, validate: validateKeyword }; /** * Define custom keyword * @this Ajv * @param {String} keyword custom keyword, should be unique (including different from all standard, custom and macro keywords). * @param {Object} definition keyword definition object with properties `type` (type(s) which the keyword applies to), `validate` or `compile`. * @return {Ajv} this for method chaining */ function addKeyword(keyword, definition) { /* jshint validthis: true */ /* eslint no-shadow: 0 */ var RULES = this.RULES; if (RULES.keywords[keyword]) throw new Error('Keyword ' + keyword + ' is already defined'); if (!IDENTIFIER.test(keyword)) throw new Error('Keyword ' + keyword + ' is not a valid identifier'); if (definition) { this.validateKeyword(definition, true); var dataType = definition.type; if (Array.isArray(dataType)) { for (var i=0; i { // Copyright 2011 Mark Cavage All rights reserved. module.exports = { newInvalidAsn1Error: function (msg) { var e = new Error(); e.name = 'InvalidAsn1Error'; e.message = msg || ''; return e; } }; /***/ }), /***/ 194: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // Copyright 2011 Mark Cavage All rights reserved. var errors = __nccwpck_require__(99348); var types = __nccwpck_require__(42473); var Reader = __nccwpck_require__(20290); var Writer = __nccwpck_require__(43200); // --- Exports module.exports = { Reader: Reader, Writer: Writer }; for (var t in types) { if (types.hasOwnProperty(t)) module.exports[t] = types[t]; } for (var e in errors) { if (errors.hasOwnProperty(e)) module.exports[e] = errors[e]; } /***/ }), /***/ 20290: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // Copyright 2011 Mark Cavage All rights reserved. var assert = __nccwpck_require__(39491); var Buffer = (__nccwpck_require__(15118).Buffer); var ASN1 = __nccwpck_require__(42473); var errors = __nccwpck_require__(99348); // --- Globals var newInvalidAsn1Error = errors.newInvalidAsn1Error; // --- API function Reader(data) { if (!data || !Buffer.isBuffer(data)) throw new TypeError('data must be a node Buffer'); this._buf = data; this._size = data.length; // These hold the "current" state this._len = 0; this._offset = 0; } Object.defineProperty(Reader.prototype, 'length', { enumerable: true, get: function () { return (this._len); } }); Object.defineProperty(Reader.prototype, 'offset', { enumerable: true, get: function () { return (this._offset); } }); Object.defineProperty(Reader.prototype, 'remain', { get: function () { return (this._size - this._offset); } }); Object.defineProperty(Reader.prototype, 'buffer', { get: function () { return (this._buf.slice(this._offset)); } }); /** * Reads a single byte and advances offset; you can pass in `true` to make this * a "peek" operation (i.e., get the byte, but don't advance the offset). * * @param {Boolean} peek true means don't move offset. * @return {Number} the next byte, null if not enough data. */ Reader.prototype.readByte = function (peek) { if (this._size - this._offset < 1) return null; var b = this._buf[this._offset] & 0xff; if (!peek) this._offset += 1; return b; }; Reader.prototype.peek = function () { return this.readByte(true); }; /** * Reads a (potentially) variable length off the BER buffer. This call is * not really meant to be called directly, as callers have to manipulate * the internal buffer afterwards. * * As a result of this call, you can call `Reader.length`, until the * next thing called that does a readLength. * * @return {Number} the amount of offset to advance the buffer. * @throws {InvalidAsn1Error} on bad ASN.1 */ Reader.prototype.readLength = function (offset) { if (offset === undefined) offset = this._offset; if (offset >= this._size) return null; var lenB = this._buf[offset++] & 0xff; if (lenB === null) return null; if ((lenB & 0x80) === 0x80) { lenB &= 0x7f; if (lenB === 0) throw newInvalidAsn1Error('Indefinite length not supported'); if (lenB > 4) throw newInvalidAsn1Error('encoding too long'); if (this._size - offset < lenB) return null; this._len = 0; for (var i = 0; i < lenB; i++) this._len = (this._len << 8) + (this._buf[offset++] & 0xff); } else { // Wasn't a variable length this._len = lenB; } return offset; }; /** * Parses the next sequence in this BER buffer. * * To get the length of the sequence, call `Reader.length`. * * @return {Number} the sequence's tag. */ Reader.prototype.readSequence = function (tag) { var seq = this.peek(); if (seq === null) return null; if (tag !== undefined && tag !== seq) throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) + ': got 0x' + seq.toString(16)); var o = this.readLength(this._offset + 1); // stored in `length` if (o === null) return null; this._offset = o; return seq; }; Reader.prototype.readInt = function () { return this._readTag(ASN1.Integer); }; Reader.prototype.readBoolean = function () { return (this._readTag(ASN1.Boolean) === 0 ? false : true); }; Reader.prototype.readEnumeration = function () { return this._readTag(ASN1.Enumeration); }; Reader.prototype.readString = function (tag, retbuf) { if (!tag) tag = ASN1.OctetString; var b = this.peek(); if (b === null) return null; if (b !== tag) throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) + ': got 0x' + b.toString(16)); var o = this.readLength(this._offset + 1); // stored in `length` if (o === null) return null; if (this.length > this._size - o) return null; this._offset = o; if (this.length === 0) return retbuf ? Buffer.alloc(0) : ''; var str = this._buf.slice(this._offset, this._offset + this.length); this._offset += this.length; return retbuf ? str : str.toString('utf8'); }; Reader.prototype.readOID = function (tag) { if (!tag) tag = ASN1.OID; var b = this.readString(tag, true); if (b === null) return null; var values = []; var value = 0; for (var i = 0; i < b.length; i++) { var byte = b[i] & 0xff; value <<= 7; value += byte & 0x7f; if ((byte & 0x80) === 0) { values.push(value); value = 0; } } value = values.shift(); values.unshift(value % 40); values.unshift((value / 40) >> 0); return values.join('.'); }; Reader.prototype._readTag = function (tag) { assert.ok(tag !== undefined); var b = this.peek(); if (b === null) return null; if (b !== tag) throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) + ': got 0x' + b.toString(16)); var o = this.readLength(this._offset + 1); // stored in `length` if (o === null) return null; if (this.length > 4) throw newInvalidAsn1Error('Integer too long: ' + this.length); if (this.length > this._size - o) return null; this._offset = o; var fb = this._buf[this._offset]; var value = 0; for (var i = 0; i < this.length; i++) { value <<= 8; value |= (this._buf[this._offset++] & 0xff); } if ((fb & 0x80) === 0x80 && i !== 4) value -= (1 << (i * 8)); return value >> 0; }; // --- Exported API module.exports = Reader; /***/ }), /***/ 42473: /***/ ((module) => { // Copyright 2011 Mark Cavage All rights reserved. module.exports = { EOC: 0, Boolean: 1, Integer: 2, BitString: 3, OctetString: 4, Null: 5, OID: 6, ObjectDescriptor: 7, External: 8, Real: 9, // float Enumeration: 10, PDV: 11, Utf8String: 12, RelativeOID: 13, Sequence: 16, Set: 17, NumericString: 18, PrintableString: 19, T61String: 20, VideotexString: 21, IA5String: 22, UTCTime: 23, GeneralizedTime: 24, GraphicString: 25, VisibleString: 26, GeneralString: 28, UniversalString: 29, CharacterString: 30, BMPString: 31, Constructor: 32, Context: 128 }; /***/ }), /***/ 43200: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // Copyright 2011 Mark Cavage All rights reserved. var assert = __nccwpck_require__(39491); var Buffer = (__nccwpck_require__(15118).Buffer); var ASN1 = __nccwpck_require__(42473); var errors = __nccwpck_require__(99348); // --- Globals var newInvalidAsn1Error = errors.newInvalidAsn1Error; var DEFAULT_OPTS = { size: 1024, growthFactor: 8 }; // --- Helpers function merge(from, to) { assert.ok(from); assert.equal(typeof (from), 'object'); assert.ok(to); assert.equal(typeof (to), 'object'); var keys = Object.getOwnPropertyNames(from); keys.forEach(function (key) { if (to[key]) return; var value = Object.getOwnPropertyDescriptor(from, key); Object.defineProperty(to, key, value); }); return to; } // --- API function Writer(options) { options = merge(DEFAULT_OPTS, options || {}); this._buf = Buffer.alloc(options.size || 1024); this._size = this._buf.length; this._offset = 0; this._options = options; // A list of offsets in the buffer where we need to insert // sequence tag/len pairs. this._seq = []; } Object.defineProperty(Writer.prototype, 'buffer', { get: function () { if (this._seq.length) throw newInvalidAsn1Error(this._seq.length + ' unended sequence(s)'); return (this._buf.slice(0, this._offset)); } }); Writer.prototype.writeByte = function (b) { if (typeof (b) !== 'number') throw new TypeError('argument must be a Number'); this._ensure(1); this._buf[this._offset++] = b; }; Writer.prototype.writeInt = function (i, tag) { if (typeof (i) !== 'number') throw new TypeError('argument must be a Number'); if (typeof (tag) !== 'number') tag = ASN1.Integer; var sz = 4; while ((((i & 0xff800000) === 0) || ((i & 0xff800000) === 0xff800000 >> 0)) && (sz > 1)) { sz--; i <<= 8; } if (sz > 4) throw newInvalidAsn1Error('BER ints cannot be > 0xffffffff'); this._ensure(2 + sz); this._buf[this._offset++] = tag; this._buf[this._offset++] = sz; while (sz-- > 0) { this._buf[this._offset++] = ((i & 0xff000000) >>> 24); i <<= 8; } }; Writer.prototype.writeNull = function () { this.writeByte(ASN1.Null); this.writeByte(0x00); }; Writer.prototype.writeEnumeration = function (i, tag) { if (typeof (i) !== 'number') throw new TypeError('argument must be a Number'); if (typeof (tag) !== 'number') tag = ASN1.Enumeration; return this.writeInt(i, tag); }; Writer.prototype.writeBoolean = function (b, tag) { if (typeof (b) !== 'boolean') throw new TypeError('argument must be a Boolean'); if (typeof (tag) !== 'number') tag = ASN1.Boolean; this._ensure(3); this._buf[this._offset++] = tag; this._buf[this._offset++] = 0x01; this._buf[this._offset++] = b ? 0xff : 0x00; }; Writer.prototype.writeString = function (s, tag) { if (typeof (s) !== 'string') throw new TypeError('argument must be a string (was: ' + typeof (s) + ')'); if (typeof (tag) !== 'number') tag = ASN1.OctetString; var len = Buffer.byteLength(s); this.writeByte(tag); this.writeLength(len); if (len) { this._ensure(len); this._buf.write(s, this._offset); this._offset += len; } }; Writer.prototype.writeBuffer = function (buf, tag) { if (typeof (tag) !== 'number') throw new TypeError('tag must be a number'); if (!Buffer.isBuffer(buf)) throw new TypeError('argument must be a buffer'); this.writeByte(tag); this.writeLength(buf.length); this._ensure(buf.length); buf.copy(this._buf, this._offset, 0, buf.length); this._offset += buf.length; }; Writer.prototype.writeStringArray = function (strings) { if ((!strings instanceof Array)) throw new TypeError('argument must be an Array[String]'); var self = this; strings.forEach(function (s) { self.writeString(s); }); }; // This is really to solve DER cases, but whatever for now Writer.prototype.writeOID = function (s, tag) { if (typeof (s) !== 'string') throw new TypeError('argument must be a string'); if (typeof (tag) !== 'number') tag = ASN1.OID; if (!/^([0-9]+\.){3,}[0-9]+$/.test(s)) throw new Error('argument is not a valid OID string'); function encodeOctet(bytes, octet) { if (octet < 128) { bytes.push(octet); } else if (octet < 16384) { bytes.push((octet >>> 7) | 0x80); bytes.push(octet & 0x7F); } else if (octet < 2097152) { bytes.push((octet >>> 14) | 0x80); bytes.push(((octet >>> 7) | 0x80) & 0xFF); bytes.push(octet & 0x7F); } else if (octet < 268435456) { bytes.push((octet >>> 21) | 0x80); bytes.push(((octet >>> 14) | 0x80) & 0xFF); bytes.push(((octet >>> 7) | 0x80) & 0xFF); bytes.push(octet & 0x7F); } else { bytes.push(((octet >>> 28) | 0x80) & 0xFF); bytes.push(((octet >>> 21) | 0x80) & 0xFF); bytes.push(((octet >>> 14) | 0x80) & 0xFF); bytes.push(((octet >>> 7) | 0x80) & 0xFF); bytes.push(octet & 0x7F); } } var tmp = s.split('.'); var bytes = []; bytes.push(parseInt(tmp[0], 10) * 40 + parseInt(tmp[1], 10)); tmp.slice(2).forEach(function (b) { encodeOctet(bytes, parseInt(b, 10)); }); var self = this; this._ensure(2 + bytes.length); this.writeByte(tag); this.writeLength(bytes.length); bytes.forEach(function (b) { self.writeByte(b); }); }; Writer.prototype.writeLength = function (len) { if (typeof (len) !== 'number') throw new TypeError('argument must be a Number'); this._ensure(4); if (len <= 0x7f) { this._buf[this._offset++] = len; } else if (len <= 0xff) { this._buf[this._offset++] = 0x81; this._buf[this._offset++] = len; } else if (len <= 0xffff) { this._buf[this._offset++] = 0x82; this._buf[this._offset++] = len >> 8; this._buf[this._offset++] = len; } else if (len <= 0xffffff) { this._buf[this._offset++] = 0x83; this._buf[this._offset++] = len >> 16; this._buf[this._offset++] = len >> 8; this._buf[this._offset++] = len; } else { throw newInvalidAsn1Error('Length too long (> 4 bytes)'); } }; Writer.prototype.startSequence = function (tag) { if (typeof (tag) !== 'number') tag = ASN1.Sequence | ASN1.Constructor; this.writeByte(tag); this._seq.push(this._offset); this._ensure(3); this._offset += 3; }; Writer.prototype.endSequence = function () { var seq = this._seq.pop(); var start = seq + 3; var len = this._offset - start; if (len <= 0x7f) { this._shift(start, len, -2); this._buf[seq] = len; } else if (len <= 0xff) { this._shift(start, len, -1); this._buf[seq] = 0x81; this._buf[seq + 1] = len; } else if (len <= 0xffff) { this._buf[seq] = 0x82; this._buf[seq + 1] = len >> 8; this._buf[seq + 2] = len; } else if (len <= 0xffffff) { this._shift(start, len, 1); this._buf[seq] = 0x83; this._buf[seq + 1] = len >> 16; this._buf[seq + 2] = len >> 8; this._buf[seq + 3] = len; } else { throw newInvalidAsn1Error('Sequence too long'); } }; Writer.prototype._shift = function (start, len, shift) { assert.ok(start !== undefined); assert.ok(len !== undefined); assert.ok(shift); this._buf.copy(this._buf, start + shift, start, start + len); this._offset += shift; }; Writer.prototype._ensure = function (len) { assert.ok(len); if (this._size - this._offset < len) { var sz = this._size * this._options.growthFactor; if (sz - this._offset < len) sz += len; var buf = Buffer.alloc(sz); this._buf.copy(buf, 0, 0, this._offset); this._buf = buf; this._size = sz; } }; // --- Exported API module.exports = Writer; /***/ }), /***/ 80970: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // Copyright 2011 Mark Cavage All rights reserved. // If you have no idea what ASN.1 or BER is, see this: // ftp://ftp.rsa.com/pub/pkcs/ascii/layman.asc var Ber = __nccwpck_require__(194); // --- Exported API module.exports = { Ber: Ber, BerReader: Ber.Reader, BerWriter: Ber.Writer }; /***/ }), /***/ 66631: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // Copyright (c) 2012, Mark Cavage. All rights reserved. // Copyright 2015 Joyent, Inc. var assert = __nccwpck_require__(39491); var Stream = (__nccwpck_require__(12781).Stream); var util = __nccwpck_require__(73837); ///--- Globals /* JSSTYLED */ var UUID_REGEXP = /^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$/; ///--- Internal function _capitalize(str) { return (str.charAt(0).toUpperCase() + str.slice(1)); } function _toss(name, expected, oper, arg, actual) { throw new assert.AssertionError({ message: util.format('%s (%s) is required', name, expected), actual: (actual === undefined) ? typeof (arg) : actual(arg), expected: expected, operator: oper || '===', stackStartFunction: _toss.caller }); } function _getClass(arg) { return (Object.prototype.toString.call(arg).slice(8, -1)); } function noop() { // Why even bother with asserts? } ///--- Exports var types = { bool: { check: function (arg) { return typeof (arg) === 'boolean'; } }, func: { check: function (arg) { return typeof (arg) === 'function'; } }, string: { check: function (arg) { return typeof (arg) === 'string'; } }, object: { check: function (arg) { return typeof (arg) === 'object' && arg !== null; } }, number: { check: function (arg) { return typeof (arg) === 'number' && !isNaN(arg); } }, finite: { check: function (arg) { return typeof (arg) === 'number' && !isNaN(arg) && isFinite(arg); } }, buffer: { check: function (arg) { return Buffer.isBuffer(arg); }, operator: 'Buffer.isBuffer' }, array: { check: function (arg) { return Array.isArray(arg); }, operator: 'Array.isArray' }, stream: { check: function (arg) { return arg instanceof Stream; }, operator: 'instanceof', actual: _getClass }, date: { check: function (arg) { return arg instanceof Date; }, operator: 'instanceof', actual: _getClass }, regexp: { check: function (arg) { return arg instanceof RegExp; }, operator: 'instanceof', actual: _getClass }, uuid: { check: function (arg) { return typeof (arg) === 'string' && UUID_REGEXP.test(arg); }, operator: 'isUUID' } }; function _setExports(ndebug) { var keys = Object.keys(types); var out; /* re-export standard assert */ if (process.env.NODE_NDEBUG) { out = noop; } else { out = function (arg, msg) { if (!arg) { _toss(msg, 'true', arg); } }; } /* standard checks */ keys.forEach(function (k) { if (ndebug) { out[k] = noop; return; } var type = types[k]; out[k] = function (arg, msg) { if (!type.check(arg)) { _toss(msg, k, type.operator, arg, type.actual); } }; }); /* optional checks */ keys.forEach(function (k) { var name = 'optional' + _capitalize(k); if (ndebug) { out[name] = noop; return; } var type = types[k]; out[name] = function (arg, msg) { if (arg === undefined || arg === null) { return; } if (!type.check(arg)) { _toss(msg, k, type.operator, arg, type.actual); } }; }); /* arrayOf checks */ keys.forEach(function (k) { var name = 'arrayOf' + _capitalize(k); if (ndebug) { out[name] = noop; return; } var type = types[k]; var expected = '[' + k + ']'; out[name] = function (arg, msg) { if (!Array.isArray(arg)) { _toss(msg, expected, type.operator, arg, type.actual); } var i; for (i = 0; i < arg.length; i++) { if (!type.check(arg[i])) { _toss(msg, expected, type.operator, arg, type.actual); } } }; }); /* optionalArrayOf checks */ keys.forEach(function (k) { var name = 'optionalArrayOf' + _capitalize(k); if (ndebug) { out[name] = noop; return; } var type = types[k]; var expected = '[' + k + ']'; out[name] = function (arg, msg) { if (arg === undefined || arg === null) { return; } if (!Array.isArray(arg)) { _toss(msg, expected, type.operator, arg, type.actual); } var i; for (i = 0; i < arg.length; i++) { if (!type.check(arg[i])) { _toss(msg, expected, type.operator, arg, type.actual); } } }; }); /* re-export built-in assertions */ Object.keys(assert).forEach(function (k) { if (k === 'AssertionError') { out[k] = assert[k]; return; } if (ndebug) { out[k] = noop; return; } out[k] = assert[k]; }); /* export ourselves (for unit tests _only_) */ out._setExports = _setExports; return out; } module.exports = _setExports(process.env.NODE_NDEBUG); /***/ }), /***/ 41299: /***/ (function(__unused_webpack_module, exports) { !function(e,t){ true?t(exports):0}(this,(function(e){"use strict";class t extends Error{constructor(e){super(null!=e?`Timed out after waiting for ${e} ms`:"Timed out"),Object.setPrototypeOf(this,t.prototype)}}const o=(e,t)=>new Promise(((o,n)=>{try{e.schedule(o,t)}catch(e){n(e)}})),n={schedule:(e,t)=>{let o;const n=e=>{null!=e&&clearTimeout(e),o=void 0};return o=setTimeout((()=>{n(o),e()}),t),{cancel:()=>n(o)}}},i=Number.POSITIVE_INFINITY,r=(e,r,l)=>{var u,s;const c=null!==(u="number"==typeof r?r:null==r?void 0:r.timeout)&&void 0!==u?u:5e3,d=null!==(s="number"==typeof r?l:null==r?void 0:r.intervalBetweenAttempts)&&void 0!==s?s:50;let a=!1;const f=()=>new Promise(((t,i)=>{const r=()=>{a||new Promise(((t,o)=>{try{t(e())}catch(e){o(e)}})).then((e=>{e?t(e):o(n,d).then(r).catch(i)})).catch(i)};r()})),T=c!==i?()=>o(n,c).then((()=>{throw a=!0,new t(c)})):void 0;return null!=T?Promise.race([f(),T()]):f()};e.DEFAULT_INTERVAL_BETWEEN_ATTEMPTS_IN_MS=50,e.DEFAULT_TIMEOUT_IN_MS=5e3,e.TimeoutError=t,e.WAIT_FOREVER=i,e.default=r,e.waitUntil=r,Object.defineProperty(e,"__esModule",{value:!0})}));//# sourceMappingURL=index.js.map /***/ }), /***/ 14812: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { module.exports = { parallel : __nccwpck_require__(8210), serial : __nccwpck_require__(50445), serialOrdered : __nccwpck_require__(3578) }; /***/ }), /***/ 1700: /***/ ((module) => { // API module.exports = abort; /** * Aborts leftover active jobs * * @param {object} state - current state object */ function abort(state) { Object.keys(state.jobs).forEach(clean.bind(state)); // reset leftover jobs state.jobs = {}; } /** * Cleans up leftover job by invoking abort function for the provided job id * * @this state * @param {string|number} key - job id to abort */ function clean(key) { if (typeof this.jobs[key] == 'function') { this.jobs[key](); } } /***/ }), /***/ 72794: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var defer = __nccwpck_require__(15295); // API module.exports = async; /** * Runs provided callback asynchronously * even if callback itself is not * * @param {function} callback - callback to invoke * @returns {function} - augmented callback */ function async(callback) { var isAsync = false; // check if async happened defer(function() { isAsync = true; }); return function async_callback(err, result) { if (isAsync) { callback(err, result); } else { defer(function nextTick_callback() { callback(err, result); }); } }; } /***/ }), /***/ 15295: /***/ ((module) => { module.exports = defer; /** * Runs provided function on next iteration of the event loop * * @param {function} fn - function to run */ function defer(fn) { var nextTick = typeof setImmediate == 'function' ? setImmediate : ( typeof process == 'object' && typeof process.nextTick == 'function' ? process.nextTick : null ); if (nextTick) { nextTick(fn); } else { setTimeout(fn, 0); } } /***/ }), /***/ 9023: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var async = __nccwpck_require__(72794) , abort = __nccwpck_require__(1700) ; // API module.exports = iterate; /** * Iterates over each job object * * @param {array|object} list - array or object (named list) to iterate over * @param {function} iterator - iterator to run * @param {object} state - current job status * @param {function} callback - invoked when all elements processed */ function iterate(list, iterator, state, callback) { // store current index var key = state['keyedList'] ? state['keyedList'][state.index] : state.index; state.jobs[key] = runJob(iterator, key, list[key], function(error, output) { // don't repeat yourself // skip secondary callbacks if (!(key in state.jobs)) { return; } // clean up jobs delete state.jobs[key]; if (error) { // don't process rest of the results // stop still active jobs // and reset the list abort(state); } else { state.results[key] = output; } // return salvaged results callback(error, state.results); }); } /** * Runs iterator over provided job element * * @param {function} iterator - iterator to invoke * @param {string|number} key - key/index of the element in the list of jobs * @param {mixed} item - job description * @param {function} callback - invoked after iterator is done with the job * @returns {function|mixed} - job abort function or something else */ function runJob(iterator, key, item, callback) { var aborter; // allow shortcut if iterator expects only two arguments if (iterator.length == 2) { aborter = iterator(item, async(callback)); } // otherwise go with full three arguments else { aborter = iterator(item, key, async(callback)); } return aborter; } /***/ }), /***/ 42474: /***/ ((module) => { // API module.exports = state; /** * Creates initial state object * for iteration over list * * @param {array|object} list - list to iterate over * @param {function|null} sortMethod - function to use for keys sort, * or `null` to keep them as is * @returns {object} - initial state object */ function state(list, sortMethod) { var isNamedList = !Array.isArray(list) , initState = { index : 0, keyedList: isNamedList || sortMethod ? Object.keys(list) : null, jobs : {}, results : isNamedList ? {} : [], size : isNamedList ? Object.keys(list).length : list.length } ; if (sortMethod) { // sort array keys based on it's values // sort object's keys just on own merit initState.keyedList.sort(isNamedList ? sortMethod : function(a, b) { return sortMethod(list[a], list[b]); }); } return initState; } /***/ }), /***/ 37942: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var abort = __nccwpck_require__(1700) , async = __nccwpck_require__(72794) ; // API module.exports = terminator; /** * Terminates jobs in the attached state context * * @this AsyncKitState# * @param {function} callback - final callback to invoke after termination */ function terminator(callback) { if (!Object.keys(this.jobs).length) { return; } // fast forward iteration index this.index = this.size; // abort jobs abort(this); // send back results we have so far async(callback)(null, this.results); } /***/ }), /***/ 8210: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var iterate = __nccwpck_require__(9023) , initState = __nccwpck_require__(42474) , terminator = __nccwpck_require__(37942) ; // Public API module.exports = parallel; /** * Runs iterator over provided array elements in parallel * * @param {array|object} list - array or object (named list) to iterate over * @param {function} iterator - iterator to run * @param {function} callback - invoked when all elements processed * @returns {function} - jobs terminator */ function parallel(list, iterator, callback) { var state = initState(list); while (state.index < (state['keyedList'] || list).length) { iterate(list, iterator, state, function(error, result) { if (error) { callback(error, result); return; } // looks like it's the last one if (Object.keys(state.jobs).length === 0) { callback(null, state.results); return; } }); state.index++; } return terminator.bind(state, callback); } /***/ }), /***/ 50445: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var serialOrdered = __nccwpck_require__(3578); // Public API module.exports = serial; /** * Runs iterator over provided array elements in series * * @param {array|object} list - array or object (named list) to iterate over * @param {function} iterator - iterator to run * @param {function} callback - invoked when all elements processed * @returns {function} - jobs terminator */ function serial(list, iterator, callback) { return serialOrdered(list, iterator, null, callback); } /***/ }), /***/ 3578: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var iterate = __nccwpck_require__(9023) , initState = __nccwpck_require__(42474) , terminator = __nccwpck_require__(37942) ; // Public API module.exports = serialOrdered; // sorting helpers module.exports.ascending = ascending; module.exports.descending = descending; /** * Runs iterator over provided sorted array elements in series * * @param {array|object} list - array or object (named list) to iterate over * @param {function} iterator - iterator to run * @param {function} sortMethod - custom sort function * @param {function} callback - invoked when all elements processed * @returns {function} - jobs terminator */ function serialOrdered(list, iterator, sortMethod, callback) { var state = initState(list, sortMethod); iterate(list, iterator, state, function iteratorHandler(error, result) { if (error) { callback(error, result); return; } state.index++; // are we there yet? if (state.index < (state['keyedList'] || list).length) { iterate(list, iterator, state, iteratorHandler); return; } // done here callback(null, state.results); }); return terminator.bind(state, callback); } /* * -- Sort methods */ /** * sort helper to sort array elements in ascending order * * @param {mixed} a - an item to compare * @param {mixed} b - an item to compare * @returns {number} - comparison result */ function ascending(a, b) { return a < b ? -1 : a > b ? 1 : 0; } /** * sort helper to sort array elements in descending order * * @param {mixed} a - an item to compare * @param {mixed} b - an item to compare * @returns {number} - comparison result */ function descending(a, b) { return -1 * ascending(a, b); } /***/ }), /***/ 96342: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /*! * Copyright 2010 LearnBoost * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Module dependencies. */ var crypto = __nccwpck_require__(6113) , parse = (__nccwpck_require__(57310).parse) ; /** * Valid keys. */ var keys = [ 'acl' , 'location' , 'logging' , 'notification' , 'partNumber' , 'policy' , 'requestPayment' , 'torrent' , 'uploadId' , 'uploads' , 'versionId' , 'versioning' , 'versions' , 'website' ] /** * Return an "Authorization" header value with the given `options` * in the form of "AWS :" * * @param {Object} options * @return {String} * @api private */ function authorization (options) { return 'AWS ' + options.key + ':' + sign(options) } module.exports = authorization module.exports.authorization = authorization /** * Simple HMAC-SHA1 Wrapper * * @param {Object} options * @return {String} * @api private */ function hmacSha1 (options) { return crypto.createHmac('sha1', options.secret).update(options.message).digest('base64') } module.exports.hmacSha1 = hmacSha1 /** * Create a base64 sha1 HMAC for `options`. * * @param {Object} options * @return {String} * @api private */ function sign (options) { options.message = stringToSign(options) return hmacSha1(options) } module.exports.sign = sign /** * Create a base64 sha1 HMAC for `options`. * * Specifically to be used with S3 presigned URLs * * @param {Object} options * @return {String} * @api private */ function signQuery (options) { options.message = queryStringToSign(options) return hmacSha1(options) } module.exports.signQuery= signQuery /** * Return a string for sign() with the given `options`. * * Spec: * * \n * \n * \n * \n * [headers\n] * * * @param {Object} options * @return {String} * @api private */ function stringToSign (options) { var headers = options.amazonHeaders || '' if (headers) headers += '\n' var r = [ options.verb , options.md5 , options.contentType , options.date ? options.date.toUTCString() : '' , headers + options.resource ] return r.join('\n') } module.exports.stringToSign = stringToSign /** * Return a string for sign() with the given `options`, but is meant exclusively * for S3 presigned URLs * * Spec: * * \n * * * @param {Object} options * @return {String} * @api private */ function queryStringToSign (options){ return 'GET\n\n\n' + options.date + '\n' + options.resource } module.exports.queryStringToSign = queryStringToSign /** * Perform the following: * * - ignore non-amazon headers * - lowercase fields * - sort lexicographically * - trim whitespace between ":" * - join with newline * * @param {Object} headers * @return {String} * @api private */ function canonicalizeHeaders (headers) { var buf = [] , fields = Object.keys(headers) ; for (var i = 0, len = fields.length; i < len; ++i) { var field = fields[i] , val = headers[field] , field = field.toLowerCase() ; if (0 !== field.indexOf('x-amz')) continue buf.push(field + ':' + val) } return buf.sort().join('\n') } module.exports.canonicalizeHeaders = canonicalizeHeaders /** * Perform the following: * * - ignore non sub-resources * - sort lexicographically * * @param {String} resource * @return {String} * @api private */ function canonicalizeResource (resource) { var url = parse(resource, true) , path = url.pathname , buf = [] ; Object.keys(url.query).forEach(function(key){ if (!~keys.indexOf(key)) return var val = '' == url.query[key] ? '' : '=' + encodeURIComponent(url.query[key]) buf.push(key + val) }) return path + (buf.length ? '?' + buf.sort().join('&') : '') } module.exports.canonicalizeResource = canonicalizeResource /***/ }), /***/ 16071: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { var aws4 = exports, url = __nccwpck_require__(57310), querystring = __nccwpck_require__(63477), crypto = __nccwpck_require__(6113), lru = __nccwpck_require__(74225), credentialsCache = lru(1000) // http://docs.amazonwebservices.com/general/latest/gr/signature-version-4.html function hmac(key, string, encoding) { return crypto.createHmac('sha256', key).update(string, 'utf8').digest(encoding) } function hash(string, encoding) { return crypto.createHash('sha256').update(string, 'utf8').digest(encoding) } // This function assumes the string has already been percent encoded function encodeRfc3986(urlEncodedString) { return urlEncodedString.replace(/[!'()*]/g, function(c) { return '%' + c.charCodeAt(0).toString(16).toUpperCase() }) } function encodeRfc3986Full(str) { return encodeRfc3986(encodeURIComponent(str)) } // A bit of a combination of: // https://github.com/aws/aws-sdk-java-v2/blob/dc695de6ab49ad03934e1b02e7263abbd2354be0/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal/AbstractAws4Signer.java#L59 // https://github.com/aws/aws-sdk-js/blob/18cb7e5b463b46239f9fdd4a65e2ff8c81831e8f/lib/signers/v4.js#L191-L199 // https://github.com/mhart/aws4fetch/blob/b3aed16b6f17384cf36ea33bcba3c1e9f3bdfefd/src/main.js#L25-L34 var HEADERS_TO_IGNORE = { 'authorization': true, 'connection': true, 'x-amzn-trace-id': true, 'user-agent': true, 'expect': true, 'presigned-expires': true, 'range': true, } // request: { path | body, [host], [method], [headers], [service], [region] } // credentials: { accessKeyId, secretAccessKey, [sessionToken] } function RequestSigner(request, credentials) { if (typeof request === 'string') request = url.parse(request) var headers = request.headers = (request.headers || {}), hostParts = (!this.service || !this.region) && this.matchHost(request.hostname || request.host || headers.Host || headers.host) this.request = request this.credentials = credentials || this.defaultCredentials() this.service = request.service || hostParts[0] || '' this.region = request.region || hostParts[1] || 'us-east-1' // SES uses a different domain from the service name if (this.service === 'email') this.service = 'ses' if (!request.method && request.body) request.method = 'POST' if (!headers.Host && !headers.host) { headers.Host = request.hostname || request.host || this.createHost() // If a port is specified explicitly, use it as is if (request.port) headers.Host += ':' + request.port } if (!request.hostname && !request.host) request.hostname = headers.Host || headers.host this.isCodeCommitGit = this.service === 'codecommit' && request.method === 'GIT' this.extraHeadersToIgnore = request.extraHeadersToIgnore || Object.create(null) this.extraHeadersToInclude = request.extraHeadersToInclude || Object.create(null) } RequestSigner.prototype.matchHost = function(host) { var match = (host || '').match(/([^\.]+)\.(?:([^\.]*)\.)?amazonaws\.com(\.cn)?$/) var hostParts = (match || []).slice(1, 3) // ES's hostParts are sometimes the other way round, if the value that is expected // to be region equals ‘es’ switch them back // e.g. search-cluster-name-aaaa00aaaa0aaa0aaaaaaa0aaa.us-east-1.es.amazonaws.com if (hostParts[1] === 'es' || hostParts[1] === 'aoss') hostParts = hostParts.reverse() if (hostParts[1] == 's3') { hostParts[0] = 's3' hostParts[1] = 'us-east-1' } else { for (var i = 0; i < 2; i++) { if (/^s3-/.test(hostParts[i])) { hostParts[1] = hostParts[i].slice(3) hostParts[0] = 's3' break } } } return hostParts } // http://docs.aws.amazon.com/general/latest/gr/rande.html RequestSigner.prototype.isSingleRegion = function() { // Special case for S3 and SimpleDB in us-east-1 if (['s3', 'sdb'].indexOf(this.service) >= 0 && this.region === 'us-east-1') return true return ['cloudfront', 'ls', 'route53', 'iam', 'importexport', 'sts'] .indexOf(this.service) >= 0 } RequestSigner.prototype.createHost = function() { var region = this.isSingleRegion() ? '' : '.' + this.region, subdomain = this.service === 'ses' ? 'email' : this.service return subdomain + region + '.amazonaws.com' } RequestSigner.prototype.prepareRequest = function() { this.parsePath() var request = this.request, headers = request.headers, query if (request.signQuery) { this.parsedPath.query = query = this.parsedPath.query || {} if (this.credentials.sessionToken) query['X-Amz-Security-Token'] = this.credentials.sessionToken if (this.service === 's3' && !query['X-Amz-Expires']) query['X-Amz-Expires'] = 86400 if (query['X-Amz-Date']) this.datetime = query['X-Amz-Date'] else query['X-Amz-Date'] = this.getDateTime() query['X-Amz-Algorithm'] = 'AWS4-HMAC-SHA256' query['X-Amz-Credential'] = this.credentials.accessKeyId + '/' + this.credentialString() query['X-Amz-SignedHeaders'] = this.signedHeaders() } else { if (!request.doNotModifyHeaders && !this.isCodeCommitGit) { if (request.body && !headers['Content-Type'] && !headers['content-type']) headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8' if (request.body && !headers['Content-Length'] && !headers['content-length']) headers['Content-Length'] = Buffer.byteLength(request.body) if (this.credentials.sessionToken && !headers['X-Amz-Security-Token'] && !headers['x-amz-security-token']) headers['X-Amz-Security-Token'] = this.credentials.sessionToken if (this.service === 's3' && !headers['X-Amz-Content-Sha256'] && !headers['x-amz-content-sha256']) headers['X-Amz-Content-Sha256'] = hash(this.request.body || '', 'hex') if (headers['X-Amz-Date'] || headers['x-amz-date']) this.datetime = headers['X-Amz-Date'] || headers['x-amz-date'] else headers['X-Amz-Date'] = this.getDateTime() } delete headers.Authorization delete headers.authorization } } RequestSigner.prototype.sign = function() { if (!this.parsedPath) this.prepareRequest() if (this.request.signQuery) { this.parsedPath.query['X-Amz-Signature'] = this.signature() } else { this.request.headers.Authorization = this.authHeader() } this.request.path = this.formatPath() return this.request } RequestSigner.prototype.getDateTime = function() { if (!this.datetime) { var headers = this.request.headers, date = new Date(headers.Date || headers.date || new Date) this.datetime = date.toISOString().replace(/[:\-]|\.\d{3}/g, '') // Remove the trailing 'Z' on the timestamp string for CodeCommit git access if (this.isCodeCommitGit) this.datetime = this.datetime.slice(0, -1) } return this.datetime } RequestSigner.prototype.getDate = function() { return this.getDateTime().substr(0, 8) } RequestSigner.prototype.authHeader = function() { return [ 'AWS4-HMAC-SHA256 Credential=' + this.credentials.accessKeyId + '/' + this.credentialString(), 'SignedHeaders=' + this.signedHeaders(), 'Signature=' + this.signature(), ].join(', ') } RequestSigner.prototype.signature = function() { var date = this.getDate(), cacheKey = [this.credentials.secretAccessKey, date, this.region, this.service].join(), kDate, kRegion, kService, kCredentials = credentialsCache.get(cacheKey) if (!kCredentials) { kDate = hmac('AWS4' + this.credentials.secretAccessKey, date) kRegion = hmac(kDate, this.region) kService = hmac(kRegion, this.service) kCredentials = hmac(kService, 'aws4_request') credentialsCache.set(cacheKey, kCredentials) } return hmac(kCredentials, this.stringToSign(), 'hex') } RequestSigner.prototype.stringToSign = function() { return [ 'AWS4-HMAC-SHA256', this.getDateTime(), this.credentialString(), hash(this.canonicalString(), 'hex'), ].join('\n') } RequestSigner.prototype.canonicalString = function() { if (!this.parsedPath) this.prepareRequest() var pathStr = this.parsedPath.path, query = this.parsedPath.query, headers = this.request.headers, queryStr = '', normalizePath = this.service !== 's3', decodePath = this.service === 's3' || this.request.doNotEncodePath, decodeSlashesInPath = this.service === 's3', firstValOnly = this.service === 's3', bodyHash if (this.service === 's3' && this.request.signQuery) { bodyHash = 'UNSIGNED-PAYLOAD' } else if (this.isCodeCommitGit) { bodyHash = '' } else { bodyHash = headers['X-Amz-Content-Sha256'] || headers['x-amz-content-sha256'] || hash(this.request.body || '', 'hex') } if (query) { var reducedQuery = Object.keys(query).reduce(function(obj, key) { if (!key) return obj obj[encodeRfc3986Full(key)] = !Array.isArray(query[key]) ? query[key] : (firstValOnly ? query[key][0] : query[key]) return obj }, {}) var encodedQueryPieces = [] Object.keys(reducedQuery).sort().forEach(function(key) { if (!Array.isArray(reducedQuery[key])) { encodedQueryPieces.push(key + '=' + encodeRfc3986Full(reducedQuery[key])) } else { reducedQuery[key].map(encodeRfc3986Full).sort() .forEach(function(val) { encodedQueryPieces.push(key + '=' + val) }) } }) queryStr = encodedQueryPieces.join('&') } if (pathStr !== '/') { if (normalizePath) pathStr = pathStr.replace(/\/{2,}/g, '/') pathStr = pathStr.split('/').reduce(function(path, piece) { if (normalizePath && piece === '..') { path.pop() } else if (!normalizePath || piece !== '.') { if (decodePath) piece = decodeURIComponent(piece.replace(/\+/g, ' ')) path.push(encodeRfc3986Full(piece)) } return path }, []).join('/') if (pathStr[0] !== '/') pathStr = '/' + pathStr if (decodeSlashesInPath) pathStr = pathStr.replace(/%2F/g, '/') } return [ this.request.method || 'GET', pathStr, queryStr, this.canonicalHeaders() + '\n', this.signedHeaders(), bodyHash, ].join('\n') } RequestSigner.prototype.canonicalHeaders = function() { var headers = this.request.headers function trimAll(header) { return header.toString().trim().replace(/\s+/g, ' ') } return Object.keys(headers) .filter(function(key) { return HEADERS_TO_IGNORE[key.toLowerCase()] == null }) .sort(function(a, b) { return a.toLowerCase() < b.toLowerCase() ? -1 : 1 }) .map(function(key) { return key.toLowerCase() + ':' + trimAll(headers[key]) }) .join('\n') } RequestSigner.prototype.signedHeaders = function() { var extraHeadersToInclude = this.extraHeadersToInclude, extraHeadersToIgnore = this.extraHeadersToIgnore return Object.keys(this.request.headers) .map(function(key) { return key.toLowerCase() }) .filter(function(key) { return extraHeadersToInclude[key] || (HEADERS_TO_IGNORE[key] == null && !extraHeadersToIgnore[key]) }) .sort() .join(';') } RequestSigner.prototype.credentialString = function() { return [ this.getDate(), this.region, this.service, 'aws4_request', ].join('/') } RequestSigner.prototype.defaultCredentials = function() { var env = process.env return { accessKeyId: env.AWS_ACCESS_KEY_ID || env.AWS_ACCESS_KEY, secretAccessKey: env.AWS_SECRET_ACCESS_KEY || env.AWS_SECRET_KEY, sessionToken: env.AWS_SESSION_TOKEN, } } RequestSigner.prototype.parsePath = function() { var path = this.request.path || '/' // S3 doesn't always encode characters > 127 correctly and // all services don't encode characters > 255 correctly // So if there are non-reserved chars (and it's not already all % encoded), just encode them all if (/[^0-9A-Za-z;,/?:@&=+$\-_.!~*'()#%]/.test(path)) { path = encodeURI(decodeURI(path)) } var queryIx = path.indexOf('?'), query = null if (queryIx >= 0) { query = querystring.parse(path.slice(queryIx + 1)) path = path.slice(0, queryIx) } this.parsedPath = { path: path, query: query, } } RequestSigner.prototype.formatPath = function() { var path = this.parsedPath.path, query = this.parsedPath.query if (!query) return path // Services don't support empty query string keys if (query[''] != null) delete query[''] return path + '?' + encodeRfc3986(querystring.stringify(query)) } aws4.RequestSigner = RequestSigner aws4.sign = function(request, credentials) { return new RequestSigner(request, credentials).sign() } /***/ }), /***/ 74225: /***/ ((module) => { module.exports = function(size) { return new LruCache(size) } function LruCache(size) { this.capacity = size | 0 this.map = Object.create(null) this.list = new DoublyLinkedList() } LruCache.prototype.get = function(key) { var node = this.map[key] if (node == null) return undefined this.used(node) return node.val } LruCache.prototype.set = function(key, val) { var node = this.map[key] if (node != null) { node.val = val } else { if (!this.capacity) this.prune() if (!this.capacity) return false node = new DoublyLinkedNode(key, val) this.map[key] = node this.capacity-- } this.used(node) return true } LruCache.prototype.used = function(node) { this.list.moveToFront(node) } LruCache.prototype.prune = function() { var node = this.list.pop() if (node != null) { delete this.map[node.key] this.capacity++ } } function DoublyLinkedList() { this.firstNode = null this.lastNode = null } DoublyLinkedList.prototype.moveToFront = function(node) { if (this.firstNode == node) return this.remove(node) if (this.firstNode == null) { this.firstNode = node this.lastNode = node node.prev = null node.next = null } else { node.prev = null node.next = this.firstNode node.next.prev = node this.firstNode = node } } DoublyLinkedList.prototype.pop = function() { var lastNode = this.lastNode if (lastNode != null) { this.remove(lastNode) } return lastNode } DoublyLinkedList.prototype.remove = function(node) { if (this.firstNode == node) { this.firstNode = node.next } else if (node.prev != null) { node.prev.next = node.next } if (this.lastNode == node) { this.lastNode = node.prev } else if (node.next != null) { node.next.prev = node.prev } } function DoublyLinkedNode(key, val) { this.key = key this.val = val this.prev = null this.next = null } /***/ }), /***/ 9417: /***/ ((module) => { "use strict"; module.exports = balanced; function balanced(a, b, str) { if (a instanceof RegExp) a = maybeMatch(a, str); if (b instanceof RegExp) b = maybeMatch(b, str); var r = range(a, b, str); return r && { start: r[0], end: r[1], pre: str.slice(0, r[0]), body: str.slice(r[0] + a.length, r[1]), post: str.slice(r[1] + b.length) }; } function maybeMatch(reg, str) { var m = str.match(reg); return m ? m[0] : null; } balanced.range = range; function range(a, b, str) { var begs, beg, left, right, result; var ai = str.indexOf(a); var bi = str.indexOf(b, ai + 1); var i = ai; if (ai >= 0 && bi > 0) { if(a===b) { return [ai, bi]; } begs = []; left = str.length; while (i >= 0 && !result) { if (i == ai) { begs.push(i); ai = str.indexOf(a, i + 1); } else if (begs.length == 1) { result = [ begs.pop(), bi ]; } else { beg = begs.pop(); if (beg < left) { left = beg; right = bi; } bi = str.indexOf(b, i + 1); } i = ai < bi && ai >= 0 ? ai : bi; } if (begs.length) { result = [ left, right ]; } } return result; } /***/ }), /***/ 85848: /***/ (function(module, exports, __nccwpck_require__) { /* module decorator */ module = __nccwpck_require__.nmd(module); /*! https://mths.be/base64 v1.0.0 by @mathias | MIT license */ ;(function(root) { // Detect free variables `exports`. var freeExports = true && exports; // Detect free variable `module`. var freeModule = true && module && module.exports == freeExports && module; // Detect free variable `global`, from Node.js or Browserified code, and use // it as `root`. var freeGlobal = typeof global == 'object' && global; if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) { root = freeGlobal; } /*--------------------------------------------------------------------------*/ var InvalidCharacterError = function(message) { this.message = message; }; InvalidCharacterError.prototype = new Error; InvalidCharacterError.prototype.name = 'InvalidCharacterError'; var error = function(message) { // Note: the error messages used throughout this file match those used by // the native `atob`/`btoa` implementation in Chromium. throw new InvalidCharacterError(message); }; var TABLE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; // http://whatwg.org/html/common-microsyntaxes.html#space-character var REGEX_SPACE_CHARACTERS = /[\t\n\f\r ]/g; // `decode` is designed to be fully compatible with `atob` as described in the // HTML Standard. http://whatwg.org/html/webappapis.html#dom-windowbase64-atob // The optimized base64-decoding algorithm used is based on @atk’s excellent // implementation. https://gist.github.com/atk/1020396 var decode = function(input) { input = String(input) .replace(REGEX_SPACE_CHARACTERS, ''); var length = input.length; if (length % 4 == 0) { input = input.replace(/==?$/, ''); length = input.length; } if ( length % 4 == 1 || // http://whatwg.org/C#alphanumeric-ascii-characters /[^+a-zA-Z0-9/]/.test(input) ) { error( 'Invalid character: the string to be decoded is not correctly encoded.' ); } var bitCounter = 0; var bitStorage; var buffer; var output = ''; var position = -1; while (++position < length) { buffer = TABLE.indexOf(input.charAt(position)); bitStorage = bitCounter % 4 ? bitStorage * 64 + buffer : buffer; // Unless this is the first of a group of 4 characters… if (bitCounter++ % 4) { // …convert the first 8 bits to a single ASCII character. output += String.fromCharCode( 0xFF & bitStorage >> (-2 * bitCounter & 6) ); } } return output; }; // `encode` is designed to be fully compatible with `btoa` as described in the // HTML Standard: http://whatwg.org/html/webappapis.html#dom-windowbase64-btoa var encode = function(input) { input = String(input); if (/[^\0-\xFF]/.test(input)) { // Note: no need to special-case astral symbols here, as surrogates are // matched, and the input is supposed to only contain ASCII anyway. error( 'The string to be encoded contains characters outside of the ' + 'Latin1 range.' ); } var padding = input.length % 3; var output = ''; var position = -1; var a; var b; var c; var buffer; // Make sure any padding is handled outside of the loop. var length = input.length - padding; while (++position < length) { // Read three bytes, i.e. 24 bits. a = input.charCodeAt(position) << 16; b = input.charCodeAt(++position) << 8; c = input.charCodeAt(++position); buffer = a + b + c; // Turn the 24 bits into four chunks of 6 bits each, and append the // matching character for each of them to the output. output += ( TABLE.charAt(buffer >> 18 & 0x3F) + TABLE.charAt(buffer >> 12 & 0x3F) + TABLE.charAt(buffer >> 6 & 0x3F) + TABLE.charAt(buffer & 0x3F) ); } if (padding == 2) { a = input.charCodeAt(position) << 8; b = input.charCodeAt(++position); buffer = a + b; output += ( TABLE.charAt(buffer >> 10) + TABLE.charAt((buffer >> 4) & 0x3F) + TABLE.charAt((buffer << 2) & 0x3F) + '=' ); } else if (padding == 1) { buffer = input.charCodeAt(position); output += ( TABLE.charAt(buffer >> 2) + TABLE.charAt((buffer << 4) & 0x3F) + '==' ); } return output; }; var base64 = { 'encode': encode, 'decode': decode, 'version': '1.0.0' }; // Some AMD build optimizers, like r.js, check for specific condition patterns // like the following: if ( typeof define == 'function' && typeof define.amd == 'object' && define.amd ) { define(function() { return base64; }); } else if (freeExports && !freeExports.nodeType) { if (freeModule) { // in Node.js or RingoJS v0.8.0+ freeModule.exports = base64; } else { // in Narwhal or RingoJS v0.7.0- for (var key in base64) { base64.hasOwnProperty(key) && (freeExports[key] = base64[key]); } } } else { // in Rhino or a web browser root.base64 = base64; } }(this)); /***/ }), /***/ 45447: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var crypto_hash_sha512 = (__nccwpck_require__(68729).lowlevel.crypto_hash); /* * This file is a 1:1 port from the OpenBSD blowfish.c and bcrypt_pbkdf.c. As a * result, it retains the original copyright and license. The two files are * under slightly different (but compatible) licenses, and are here combined in * one file. * * Credit for the actual porting work goes to: * Devi Mandiri */ /* * The Blowfish portions are under the following license: * * Blowfish block cipher for OpenBSD * Copyright 1997 Niels Provos * All rights reserved. * * Implementation advice by David Mazieres . * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * The bcrypt_pbkdf portions are under the following license: * * Copyright (c) 2013 Ted Unangst * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ /* * Performance improvements (Javascript-specific): * * Copyright 2016, Joyent Inc * Author: Alex Wilson * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ // Ported from OpenBSD bcrypt_pbkdf.c v1.9 var BLF_J = 0; var Blowfish = function() { this.S = [ new Uint32Array([ 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a, 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677, 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239, 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0, 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe, 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d, 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463, 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8, 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8, 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c, 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1, 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf, 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af, 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915, 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a]), new Uint32Array([ 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266, 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7, 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af, 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87, 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd, 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509, 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a, 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960, 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061, 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc, 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340, 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7]), new Uint32Array([ 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068, 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504, 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb, 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb, 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115, 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728, 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d, 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b, 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c, 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9, 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61, 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027, 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62, 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc, 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c, 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0]), new Uint32Array([ 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6, 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22, 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59, 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28, 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb, 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47, 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048, 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd, 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f, 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525, 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e, 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060, 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6]) ]; this.P = new Uint32Array([ 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b]); }; function F(S, x8, i) { return (((S[0][x8[i+3]] + S[1][x8[i+2]]) ^ S[2][x8[i+1]]) + S[3][x8[i]]); }; Blowfish.prototype.encipher = function(x, x8) { if (x8 === undefined) { x8 = new Uint8Array(x.buffer); if (x.byteOffset !== 0) x8 = x8.subarray(x.byteOffset); } x[0] ^= this.P[0]; for (var i = 1; i < 16; i += 2) { x[1] ^= F(this.S, x8, 0) ^ this.P[i]; x[0] ^= F(this.S, x8, 4) ^ this.P[i+1]; } var t = x[0]; x[0] = x[1] ^ this.P[17]; x[1] = t; }; Blowfish.prototype.decipher = function(x) { var x8 = new Uint8Array(x.buffer); if (x.byteOffset !== 0) x8 = x8.subarray(x.byteOffset); x[0] ^= this.P[17]; for (var i = 16; i > 0; i -= 2) { x[1] ^= F(this.S, x8, 0) ^ this.P[i]; x[0] ^= F(this.S, x8, 4) ^ this.P[i-1]; } var t = x[0]; x[0] = x[1] ^ this.P[0]; x[1] = t; }; function stream2word(data, databytes){ var i, temp = 0; for (i = 0; i < 4; i++, BLF_J++) { if (BLF_J >= databytes) BLF_J = 0; temp = (temp << 8) | data[BLF_J]; } return temp; }; Blowfish.prototype.expand0state = function(key, keybytes) { var d = new Uint32Array(2), i, k; var d8 = new Uint8Array(d.buffer); for (i = 0, BLF_J = 0; i < 18; i++) { this.P[i] ^= stream2word(key, keybytes); } BLF_J = 0; for (i = 0; i < 18; i += 2) { this.encipher(d, d8); this.P[i] = d[0]; this.P[i+1] = d[1]; } for (i = 0; i < 4; i++) { for (k = 0; k < 256; k += 2) { this.encipher(d, d8); this.S[i][k] = d[0]; this.S[i][k+1] = d[1]; } } }; Blowfish.prototype.expandstate = function(data, databytes, key, keybytes) { var d = new Uint32Array(2), i, k; for (i = 0, BLF_J = 0; i < 18; i++) { this.P[i] ^= stream2word(key, keybytes); } for (i = 0, BLF_J = 0; i < 18; i += 2) { d[0] ^= stream2word(data, databytes); d[1] ^= stream2word(data, databytes); this.encipher(d); this.P[i] = d[0]; this.P[i+1] = d[1]; } for (i = 0; i < 4; i++) { for (k = 0; k < 256; k += 2) { d[0] ^= stream2word(data, databytes); d[1] ^= stream2word(data, databytes); this.encipher(d); this.S[i][k] = d[0]; this.S[i][k+1] = d[1]; } } BLF_J = 0; }; Blowfish.prototype.enc = function(data, blocks) { for (var i = 0; i < blocks; i++) { this.encipher(data.subarray(i*2)); } }; Blowfish.prototype.dec = function(data, blocks) { for (var i = 0; i < blocks; i++) { this.decipher(data.subarray(i*2)); } }; var BCRYPT_BLOCKS = 8, BCRYPT_HASHSIZE = 32; function bcrypt_hash(sha2pass, sha2salt, out) { var state = new Blowfish(), cdata = new Uint32Array(BCRYPT_BLOCKS), i, ciphertext = new Uint8Array([79,120,121,99,104,114,111,109,97,116,105, 99,66,108,111,119,102,105,115,104,83,119,97,116,68,121,110,97,109, 105,116,101]); //"OxychromaticBlowfishSwatDynamite" state.expandstate(sha2salt, 64, sha2pass, 64); for (i = 0; i < 64; i++) { state.expand0state(sha2salt, 64); state.expand0state(sha2pass, 64); } for (i = 0; i < BCRYPT_BLOCKS; i++) cdata[i] = stream2word(ciphertext, ciphertext.byteLength); for (i = 0; i < 64; i++) state.enc(cdata, cdata.byteLength / 8); for (i = 0; i < BCRYPT_BLOCKS; i++) { out[4*i+3] = cdata[i] >>> 24; out[4*i+2] = cdata[i] >>> 16; out[4*i+1] = cdata[i] >>> 8; out[4*i+0] = cdata[i]; } }; function bcrypt_pbkdf(pass, passlen, salt, saltlen, key, keylen, rounds) { var sha2pass = new Uint8Array(64), sha2salt = new Uint8Array(64), out = new Uint8Array(BCRYPT_HASHSIZE), tmpout = new Uint8Array(BCRYPT_HASHSIZE), countsalt = new Uint8Array(saltlen+4), i, j, amt, stride, dest, count, origkeylen = keylen; if (rounds < 1) return -1; if (passlen === 0 || saltlen === 0 || keylen === 0 || keylen > (out.byteLength * out.byteLength) || saltlen > (1<<20)) return -1; stride = Math.floor((keylen + out.byteLength - 1) / out.byteLength); amt = Math.floor((keylen + stride - 1) / stride); for (i = 0; i < saltlen; i++) countsalt[i] = salt[i]; crypto_hash_sha512(sha2pass, pass, passlen); for (count = 1; keylen > 0; count++) { countsalt[saltlen+0] = count >>> 24; countsalt[saltlen+1] = count >>> 16; countsalt[saltlen+2] = count >>> 8; countsalt[saltlen+3] = count; crypto_hash_sha512(sha2salt, countsalt, saltlen + 4); bcrypt_hash(sha2pass, sha2salt, tmpout); for (i = out.byteLength; i--;) out[i] = tmpout[i]; for (i = 1; i < rounds; i++) { crypto_hash_sha512(sha2salt, tmpout, tmpout.byteLength); bcrypt_hash(sha2pass, sha2salt, tmpout); for (j = 0; j < out.byteLength; j++) out[j] ^= tmpout[j]; } amt = Math.min(amt, keylen); for (i = 0; i < amt; i++) { dest = i * stride + (count - 1); if (dest >= origkeylen) break; key[dest] = out[i]; } keylen -= i; } return 0; }; module.exports = { BLOCKS: BCRYPT_BLOCKS, HASHSIZE: BCRYPT_HASHSIZE, hash: bcrypt_hash, pbkdf: bcrypt_pbkdf }; /***/ }), /***/ 83682: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var register = __nccwpck_require__(44670); var addHook = __nccwpck_require__(5549); var removeHook = __nccwpck_require__(6819); // bind with array of arguments: https://stackoverflow.com/a/21792913 var bind = Function.bind; var bindable = bind.bind(bind); function bindApi(hook, state, name) { var removeHookRef = bindable(removeHook, null).apply( null, name ? [state, name] : [state] ); hook.api = { remove: removeHookRef }; hook.remove = removeHookRef; ["before", "error", "after", "wrap"].forEach(function (kind) { var args = name ? [state, kind, name] : [state, kind]; hook[kind] = hook.api[kind] = bindable(addHook, null).apply(null, args); }); } function HookSingular() { var singularHookName = "h"; var singularHookState = { registry: {}, }; var singularHook = register.bind(null, singularHookState, singularHookName); bindApi(singularHook, singularHookState, singularHookName); return singularHook; } function HookCollection() { var state = { registry: {}, }; var hook = register.bind(null, state); bindApi(hook, state); return hook; } var collectionHookDeprecationMessageDisplayed = false; function Hook() { if (!collectionHookDeprecationMessageDisplayed) { console.warn( '[before-after-hook]: "Hook()" repurposing warning, use "Hook.Collection()". Read more: https://git.io/upgrade-before-after-hook-to-1.4' ); collectionHookDeprecationMessageDisplayed = true; } return HookCollection(); } Hook.Singular = HookSingular.bind(); Hook.Collection = HookCollection.bind(); module.exports = Hook; // expose constructors as a named property for TypeScript module.exports.Hook = Hook; module.exports.Singular = Hook.Singular; module.exports.Collection = Hook.Collection; /***/ }), /***/ 5549: /***/ ((module) => { module.exports = addHook; function addHook(state, kind, name, hook) { var orig = hook; if (!state.registry[name]) { state.registry[name] = []; } if (kind === "before") { hook = function (method, options) { return Promise.resolve() .then(orig.bind(null, options)) .then(method.bind(null, options)); }; } if (kind === "after") { hook = function (method, options) { var result; return Promise.resolve() .then(method.bind(null, options)) .then(function (result_) { result = result_; return orig(result, options); }) .then(function () { return result; }); }; } if (kind === "error") { hook = function (method, options) { return Promise.resolve() .then(method.bind(null, options)) .catch(function (error) { return orig(error, options); }); }; } state.registry[name].push({ hook: hook, orig: orig, }); } /***/ }), /***/ 44670: /***/ ((module) => { module.exports = register; 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(function (callback, name) { return register.bind(null, state, name, callback, options); }, method)(); } return Promise.resolve().then(function () { if (!state.registry[name]) { return method(options); } return state.registry[name].reduce(function (method, registered) { return registered.hook.bind(null, method, options); }, method)(); }); } /***/ }), /***/ 6819: /***/ ((module) => { module.exports = removeHook; function removeHook(state, name, method) { if (!state.registry[name]) { return; } var index = state.registry[name] .map(function (registered) { return registered.orig; }) .indexOf(method); if (index === -1) { return; } state.registry[name].splice(index, 1); } /***/ }), /***/ 33717: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var concatMap = __nccwpck_require__(86891); var balanced = __nccwpck_require__(9417); module.exports = expandTop; var escSlash = '\0SLASH'+Math.random()+'\0'; var escOpen = '\0OPEN'+Math.random()+'\0'; var escClose = '\0CLOSE'+Math.random()+'\0'; var escComma = '\0COMMA'+Math.random()+'\0'; var escPeriod = '\0PERIOD'+Math.random()+'\0'; function numeric(str) { return parseInt(str, 10) == str ? parseInt(str, 10) : str.charCodeAt(0); } function escapeBraces(str) { return str.split('\\\\').join(escSlash) .split('\\{').join(escOpen) .split('\\}').join(escClose) .split('\\,').join(escComma) .split('\\.').join(escPeriod); } function unescapeBraces(str) { return str.split(escSlash).join('\\') .split(escOpen).join('{') .split(escClose).join('}') .split(escComma).join(',') .split(escPeriod).join('.'); } // Basically just str.split(","), but handling cases // where we have nested braced sections, which should be // treated as individual members, like {a,{b,c},d} function parseCommaParts(str) { if (!str) return ['']; var parts = []; var m = balanced('{', '}', str); if (!m) return str.split(','); var pre = m.pre; var body = m.body; var post = m.post; var p = pre.split(','); p[p.length-1] += '{' + body + '}'; var postParts = parseCommaParts(post); if (post.length) { p[p.length-1] += postParts.shift(); p.push.apply(p, postParts); } parts.push.apply(parts, p); return parts; } function expandTop(str) { if (!str) return []; // I don't know why Bash 4.3 does this, but it does. // Anything starting with {} will have the first two bytes preserved // but *only* at the top level, so {},a}b will not expand to anything, // but a{},b}c will be expanded to [a}c,abc]. // One could argue that this is a bug in Bash, but since the goal of // this module is to match Bash's rules, we escape a leading {} if (str.substr(0, 2) === '{}') { str = '\\{\\}' + str.substr(2); } return expand(escapeBraces(str), true).map(unescapeBraces); } function identity(e) { return e; } function embrace(str) { return '{' + str + '}'; } function isPadded(el) { return /^-?0\d/.test(el); } function lte(i, y) { return i <= y; } function gte(i, y) { return i >= y; } function expand(str, isTop) { var expansions = []; var m = balanced('{', '}', str); if (!m || /\$$/.test(m.pre)) return [str]; var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); var isSequence = isNumericSequence || isAlphaSequence; var isOptions = m.body.indexOf(',') >= 0; if (!isSequence && !isOptions) { // {a},b} if (m.post.match(/,.*\}/)) { str = m.pre + '{' + m.body + escClose + m.post; return expand(str); } return [str]; } var n; if (isSequence) { n = m.body.split(/\.\./); } else { n = parseCommaParts(m.body); if (n.length === 1) { // x{{a,b}}y ==> x{a}y x{b}y n = expand(n[0], false).map(embrace); if (n.length === 1) { var post = m.post.length ? expand(m.post, false) : ['']; return post.map(function(p) { return m.pre + n[0] + p; }); } } } // at this point, n is the parts, and we know it's not a comma set // with a single entry. // no need to expand pre, since it is guaranteed to be free of brace-sets var pre = m.pre; var post = m.post.length ? expand(m.post, false) : ['']; var N; if (isSequence) { var x = numeric(n[0]); var y = numeric(n[1]); var width = Math.max(n[0].length, n[1].length) var incr = n.length == 3 ? Math.abs(numeric(n[2])) : 1; var test = lte; var reverse = y < x; if (reverse) { incr *= -1; test = gte; } var pad = n.some(isPadded); N = []; for (var i = x; test(i, y); i += incr) { var c; if (isAlphaSequence) { c = String.fromCharCode(i); if (c === '\\') c = ''; } else { c = String(i); if (pad) { var need = width - c.length; if (need > 0) { var z = new Array(need + 1).join('0'); if (i < 0) c = '-' + z + c.slice(1); else c = z + c; } } } N.push(c); } } else { N = concatMap(n, function(el) { return expand(el, false) }); } for (var j = 0; j < N.length; j++) { for (var k = 0; k < post.length; k++) { var expansion = pre + N[j] + post[k]; if (!isTop || isSequence || expansion) expansions.push(expansion); } } return expansions; } /***/ }), /***/ 29700: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // Copyright (C) 2011-2015 John Hewson // // 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. var stream = __nccwpck_require__(12781), util = __nccwpck_require__(73837), timers = __nccwpck_require__(39512); // convinience API module.exports = function(readStream, options) { return module.exports.createStream(readStream, options); }; // basic API module.exports.createStream = function(readStream, options) { if (readStream) { return createLineStream(readStream, options); } else { return new LineStream(options); } }; // deprecated API module.exports.createLineStream = function(readStream) { console.log('WARNING: byline#createLineStream is deprecated and will be removed soon'); return createLineStream(readStream); }; function createLineStream(readStream, options) { if (!readStream) { throw new Error('expected readStream'); } if (!readStream.readable) { throw new Error('readStream must be readable'); } var ls = new LineStream(options); readStream.pipe(ls); return ls; } // // using the new node v0.10 "streams2" API // module.exports.LineStream = LineStream; function LineStream(options) { stream.Transform.call(this, options); options = options || {}; // use objectMode to stop the output from being buffered // which re-concatanates the lines, just without newlines. this._readableState.objectMode = true; this._lineBuffer = []; this._keepEmptyLines = options.keepEmptyLines || false; this._lastChunkEndedWithCR = false; // take the source's encoding if we don't have one var self = this; this.on('pipe', function(src) { if (!self.encoding) { // but we can't do this for old-style streams if (src instanceof stream.Readable) { self.encoding = src._readableState.encoding; } } }); } util.inherits(LineStream, stream.Transform); LineStream.prototype._transform = function(chunk, encoding, done) { // decode binary chunks as UTF-8 encoding = encoding || 'utf8'; if (Buffer.isBuffer(chunk)) { if (encoding == 'buffer') { chunk = chunk.toString(); // utf8 encoding = 'utf8'; } else { chunk = chunk.toString(encoding); } } this._chunkEncoding = encoding; // see: http://www.unicode.org/reports/tr18/#Line_Boundaries var lines = chunk.split(/\r\n|[\n\v\f\r\x85\u2028\u2029]/g); // don't split CRLF which spans chunks if (this._lastChunkEndedWithCR && chunk[0] == '\n') { lines.shift(); } if (this._lineBuffer.length > 0) { this._lineBuffer[this._lineBuffer.length - 1] += lines[0]; lines.shift(); } this._lastChunkEndedWithCR = chunk[chunk.length - 1] == '\r'; this._lineBuffer = this._lineBuffer.concat(lines); this._pushBuffer(encoding, 1, done); }; LineStream.prototype._pushBuffer = function(encoding, keep, done) { // always buffer the last (possibly partial) line while (this._lineBuffer.length > keep) { var line = this._lineBuffer.shift(); // skip empty lines if (this._keepEmptyLines || line.length > 0 ) { if (!this.push(this._reencode(line, encoding))) { // when the high-water mark is reached, defer pushes until the next tick var self = this; timers.setImmediate(function() { self._pushBuffer(encoding, keep, done); }); return; } } } done(); }; LineStream.prototype._flush = function(done) { this._pushBuffer(this._chunkEncoding, 0, done); }; // see Readable::push LineStream.prototype._reencode = function(line, chunkEncoding) { if (this.encoding && this.encoding != chunkEncoding) { return new Buffer(line, chunkEncoding).toString(this.encoding); } else if (this.encoding) { // this should be the most common case, i.e. we're using an encoded source stream return line; } else { return new Buffer(line, chunkEncoding); } }; /***/ }), /***/ 2286: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { V4MAPPED, ADDRCONFIG, ALL, promises: { Resolver: AsyncResolver }, lookup: dnsLookup } = __nccwpck_require__(17578); const {promisify} = __nccwpck_require__(73837); const os = __nccwpck_require__(22037); const kCacheableLookupCreateConnection = Symbol('cacheableLookupCreateConnection'); const kCacheableLookupInstance = Symbol('cacheableLookupInstance'); const kExpires = Symbol('expires'); const supportsALL = typeof ALL === 'number'; const verifyAgent = agent => { if (!(agent && typeof agent.createConnection === 'function')) { throw new Error('Expected an Agent instance as the first argument'); } }; const map4to6 = entries => { for (const entry of entries) { if (entry.family === 6) { continue; } entry.address = `::ffff:${entry.address}`; entry.family = 6; } }; const getIfaceInfo = () => { let has4 = false; let has6 = false; for (const device of Object.values(os.networkInterfaces())) { for (const iface of device) { if (iface.internal) { continue; } if (iface.family === 'IPv6') { has6 = true; } else { has4 = true; } if (has4 && has6) { return {has4, has6}; } } } return {has4, has6}; }; const isIterable = map => { return Symbol.iterator in map; }; const ttl = {ttl: true}; const all = {all: true}; class CacheableLookup { constructor({ cache = new Map(), maxTtl = Infinity, fallbackDuration = 3600, errorTtl = 0.15, resolver = new AsyncResolver(), lookup = dnsLookup } = {}) { this.maxTtl = maxTtl; this.errorTtl = errorTtl; this._cache = cache; this._resolver = resolver; this._dnsLookup = promisify(lookup); if (this._resolver instanceof AsyncResolver) { this._resolve4 = this._resolver.resolve4.bind(this._resolver); this._resolve6 = this._resolver.resolve6.bind(this._resolver); } else { this._resolve4 = promisify(this._resolver.resolve4.bind(this._resolver)); this._resolve6 = promisify(this._resolver.resolve6.bind(this._resolver)); } this._iface = getIfaceInfo(); this._pending = {}; this._nextRemovalTime = false; this._hostnamesToFallback = new Set(); if (fallbackDuration < 1) { this._fallback = false; } else { this._fallback = true; const interval = setInterval(() => { this._hostnamesToFallback.clear(); }, fallbackDuration * 1000); /* istanbul ignore next: There is no `interval.unref()` when running inside an Electron renderer */ if (interval.unref) { interval.unref(); } } this.lookup = this.lookup.bind(this); this.lookupAsync = this.lookupAsync.bind(this); } set servers(servers) { this.clear(); this._resolver.setServers(servers); } get servers() { return this._resolver.getServers(); } lookup(hostname, options, callback) { if (typeof options === 'function') { callback = options; options = {}; } else if (typeof options === 'number') { options = { family: options }; } if (!callback) { throw new Error('Callback must be a function.'); } // eslint-disable-next-line promise/prefer-await-to-then this.lookupAsync(hostname, options).then(result => { if (options.all) { callback(null, result); } else { callback(null, result.address, result.family, result.expires, result.ttl); } }, callback); } async lookupAsync(hostname, options = {}) { if (typeof options === 'number') { options = { family: options }; } let cached = await this.query(hostname); if (options.family === 6) { const filtered = cached.filter(entry => entry.family === 6); if (options.hints & V4MAPPED) { if ((supportsALL && options.hints & ALL) || filtered.length === 0) { map4to6(cached); } else { cached = filtered; } } else { cached = filtered; } } else if (options.family === 4) { cached = cached.filter(entry => entry.family === 4); } if (options.hints & ADDRCONFIG) { const {_iface} = this; cached = cached.filter(entry => entry.family === 6 ? _iface.has6 : _iface.has4); } if (cached.length === 0) { const error = new Error(`cacheableLookup ENOTFOUND ${hostname}`); error.code = 'ENOTFOUND'; error.hostname = hostname; throw error; } if (options.all) { return cached; } return cached[0]; } async query(hostname) { let cached = await this._cache.get(hostname); if (!cached) { const pending = this._pending[hostname]; if (pending) { cached = await pending; } else { const newPromise = this.queryAndCache(hostname); this._pending[hostname] = newPromise; try { cached = await newPromise; } finally { delete this._pending[hostname]; } } } cached = cached.map(entry => { return {...entry}; }); return cached; } async _resolve(hostname) { const wrap = async promise => { try { return await promise; } catch (error) { if (error.code === 'ENODATA' || error.code === 'ENOTFOUND') { return []; } throw error; } }; // ANY is unsafe as it doesn't trigger new queries in the underlying server. const [A, AAAA] = await Promise.all([ this._resolve4(hostname, ttl), this._resolve6(hostname, ttl) ].map(promise => wrap(promise))); let aTtl = 0; let aaaaTtl = 0; let cacheTtl = 0; const now = Date.now(); for (const entry of A) { entry.family = 4; entry.expires = now + (entry.ttl * 1000); aTtl = Math.max(aTtl, entry.ttl); } for (const entry of AAAA) { entry.family = 6; entry.expires = now + (entry.ttl * 1000); aaaaTtl = Math.max(aaaaTtl, entry.ttl); } if (A.length > 0) { if (AAAA.length > 0) { cacheTtl = Math.min(aTtl, aaaaTtl); } else { cacheTtl = aTtl; } } else { cacheTtl = aaaaTtl; } return { entries: [ ...A, ...AAAA ], cacheTtl }; } async _lookup(hostname) { try { const entries = await this._dnsLookup(hostname, { all: true }); return { entries, cacheTtl: 0 }; } catch (_) { return { entries: [], cacheTtl: 0 }; } } async _set(hostname, data, cacheTtl) { if (this.maxTtl > 0 && cacheTtl > 0) { cacheTtl = Math.min(cacheTtl, this.maxTtl) * 1000; data[kExpires] = Date.now() + cacheTtl; try { await this._cache.set(hostname, data, cacheTtl); } catch (error) { this.lookupAsync = async () => { const cacheError = new Error('Cache Error. Please recreate the CacheableLookup instance.'); cacheError.cause = error; throw cacheError; }; } if (isIterable(this._cache)) { this._tick(cacheTtl); } } } async queryAndCache(hostname) { if (this._hostnamesToFallback.has(hostname)) { return this._dnsLookup(hostname, all); } let query = await this._resolve(hostname); if (query.entries.length === 0 && this._fallback) { query = await this._lookup(hostname); if (query.entries.length !== 0) { // Use `dns.lookup(...)` for that particular hostname this._hostnamesToFallback.add(hostname); } } const cacheTtl = query.entries.length === 0 ? this.errorTtl : query.cacheTtl; await this._set(hostname, query.entries, cacheTtl); return query.entries; } _tick(ms) { const nextRemovalTime = this._nextRemovalTime; if (!nextRemovalTime || ms < nextRemovalTime) { clearTimeout(this._removalTimeout); this._nextRemovalTime = ms; this._removalTimeout = setTimeout(() => { this._nextRemovalTime = false; let nextExpiry = Infinity; const now = Date.now(); for (const [hostname, entries] of this._cache) { const expires = entries[kExpires]; if (now >= expires) { this._cache.delete(hostname); } else if (expires < nextExpiry) { nextExpiry = expires; } } if (nextExpiry !== Infinity) { this._tick(nextExpiry - now); } }, ms); /* istanbul ignore next: There is no `timeout.unref()` when running inside an Electron renderer */ if (this._removalTimeout.unref) { this._removalTimeout.unref(); } } } install(agent) { verifyAgent(agent); if (kCacheableLookupCreateConnection in agent) { throw new Error('CacheableLookup has been already installed'); } agent[kCacheableLookupCreateConnection] = agent.createConnection; agent[kCacheableLookupInstance] = this; agent.createConnection = (options, callback) => { if (!('lookup' in options)) { options.lookup = this.lookup; } return agent[kCacheableLookupCreateConnection](options, callback); }; } uninstall(agent) { verifyAgent(agent); if (agent[kCacheableLookupCreateConnection]) { if (agent[kCacheableLookupInstance] !== this) { throw new Error('The agent is not owned by this CacheableLookup instance'); } agent.createConnection = agent[kCacheableLookupCreateConnection]; delete agent[kCacheableLookupCreateConnection]; delete agent[kCacheableLookupInstance]; } } updateInterfaceInfo() { const {_iface} = this; this._iface = getIfaceInfo(); if ((_iface.has4 && !this._iface.has4) || (_iface.has6 && !this._iface.has6)) { this._cache.clear(); } } clear(hostname) { if (hostname) { this._cache.delete(hostname); return; } this._cache.clear(); } } module.exports = CacheableLookup; module.exports["default"] = CacheableLookup; /***/ }), /***/ 35684: /***/ ((module) => { function Caseless (dict) { this.dict = dict || {} } Caseless.prototype.set = function (name, value, clobber) { if (typeof name === 'object') { for (var i in name) { this.set(i, name[i], value) } } else { if (typeof clobber === 'undefined') clobber = true var has = this.has(name) if (!clobber && has) this.dict[has] = this.dict[has] + ',' + value else this.dict[has || name] = value return has } } Caseless.prototype.has = function (name) { var keys = Object.keys(this.dict) , name = name.toLowerCase() ; for (var i=0;i { "use strict"; const fs = __nccwpck_require__(57147) const path = __nccwpck_require__(71017) /* istanbul ignore next */ const LCHOWN = fs.lchown ? 'lchown' : 'chown' /* istanbul ignore next */ const LCHOWNSYNC = fs.lchownSync ? 'lchownSync' : 'chownSync' /* istanbul ignore next */ const needEISDIRHandled = fs.lchown && !process.version.match(/v1[1-9]+\./) && !process.version.match(/v10\.[6-9]/) const lchownSync = (path, uid, gid) => { try { return fs[LCHOWNSYNC](path, uid, gid) } catch (er) { if (er.code !== 'ENOENT') throw er } } /* istanbul ignore next */ const chownSync = (path, uid, gid) => { try { return fs.chownSync(path, uid, gid) } catch (er) { if (er.code !== 'ENOENT') throw er } } /* istanbul ignore next */ const handleEISDIR = needEISDIRHandled ? (path, uid, gid, cb) => er => { // Node prior to v10 had a very questionable implementation of // fs.lchown, which would always try to call fs.open on a directory // Fall back to fs.chown in those cases. if (!er || er.code !== 'EISDIR') cb(er) else fs.chown(path, uid, gid, cb) } : (_, __, ___, cb) => cb /* istanbul ignore next */ const handleEISDirSync = needEISDIRHandled ? (path, uid, gid) => { try { return lchownSync(path, uid, gid) } catch (er) { if (er.code !== 'EISDIR') throw er chownSync(path, uid, gid) } } : (path, uid, gid) => lchownSync(path, uid, gid) // fs.readdir could only accept an options object as of node v6 const nodeVersion = process.version let readdir = (path, options, cb) => fs.readdir(path, options, cb) let readdirSync = (path, options) => fs.readdirSync(path, options) /* istanbul ignore next */ if (/^v4\./.test(nodeVersion)) readdir = (path, options, cb) => fs.readdir(path, cb) const chown = (cpath, uid, gid, cb) => { fs[LCHOWN](cpath, uid, gid, handleEISDIR(cpath, uid, gid, er => { // Skip ENOENT error cb(er && er.code !== 'ENOENT' ? er : null) })) } const chownrKid = (p, child, uid, gid, cb) => { if (typeof child === 'string') return fs.lstat(path.resolve(p, child), (er, stats) => { // Skip ENOENT error if (er) return cb(er.code !== 'ENOENT' ? er : null) stats.name = child chownrKid(p, stats, uid, gid, cb) }) if (child.isDirectory()) { chownr(path.resolve(p, child.name), uid, gid, er => { if (er) return cb(er) const cpath = path.resolve(p, child.name) chown(cpath, uid, gid, cb) }) } else { const cpath = path.resolve(p, child.name) chown(cpath, uid, gid, cb) } } const chownr = (p, uid, gid, cb) => { readdir(p, { withFileTypes: true }, (er, children) => { // any error other than ENOTDIR or ENOTSUP means it's not readable, // or doesn't exist. give up. if (er) { if (er.code === 'ENOENT') return cb() else if (er.code !== 'ENOTDIR' && er.code !== 'ENOTSUP') return cb(er) } if (er || !children.length) return chown(p, uid, gid, cb) let len = children.length let errState = null const then = er => { if (errState) return if (er) return cb(errState = er) if (-- len === 0) return chown(p, uid, gid, cb) } children.forEach(child => chownrKid(p, child, uid, gid, then)) }) } const chownrKidSync = (p, child, uid, gid) => { if (typeof child === 'string') { try { const stats = fs.lstatSync(path.resolve(p, child)) stats.name = child child = stats } catch (er) { if (er.code === 'ENOENT') return else throw er } } if (child.isDirectory()) chownrSync(path.resolve(p, child.name), uid, gid) handleEISDirSync(path.resolve(p, child.name), uid, gid) } const chownrSync = (p, uid, gid) => { let children try { children = readdirSync(p, { withFileTypes: true }) } catch (er) { if (er.code === 'ENOENT') return else if (er.code === 'ENOTDIR' || er.code === 'ENOTSUP') return handleEISDirSync(p, uid, gid) else throw er } if (children && children.length) children.forEach(child => chownrKidSync(p, child, uid, gid)) return handleEISDirSync(p, uid, gid) } module.exports = chownr chownr.sync = chownrSync /***/ }), /***/ 27972: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const os = __nccwpck_require__(22037); const extractPathRegex = /\s+at.*(?:\(|\s)(.*)\)?/; const pathRegex = /^(?:(?:(?:node|(?:internal\/[\w/]*|.*node_modules\/(?:babel-polyfill|pirates)\/.*)?\w+)\.js:\d+:\d+)|native)/; const homeDir = typeof os.homedir === 'undefined' ? '' : os.homedir(); module.exports = (stack, options) => { options = Object.assign({pretty: false}, options); return stack.replace(/\\/g, '/') .split('\n') .filter(line => { const pathMatches = line.match(extractPathRegex); if (pathMatches === null || !pathMatches[1]) { return true; } const match = pathMatches[1]; // Electron if ( match.includes('.app/Contents/Resources/electron.asar') || match.includes('.app/Contents/Resources/default_app.asar') ) { return false; } return !pathRegex.test(match); }) .filter(line => line.trim() !== '') .map(line => { if (options.pretty) { return line.replace(extractPathRegex, (m, p1) => m.replace(p1, p1.replace(homeDir, '~'))); } return line; }) .join('\n'); }; /***/ }), /***/ 81312: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const PassThrough = (__nccwpck_require__(12781).PassThrough); const mimicResponse = __nccwpck_require__(42610); const cloneResponse = response => { if (!(response && response.pipe)) { throw new TypeError('Parameter `response` must be a response stream.'); } const clone = new PassThrough(); mimicResponse(response, clone); return response.pipe(clone); }; module.exports = cloneResponse; /***/ }), /***/ 85443: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var util = __nccwpck_require__(73837); var Stream = (__nccwpck_require__(12781).Stream); var DelayedStream = __nccwpck_require__(18611); module.exports = CombinedStream; function CombinedStream() { this.writable = false; this.readable = true; this.dataSize = 0; this.maxDataSize = 2 * 1024 * 1024; this.pauseStreams = true; this._released = false; this._streams = []; this._currentStream = null; this._insideLoop = false; this._pendingNext = false; } util.inherits(CombinedStream, Stream); CombinedStream.create = function(options) { var combinedStream = new this(); options = options || {}; for (var option in options) { combinedStream[option] = options[option]; } return combinedStream; }; CombinedStream.isStreamLike = function(stream) { return (typeof stream !== 'function') && (typeof stream !== 'string') && (typeof stream !== 'boolean') && (typeof stream !== 'number') && (!Buffer.isBuffer(stream)); }; CombinedStream.prototype.append = function(stream) { var isStreamLike = CombinedStream.isStreamLike(stream); if (isStreamLike) { if (!(stream instanceof DelayedStream)) { var newStream = DelayedStream.create(stream, { maxDataSize: Infinity, pauseStream: this.pauseStreams, }); stream.on('data', this._checkDataSize.bind(this)); stream = newStream; } this._handleErrors(stream); if (this.pauseStreams) { stream.pause(); } } this._streams.push(stream); return this; }; CombinedStream.prototype.pipe = function(dest, options) { Stream.prototype.pipe.call(this, dest, options); this.resume(); return dest; }; CombinedStream.prototype._getNext = function() { this._currentStream = null; if (this._insideLoop) { this._pendingNext = true; return; // defer call } this._insideLoop = true; try { do { this._pendingNext = false; this._realGetNext(); } while (this._pendingNext); } finally { this._insideLoop = false; } }; CombinedStream.prototype._realGetNext = function() { var stream = this._streams.shift(); if (typeof stream == 'undefined') { this.end(); return; } if (typeof stream !== 'function') { this._pipeNext(stream); return; } var getStream = stream; getStream(function(stream) { var isStreamLike = CombinedStream.isStreamLike(stream); if (isStreamLike) { stream.on('data', this._checkDataSize.bind(this)); this._handleErrors(stream); } this._pipeNext(stream); }.bind(this)); }; CombinedStream.prototype._pipeNext = function(stream) { this._currentStream = stream; var isStreamLike = CombinedStream.isStreamLike(stream); if (isStreamLike) { stream.on('end', this._getNext.bind(this)); stream.pipe(this, {end: false}); return; } var value = stream; this.write(value); this._getNext(); }; CombinedStream.prototype._handleErrors = function(stream) { var self = this; stream.on('error', function(err) { self._emitError(err); }); }; CombinedStream.prototype.write = function(data) { this.emit('data', data); }; CombinedStream.prototype.pause = function() { if (!this.pauseStreams) { return; } if(this.pauseStreams && this._currentStream && typeof(this._currentStream.pause) == 'function') this._currentStream.pause(); this.emit('pause'); }; CombinedStream.prototype.resume = function() { if (!this._released) { this._released = true; this.writable = true; this._getNext(); } if(this.pauseStreams && this._currentStream && typeof(this._currentStream.resume) == 'function') this._currentStream.resume(); this.emit('resume'); }; CombinedStream.prototype.end = function() { this._reset(); this.emit('end'); }; CombinedStream.prototype.destroy = function() { this._reset(); this.emit('close'); }; CombinedStream.prototype._reset = function() { this.writable = false; this._streams = []; this._currentStream = null; }; CombinedStream.prototype._checkDataSize = function() { this._updateDataSize(); if (this.dataSize <= this.maxDataSize) { return; } var message = 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.'; this._emitError(new Error(message)); }; CombinedStream.prototype._updateDataSize = function() { this.dataSize = 0; var self = this; this._streams.forEach(function(stream) { if (!stream.dataSize) { return; } self.dataSize += stream.dataSize; }); if (this._currentStream && this._currentStream.dataSize) { this.dataSize += this._currentStream.dataSize; } }; CombinedStream.prototype._emitError = function(err) { this._reset(); this.emit('error', err); }; /***/ }), /***/ 17044: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.action = void 0; const commander = __nccwpck_require__(86987); function action() { return (target, propertyKey, descriptor) => { commander.action(target[propertyKey]); }; } exports.action = action; //# sourceMappingURL=action.decorator.js.map /***/ }), /***/ 71303: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.alias = void 0; const program = __nccwpck_require__(86987); function alias(text) { return (target) => { program.usage(text); }; } exports.alias = alias; //# sourceMappingURL=alias.decorator.js.map /***/ }), /***/ 55508: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.variadicArg = exports.requiredArg = exports.optionalArg = void 0; const metadata_1 = __nccwpck_require__(104); const models_1 = __nccwpck_require__(84908); const utils_1 = __nccwpck_require__(66725); /** * Parameter decorator used in subcommand function to denote an optional argument. */ function optionalArg(name) { return (target, propertyKey, parameterIndex) => { const args = (0, utils_1.decorateIfNot)(metadata_1.ArgsMetadata, [], target, propertyKey); args.unshift(new models_1.OptionalArg(name, parameterIndex)); }; } exports.optionalArg = optionalArg; /** * Parameter decorator used in subcommand function to denote a required argument. */ function requiredArg(name) { return (target, propertyKey, parameterIndex) => { const args = (0, utils_1.decorateIfNot)(metadata_1.ArgsMetadata, [], target, propertyKey); args.unshift(new models_1.RequiredArg(name, parameterIndex)); }; } exports.requiredArg = requiredArg; /** * Parameter decorator used in subcommand function to denote variadic arguments. */ function variadicArg(name) { return (target, propertyKey, parameterIndex) => { const args = (0, utils_1.decorateIfNot)(metadata_1.ArgsMetadata, [], target, propertyKey); args.unshift(new models_1.VariadicArg(name, parameterIndex)); }; } exports.variadicArg = variadicArg; //# sourceMappingURL=arg.decorator.js.map /***/ }), /***/ 71196: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.args = void 0; const commander = __nccwpck_require__(86987); function args() { return (target, propertyKey, parameterIndex) => { commander .option(propertyKey) .action(target[propertyKey]); }; } exports.args = args; //# sourceMappingURL=arguments.decorator.js.map /***/ }), /***/ 69904: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.commandOption = void 0; const metadata_1 = __nccwpck_require__(104); const utils_1 = __nccwpck_require__(66725); function commandOption(...args) { return ((target, propertyKey, descriptor) => { args[0] = args[0] || `--${String(propertyKey)}`; (0, utils_1.decorateIfNot)(metadata_1.CommandOptionsMetadata, [], target, propertyKey); const options = Reflect.getMetadata(metadata_1.CommandOptionsMetadata, target, propertyKey); options.push(args); }); } exports.commandOption = commandOption; //# sourceMappingURL=command-option.decorator.js.map /***/ }), /***/ 1442: /***/ (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.command = void 0; const commander = __nccwpck_require__(86987); const helpers_1 = __nccwpck_require__(69882); const metadata_1 = __nccwpck_require__(104); function command() { return (target, propertyKey, descriptor) => { try { const cmd = (0, helpers_1.prepareSubcommand)(target, propertyKey); let chain = commander.command(cmd); if (Reflect.hasMetadata(metadata_1.CommandOptionsMetadata, target, propertyKey)) { const options = Reflect.getMetadata(metadata_1.CommandOptionsMetadata, target, propertyKey); chain = options.reduce((prev, opt) => { const [arg1, arg2, arg3, arg4] = opt; return chain.option(arg1, arg2, arg3, arg4); }, chain); } chain.action((...args) => __awaiter(this, void 0, void 0, function* () { const context = args[args.length - 1]; const cmdArgs = args.slice(0, args.length - 1); try { const result = target[propertyKey].apply(context, cmdArgs); if (result instanceof Promise) { yield result; } } catch (_a) { process.exit(1); } finally { process.exit(0); } })); } catch (e) { console.error(e.message); process.exit(1); } }; } exports.command = command; //# sourceMappingURL=command.decorator.js.map /***/ }), /***/ 14432: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.description = void 0; const program = __nccwpck_require__(86987); function description(text) { return (target) => { program.description(text); }; } exports.description = description; //# sourceMappingURL=description.decorator.js.map /***/ }), /***/ 90154: /***/ (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; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __exportStar = (this && this.__exportStar) || function(m, exports) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); }; Object.defineProperty(exports, "__esModule", ({ value: true })); __exportStar(__nccwpck_require__(104), exports); __exportStar(__nccwpck_require__(17044), exports); __exportStar(__nccwpck_require__(71303), exports); __exportStar(__nccwpck_require__(55508), exports); __exportStar(__nccwpck_require__(71196), exports); __exportStar(__nccwpck_require__(69904), exports); __exportStar(__nccwpck_require__(1442), exports); __exportStar(__nccwpck_require__(14432), exports); __exportStar(__nccwpck_require__(98166), exports); __exportStar(__nccwpck_require__(42991), exports); __exportStar(__nccwpck_require__(3813), exports); __exportStar(__nccwpck_require__(84768), exports); __exportStar(__nccwpck_require__(98162), exports); //# sourceMappingURL=index.js.map /***/ }), /***/ 98166: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.on = void 0; const commander = __nccwpck_require__(86987); function on(event, handler) { return (target, propertyKey, descriptor) => { commander.on(event, handler); }; } exports.on = on; //# sourceMappingURL=on.decorator.js.map /***/ }), /***/ 42991: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.option = void 0; const metadata_1 = __nccwpck_require__(104); const models_1 = __nccwpck_require__(84908); const utils_1 = __nccwpck_require__(66725); function option(...args) { return ((target, propertyKey) => { args[0] = args[0] || `--${String(propertyKey)}`; (0, utils_1.decorateIfNot)(metadata_1.OptionsMetadata, [], target, propertyKey); const options = Reflect.getMetadata(metadata_1.OptionsMetadata, target, propertyKey); options.push(new models_1.Option(propertyKey, args)); }); } exports.option = option; //# sourceMappingURL=option.decorator.js.map /***/ }), /***/ 3813: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.program = void 0; const commander = __nccwpck_require__(86987); const helpers_1 = __nccwpck_require__(69882); const metadata_1 = __nccwpck_require__(104); let instances = 0; function program() { instances += 1; if (instances > 1) { throw new Error('Only one instance of @program is permitted.'); } return function (constructor) { const mixin = class extends constructor { constructor(...args) { super(...args); if (!this.run) { console.error('Program class must define a run() method.'); process.exit(1); } const cmd = (0, helpers_1.prepareCommand)(this, 'run'); if (cmd) { commander.command(cmd); } const options = Object.keys(this).reduce((list, prop) => { if (Reflect.hasMetadata(metadata_1.OptionsMetadata, this, prop)) { const metadata = Reflect.getMetadata(metadata_1.OptionsMetadata, this, prop); list.push(metadata); } return list; }, []); const chainAfterOptions = options .reduce((prev, option) => { return prev.option.apply(prev, option[0].args); }, commander); commander.parse(process.argv); if (this.run) { this.run.apply(commander, (0, helpers_1.injectArgs)(commander, this, 'run')); } } }; (0, helpers_1.initCommander)(constructor); return mixin; }; } exports.program = program; function prepareProgram(target) { let argList = ''; if (Reflect.hasMetadata(metadata_1.OptionsMetadata, target)) { const args = Reflect.getMetadata(metadata_1.OptionsMetadata, target); argList = args .map((arg) => { return arg.toString(); }) .join(' ') .replace(/^(.)/, ' $1'); } return `${argList}`; } //# sourceMappingURL=program.decorator.js.map /***/ }), /***/ 84768: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.usage = void 0; const commander = __nccwpck_require__(86987); function usage(text) { return (target) => { commander.usage(text); }; } exports.usage = usage; //# sourceMappingURL=usage.decorator.js.map /***/ }), /***/ 98162: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.version = void 0; const helpers_1 = __nccwpck_require__(69882); const metadata_1 = __nccwpck_require__(104); function version(text) { return (target) => { (0, helpers_1.initCommander)(target); const program = Reflect.getMetadata(metadata_1.ProgramMetadata, target); program.version(text); }; } exports.version = version; //# sourceMappingURL=version.decorator.js.map /***/ }), /***/ 69882: /***/ (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; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __exportStar = (this && this.__exportStar) || function(m, exports) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); }; Object.defineProperty(exports, "__esModule", ({ value: true })); __exportStar(__nccwpck_require__(65339), exports); __exportStar(__nccwpck_require__(70), exports); __exportStar(__nccwpck_require__(11413), exports); //# sourceMappingURL=index.js.map /***/ }), /***/ 65339: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.initCommander = void 0; const commander = __nccwpck_require__(86987); const metadata_1 = __nccwpck_require__(104); function initCommander(target) { if (!Reflect.hasMetadata(metadata_1.ProgramMetadata, target)) { const decorator = Reflect.metadata(metadata_1.ProgramMetadata, commander); Reflect.decorate([decorator], target); } } exports.initCommander = initCommander; //# sourceMappingURL=init-commander.js.map /***/ }), /***/ 70: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.injectArgs = void 0; const metadata_1 = __nccwpck_require__(104); const index_1 = __nccwpck_require__(84908); function injectArgs(program, target, propertyKey) { if (Reflect.hasMetadata(metadata_1.ArgsMetadata, target, propertyKey)) { const args = Reflect.getMetadata(metadata_1.ArgsMetadata, target, propertyKey); const predicate = (arg) => arg instanceof index_1.VariadicArg; const variadic = args.find(predicate); if (variadic && (args.findIndex(predicate) !== (args.length - 1))) { throw new TypeError(`Variadic argument must be specified last the argument list of the ${String(propertyKey)}() function.`); } const argv = []; let index = 0; for (let i = 0; i < args.length; i += 1) { if (args.find(arg => arg.index === i)) { argv.push(program.args[index]); index += 1; } else { argv.push(undefined); } } return argv; } } exports.injectArgs = injectArgs; //# sourceMappingURL=inject-args.js.map /***/ }), /***/ 11413: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.prepareSubcommand = exports.prepareCommand = void 0; const metadata_1 = __nccwpck_require__(104); const index_1 = __nccwpck_require__(84908); function prepareCommand(target, propertyKey) { let argList = ''; if (Reflect.hasMetadata(metadata_1.ArgsMetadata, target, propertyKey)) { const args = Reflect.getMetadata(metadata_1.ArgsMetadata, target, propertyKey); const predicate = (arg) => arg instanceof index_1.VariadicArg; const variadic = args.find(predicate); if (variadic && (args.findIndex(predicate) !== (args.length - 1))) { throw new TypeError(`Variadic argument must be specified last the argument list of the ${String(propertyKey)}() function.`); } argList = args .map((arg) => { return arg.toString(); }) .join(' ') .replace(/^(.)/, '$1'); } return `${argList}`; } exports.prepareCommand = prepareCommand; function prepareSubcommand(target, propertyKey) { const argList = prepareCommand(target, propertyKey); return `${String(propertyKey)} ${argList}`; } exports.prepareSubcommand = prepareSubcommand; //# sourceMappingURL=prepare-command.js.map /***/ }), /***/ 40451: /***/ (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; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __exportStar = (this && this.__exportStar) || function(m, exports) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Option = exports.Command = void 0; __nccwpck_require__(29977); var commander_1 = __nccwpck_require__(86987); Object.defineProperty(exports, "Command", ({ enumerable: true, get: function () { return commander_1.Command; } })); Object.defineProperty(exports, "Option", ({ enumerable: true, get: function () { return commander_1.Option; } })); __exportStar(__nccwpck_require__(90154), exports); //# sourceMappingURL=index.js.map /***/ }), /***/ 104: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SubcommandMetadata = exports.ProgramMetadata = exports.OptionsMetadata = exports.CommandOptionsMetadata = exports.ArgsMetadata = void 0; exports.ArgsMetadata = Symbol('ArgsMetadata'); exports.CommandOptionsMetadata = Symbol('CommandOptionsMetadata'); exports.OptionsMetadata = Symbol('OptionsMetadata'); exports.ProgramMetadata = Symbol('ProgramMetadata'); exports.SubcommandMetadata = Symbol('SubcommandMetadata'); //# sourceMappingURL=metadata.js.map /***/ }), /***/ 6312: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.VariadicArg = exports.RequiredArg = exports.OptionalArg = exports.CommandArg = void 0; class CommandArg { constructor(name, index) { this.name = name; this.index = index; if (typeof name === 'symbol') { throw new TypeError('Symbols are not supported as argument names.'); } } } exports.CommandArg = CommandArg; class OptionalArg extends CommandArg { toString() { return `[${String(this.name)}]`; } } exports.OptionalArg = OptionalArg; class RequiredArg extends CommandArg { toString() { return `<${String(this.name)}>`; } } exports.RequiredArg = RequiredArg; class VariadicArg extends CommandArg { toString() { return `[${String(this.name)}...]`; } } exports.VariadicArg = VariadicArg; //# sourceMappingURL=arg.model.js.map /***/ }), /***/ 84908: /***/ (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; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __exportStar = (this && this.__exportStar) || function(m, exports) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); }; Object.defineProperty(exports, "__esModule", ({ value: true })); __exportStar(__nccwpck_require__(6312), exports); __exportStar(__nccwpck_require__(4860), exports); //# sourceMappingURL=index.js.map /***/ }), /***/ 4860: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Option = void 0; class Option { constructor(name, args) { this.name = name; this.args = args; } } exports.Option = Option; //# sourceMappingURL=option.model.js.map /***/ }), /***/ 65058: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.decorateIfNot = void 0; function decorateIfNot(metadataKey, value, target, propertyKey) { if (!Reflect.hasMetadata(metadataKey, target, propertyKey)) { const decorator = Reflect.metadata(metadataKey, value); Reflect.decorate([decorator], target, propertyKey); } return Reflect.getMetadata(metadataKey, target, propertyKey); } exports.decorateIfNot = decorateIfNot; //# sourceMappingURL=decorateIfNot.js.map /***/ }), /***/ 66725: /***/ (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; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __exportStar = (this && this.__exportStar) || function(m, exports) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); }; Object.defineProperty(exports, "__esModule", ({ value: true })); __exportStar(__nccwpck_require__(65058), exports); //# sourceMappingURL=index.js.map /***/ }), /***/ 86891: /***/ ((module) => { module.exports = function (xs, fn) { var res = []; for (var i = 0; i < xs.length; i++) { var x = fn(xs[i], i); if (isArray(x)) res.push.apply(res, x); else res.push(x); } return res; }; var isArray = Array.isArray || function (xs) { return Object.prototype.toString.call(xs) === '[object Array]'; }; /***/ }), /***/ 95898: /***/ ((__unused_webpack_module, exports) => { var __webpack_unused_export__; // Copyright Joyent, Inc. and other Node contributors. // // 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. // NOTE: These type checking functions intentionally don't use `instanceof` // because it is fragile and can be easily faked with `Object.create()`. function isArray(arg) { if (Array.isArray) { return Array.isArray(arg); } return objectToString(arg) === '[object Array]'; } __webpack_unused_export__ = isArray; function isBoolean(arg) { return typeof arg === 'boolean'; } __webpack_unused_export__ = isBoolean; function isNull(arg) { return arg === null; } __webpack_unused_export__ = isNull; function isNullOrUndefined(arg) { return arg == null; } __webpack_unused_export__ = isNullOrUndefined; function isNumber(arg) { return typeof arg === 'number'; } __webpack_unused_export__ = isNumber; function isString(arg) { return typeof arg === 'string'; } __webpack_unused_export__ = isString; function isSymbol(arg) { return typeof arg === 'symbol'; } __webpack_unused_export__ = isSymbol; function isUndefined(arg) { return arg === void 0; } __webpack_unused_export__ = isUndefined; function isRegExp(re) { return objectToString(re) === '[object RegExp]'; } __webpack_unused_export__ = isRegExp; function isObject(arg) { return typeof arg === 'object' && arg !== null; } __webpack_unused_export__ = isObject; function isDate(d) { return objectToString(d) === '[object Date]'; } __webpack_unused_export__ = isDate; function isError(e) { return (objectToString(e) === '[object Error]' || e instanceof Error); } exports.VZ = isError; function isFunction(arg) { return typeof arg === 'function'; } __webpack_unused_export__ = isFunction; function isPrimitive(arg) { return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'symbol' || // ES6 symbol typeof arg === 'undefined'; } __webpack_unused_export__ = isPrimitive; __webpack_unused_export__ = Buffer.isBuffer; function objectToString(o) { return Object.prototype.toString.call(o); } /***/ }), /***/ 72746: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const cp = __nccwpck_require__(32081); const parse = __nccwpck_require__(66855); const enoent = __nccwpck_require__(44101); function spawn(command, args, options) { // Parse the arguments const parsed = parse(command, args, options); // Spawn the child process const spawned = cp.spawn(parsed.command, parsed.args, parsed.options); // Hook into child process "exit" event to emit an error if the command // does not exists, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16 enoent.hookChildProcess(spawned, parsed); return spawned; } function spawnSync(command, args, options) { // Parse the arguments const parsed = parse(command, args, options); // Spawn the child process const result = cp.spawnSync(parsed.command, parsed.args, parsed.options); // Analyze if the command does not exist, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16 result.error = result.error || enoent.verifyENOENTSync(result.status, parsed); return result; } module.exports = spawn; module.exports.spawn = spawn; module.exports.sync = spawnSync; module.exports._parse = parse; module.exports._enoent = enoent; /***/ }), /***/ 44101: /***/ ((module) => { "use strict"; const isWin = process.platform === 'win32'; function notFoundError(original, syscall) { return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), { code: 'ENOENT', errno: 'ENOENT', syscall: `${syscall} ${original.command}`, path: original.command, spawnargs: original.args, }); } function hookChildProcess(cp, parsed) { if (!isWin) { return; } const originalEmit = cp.emit; cp.emit = function (name, arg1) { // If emitting "exit" event and exit code is 1, we need to check if // the command exists and emit an "error" instead // See https://github.com/IndigoUnited/node-cross-spawn/issues/16 if (name === 'exit') { const err = verifyENOENT(arg1, parsed, 'spawn'); if (err) { return originalEmit.call(cp, 'error', err); } } return originalEmit.apply(cp, arguments); // eslint-disable-line prefer-rest-params }; } function verifyENOENT(status, parsed) { if (isWin && status === 1 && !parsed.file) { return notFoundError(parsed.original, 'spawn'); } return null; } function verifyENOENTSync(status, parsed) { if (isWin && status === 1 && !parsed.file) { return notFoundError(parsed.original, 'spawnSync'); } return null; } module.exports = { hookChildProcess, verifyENOENT, verifyENOENTSync, notFoundError, }; /***/ }), /***/ 66855: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const path = __nccwpck_require__(71017); const resolveCommand = __nccwpck_require__(87274); const escape = __nccwpck_require__(34274); const readShebang = __nccwpck_require__(41252); const isWin = process.platform === 'win32'; const isExecutableRegExp = /\.(?:com|exe)$/i; const isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i; function detectShebang(parsed) { parsed.file = resolveCommand(parsed); const shebang = parsed.file && readShebang(parsed.file); if (shebang) { parsed.args.unshift(parsed.file); parsed.command = shebang; return resolveCommand(parsed); } return parsed.file; } function parseNonShell(parsed) { if (!isWin) { return parsed; } // Detect & add support for shebangs const commandFile = detectShebang(parsed); // We don't need a shell if the command filename is an executable const needsShell = !isExecutableRegExp.test(commandFile); // If a shell is required, use cmd.exe and take care of escaping everything correctly // Note that `forceShell` is an hidden option used only in tests if (parsed.options.forceShell || needsShell) { // Need to double escape meta chars if the command is a cmd-shim located in `node_modules/.bin/` // The cmd-shim simply calls execute the package bin file with NodeJS, proxying any argument // Because the escape of metachars with ^ gets interpreted when the cmd.exe is first called, // we need to double escape them const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile); // Normalize posix paths into OS compatible paths (e.g.: foo/bar -> foo\bar) // This is necessary otherwise it will always fail with ENOENT in those cases parsed.command = path.normalize(parsed.command); // Escape command & arguments parsed.command = escape.command(parsed.command); parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars)); const shellCommand = [parsed.command].concat(parsed.args).join(' '); parsed.args = ['/d', '/s', '/c', `"${shellCommand}"`]; parsed.command = process.env.comspec || 'cmd.exe'; parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped } return parsed; } function parse(command, args, options) { // Normalize arguments, similar to nodejs if (args && !Array.isArray(args)) { options = args; args = null; } args = args ? args.slice(0) : []; // Clone array to avoid changing the original options = Object.assign({}, options); // Clone object to avoid changing the original // Build our parsed object const parsed = { command, args, options, file: undefined, original: { command, args, }, }; // Delegate further parsing to shell or non-shell return options.shell ? parsed : parseNonShell(parsed); } module.exports = parse; /***/ }), /***/ 34274: /***/ ((module) => { "use strict"; // See http://www.robvanderwoude.com/escapechars.php const metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g; function escapeCommand(arg) { // Escape meta chars arg = arg.replace(metaCharsRegExp, '^$1'); return arg; } function escapeArgument(arg, doubleEscapeMetaChars) { // Convert to string arg = `${arg}`; // Algorithm below is based on https://qntm.org/cmd // Sequence of backslashes followed by a double quote: // double up all the backslashes and escape the double quote arg = arg.replace(/(\\*)"/g, '$1$1\\"'); // Sequence of backslashes followed by the end of the string // (which will become a double quote later): // double up all the backslashes arg = arg.replace(/(\\*)$/, '$1$1'); // All other backslashes occur literally // Quote the whole thing: arg = `"${arg}"`; // Escape meta chars arg = arg.replace(metaCharsRegExp, '^$1'); // Double escape meta chars if necessary if (doubleEscapeMetaChars) { arg = arg.replace(metaCharsRegExp, '^$1'); } return arg; } module.exports.command = escapeCommand; module.exports.argument = escapeArgument; /***/ }), /***/ 41252: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const fs = __nccwpck_require__(57147); const shebangCommand = __nccwpck_require__(67032); function readShebang(command) { // Read the first 150 bytes from the file const size = 150; const buffer = Buffer.alloc(size); let fd; try { fd = fs.openSync(command, 'r'); fs.readSync(fd, buffer, 0, size, 0); fs.closeSync(fd); } catch (e) { /* Empty */ } // Attempt to extract shebang (null is returned if not a shebang) return shebangCommand(buffer.toString()); } module.exports = readShebang; /***/ }), /***/ 87274: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const path = __nccwpck_require__(71017); const which = __nccwpck_require__(34207); const getPathKey = __nccwpck_require__(20539); function resolveCommandAttempt(parsed, withoutPathExt) { const env = parsed.options.env || process.env; const cwd = process.cwd(); const hasCustomCwd = parsed.options.cwd != null; // Worker threads do not have process.chdir() const shouldSwitchCwd = hasCustomCwd && process.chdir !== undefined && !process.chdir.disabled; // If a custom `cwd` was specified, we need to change the process cwd // because `which` will do stat calls but does not support a custom cwd if (shouldSwitchCwd) { try { process.chdir(parsed.options.cwd); } catch (err) { /* Empty */ } } let resolved; try { resolved = which.sync(parsed.command, { path: env[getPathKey({ env })], pathExt: withoutPathExt ? path.delimiter : undefined, }); } catch (e) { /* Empty */ } finally { if (shouldSwitchCwd) { process.chdir(cwd); } } // If we successfully resolved, ensure that an absolute path is returned // Note that when a custom `cwd` was used, we need to resolve to an absolute path based on it if (resolved) { resolved = path.resolve(hasCustomCwd ? parsed.options.cwd : '', resolved); } return resolved; } function resolveCommand(parsed) { return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true); } module.exports = resolveCommand; /***/ }), /***/ 18611: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var Stream = (__nccwpck_require__(12781).Stream); var util = __nccwpck_require__(73837); module.exports = DelayedStream; function DelayedStream() { this.source = null; this.dataSize = 0; this.maxDataSize = 1024 * 1024; this.pauseStream = true; this._maxDataSizeExceeded = false; this._released = false; this._bufferedEvents = []; } util.inherits(DelayedStream, Stream); DelayedStream.create = function(source, options) { var delayedStream = new this(); options = options || {}; for (var option in options) { delayedStream[option] = options[option]; } delayedStream.source = source; var realEmit = source.emit; source.emit = function() { delayedStream._handleEmit(arguments); return realEmit.apply(source, arguments); }; source.on('error', function() {}); if (delayedStream.pauseStream) { source.pause(); } return delayedStream; }; Object.defineProperty(DelayedStream.prototype, 'readable', { configurable: true, enumerable: true, get: function() { return this.source.readable; } }); DelayedStream.prototype.setEncoding = function() { return this.source.setEncoding.apply(this.source, arguments); }; DelayedStream.prototype.resume = function() { if (!this._released) { this.release(); } this.source.resume(); }; DelayedStream.prototype.pause = function() { this.source.pause(); }; DelayedStream.prototype.release = function() { this._released = true; this._bufferedEvents.forEach(function(args) { this.emit.apply(this, args); }.bind(this)); this._bufferedEvents = []; }; DelayedStream.prototype.pipe = function() { var r = Stream.prototype.pipe.apply(this, arguments); this.resume(); return r; }; DelayedStream.prototype._handleEmit = function(args) { if (this._released) { this.emit.apply(this, args); return; } if (args[0] === 'data') { this.dataSize += args[1].length; this._checkIfMaxDataSizeExceeded(); } this._bufferedEvents.push(args); }; DelayedStream.prototype._checkIfMaxDataSizeExceeded = function() { if (this._maxDataSizeExceeded) { return; } if (this.dataSize <= this.maxDataSize) { return; } this._maxDataSizeExceeded = true; var message = 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.' this.emit('error', new Error(message)); }; /***/ }), /***/ 58932: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); class Deprecation extends Error { constructor(message) { super(message); // Maintains proper stack trace (only available on V8) /* istanbul ignore next */ if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); } this.name = 'Deprecation'; } } exports.Deprecation = Deprecation; /***/ }), /***/ 13598: /***/ ((module) => { "use strict"; function _process (v, mod) { var i var r if (typeof mod === 'function') { r = mod(v) if (r !== undefined) { v = r } } else if (Array.isArray(mod)) { for (i = 0; i < mod.length; i++) { r = mod[i](v) if (r !== undefined) { v = r } } } return v } function parseKey (key, val) { // detect negative index notation if (key[0] === '-' && Array.isArray(val) && /^-\d+$/.test(key)) { return val.length + parseInt(key, 10) } return key } function isIndex (k) { return /^\d+$/.test(k) } function isObject (val) { return Object.prototype.toString.call(val) === '[object Object]' } function isArrayOrObject (val) { return Object(val) === val } function isEmptyObject (val) { return Object.keys(val).length === 0 } var blacklist = ['__proto__', 'prototype', 'constructor'] var blacklistFilter = function (part) { return blacklist.indexOf(part) === -1 } function parsePath (path, sep) { if (path.indexOf('[') >= 0) { path = path.replace(/\[/g, sep).replace(/]/g, '') } var parts = path.split(sep) var check = parts.filter(blacklistFilter) if (check.length !== parts.length) { throw Error('Refusing to update blacklisted property ' + path) } return parts } var hasOwnProperty = Object.prototype.hasOwnProperty function DotObject (separator, override, useArray, useBrackets) { if (!(this instanceof DotObject)) { return new DotObject(separator, override, useArray, useBrackets) } if (typeof override === 'undefined') override = false if (typeof useArray === 'undefined') useArray = true if (typeof useBrackets === 'undefined') useBrackets = true this.separator = separator || '.' this.override = override this.useArray = useArray this.useBrackets = useBrackets this.keepArray = false // contains touched arrays this.cleanup = [] } var dotDefault = new DotObject('.', false, true, true) function wrap (method) { return function () { return dotDefault[method].apply(dotDefault, arguments) } } DotObject.prototype._fill = function (a, obj, v, mod) { var k = a.shift() if (a.length > 0) { obj[k] = obj[k] || (this.useArray && isIndex(a[0]) ? [] : {}) if (!isArrayOrObject(obj[k])) { if (this.override) { obj[k] = {} } else { if (!(isArrayOrObject(v) && isEmptyObject(v))) { throw new Error( 'Trying to redefine `' + k + '` which is a ' + typeof obj[k] ) } return } } this._fill(a, obj[k], v, mod) } else { if (!this.override && isArrayOrObject(obj[k]) && !isEmptyObject(obj[k])) { if (!(isArrayOrObject(v) && isEmptyObject(v))) { throw new Error("Trying to redefine non-empty obj['" + k + "']") } return } obj[k] = _process(v, mod) } } /** * * Converts an object with dotted-key/value pairs to it's expanded version * * Optionally transformed by a set of modifiers. * * Usage: * * var row = { * 'nr': 200, * 'doc.name': ' My Document ' * } * * var mods = { * 'doc.name': [_s.trim, _s.underscored] * } * * dot.object(row, mods) * * @param {Object} obj * @param {Object} mods */ DotObject.prototype.object = function (obj, mods) { var self = this Object.keys(obj).forEach(function (k) { var mod = mods === undefined ? null : mods[k] // normalize array notation. var ok = parsePath(k, self.separator).join(self.separator) if (ok.indexOf(self.separator) !== -1) { self._fill(ok.split(self.separator), obj, obj[k], mod) delete obj[k] } else { obj[k] = _process(obj[k], mod) } }) return obj } /** * @param {String} path dotted path * @param {String} v value to be set * @param {Object} obj object to be modified * @param {Function|Array} mod optional modifier */ DotObject.prototype.str = function (path, v, obj, mod) { var ok = parsePath(path, this.separator).join(this.separator) if (path.indexOf(this.separator) !== -1) { this._fill(ok.split(this.separator), obj, v, mod) } else { obj[path] = _process(v, mod) } return obj } /** * * Pick a value from an object using dot notation. * * Optionally remove the value * * @param {String} path * @param {Object} obj * @param {Boolean} remove */ DotObject.prototype.pick = function (path, obj, remove, reindexArray) { var i var keys var val var key var cp keys = parsePath(path, this.separator) for (i = 0; i < keys.length; i++) { key = parseKey(keys[i], obj) if (obj && typeof obj === 'object' && key in obj) { if (i === keys.length - 1) { if (remove) { val = obj[key] if (reindexArray && Array.isArray(obj)) { obj.splice(key, 1) } else { delete obj[key] } if (Array.isArray(obj)) { cp = keys.slice(0, -1).join('.') if (this.cleanup.indexOf(cp) === -1) { this.cleanup.push(cp) } } return val } else { return obj[key] } } else { obj = obj[key] } } else { return undefined } } if (remove && Array.isArray(obj)) { obj = obj.filter(function (n) { return n !== undefined }) } return obj } /** * * Delete value from an object using dot notation. * * @param {String} path * @param {Object} obj * @return {any} The removed value */ DotObject.prototype.delete = function (path, obj) { return this.remove(path, obj, true) } /** * * Remove value from an object using dot notation. * * Will remove multiple items if path is an array. * In this case array indexes will be retained until all * removals have been processed. * * Use dot.delete() to automatically re-index arrays. * * @param {String|Array} path * @param {Object} obj * @param {Boolean} reindexArray * @return {any} The removed value */ DotObject.prototype.remove = function (path, obj, reindexArray) { var i this.cleanup = [] if (Array.isArray(path)) { for (i = 0; i < path.length; i++) { this.pick(path[i], obj, true, reindexArray) } if (!reindexArray) { this._cleanup(obj) } return obj } else { return this.pick(path, obj, true, reindexArray) } } DotObject.prototype._cleanup = function (obj) { var ret var i var keys var root if (this.cleanup.length) { for (i = 0; i < this.cleanup.length; i++) { keys = this.cleanup[i].split('.') root = keys.splice(0, -1).join('.') ret = root ? this.pick(root, obj) : obj ret = ret[keys[0]].filter(function (v) { return v !== undefined }) this.set(this.cleanup[i], ret, obj) } this.cleanup = [] } } /** * Alias method for `dot.remove` * * Note: this is not an alias for dot.delete() * * @param {String|Array} path * @param {Object} obj * @param {Boolean} reindexArray * @return {any} The removed value */ DotObject.prototype.del = DotObject.prototype.remove /** * * Move a property from one place to the other. * * If the source path does not exist (undefined) * the target property will not be set. * * @param {String} source * @param {String} target * @param {Object} obj * @param {Function|Array} mods * @param {Boolean} merge */ DotObject.prototype.move = function (source, target, obj, mods, merge) { if (typeof mods === 'function' || Array.isArray(mods)) { this.set(target, _process(this.pick(source, obj, true), mods), obj, merge) } else { merge = mods this.set(target, this.pick(source, obj, true), obj, merge) } return obj } /** * * Transfer a property from one object to another object. * * If the source path does not exist (undefined) * the property on the other object will not be set. * * @param {String} source * @param {String} target * @param {Object} obj1 * @param {Object} obj2 * @param {Function|Array} mods * @param {Boolean} merge */ DotObject.prototype.transfer = function ( source, target, obj1, obj2, mods, merge ) { if (typeof mods === 'function' || Array.isArray(mods)) { this.set( target, _process(this.pick(source, obj1, true), mods), obj2, merge ) } else { merge = mods this.set(target, this.pick(source, obj1, true), obj2, merge) } return obj2 } /** * * Copy a property from one object to another object. * * If the source path does not exist (undefined) * the property on the other object will not be set. * * @param {String} source * @param {String} target * @param {Object} obj1 * @param {Object} obj2 * @param {Function|Array} mods * @param {Boolean} merge */ DotObject.prototype.copy = function (source, target, obj1, obj2, mods, merge) { if (typeof mods === 'function' || Array.isArray(mods)) { this.set( target, _process( // clone what is picked JSON.parse(JSON.stringify(this.pick(source, obj1, false))), mods ), obj2, merge ) } else { merge = mods this.set(target, this.pick(source, obj1, false), obj2, merge) } return obj2 } /** * * Set a property on an object using dot notation. * * @param {String} path * @param {any} val * @param {Object} obj * @param {Boolean} merge */ DotObject.prototype.set = function (path, val, obj, merge) { var i var k var keys var key // Do not operate if the value is undefined. if (typeof val === 'undefined') { return obj } keys = parsePath(path, this.separator) for (i = 0; i < keys.length; i++) { key = keys[i] if (i === keys.length - 1) { if (merge && isObject(val) && isObject(obj[key])) { for (k in val) { if (hasOwnProperty.call(val, k)) { obj[key][k] = val[k] } } } else if (merge && Array.isArray(obj[key]) && Array.isArray(val)) { for (var j = 0; j < val.length; j++) { obj[keys[i]].push(val[j]) } } else { obj[key] = val } } else if ( // force the value to be an object !hasOwnProperty.call(obj, key) || (!isObject(obj[key]) && !Array.isArray(obj[key])) ) { // initialize as array if next key is numeric if (/^\d+$/.test(keys[i + 1])) { obj[key] = [] } else { obj[key] = {} } } obj = obj[key] } return obj } /** * * Transform an object * * Usage: * * var obj = { * "id": 1, * "some": { * "thing": "else" * } * } * * var transform = { * "id": "nr", * "some.thing": "name" * } * * var tgt = dot.transform(transform, obj) * * @param {Object} recipe Transform recipe * @param {Object} obj Object to be transformed * @param {Array} mods modifiers for the target */ DotObject.prototype.transform = function (recipe, obj, tgt) { obj = obj || {} tgt = tgt || {} Object.keys(recipe).forEach( function (key) { this.set(recipe[key], this.pick(key, obj), tgt) }.bind(this) ) return tgt } /** * * Convert object to dotted-key/value pair * * Usage: * * var tgt = dot.dot(obj) * * or * * var tgt = {} * dot.dot(obj, tgt) * * @param {Object} obj source object * @param {Object} tgt target object * @param {Array} path path array (internal) */ DotObject.prototype.dot = function (obj, tgt, path) { tgt = tgt || {} path = path || [] var isArray = Array.isArray(obj) Object.keys(obj).forEach( function (key) { var index = isArray && this.useBrackets ? '[' + key + ']' : key if ( isArrayOrObject(obj[key]) && ((isObject(obj[key]) && !isEmptyObject(obj[key])) || (Array.isArray(obj[key]) && !this.keepArray && obj[key].length !== 0)) ) { if (isArray && this.useBrackets) { var previousKey = path[path.length - 1] || '' return this.dot( obj[key], tgt, path.slice(0, -1).concat(previousKey + index) ) } else { return this.dot(obj[key], tgt, path.concat(index)) } } else { if (isArray && this.useBrackets) { tgt[path.join(this.separator).concat('[' + key + ']')] = obj[key] } else { tgt[path.concat(index).join(this.separator)] = obj[key] } } }.bind(this) ) return tgt } DotObject.pick = wrap('pick') DotObject.move = wrap('move') DotObject.transfer = wrap('transfer') DotObject.transform = wrap('transform') DotObject.copy = wrap('copy') DotObject.object = wrap('object') DotObject.str = wrap('str') DotObject.set = wrap('set') DotObject.delete = wrap('delete') DotObject.del = DotObject.remove = wrap('remove') DotObject.dot = wrap('dot'); ['override', 'overwrite'].forEach(function (prop) { Object.defineProperty(DotObject, prop, { get: function () { return dotDefault.override }, set: function (val) { dotDefault.override = !!val } }) }); ['useArray', 'keepArray', 'useBrackets'].forEach(function (prop) { Object.defineProperty(DotObject, prop, { get: function () { return dotDefault[prop] }, set: function (val) { dotDefault[prop] = val } }) }) DotObject._process = _process module.exports = DotObject /***/ }), /***/ 49865: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { var crypto = __nccwpck_require__(6113); var BigInteger = (__nccwpck_require__(85587).BigInteger); var ECPointFp = (__nccwpck_require__(3943).ECPointFp); var Buffer = (__nccwpck_require__(15118).Buffer); exports.ECCurves = __nccwpck_require__(41452); // zero prepad function unstupid(hex,len) { return (hex.length >= len) ? hex : unstupid("0"+hex,len); } exports.ECKey = function(curve, key, isPublic) { var priv; var c = curve(); var n = c.getN(); var bytes = Math.floor(n.bitLength()/8); if(key) { if(isPublic) { var curve = c.getCurve(); // var x = key.slice(1,bytes+1); // skip the 04 for uncompressed format // var y = key.slice(bytes+1); // this.P = new ECPointFp(curve, // curve.fromBigInteger(new BigInteger(x.toString("hex"), 16)), // curve.fromBigInteger(new BigInteger(y.toString("hex"), 16))); this.P = curve.decodePointHex(key.toString("hex")); }else{ if(key.length != bytes) return false; priv = new BigInteger(key.toString("hex"), 16); } }else{ var n1 = n.subtract(BigInteger.ONE); var r = new BigInteger(crypto.randomBytes(n.bitLength())); priv = r.mod(n1).add(BigInteger.ONE); this.P = c.getG().multiply(priv); } if(this.P) { // var pubhex = unstupid(this.P.getX().toBigInteger().toString(16),bytes*2)+unstupid(this.P.getY().toBigInteger().toString(16),bytes*2); // this.PublicKey = Buffer.from("04"+pubhex,"hex"); this.PublicKey = Buffer.from(c.getCurve().encodeCompressedPointHex(this.P),"hex"); } if(priv) { this.PrivateKey = Buffer.from(unstupid(priv.toString(16),bytes*2),"hex"); this.deriveSharedSecret = function(key) { if(!key || !key.P) return false; var S = key.P.multiply(priv); return Buffer.from(unstupid(S.getX().toBigInteger().toString(16),bytes*2),"hex"); } } } /***/ }), /***/ 3943: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // Basic Javascript Elliptic Curve implementation // Ported loosely from BouncyCastle's Java EC code // Only Fp curves implemented for now // Requires jsbn.js and jsbn2.js var BigInteger = (__nccwpck_require__(85587).BigInteger) var Barrett = BigInteger.prototype.Barrett // ---------------- // ECFieldElementFp // constructor function ECFieldElementFp(q,x) { this.x = x; // TODO if(x.compareTo(q) >= 0) error this.q = q; } function feFpEquals(other) { if(other == this) return true; return (this.q.equals(other.q) && this.x.equals(other.x)); } function feFpToBigInteger() { return this.x; } function feFpNegate() { return new ECFieldElementFp(this.q, this.x.negate().mod(this.q)); } function feFpAdd(b) { return new ECFieldElementFp(this.q, this.x.add(b.toBigInteger()).mod(this.q)); } function feFpSubtract(b) { return new ECFieldElementFp(this.q, this.x.subtract(b.toBigInteger()).mod(this.q)); } function feFpMultiply(b) { return new ECFieldElementFp(this.q, this.x.multiply(b.toBigInteger()).mod(this.q)); } function feFpSquare() { return new ECFieldElementFp(this.q, this.x.square().mod(this.q)); } function feFpDivide(b) { return new ECFieldElementFp(this.q, this.x.multiply(b.toBigInteger().modInverse(this.q)).mod(this.q)); } ECFieldElementFp.prototype.equals = feFpEquals; ECFieldElementFp.prototype.toBigInteger = feFpToBigInteger; ECFieldElementFp.prototype.negate = feFpNegate; ECFieldElementFp.prototype.add = feFpAdd; ECFieldElementFp.prototype.subtract = feFpSubtract; ECFieldElementFp.prototype.multiply = feFpMultiply; ECFieldElementFp.prototype.square = feFpSquare; ECFieldElementFp.prototype.divide = feFpDivide; // ---------------- // ECPointFp // constructor function ECPointFp(curve,x,y,z) { this.curve = curve; this.x = x; this.y = y; // Projective coordinates: either zinv == null or z * zinv == 1 // z and zinv are just BigIntegers, not fieldElements if(z == null) { this.z = BigInteger.ONE; } else { this.z = z; } this.zinv = null; //TODO: compression flag } function pointFpGetX() { if(this.zinv == null) { this.zinv = this.z.modInverse(this.curve.q); } var r = this.x.toBigInteger().multiply(this.zinv); this.curve.reduce(r); return this.curve.fromBigInteger(r); } function pointFpGetY() { if(this.zinv == null) { this.zinv = this.z.modInverse(this.curve.q); } var r = this.y.toBigInteger().multiply(this.zinv); this.curve.reduce(r); return this.curve.fromBigInteger(r); } function pointFpEquals(other) { if(other == this) return true; if(this.isInfinity()) return other.isInfinity(); if(other.isInfinity()) return this.isInfinity(); var u, v; // u = Y2 * Z1 - Y1 * Z2 u = other.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(other.z)).mod(this.curve.q); if(!u.equals(BigInteger.ZERO)) return false; // v = X2 * Z1 - X1 * Z2 v = other.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(other.z)).mod(this.curve.q); return v.equals(BigInteger.ZERO); } function pointFpIsInfinity() { if((this.x == null) && (this.y == null)) return true; return this.z.equals(BigInteger.ZERO) && !this.y.toBigInteger().equals(BigInteger.ZERO); } function pointFpNegate() { return new ECPointFp(this.curve, this.x, this.y.negate(), this.z); } function pointFpAdd(b) { if(this.isInfinity()) return b; if(b.isInfinity()) return this; // u = Y2 * Z1 - Y1 * Z2 var u = b.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(b.z)).mod(this.curve.q); // v = X2 * Z1 - X1 * Z2 var v = b.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(b.z)).mod(this.curve.q); if(BigInteger.ZERO.equals(v)) { if(BigInteger.ZERO.equals(u)) { return this.twice(); // this == b, so double } return this.curve.getInfinity(); // this = -b, so infinity } var THREE = new BigInteger("3"); var x1 = this.x.toBigInteger(); var y1 = this.y.toBigInteger(); var x2 = b.x.toBigInteger(); var y2 = b.y.toBigInteger(); var v2 = v.square(); var v3 = v2.multiply(v); var x1v2 = x1.multiply(v2); var zu2 = u.square().multiply(this.z); // x3 = v * (z2 * (z1 * u^2 - 2 * x1 * v^2) - v^3) var x3 = zu2.subtract(x1v2.shiftLeft(1)).multiply(b.z).subtract(v3).multiply(v).mod(this.curve.q); // y3 = z2 * (3 * x1 * u * v^2 - y1 * v^3 - z1 * u^3) + u * v^3 var y3 = x1v2.multiply(THREE).multiply(u).subtract(y1.multiply(v3)).subtract(zu2.multiply(u)).multiply(b.z).add(u.multiply(v3)).mod(this.curve.q); // z3 = v^3 * z1 * z2 var z3 = v3.multiply(this.z).multiply(b.z).mod(this.curve.q); return new ECPointFp(this.curve, this.curve.fromBigInteger(x3), this.curve.fromBigInteger(y3), z3); } function pointFpTwice() { if(this.isInfinity()) return this; if(this.y.toBigInteger().signum() == 0) return this.curve.getInfinity(); // TODO: optimized handling of constants var THREE = new BigInteger("3"); var x1 = this.x.toBigInteger(); var y1 = this.y.toBigInteger(); var y1z1 = y1.multiply(this.z); var y1sqz1 = y1z1.multiply(y1).mod(this.curve.q); var a = this.curve.a.toBigInteger(); // w = 3 * x1^2 + a * z1^2 var w = x1.square().multiply(THREE); if(!BigInteger.ZERO.equals(a)) { w = w.add(this.z.square().multiply(a)); } w = w.mod(this.curve.q); //this.curve.reduce(w); // x3 = 2 * y1 * z1 * (w^2 - 8 * x1 * y1^2 * z1) var x3 = w.square().subtract(x1.shiftLeft(3).multiply(y1sqz1)).shiftLeft(1).multiply(y1z1).mod(this.curve.q); // y3 = 4 * y1^2 * z1 * (3 * w * x1 - 2 * y1^2 * z1) - w^3 var y3 = w.multiply(THREE).multiply(x1).subtract(y1sqz1.shiftLeft(1)).shiftLeft(2).multiply(y1sqz1).subtract(w.square().multiply(w)).mod(this.curve.q); // z3 = 8 * (y1 * z1)^3 var z3 = y1z1.square().multiply(y1z1).shiftLeft(3).mod(this.curve.q); return new ECPointFp(this.curve, this.curve.fromBigInteger(x3), this.curve.fromBigInteger(y3), z3); } // Simple NAF (Non-Adjacent Form) multiplication algorithm // TODO: modularize the multiplication algorithm function pointFpMultiply(k) { if(this.isInfinity()) return this; if(k.signum() == 0) return this.curve.getInfinity(); var e = k; var h = e.multiply(new BigInteger("3")); var neg = this.negate(); var R = this; var i; for(i = h.bitLength() - 2; i > 0; --i) { R = R.twice(); var hBit = h.testBit(i); var eBit = e.testBit(i); if (hBit != eBit) { R = R.add(hBit ? this : neg); } } return R; } // Compute this*j + x*k (simultaneous multiplication) function pointFpMultiplyTwo(j,x,k) { var i; if(j.bitLength() > k.bitLength()) i = j.bitLength() - 1; else i = k.bitLength() - 1; var R = this.curve.getInfinity(); var both = this.add(x); while(i >= 0) { R = R.twice(); if(j.testBit(i)) { if(k.testBit(i)) { R = R.add(both); } else { R = R.add(this); } } else { if(k.testBit(i)) { R = R.add(x); } } --i; } return R; } ECPointFp.prototype.getX = pointFpGetX; ECPointFp.prototype.getY = pointFpGetY; ECPointFp.prototype.equals = pointFpEquals; ECPointFp.prototype.isInfinity = pointFpIsInfinity; ECPointFp.prototype.negate = pointFpNegate; ECPointFp.prototype.add = pointFpAdd; ECPointFp.prototype.twice = pointFpTwice; ECPointFp.prototype.multiply = pointFpMultiply; ECPointFp.prototype.multiplyTwo = pointFpMultiplyTwo; // ---------------- // ECCurveFp // constructor function ECCurveFp(q,a,b) { this.q = q; this.a = this.fromBigInteger(a); this.b = this.fromBigInteger(b); this.infinity = new ECPointFp(this, null, null); this.reducer = new Barrett(this.q); } function curveFpGetQ() { return this.q; } function curveFpGetA() { return this.a; } function curveFpGetB() { return this.b; } function curveFpEquals(other) { if(other == this) return true; return(this.q.equals(other.q) && this.a.equals(other.a) && this.b.equals(other.b)); } function curveFpGetInfinity() { return this.infinity; } function curveFpFromBigInteger(x) { return new ECFieldElementFp(this.q, x); } function curveReduce(x) { this.reducer.reduce(x); } // for now, work with hex strings because they're easier in JS function curveFpDecodePointHex(s) { switch(parseInt(s.substr(0,2), 16)) { // first byte case 0: return this.infinity; case 2: case 3: // point compression not supported yet return null; case 4: case 6: case 7: var len = (s.length - 2) / 2; var xHex = s.substr(2, len); var yHex = s.substr(len+2, len); return new ECPointFp(this, this.fromBigInteger(new BigInteger(xHex, 16)), this.fromBigInteger(new BigInteger(yHex, 16))); default: // unsupported return null; } } function curveFpEncodePointHex(p) { if (p.isInfinity()) return "00"; var xHex = p.getX().toBigInteger().toString(16); var yHex = p.getY().toBigInteger().toString(16); var oLen = this.getQ().toString(16).length; if ((oLen % 2) != 0) oLen++; while (xHex.length < oLen) { xHex = "0" + xHex; } while (yHex.length < oLen) { yHex = "0" + yHex; } return "04" + xHex + yHex; } ECCurveFp.prototype.getQ = curveFpGetQ; ECCurveFp.prototype.getA = curveFpGetA; ECCurveFp.prototype.getB = curveFpGetB; ECCurveFp.prototype.equals = curveFpEquals; ECCurveFp.prototype.getInfinity = curveFpGetInfinity; ECCurveFp.prototype.fromBigInteger = curveFpFromBigInteger; ECCurveFp.prototype.reduce = curveReduce; //ECCurveFp.prototype.decodePointHex = curveFpDecodePointHex; ECCurveFp.prototype.encodePointHex = curveFpEncodePointHex; // from: https://github.com/kaielvin/jsbn-ec-point-compression ECCurveFp.prototype.decodePointHex = function(s) { var yIsEven; switch(parseInt(s.substr(0,2), 16)) { // first byte case 0: return this.infinity; case 2: yIsEven = false; case 3: if(yIsEven == undefined) yIsEven = true; var len = s.length - 2; var xHex = s.substr(2, len); var x = this.fromBigInteger(new BigInteger(xHex,16)); var alpha = x.multiply(x.square().add(this.getA())).add(this.getB()); var beta = alpha.sqrt(); if (beta == null) throw "Invalid point compression"; var betaValue = beta.toBigInteger(); if (betaValue.testBit(0) != yIsEven) { // Use the other root beta = this.fromBigInteger(this.getQ().subtract(betaValue)); } return new ECPointFp(this,x,beta); case 4: case 6: case 7: var len = (s.length - 2) / 2; var xHex = s.substr(2, len); var yHex = s.substr(len+2, len); return new ECPointFp(this, this.fromBigInteger(new BigInteger(xHex, 16)), this.fromBigInteger(new BigInteger(yHex, 16))); default: // unsupported return null; } } ECCurveFp.prototype.encodeCompressedPointHex = function(p) { if (p.isInfinity()) return "00"; var xHex = p.getX().toBigInteger().toString(16); var oLen = this.getQ().toString(16).length; if ((oLen % 2) != 0) oLen++; while (xHex.length < oLen) xHex = "0" + xHex; var yPrefix; if(p.getY().toBigInteger().isEven()) yPrefix = "02"; else yPrefix = "03"; return yPrefix + xHex; } ECFieldElementFp.prototype.getR = function() { if(this.r != undefined) return this.r; this.r = null; var bitLength = this.q.bitLength(); if (bitLength > 128) { var firstWord = this.q.shiftRight(bitLength - 64); if (firstWord.intValue() == -1) { this.r = BigInteger.ONE.shiftLeft(bitLength).subtract(this.q); } } return this.r; } ECFieldElementFp.prototype.modMult = function(x1,x2) { return this.modReduce(x1.multiply(x2)); } ECFieldElementFp.prototype.modReduce = function(x) { if (this.getR() != null) { var qLen = q.bitLength(); while (x.bitLength() > (qLen + 1)) { var u = x.shiftRight(qLen); var v = x.subtract(u.shiftLeft(qLen)); if (!this.getR().equals(BigInteger.ONE)) { u = u.multiply(this.getR()); } x = u.add(v); } while (x.compareTo(q) >= 0) { x = x.subtract(q); } } else { x = x.mod(q); } return x; } ECFieldElementFp.prototype.sqrt = function() { if (!this.q.testBit(0)) throw "unsupported"; // p mod 4 == 3 if (this.q.testBit(1)) { var z = new ECFieldElementFp(this.q,this.x.modPow(this.q.shiftRight(2).add(BigInteger.ONE),this.q)); return z.square().equals(this) ? z : null; } // p mod 4 == 1 var qMinusOne = this.q.subtract(BigInteger.ONE); var legendreExponent = qMinusOne.shiftRight(1); if (!(this.x.modPow(legendreExponent, this.q).equals(BigInteger.ONE))) { return null; } var u = qMinusOne.shiftRight(2); var k = u.shiftLeft(1).add(BigInteger.ONE); var Q = this.x; var fourQ = modDouble(modDouble(Q)); var U, V; do { var P; do { P = new BigInteger(this.q.bitLength(), new SecureRandom()); } while (P.compareTo(this.q) >= 0 || !(P.multiply(P).subtract(fourQ).modPow(legendreExponent, this.q).equals(qMinusOne))); var result = this.lucasSequence(P, Q, k); U = result[0]; V = result[1]; if (this.modMult(V, V).equals(fourQ)) { // Integer division by 2, mod q if (V.testBit(0)) { V = V.add(q); } V = V.shiftRight(1); return new ECFieldElementFp(q,V); } } while (U.equals(BigInteger.ONE) || U.equals(qMinusOne)); return null; } ECFieldElementFp.prototype.lucasSequence = function(P,Q,k) { var n = k.bitLength(); var s = k.getLowestSetBit(); var Uh = BigInteger.ONE; var Vl = BigInteger.TWO; var Vh = P; var Ql = BigInteger.ONE; var Qh = BigInteger.ONE; for (var j = n - 1; j >= s + 1; --j) { Ql = this.modMult(Ql, Qh); if (k.testBit(j)) { Qh = this.modMult(Ql, Q); Uh = this.modMult(Uh, Vh); Vl = this.modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql))); Vh = this.modReduce(Vh.multiply(Vh).subtract(Qh.shiftLeft(1))); } else { Qh = Ql; Uh = this.modReduce(Uh.multiply(Vl).subtract(Ql)); Vh = this.modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql))); Vl = this.modReduce(Vl.multiply(Vl).subtract(Ql.shiftLeft(1))); } } Ql = this.modMult(Ql, Qh); Qh = this.modMult(Ql, Q); Uh = this.modReduce(Uh.multiply(Vl).subtract(Ql)); Vl = this.modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql))); Ql = this.modMult(Ql, Qh); for (var j = 1; j <= s; ++j) { Uh = this.modMult(Uh, Vl); Vl = this.modReduce(Vl.multiply(Vl).subtract(Ql.shiftLeft(1))); Ql = this.modMult(Ql, Ql); } return [ Uh, Vl ]; } var exports = { ECCurveFp: ECCurveFp, ECPointFp: ECPointFp, ECFieldElementFp: ECFieldElementFp } module.exports = exports /***/ }), /***/ 41452: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // Named EC curves // Requires ec.js, jsbn.js, and jsbn2.js var BigInteger = (__nccwpck_require__(85587).BigInteger) var ECCurveFp = (__nccwpck_require__(3943).ECCurveFp) // ---------------- // X9ECParameters // constructor function X9ECParameters(curve,g,n,h) { this.curve = curve; this.g = g; this.n = n; this.h = h; } function x9getCurve() { return this.curve; } function x9getG() { return this.g; } function x9getN() { return this.n; } function x9getH() { return this.h; } X9ECParameters.prototype.getCurve = x9getCurve; X9ECParameters.prototype.getG = x9getG; X9ECParameters.prototype.getN = x9getN; X9ECParameters.prototype.getH = x9getH; // ---------------- // SECNamedCurves function fromHex(s) { return new BigInteger(s, 16); } function secp128r1() { // p = 2^128 - 2^97 - 1 var p = fromHex("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFF"); var a = fromHex("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFC"); var b = fromHex("E87579C11079F43DD824993C2CEE5ED3"); //byte[] S = Hex.decode("000E0D4D696E6768756151750CC03A4473D03679"); var n = fromHex("FFFFFFFE0000000075A30D1B9038A115"); var h = BigInteger.ONE; var curve = new ECCurveFp(p, a, b); var G = curve.decodePointHex("04" + "161FF7528B899B2D0C28607CA52C5B86" + "CF5AC8395BAFEB13C02DA292DDED7A83"); return new X9ECParameters(curve, G, n, h); } function secp160k1() { // p = 2^160 - 2^32 - 2^14 - 2^12 - 2^9 - 2^8 - 2^7 - 2^3 - 2^2 - 1 var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73"); var a = BigInteger.ZERO; var b = fromHex("7"); //byte[] S = null; var n = fromHex("0100000000000000000001B8FA16DFAB9ACA16B6B3"); var h = BigInteger.ONE; var curve = new ECCurveFp(p, a, b); var G = curve.decodePointHex("04" + "3B4C382CE37AA192A4019E763036F4F5DD4D7EBB" + "938CF935318FDCED6BC28286531733C3F03C4FEE"); return new X9ECParameters(curve, G, n, h); } function secp160r1() { // p = 2^160 - 2^31 - 1 var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFF"); var a = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFC"); var b = fromHex("1C97BEFC54BD7A8B65ACF89F81D4D4ADC565FA45"); //byte[] S = Hex.decode("1053CDE42C14D696E67687561517533BF3F83345"); var n = fromHex("0100000000000000000001F4C8F927AED3CA752257"); var h = BigInteger.ONE; var curve = new ECCurveFp(p, a, b); var G = curve.decodePointHex("04" + "4A96B5688EF573284664698968C38BB913CBFC82" + "23A628553168947D59DCC912042351377AC5FB32"); return new X9ECParameters(curve, G, n, h); } function secp192k1() { // p = 2^192 - 2^32 - 2^12 - 2^8 - 2^7 - 2^6 - 2^3 - 1 var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFEE37"); var a = BigInteger.ZERO; var b = fromHex("3"); //byte[] S = null; var n = fromHex("FFFFFFFFFFFFFFFFFFFFFFFE26F2FC170F69466A74DEFD8D"); var h = BigInteger.ONE; var curve = new ECCurveFp(p, a, b); var G = curve.decodePointHex("04" + "DB4FF10EC057E9AE26B07D0280B7F4341DA5D1B1EAE06C7D" + "9B2F2F6D9C5628A7844163D015BE86344082AA88D95E2F9D"); return new X9ECParameters(curve, G, n, h); } function secp192r1() { // p = 2^192 - 2^64 - 1 var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF"); var a = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC"); var b = fromHex("64210519E59C80E70FA7E9AB72243049FEB8DEECC146B9B1"); //byte[] S = Hex.decode("3045AE6FC8422F64ED579528D38120EAE12196D5"); var n = fromHex("FFFFFFFFFFFFFFFFFFFFFFFF99DEF836146BC9B1B4D22831"); var h = BigInteger.ONE; var curve = new ECCurveFp(p, a, b); var G = curve.decodePointHex("04" + "188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012" + "07192B95FFC8DA78631011ED6B24CDD573F977A11E794811"); return new X9ECParameters(curve, G, n, h); } function secp224r1() { // p = 2^224 - 2^96 + 1 var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000001"); var a = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFE"); var b = fromHex("B4050A850C04B3ABF54132565044B0B7D7BFD8BA270B39432355FFB4"); //byte[] S = Hex.decode("BD71344799D5C7FCDC45B59FA3B9AB8F6A948BC5"); var n = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFF16A2E0B8F03E13DD29455C5C2A3D"); var h = BigInteger.ONE; var curve = new ECCurveFp(p, a, b); var G = curve.decodePointHex("04" + "B70E0CBD6BB4BF7F321390B94A03C1D356C21122343280D6115C1D21" + "BD376388B5F723FB4C22DFE6CD4375A05A07476444D5819985007E34"); return new X9ECParameters(curve, G, n, h); } function secp256r1() { // p = 2^224 (2^32 - 1) + 2^192 + 2^96 - 1 var p = fromHex("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF"); var a = fromHex("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC"); var b = fromHex("5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B"); //byte[] S = Hex.decode("C49D360886E704936A6678E1139D26B7819F7E90"); var n = fromHex("FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551"); var h = BigInteger.ONE; var curve = new ECCurveFp(p, a, b); var G = curve.decodePointHex("04" + "6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296" + "4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5"); return new X9ECParameters(curve, G, n, h); } // TODO: make this into a proper hashtable function getSECCurveByName(name) { if(name == "secp128r1") return secp128r1(); if(name == "secp160k1") return secp160k1(); if(name == "secp160r1") return secp160r1(); if(name == "secp192k1") return secp192k1(); if(name == "secp192r1") return secp192r1(); if(name == "secp224r1") return secp224r1(); if(name == "secp256r1") return secp256r1(); return null; } module.exports = { "secp128r1":secp128r1, "secp160k1":secp160k1, "secp160r1":secp160r1, "secp192k1":secp192k1, "secp192r1":secp192r1, "secp224r1":secp224r1, "secp256r1":secp256r1 } /***/ }), /***/ 81205: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var once = __nccwpck_require__(1223); var noop = function() {}; var isRequest = function(stream) { return stream.setHeader && typeof stream.abort === 'function'; }; var isChildProcess = function(stream) { return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3 }; var eos = function(stream, opts, callback) { if (typeof opts === 'function') return eos(stream, null, opts); if (!opts) opts = {}; callback = once(callback || noop); var ws = stream._writableState; var rs = stream._readableState; var readable = opts.readable || (opts.readable !== false && stream.readable); var writable = opts.writable || (opts.writable !== false && stream.writable); var cancelled = false; var onlegacyfinish = function() { if (!stream.writable) onfinish(); }; var onfinish = function() { writable = false; if (!readable) callback.call(stream); }; var onend = function() { readable = false; if (!writable) callback.call(stream); }; var onexit = function(exitCode) { callback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null); }; var onerror = function(err) { callback.call(stream, err); }; var onclose = function() { process.nextTick(onclosenexttick); }; var onclosenexttick = function() { if (cancelled) return; if (readable && !(rs && (rs.ended && !rs.destroyed))) return callback.call(stream, new Error('premature close')); if (writable && !(ws && (ws.ended && !ws.destroyed))) return callback.call(stream, new Error('premature close')); }; var onrequest = function() { stream.req.on('finish', onfinish); }; if (isRequest(stream)) { stream.on('complete', onfinish); stream.on('abort', onclose); if (stream.req) onrequest(); else stream.on('request', onrequest); } else if (writable && !ws) { // legacy streams stream.on('end', onlegacyfinish); stream.on('close', onlegacyfinish); } if (isChildProcess(stream)) stream.on('exit', onexit); stream.on('end', onend); stream.on('finish', onfinish); if (opts.error !== false) stream.on('error', onerror); stream.on('close', onclose); return function() { cancelled = true; stream.removeListener('complete', onfinish); stream.removeListener('abort', onclose); stream.removeListener('request', onrequest); if (stream.req) stream.req.removeListener('finish', onfinish); stream.removeListener('end', onlegacyfinish); stream.removeListener('close', onlegacyfinish); stream.removeListener('finish', onfinish); stream.removeListener('exit', onexit); stream.removeListener('end', onend); stream.removeListener('error', onerror); stream.removeListener('close', onclose); }; }; module.exports = eos; /***/ }), /***/ 38171: /***/ ((module) => { "use strict"; var hasOwn = Object.prototype.hasOwnProperty; var toStr = Object.prototype.toString; var defineProperty = Object.defineProperty; var gOPD = Object.getOwnPropertyDescriptor; var isArray = function isArray(arr) { if (typeof Array.isArray === 'function') { return Array.isArray(arr); } return toStr.call(arr) === '[object Array]'; }; var isPlainObject = function isPlainObject(obj) { if (!obj || toStr.call(obj) !== '[object Object]') { return false; } var hasOwnConstructor = hasOwn.call(obj, 'constructor'); var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf'); // Not own constructor property must be Object if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) { return false; } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. var key; for (key in obj) { /**/ } return typeof key === 'undefined' || hasOwn.call(obj, key); }; // If name is '__proto__', and Object.defineProperty is available, define __proto__ as an own property on target var setProperty = function setProperty(target, options) { if (defineProperty && options.name === '__proto__') { defineProperty(target, options.name, { enumerable: true, configurable: true, value: options.newValue, writable: true }); } else { target[options.name] = options.newValue; } }; // Return undefined instead of __proto__ if '__proto__' is not an own property var getProperty = function getProperty(obj, name) { if (name === '__proto__') { if (!hasOwn.call(obj, name)) { return void 0; } else if (gOPD) { // In early versions of node, obj['__proto__'] is buggy when obj has // __proto__ as an own property. Object.getOwnPropertyDescriptor() works. return gOPD(obj, name).value; } } return obj[name]; }; module.exports = function extend() { var options, name, src, copy, copyIsArray, clone; var target = arguments[0]; var i = 1; var length = arguments.length; var deep = false; // Handle a deep copy situation if (typeof target === 'boolean') { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } if (target == null || (typeof target !== 'object' && typeof target !== 'function')) { target = {}; } for (; i < length; ++i) { options = arguments[i]; // Only deal with non-null/undefined values if (options != null) { // Extend the base object for (name in options) { src = getProperty(target, name); copy = getProperty(options, name); // Prevent never-ending loop if (target !== copy) { // Recurse if we're merging plain objects or arrays if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) { if (copyIsArray) { copyIsArray = false; clone = src && isArray(src) ? src : []; } else { clone = src && isPlainObject(src) ? src : {}; } // Never move original objects, clone them setProperty(target, { name: name, newValue: extend(deep, clone, copy) }); // Don't bring in undefined values } else if (typeof copy !== 'undefined') { setProperty(target, { name: name, newValue: copy }); } } } } } // Return the modified object return target; }; /***/ }), /***/ 87264: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { /* * extsprintf.js: extended POSIX-style sprintf */ var mod_assert = __nccwpck_require__(39491); var mod_util = __nccwpck_require__(73837); /* * Public interface */ exports.sprintf = jsSprintf; exports.printf = jsPrintf; exports.fprintf = jsFprintf; /* * Stripped down version of s[n]printf(3c). We make a best effort to throw an * exception when given a format string we don't understand, rather than * ignoring it, so that we won't break existing programs if/when we go implement * the rest of this. * * This implementation currently supports specifying * - field alignment ('-' flag), * - zero-pad ('0' flag) * - always show numeric sign ('+' flag), * - field width * - conversions for strings, decimal integers, and floats (numbers). * - argument size specifiers. These are all accepted but ignored, since * Javascript has no notion of the physical size of an argument. * * Everything else is currently unsupported, most notably precision, unsigned * numbers, non-decimal numbers, and characters. */ function jsSprintf(fmt) { var regex = [ '([^%]*)', /* normal text */ '%', /* start of format */ '([\'\\-+ #0]*?)', /* flags (optional) */ '([1-9]\\d*)?', /* width (optional) */ '(\\.([1-9]\\d*))?', /* precision (optional) */ '[lhjztL]*?', /* length mods (ignored) */ '([diouxXfFeEgGaAcCsSp%jr])' /* conversion */ ].join(''); var re = new RegExp(regex); var args = Array.prototype.slice.call(arguments, 1); var flags, width, precision, conversion; var left, pad, sign, arg, match; var ret = ''; var argn = 1; mod_assert.equal('string', typeof (fmt)); while ((match = re.exec(fmt)) !== null) { ret += match[1]; fmt = fmt.substring(match[0].length); flags = match[2] || ''; width = match[3] || 0; precision = match[4] || ''; conversion = match[6]; left = false; sign = false; pad = ' '; if (conversion == '%') { ret += '%'; continue; } if (args.length === 0) throw (new Error('too few args to sprintf')); arg = args.shift(); argn++; if (flags.match(/[\' #]/)) throw (new Error( 'unsupported flags: ' + flags)); if (precision.length > 0) throw (new Error( 'non-zero precision not supported')); if (flags.match(/-/)) left = true; if (flags.match(/0/)) pad = '0'; if (flags.match(/\+/)) sign = true; switch (conversion) { case 's': if (arg === undefined || arg === null) throw (new Error('argument ' + argn + ': attempted to print undefined or null ' + 'as a string')); ret += doPad(pad, width, left, arg.toString()); break; case 'd': arg = Math.floor(arg); /*jsl:fallthru*/ case 'f': sign = sign && arg > 0 ? '+' : ''; ret += sign + doPad(pad, width, left, arg.toString()); break; case 'x': ret += doPad(pad, width, left, arg.toString(16)); break; case 'j': /* non-standard */ if (width === 0) width = 10; ret += mod_util.inspect(arg, false, width); break; case 'r': /* non-standard */ ret += dumpException(arg); break; default: throw (new Error('unsupported conversion: ' + conversion)); } } ret += fmt; return (ret); } function jsPrintf() { var args = Array.prototype.slice.call(arguments); args.unshift(process.stdout); jsFprintf.apply(null, args); } function jsFprintf(stream) { var args = Array.prototype.slice.call(arguments, 1); return (stream.write(jsSprintf.apply(this, args))); } function doPad(chr, width, left, str) { var ret = str; while (ret.length < width) { if (left) ret += chr; else ret = chr + ret; } return (ret); } /* * This function dumps long stack traces for exceptions having a cause() method. * See node-verror for an example. */ function dumpException(ex) { var ret; if (!(ex instanceof Error)) throw (new Error(jsSprintf('invalid type for %%r: %j', ex))); /* Note that V8 prepends "ex.stack" with ex.toString(). */ ret = 'EXCEPTION: ' + ex.constructor.name + ': ' + ex.stack; if (ex.cause && typeof (ex.cause) === 'function') { var cex = ex.cause(); if (cex) { ret += '\nCaused by: ' + dumpException(cex); } } return (ret); } /***/ }), /***/ 28206: /***/ ((module) => { "use strict"; // do not edit .js files directly - edit src/index.jst module.exports = function equal(a, b) { if (a === b) return true; if (a && b && typeof a == 'object' && typeof b == 'object') { if (a.constructor !== b.constructor) return false; var length, i, keys; if (Array.isArray(a)) { length = a.length; if (length != b.length) return false; for (i = length; i-- !== 0;) if (!equal(a[i], b[i])) return false; return true; } if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); keys = Object.keys(a); length = keys.length; if (length !== Object.keys(b).length) return false; for (i = length; i-- !== 0;) if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; for (i = length; i-- !== 0;) { var key = keys[i]; if (!equal(a[key], b[key])) return false; } return true; } // true if both NaN, false otherwise return a!==a && b!==b; }; /***/ }), /***/ 30969: /***/ ((module) => { "use strict"; module.exports = function (data, opts) { if (!opts) opts = {}; if (typeof opts === 'function') opts = { cmp: opts }; var cycles = (typeof opts.cycles === 'boolean') ? opts.cycles : false; var cmp = opts.cmp && (function (f) { return function (node) { return function (a, b) { var aobj = { key: a, value: node[a] }; var bobj = { key: b, value: node[b] }; return f(aobj, bobj); }; }; })(opts.cmp); var seen = []; return (function stringify (node) { if (node && node.toJSON && typeof node.toJSON === 'function') { node = node.toJSON(); } if (node === undefined) return; if (typeof node == 'number') return isFinite(node) ? '' + node : 'null'; if (typeof node !== 'object') return JSON.stringify(node); var i, out; if (Array.isArray(node)) { out = '['; for (i = 0; i < node.length; i++) { if (i) out += ','; out += stringify(node[i]) || 'null'; } return out + ']'; } if (node === null) return 'null'; if (seen.indexOf(node) !== -1) { if (cycles) return JSON.stringify('__cycle__'); throw new TypeError('Converting circular structure to JSON'); } var seenIndex = seen.push(node) - 1; var keys = Object.keys(node).sort(cmp && cmp(node)); out = ''; for (i = 0; i < keys.length; i++) { var key = keys[i]; var value = stringify(node[key]); if (!value) continue; if (out) out += ','; out += JSON.stringify(key) + ':' + value; } seen.splice(seenIndex, 1); return '{' + out + '}'; })(data); }; /***/ }), /***/ 12603: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const validator = __nccwpck_require__(61739); const XMLParser = __nccwpck_require__(42380); const XMLBuilder = __nccwpck_require__(80660); module.exports = { XMLParser: XMLParser, XMLValidator: validator, XMLBuilder: XMLBuilder } /***/ }), /***/ 38280: /***/ ((__unused_webpack_module, exports) => { "use strict"; const nameStartChar = ':A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD'; const nameChar = nameStartChar + '\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040'; const nameRegexp = '[' + nameStartChar + '][' + nameChar + ']*' const regexName = new RegExp('^' + nameRegexp + '$'); const getAllMatches = function(string, regex) { const matches = []; let match = regex.exec(string); while (match) { const allmatches = []; allmatches.startIndex = regex.lastIndex - match[0].length; const len = match.length; for (let index = 0; index < len; index++) { allmatches.push(match[index]); } matches.push(allmatches); match = regex.exec(string); } return matches; }; const isName = function(string) { const match = regexName.exec(string); return !(match === null || typeof match === 'undefined'); }; exports.isExist = function(v) { return typeof v !== 'undefined'; }; exports.isEmptyObject = function(obj) { return Object.keys(obj).length === 0; }; /** * Copy all the properties of a into b. * @param {*} target * @param {*} a */ exports.merge = function(target, a, arrayMode) { if (a) { const keys = Object.keys(a); // will return an array of own properties const len = keys.length; //don't make it inline for (let i = 0; i < len; i++) { if (arrayMode === 'strict') { target[keys[i]] = [ a[keys[i]] ]; } else { target[keys[i]] = a[keys[i]]; } } } }; /* exports.merge =function (b,a){ return Object.assign(b,a); } */ exports.getValue = function(v) { if (exports.isExist(v)) { return v; } else { return ''; } }; // const fakeCall = function(a) {return a;}; // const fakeCallNoReturn = function() {}; exports.isName = isName; exports.getAllMatches = getAllMatches; exports.nameRegexp = nameRegexp; /***/ }), /***/ 61739: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; const util = __nccwpck_require__(38280); const defaultOptions = { allowBooleanAttributes: false, //A tag can have attributes without any value unpairedTags: [] }; //const tagsPattern = new RegExp("<\\/?([\\w:\\-_\.]+)\\s*\/?>","g"); exports.validate = function (xmlData, options) { options = Object.assign({}, defaultOptions, options); //xmlData = xmlData.replace(/(\r\n|\n|\r)/gm,"");//make it single line //xmlData = xmlData.replace(/(^\s*<\?xml.*?\?>)/g,"");//Remove XML starting tag //xmlData = xmlData.replace(/()/g,"");//Remove DOCTYPE const tags = []; let tagFound = false; //indicates that the root tag has been closed (aka. depth 0 has been reached) let reachedRoot = false; if (xmlData[0] === '\ufeff') { // check for byte order mark (BOM) xmlData = xmlData.substr(1); } for (let i = 0; i < xmlData.length; i++) { if (xmlData[i] === '<' && xmlData[i+1] === '?') { i+=2; i = readPI(xmlData,i); if (i.err) return i; }else if (xmlData[i] === '<') { //starting of tag //read until you reach to '>' avoiding any '>' in attribute value let tagStartPos = i; i++; if (xmlData[i] === '!') { i = readCommentAndCDATA(xmlData, i); continue; } else { let closingTag = false; if (xmlData[i] === '/') { //closing tag closingTag = true; i++; } //read tagname let tagName = ''; for (; i < xmlData.length && xmlData[i] !== '>' && xmlData[i] !== ' ' && xmlData[i] !== '\t' && xmlData[i] !== '\n' && xmlData[i] !== '\r'; i++ ) { tagName += xmlData[i]; } tagName = tagName.trim(); //console.log(tagName); if (tagName[tagName.length - 1] === '/') { //self closing tag without attributes tagName = tagName.substring(0, tagName.length - 1); //continue; i--; } if (!validateTagName(tagName)) { let msg; if (tagName.trim().length === 0) { msg = "Invalid space after '<'."; } else { msg = "Tag '"+tagName+"' is an invalid name."; } return getErrorObject('InvalidTag', msg, getLineNumberForPosition(xmlData, i)); } const result = readAttributeStr(xmlData, i); if (result === false) { return getErrorObject('InvalidAttr', "Attributes for '"+tagName+"' have open quote.", getLineNumberForPosition(xmlData, i)); } let attrStr = result.value; i = result.index; if (attrStr[attrStr.length - 1] === '/') { //self closing tag const attrStrStart = i - attrStr.length; attrStr = attrStr.substring(0, attrStr.length - 1); const isValid = validateAttributeString(attrStr, options); if (isValid === true) { tagFound = true; //continue; //text may presents after self closing tag } else { //the result from the nested function returns the position of the error within the attribute //in order to get the 'true' error line, we need to calculate the position where the attribute begins (i - attrStr.length) and then add the position within the attribute //this gives us the absolute index in the entire xml, which we can use to find the line at last return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, attrStrStart + isValid.err.line)); } } else if (closingTag) { if (!result.tagClosed) { return getErrorObject('InvalidTag', "Closing tag '"+tagName+"' doesn't have proper closing.", getLineNumberForPosition(xmlData, i)); } else if (attrStr.trim().length > 0) { return getErrorObject('InvalidTag', "Closing tag '"+tagName+"' can't have attributes or invalid starting.", getLineNumberForPosition(xmlData, tagStartPos)); } else if (tags.length === 0) { return getErrorObject('InvalidTag', "Closing tag '"+tagName+"' has not been opened.", getLineNumberForPosition(xmlData, tagStartPos)); } else { const otg = tags.pop(); if (tagName !== otg.tagName) { let openPos = getLineNumberForPosition(xmlData, otg.tagStartPos); return getErrorObject('InvalidTag', "Expected closing tag '"+otg.tagName+"' (opened in line "+openPos.line+", col "+openPos.col+") instead of closing tag '"+tagName+"'.", getLineNumberForPosition(xmlData, tagStartPos)); } //when there are no more tags, we reached the root level. if (tags.length == 0) { reachedRoot = true; } } } else { const isValid = validateAttributeString(attrStr, options); if (isValid !== true) { //the result from the nested function returns the position of the error within the attribute //in order to get the 'true' error line, we need to calculate the position where the attribute begins (i - attrStr.length) and then add the position within the attribute //this gives us the absolute index in the entire xml, which we can use to find the line at last return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, i - attrStr.length + isValid.err.line)); } //if the root level has been reached before ... if (reachedRoot === true) { return getErrorObject('InvalidXml', 'Multiple possible root nodes found.', getLineNumberForPosition(xmlData, i)); } else if(options.unpairedTags.indexOf(tagName) !== -1){ //don't push into stack } else { tags.push({tagName, tagStartPos}); } tagFound = true; } //skip tag text value //It may include comments and CDATA value for (i++; i < xmlData.length; i++) { if (xmlData[i] === '<') { if (xmlData[i + 1] === '!') { //comment or CADATA i++; i = readCommentAndCDATA(xmlData, i); continue; } else if (xmlData[i+1] === '?') { i = readPI(xmlData, ++i); if (i.err) return i; } else{ break; } } else if (xmlData[i] === '&') { const afterAmp = validateAmpersand(xmlData, i); if (afterAmp == -1) return getErrorObject('InvalidChar', "char '&' is not expected.", getLineNumberForPosition(xmlData, i)); i = afterAmp; }else{ if (reachedRoot === true && !isWhiteSpace(xmlData[i])) { return getErrorObject('InvalidXml', "Extra text at the end", getLineNumberForPosition(xmlData, i)); } } } //end of reading tag text value if (xmlData[i] === '<') { i--; } } } else { if ( isWhiteSpace(xmlData[i])) { continue; } return getErrorObject('InvalidChar', "char '"+xmlData[i]+"' is not expected.", getLineNumberForPosition(xmlData, i)); } } if (!tagFound) { return getErrorObject('InvalidXml', 'Start tag expected.', 1); }else if (tags.length == 1) { return getErrorObject('InvalidTag', "Unclosed tag '"+tags[0].tagName+"'.", getLineNumberForPosition(xmlData, tags[0].tagStartPos)); }else if (tags.length > 0) { return getErrorObject('InvalidXml', "Invalid '"+ JSON.stringify(tags.map(t => t.tagName), null, 4).replace(/\r?\n/g, '')+ "' found.", {line: 1, col: 1}); } return true; }; function isWhiteSpace(char){ return char === ' ' || char === '\t' || char === '\n' || char === '\r'; } /** * Read Processing insstructions and skip * @param {*} xmlData * @param {*} i */ function readPI(xmlData, i) { const start = i; for (; i < xmlData.length; i++) { if (xmlData[i] == '?' || xmlData[i] == ' ') { //tagname const tagname = xmlData.substr(start, i - start); if (i > 5 && tagname === 'xml') { return getErrorObject('InvalidXml', 'XML declaration allowed only at the start of the document.', getLineNumberForPosition(xmlData, i)); } else if (xmlData[i] == '?' && xmlData[i + 1] == '>') { //check if valid attribut string i++; break; } else { continue; } } } return i; } function readCommentAndCDATA(xmlData, i) { if (xmlData.length > i + 5 && xmlData[i + 1] === '-' && xmlData[i + 2] === '-') { //comment for (i += 3; i < xmlData.length; i++) { if (xmlData[i] === '-' && xmlData[i + 1] === '-' && xmlData[i + 2] === '>') { i += 2; break; } } } else if ( xmlData.length > i + 8 && xmlData[i + 1] === 'D' && xmlData[i + 2] === 'O' && xmlData[i + 3] === 'C' && xmlData[i + 4] === 'T' && xmlData[i + 5] === 'Y' && xmlData[i + 6] === 'P' && xmlData[i + 7] === 'E' ) { let angleBracketsCount = 1; for (i += 8; i < xmlData.length; i++) { if (xmlData[i] === '<') { angleBracketsCount++; } else if (xmlData[i] === '>') { angleBracketsCount--; if (angleBracketsCount === 0) { break; } } } } else if ( xmlData.length > i + 9 && xmlData[i + 1] === '[' && xmlData[i + 2] === 'C' && xmlData[i + 3] === 'D' && xmlData[i + 4] === 'A' && xmlData[i + 5] === 'T' && xmlData[i + 6] === 'A' && xmlData[i + 7] === '[' ) { for (i += 8; i < xmlData.length; i++) { if (xmlData[i] === ']' && xmlData[i + 1] === ']' && xmlData[i + 2] === '>') { i += 2; break; } } } return i; } const doubleQuote = '"'; const singleQuote = "'"; /** * Keep reading xmlData until '<' is found outside the attribute value. * @param {string} xmlData * @param {number} i */ function readAttributeStr(xmlData, i) { let attrStr = ''; let startChar = ''; let tagClosed = false; for (; i < xmlData.length; i++) { if (xmlData[i] === doubleQuote || xmlData[i] === singleQuote) { if (startChar === '') { startChar = xmlData[i]; } else if (startChar !== xmlData[i]) { //if vaue is enclosed with double quote then single quotes are allowed inside the value and vice versa } else { startChar = ''; } } else if (xmlData[i] === '>') { if (startChar === '') { tagClosed = true; break; } } attrStr += xmlData[i]; } if (startChar !== '') { return false; } return { value: attrStr, index: i, tagClosed: tagClosed }; } /** * Select all the attributes whether valid or invalid. */ const validAttrStrRegxp = new RegExp('(\\s*)([^\\s=]+)(\\s*=)?(\\s*([\'"])(([\\s\\S])*?)\\5)?', 'g'); //attr, ="sd", a="amit's", a="sd"b="saf", ab cd="" function validateAttributeString(attrStr, options) { //console.log("start:"+attrStr+":end"); //if(attrStr.trim().length === 0) return true; //empty string const matches = util.getAllMatches(attrStr, validAttrStrRegxp); const attrNames = {}; for (let i = 0; i < matches.length; i++) { if (matches[i][1].length === 0) { //nospace before attribute name: a="sd"b="saf" return getErrorObject('InvalidAttr', "Attribute '"+matches[i][2]+"' has no space in starting.", getPositionFromMatch(matches[i])) } else if (matches[i][3] !== undefined && matches[i][4] === undefined) { return getErrorObject('InvalidAttr', "Attribute '"+matches[i][2]+"' is without value.", getPositionFromMatch(matches[i])); } else if (matches[i][3] === undefined && !options.allowBooleanAttributes) { //independent attribute: ab return getErrorObject('InvalidAttr', "boolean attribute '"+matches[i][2]+"' is not allowed.", getPositionFromMatch(matches[i])); } /* else if(matches[i][6] === undefined){//attribute without value: ab= return { err: { code:"InvalidAttr",msg:"attribute " + matches[i][2] + " has no value assigned."}}; } */ const attrName = matches[i][2]; if (!validateAttrName(attrName)) { return getErrorObject('InvalidAttr', "Attribute '"+attrName+"' is an invalid name.", getPositionFromMatch(matches[i])); } if (!attrNames.hasOwnProperty(attrName)) { //check for duplicate attribute. attrNames[attrName] = 1; } else { return getErrorObject('InvalidAttr', "Attribute '"+attrName+"' is repeated.", getPositionFromMatch(matches[i])); } } return true; } function validateNumberAmpersand(xmlData, i) { let re = /\d/; if (xmlData[i] === 'x') { i++; re = /[\da-fA-F]/; } for (; i < xmlData.length; i++) { if (xmlData[i] === ';') return i; if (!xmlData[i].match(re)) break; } return -1; } function validateAmpersand(xmlData, i) { // https://www.w3.org/TR/xml/#dt-charref i++; if (xmlData[i] === ';') return -1; if (xmlData[i] === '#') { i++; return validateNumberAmpersand(xmlData, i); } let count = 0; for (; i < xmlData.length; i++, count++) { if (xmlData[i].match(/\w/) && count < 20) continue; if (xmlData[i] === ';') break; return -1; } return i; } function getErrorObject(code, message, lineNumber) { return { err: { code: code, msg: message, line: lineNumber.line || lineNumber, col: lineNumber.col, }, }; } function validateAttrName(attrName) { return util.isName(attrName); } // const startsWithXML = /^xml/i; function validateTagName(tagname) { return util.isName(tagname) /* && !tagname.match(startsWithXML) */; } //this function returns the line number for the character at the given index function getLineNumberForPosition(xmlData, index) { const lines = xmlData.substring(0, index).split(/\r?\n/); return { line: lines.length, // column number is last line's length + 1, because column numbering starts at 1: col: lines[lines.length - 1].length + 1 }; } //this function returns the position of the first character of match within attrStr function getPositionFromMatch(match) { return match.startIndex + match[1].length; } /***/ }), /***/ 80660: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; //parse Empty Node as self closing node const buildFromOrderedJs = __nccwpck_require__(72462); const defaultOptions = { attributeNamePrefix: '@_', attributesGroupName: false, textNodeName: '#text', ignoreAttributes: true, cdataPropName: false, format: false, indentBy: ' ', suppressEmptyNode: false, suppressUnpairedNode: true, suppressBooleanAttributes: true, tagValueProcessor: function(key, a) { return a; }, attributeValueProcessor: function(attrName, a) { return a; }, preserveOrder: false, commentPropName: false, unpairedTags: [], entities: [ { regex: new RegExp("&", "g"), val: "&" },//it must be on top { regex: new RegExp(">", "g"), val: ">" }, { regex: new RegExp("<", "g"), val: "<" }, { regex: new RegExp("\'", "g"), val: "'" }, { regex: new RegExp("\"", "g"), val: """ } ], processEntities: true, stopNodes: [], // transformTagName: false, // transformAttributeName: false, oneListGroup: false }; function Builder(options) { this.options = Object.assign({}, defaultOptions, options); if (this.options.ignoreAttributes || this.options.attributesGroupName) { this.isAttribute = function(/*a*/) { return false; }; } else { this.attrPrefixLen = this.options.attributeNamePrefix.length; this.isAttribute = isAttribute; } this.processTextOrObjNode = processTextOrObjNode if (this.options.format) { this.indentate = indentate; this.tagEndChar = '>\n'; this.newLine = '\n'; } else { this.indentate = function() { return ''; }; this.tagEndChar = '>'; this.newLine = ''; } } Builder.prototype.build = function(jObj) { if(this.options.preserveOrder){ return buildFromOrderedJs(jObj, this.options); }else { if(Array.isArray(jObj) && this.options.arrayNodeName && this.options.arrayNodeName.length > 1){ jObj = { [this.options.arrayNodeName] : jObj } } return this.j2x(jObj, 0).val; } }; Builder.prototype.j2x = function(jObj, level) { let attrStr = ''; let val = ''; for (let key in jObj) { if(!Object.prototype.hasOwnProperty.call(jObj, key)) continue; if (typeof jObj[key] === 'undefined') { // supress undefined node only if it is not an attribute if (this.isAttribute(key)) { val += ''; } } else if (jObj[key] === null) { // null attribute should be ignored by the attribute list, but should not cause the tag closing if (this.isAttribute(key)) { val += ''; } else if (key[0] === '?') { val += this.indentate(level) + '<' + key + '?' + this.tagEndChar; } else { val += this.indentate(level) + '<' + key + '/' + this.tagEndChar; } // val += this.indentate(level) + '<' + key + '/' + this.tagEndChar; } else if (jObj[key] instanceof Date) { val += this.buildTextValNode(jObj[key], key, '', level); } else if (typeof jObj[key] !== 'object') { //premitive type const attr = this.isAttribute(key); if (attr) { attrStr += this.buildAttrPairStr(attr, '' + jObj[key]); }else { //tag value if (key === this.options.textNodeName) { let newval = this.options.tagValueProcessor(key, '' + jObj[key]); val += this.replaceEntitiesValue(newval); } else { val += this.buildTextValNode(jObj[key], key, '', level); } } } else if (Array.isArray(jObj[key])) { //repeated nodes const arrLen = jObj[key].length; let listTagVal = ""; let listTagAttr = ""; for (let j = 0; j < arrLen; j++) { const item = jObj[key][j]; if (typeof item === 'undefined') { // supress undefined node } else if (item === null) { if(key[0] === "?") val += this.indentate(level) + '<' + key + '?' + this.tagEndChar; else val += this.indentate(level) + '<' + key + '/' + this.tagEndChar; // val += this.indentate(level) + '<' + key + '/' + this.tagEndChar; } else if (typeof item === 'object') { if(this.options.oneListGroup){ const result = this.j2x(item, level + 1); listTagVal += result.val; if (this.options.attributesGroupName && item.hasOwnProperty(this.options.attributesGroupName)) { listTagAttr += result.attrStr } }else{ listTagVal += this.processTextOrObjNode(item, key, level) } } else { if (this.options.oneListGroup) { let textValue = this.options.tagValueProcessor(key, item); textValue = this.replaceEntitiesValue(textValue); listTagVal += textValue; } else { listTagVal += this.buildTextValNode(item, key, '', level); } } } if(this.options.oneListGroup){ listTagVal = this.buildObjectNode(listTagVal, key, listTagAttr, level); } val += listTagVal; } else { //nested node if (this.options.attributesGroupName && key === this.options.attributesGroupName) { const Ks = Object.keys(jObj[key]); const L = Ks.length; for (let j = 0; j < L; j++) { attrStr += this.buildAttrPairStr(Ks[j], '' + jObj[key][Ks[j]]); } } else { val += this.processTextOrObjNode(jObj[key], key, level) } } } return {attrStr: attrStr, val: val}; }; Builder.prototype.buildAttrPairStr = function(attrName, val){ val = this.options.attributeValueProcessor(attrName, '' + val); val = this.replaceEntitiesValue(val); if (this.options.suppressBooleanAttributes && val === "true") { return ' ' + attrName; } else return ' ' + attrName + '="' + val + '"'; } function processTextOrObjNode (object, key, level) { const result = this.j2x(object, level + 1); if (object[this.options.textNodeName] !== undefined && Object.keys(object).length === 1) { return this.buildTextValNode(object[this.options.textNodeName], key, result.attrStr, level); } else { return this.buildObjectNode(result.val, key, result.attrStr, level); } } Builder.prototype.buildObjectNode = function(val, key, attrStr, level) { if(val === ""){ if(key[0] === "?") return this.indentate(level) + '<' + key + attrStr+ '?' + this.tagEndChar; else { return this.indentate(level) + '<' + key + attrStr + this.closeTag(key) + this.tagEndChar; } }else{ let tagEndExp = '' + val + tagEndExp ); } else if (this.options.commentPropName !== false && key === this.options.commentPropName && piClosingChar.length === 0) { return this.indentate(level) + `` + this.newLine; }else { return ( this.indentate(level) + '<' + key + attrStr + piClosingChar + this.tagEndChar + val + this.indentate(level) + tagEndExp ); } } } Builder.prototype.closeTag = function(key){ let closeTag = ""; if(this.options.unpairedTags.indexOf(key) !== -1){ //unpaired if(!this.options.suppressUnpairedNode) closeTag = "/" }else if(this.options.suppressEmptyNode){ //empty closeTag = "/"; }else{ closeTag = `>` + this.newLine; }else if (this.options.commentPropName !== false && key === this.options.commentPropName) { return this.indentate(level) + `` + this.newLine; }else if(key[0] === "?") {//PI tag return this.indentate(level) + '<' + key + attrStr+ '?' + this.tagEndChar; }else{ let textValue = this.options.tagValueProcessor(key, val); textValue = this.replaceEntitiesValue(textValue); if( textValue === ''){ return this.indentate(level) + '<' + key + attrStr + this.closeTag(key) + this.tagEndChar; }else{ return this.indentate(level) + '<' + key + attrStr + '>' + textValue + ' 0 && this.options.processEntities){ for (let i=0; i { const EOL = "\n"; /** * * @param {array} jArray * @param {any} options * @returns */ function toXml(jArray, options) { let indentation = ""; if (options.format && options.indentBy.length > 0) { indentation = EOL; } return arrToStr(jArray, options, "", indentation); } function arrToStr(arr, options, jPath, indentation) { let xmlStr = ""; let isPreviousElementTag = false; for (let i = 0; i < arr.length; i++) { const tagObj = arr[i]; const tagName = propName(tagObj); if(tagName === undefined) continue; let newJPath = ""; if (jPath.length === 0) newJPath = tagName else newJPath = `${jPath}.${tagName}`; if (tagName === options.textNodeName) { let tagText = tagObj[tagName]; if (!isStopNode(newJPath, options)) { tagText = options.tagValueProcessor(tagName, tagText); tagText = replaceEntitiesValue(tagText, options); } if (isPreviousElementTag) { xmlStr += indentation; } xmlStr += tagText; isPreviousElementTag = false; continue; } else if (tagName === options.cdataPropName) { if (isPreviousElementTag) { xmlStr += indentation; } xmlStr += ``; isPreviousElementTag = false; continue; } else if (tagName === options.commentPropName) { xmlStr += indentation + ``; isPreviousElementTag = true; continue; } else if (tagName[0] === "?") { const attStr = attr_to_str(tagObj[":@"], options); const tempInd = tagName === "?xml" ? "" : indentation; let piTextNodeName = tagObj[tagName][0][options.textNodeName]; piTextNodeName = piTextNodeName.length !== 0 ? " " + piTextNodeName : ""; //remove extra spacing xmlStr += tempInd + `<${tagName}${piTextNodeName}${attStr}?>`; isPreviousElementTag = true; continue; } let newIdentation = indentation; if (newIdentation !== "") { newIdentation += options.indentBy; } const attStr = attr_to_str(tagObj[":@"], options); const tagStart = indentation + `<${tagName}${attStr}`; const tagValue = arrToStr(tagObj[tagName], options, newJPath, newIdentation); if (options.unpairedTags.indexOf(tagName) !== -1) { if (options.suppressUnpairedNode) xmlStr += tagStart + ">"; else xmlStr += tagStart + "/>"; } else if ((!tagValue || tagValue.length === 0) && options.suppressEmptyNode) { xmlStr += tagStart + "/>"; } else if (tagValue && tagValue.endsWith(">")) { xmlStr += tagStart + `>${tagValue}${indentation}`; } else { xmlStr += tagStart + ">"; if (tagValue && indentation !== "" && (tagValue.includes("/>") || tagValue.includes("`; } isPreviousElementTag = true; } return xmlStr; } function propName(obj) { const keys = Object.keys(obj); for (let i = 0; i < keys.length; i++) { const key = keys[i]; if(!obj.hasOwnProperty(key)) continue; if (key !== ":@") return key; } } function attr_to_str(attrMap, options) { let attrStr = ""; if (attrMap && !options.ignoreAttributes) { for (let attr in attrMap) { if(!attrMap.hasOwnProperty(attr)) continue; let attrVal = options.attributeValueProcessor(attr, attrMap[attr]); attrVal = replaceEntitiesValue(attrVal, options); if (attrVal === true && options.suppressBooleanAttributes) { attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}`; } else { attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}="${attrVal}"`; } } } return attrStr; } function isStopNode(jPath, options) { jPath = jPath.substr(0, jPath.length - options.textNodeName.length - 1); let tagName = jPath.substr(jPath.lastIndexOf(".") + 1); for (let index in options.stopNodes) { if (options.stopNodes[index] === jPath || options.stopNodes[index] === "*." + tagName) return true; } return false; } function replaceEntitiesValue(textValue, options) { if (textValue && textValue.length > 0 && options.processEntities) { for (let i = 0; i < options.entities.length; i++) { const entity = options.entities[i]; textValue = textValue.replace(entity.regex, entity.val); } } return textValue; } module.exports = toXml; /***/ }), /***/ 6072: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const util = __nccwpck_require__(38280); //TODO: handle comments function readDocType(xmlData, i){ const entities = {}; if( xmlData[i + 3] === 'O' && xmlData[i + 4] === 'C' && xmlData[i + 5] === 'T' && xmlData[i + 6] === 'Y' && xmlData[i + 7] === 'P' && xmlData[i + 8] === 'E') { i = i+9; let angleBracketsCount = 1; let hasBody = false, comment = false; let exp = ""; for(;i') { //Read tag content if(comment){ if( xmlData[i - 1] === "-" && xmlData[i - 2] === "-"){ comment = false; angleBracketsCount--; } }else{ angleBracketsCount--; } if (angleBracketsCount === 0) { break; } }else if( xmlData[i] === '['){ hasBody = true; }else{ exp += xmlData[i]; } } if(angleBracketsCount !== 0){ throw new Error(`Unclosed DOCTYPE`); } }else{ throw new Error(`Invalid Tag instead of DOCTYPE`); } return {entities, i}; } function readEntityExp(xmlData,i){ //External entities are not supported // //Parameter entities are not supported // //Internal entities are supported // //read EntityName let entityName = ""; for (; i < xmlData.length && (xmlData[i] !== "'" && xmlData[i] !== '"' ); i++) { // if(xmlData[i] === " ") continue; // else entityName += xmlData[i]; } entityName = entityName.trim(); if(entityName.indexOf(" ") !== -1) throw new Error("External entites are not supported"); //read Entity Value const startChar = xmlData[i++]; let val = "" for (; i < xmlData.length && xmlData[i] !== startChar ; i++) { val += xmlData[i]; } return [entityName, val, i]; } function isComment(xmlData, i){ if(xmlData[i+1] === '!' && xmlData[i+2] === '-' && xmlData[i+3] === '-') return true return false } function isEntity(xmlData, i){ if(xmlData[i+1] === '!' && xmlData[i+2] === 'E' && xmlData[i+3] === 'N' && xmlData[i+4] === 'T' && xmlData[i+5] === 'I' && xmlData[i+6] === 'T' && xmlData[i+7] === 'Y') return true return false } function isElement(xmlData, i){ if(xmlData[i+1] === '!' && xmlData[i+2] === 'E' && xmlData[i+3] === 'L' && xmlData[i+4] === 'E' && xmlData[i+5] === 'M' && xmlData[i+6] === 'E' && xmlData[i+7] === 'N' && xmlData[i+8] === 'T') return true return false } function isAttlist(xmlData, i){ if(xmlData[i+1] === '!' && xmlData[i+2] === 'A' && xmlData[i+3] === 'T' && xmlData[i+4] === 'T' && xmlData[i+5] === 'L' && xmlData[i+6] === 'I' && xmlData[i+7] === 'S' && xmlData[i+8] === 'T') return true return false } function isNotation(xmlData, i){ if(xmlData[i+1] === '!' && xmlData[i+2] === 'N' && xmlData[i+3] === 'O' && xmlData[i+4] === 'T' && xmlData[i+5] === 'A' && xmlData[i+6] === 'T' && xmlData[i+7] === 'I' && xmlData[i+8] === 'O' && xmlData[i+9] === 'N') return true return false } function validateEntityName(name){ if (util.isName(name)) return name; else throw new Error(`Invalid entity name ${name}`); } module.exports = readDocType; /***/ }), /***/ 86993: /***/ ((__unused_webpack_module, exports) => { const defaultOptions = { preserveOrder: false, attributeNamePrefix: '@_', attributesGroupName: false, textNodeName: '#text', ignoreAttributes: true, removeNSPrefix: false, // remove NS from tag name or attribute name if true allowBooleanAttributes: false, //a tag can have attributes without any value //ignoreRootElement : false, parseTagValue: true, parseAttributeValue: false, trimValues: true, //Trim string values of tag and attributes cdataPropName: false, numberParseOptions: { hex: true, leadingZeros: true, eNotation: true }, tagValueProcessor: function(tagName, val) { return val; }, attributeValueProcessor: function(attrName, val) { return val; }, stopNodes: [], //nested tags will not be parsed even for errors alwaysCreateTextNode: false, isArray: () => false, commentPropName: false, unpairedTags: [], processEntities: true, htmlEntities: false, ignoreDeclaration: false, ignorePiTags: false, transformTagName: false, transformAttributeName: false, updateTag: function(tagName, jPath, attrs){ return tagName }, // skipEmptyListItem: false }; const buildOptions = function(options) { return Object.assign({}, defaultOptions, options); }; exports.buildOptions = buildOptions; exports.defaultOptions = defaultOptions; /***/ }), /***/ 25832: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; ///@ts-check const util = __nccwpck_require__(38280); const xmlNode = __nccwpck_require__(7462); const readDocType = __nccwpck_require__(6072); const toNumber = __nccwpck_require__(14526); // const regx = // '<((!\\[CDATA\\[([\\s\\S]*?)(]]>))|((NAME:)?(NAME))([^>]*)>|((\\/)(NAME)\\s*>))([^<]*)' // .replace(/NAME/g, util.nameRegexp); //const tagsRegx = new RegExp("<(\\/?[\\w:\\-\._]+)([^>]*)>(\\s*"+cdataRegx+")*([^<]+)?","g"); //const tagsRegx = new RegExp("<(\\/?)((\\w*:)?([\\w:\\-\._]+))([^>]*)>([^<]*)("+cdataRegx+"([^<]*))*([^<]+)?","g"); class OrderedObjParser{ constructor(options){ this.options = options; this.currentNode = null; this.tagsNodeStack = []; this.docTypeEntities = {}; this.lastEntities = { "apos" : { regex: /&(apos|#39|#x27);/g, val : "'"}, "gt" : { regex: /&(gt|#62|#x3E);/g, val : ">"}, "lt" : { regex: /&(lt|#60|#x3C);/g, val : "<"}, "quot" : { regex: /&(quot|#34|#x22);/g, val : "\""}, }; this.ampEntity = { regex: /&(amp|#38|#x26);/g, val : "&"}; this.htmlEntities = { "space": { regex: /&(nbsp|#160);/g, val: " " }, // "lt" : { regex: /&(lt|#60);/g, val: "<" }, // "gt" : { regex: /&(gt|#62);/g, val: ">" }, // "amp" : { regex: /&(amp|#38);/g, val: "&" }, // "quot" : { regex: /&(quot|#34);/g, val: "\"" }, // "apos" : { regex: /&(apos|#39);/g, val: "'" }, "cent" : { regex: /&(cent|#162);/g, val: "¢" }, "pound" : { regex: /&(pound|#163);/g, val: "£" }, "yen" : { regex: /&(yen|#165);/g, val: "¥" }, "euro" : { regex: /&(euro|#8364);/g, val: "€" }, "copyright" : { regex: /&(copy|#169);/g, val: "©" }, "reg" : { regex: /&(reg|#174);/g, val: "®" }, "inr" : { regex: /&(inr|#8377);/g, val: "₹" }, "num_dec": { regex: /&#([0-9]{1,7});/g, val : (_, str) => String.fromCharCode(Number.parseInt(str, 10)) }, "num_hex": { regex: /&#x([0-9a-fA-F]{1,6});/g, val : (_, str) => String.fromCharCode(Number.parseInt(str, 16)) }, }; this.addExternalEntities = addExternalEntities; this.parseXml = parseXml; this.parseTextData = parseTextData; this.resolveNameSpace = resolveNameSpace; this.buildAttributesMap = buildAttributesMap; this.isItStopNode = isItStopNode; this.replaceEntitiesValue = replaceEntitiesValue; this.readStopNodeData = readStopNodeData; this.saveTextToParentTag = saveTextToParentTag; this.addChild = addChild; } } function addExternalEntities(externalEntities){ const entKeys = Object.keys(externalEntities); for (let i = 0; i < entKeys.length; i++) { const ent = entKeys[i]; this.lastEntities[ent] = { regex: new RegExp("&"+ent+";","g"), val : externalEntities[ent] } } } /** * @param {string} val * @param {string} tagName * @param {string} jPath * @param {boolean} dontTrim * @param {boolean} hasAttributes * @param {boolean} isLeafNode * @param {boolean} escapeEntities */ function parseTextData(val, tagName, jPath, dontTrim, hasAttributes, isLeafNode, escapeEntities) { if (val !== undefined) { if (this.options.trimValues && !dontTrim) { val = val.trim(); } if(val.length > 0){ if(!escapeEntities) val = this.replaceEntitiesValue(val); const newval = this.options.tagValueProcessor(tagName, val, jPath, hasAttributes, isLeafNode); if(newval === null || newval === undefined){ //don't parse return val; }else if(typeof newval !== typeof val || newval !== val){ //overwrite return newval; }else if(this.options.trimValues){ return parseValue(val, this.options.parseTagValue, this.options.numberParseOptions); }else{ const trimmedVal = val.trim(); if(trimmedVal === val){ return parseValue(val, this.options.parseTagValue, this.options.numberParseOptions); }else{ return val; } } } } } function resolveNameSpace(tagname) { if (this.options.removeNSPrefix) { const tags = tagname.split(':'); const prefix = tagname.charAt(0) === '/' ? '/' : ''; if (tags[0] === 'xmlns') { return ''; } if (tags.length === 2) { tagname = prefix + tags[1]; } } return tagname; } //TODO: change regex to capture NS //const attrsRegx = new RegExp("([\\w\\-\\.\\:]+)\\s*=\\s*(['\"])((.|\n)*?)\\2","gm"); const attrsRegx = new RegExp('([^\\s=]+)\\s*(=\\s*([\'"])([\\s\\S]*?)\\3)?', 'gm'); function buildAttributesMap(attrStr, jPath, tagName) { if (!this.options.ignoreAttributes && typeof attrStr === 'string') { // attrStr = attrStr.replace(/\r?\n/g, ' '); //attrStr = attrStr || attrStr.trim(); const matches = util.getAllMatches(attrStr, attrsRegx); const len = matches.length; //don't make it inline const attrs = {}; for (let i = 0; i < len; i++) { const attrName = this.resolveNameSpace(matches[i][1]); let oldVal = matches[i][4]; let aName = this.options.attributeNamePrefix + attrName; if (attrName.length) { if (this.options.transformAttributeName) { aName = this.options.transformAttributeName(aName); } if(aName === "__proto__") aName = "#__proto__"; if (oldVal !== undefined) { if (this.options.trimValues) { oldVal = oldVal.trim(); } oldVal = this.replaceEntitiesValue(oldVal); const newVal = this.options.attributeValueProcessor(attrName, oldVal, jPath); if(newVal === null || newVal === undefined){ //don't parse attrs[aName] = oldVal; }else if(typeof newVal !== typeof oldVal || newVal !== oldVal){ //overwrite attrs[aName] = newVal; }else{ //parse attrs[aName] = parseValue( oldVal, this.options.parseAttributeValue, this.options.numberParseOptions ); } } else if (this.options.allowBooleanAttributes) { attrs[aName] = true; } } } if (!Object.keys(attrs).length) { return; } if (this.options.attributesGroupName) { const attrCollection = {}; attrCollection[this.options.attributesGroupName] = attrs; return attrCollection; } return attrs } } const parseXml = function(xmlData) { xmlData = xmlData.replace(/\r\n?/g, "\n"); //TODO: remove this line const xmlObj = new xmlNode('!xml'); let currentNode = xmlObj; let textData = ""; let jPath = ""; for(let i=0; i< xmlData.length; i++){//for each char in XML data const ch = xmlData[i]; if(ch === '<'){ // const nextIndex = i+1; // const _2ndChar = xmlData[nextIndex]; if( xmlData[i+1] === '/') {//Closing Tag const closeIndex = findClosingIndex(xmlData, ">", i, "Closing Tag is not closed.") let tagName = xmlData.substring(i+2,closeIndex).trim(); if(this.options.removeNSPrefix){ const colonIndex = tagName.indexOf(":"); if(colonIndex !== -1){ tagName = tagName.substr(colonIndex+1); } } if(this.options.transformTagName) { tagName = this.options.transformTagName(tagName); } if(currentNode){ textData = this.saveTextToParentTag(textData, currentNode, jPath); } //check if last tag of nested tag was unpaired tag const lastTagName = jPath.substring(jPath.lastIndexOf(".")+1); if(tagName && this.options.unpairedTags.indexOf(tagName) !== -1 ){ throw new Error(`Unpaired tag can not be used as closing tag: `); } let propIndex = 0 if(lastTagName && this.options.unpairedTags.indexOf(lastTagName) !== -1 ){ propIndex = jPath.lastIndexOf('.', jPath.lastIndexOf('.')-1) this.tagsNodeStack.pop(); }else{ propIndex = jPath.lastIndexOf("."); } jPath = jPath.substring(0, propIndex); currentNode = this.tagsNodeStack.pop();//avoid recursion, set the parent tag scope textData = ""; i = closeIndex; } else if( xmlData[i+1] === '?') { let tagData = readTagExp(xmlData,i, false, "?>"); if(!tagData) throw new Error("Pi Tag is not closed."); textData = this.saveTextToParentTag(textData, currentNode, jPath); if( (this.options.ignoreDeclaration && tagData.tagName === "?xml") || this.options.ignorePiTags){ }else{ const childNode = new xmlNode(tagData.tagName); childNode.add(this.options.textNodeName, ""); if(tagData.tagName !== tagData.tagExp && tagData.attrExpPresent){ childNode[":@"] = this.buildAttributesMap(tagData.tagExp, jPath, tagData.tagName); } this.addChild(currentNode, childNode, jPath) } i = tagData.closeIndex + 1; } else if(xmlData.substr(i + 1, 3) === '!--') { const endIndex = findClosingIndex(xmlData, "-->", i+4, "Comment is not closed.") if(this.options.commentPropName){ const comment = xmlData.substring(i + 4, endIndex - 2); textData = this.saveTextToParentTag(textData, currentNode, jPath); currentNode.add(this.options.commentPropName, [ { [this.options.textNodeName] : comment } ]); } i = endIndex; } else if( xmlData.substr(i + 1, 2) === '!D') { const result = readDocType(xmlData, i); this.docTypeEntities = result.entities; i = result.i; }else if(xmlData.substr(i + 1, 2) === '![') { const closeIndex = findClosingIndex(xmlData, "]]>", i, "CDATA is not closed.") - 2; const tagExp = xmlData.substring(i + 9,closeIndex); textData = this.saveTextToParentTag(textData, currentNode, jPath); let val = this.parseTextData(tagExp, currentNode.tagname, jPath, true, false, true, true); if(val == undefined) val = ""; //cdata should be set even if it is 0 length string if(this.options.cdataPropName){ currentNode.add(this.options.cdataPropName, [ { [this.options.textNodeName] : tagExp } ]); }else{ currentNode.add(this.options.textNodeName, val); } i = closeIndex + 2; }else {//Opening tag let result = readTagExp(xmlData,i, this.options.removeNSPrefix); let tagName= result.tagName; const rawTagName = result.rawTagName; let tagExp = result.tagExp; let attrExpPresent = result.attrExpPresent; let closeIndex = result.closeIndex; if (this.options.transformTagName) { tagName = this.options.transformTagName(tagName); } //save text as child node if (currentNode && textData) { if(currentNode.tagname !== '!xml'){ //when nested tag is found textData = this.saveTextToParentTag(textData, currentNode, jPath, false); } } //check if last tag was unpaired tag const lastTag = currentNode; if(lastTag && this.options.unpairedTags.indexOf(lastTag.tagname) !== -1 ){ currentNode = this.tagsNodeStack.pop(); jPath = jPath.substring(0, jPath.lastIndexOf(".")); } if(tagName !== xmlObj.tagname){ jPath += jPath ? "." + tagName : tagName; } if (this.isItStopNode(this.options.stopNodes, jPath, tagName)) { let tagContent = ""; //self-closing tag if(tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1){ if(tagName[tagName.length - 1] === "/"){ //remove trailing '/' tagName = tagName.substr(0, tagName.length - 1); jPath = jPath.substr(0, jPath.length - 1); tagExp = tagName; }else{ tagExp = tagExp.substr(0, tagExp.length - 1); } i = result.closeIndex; } //unpaired tag else if(this.options.unpairedTags.indexOf(tagName) !== -1){ i = result.closeIndex; } //normal tag else{ //read until closing tag is found const result = this.readStopNodeData(xmlData, rawTagName, closeIndex + 1); if(!result) throw new Error(`Unexpected end of ${rawTagName}`); i = result.i; tagContent = result.tagContent; } const childNode = new xmlNode(tagName); if(tagName !== tagExp && attrExpPresent){ childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName); } if(tagContent) { tagContent = this.parseTextData(tagContent, tagName, jPath, true, attrExpPresent, true, true); } jPath = jPath.substr(0, jPath.lastIndexOf(".")); childNode.add(this.options.textNodeName, tagContent); this.addChild(currentNode, childNode, jPath) }else{ //selfClosing tag if(tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1){ if(tagName[tagName.length - 1] === "/"){ //remove trailing '/' tagName = tagName.substr(0, tagName.length - 1); jPath = jPath.substr(0, jPath.length - 1); tagExp = tagName; }else{ tagExp = tagExp.substr(0, tagExp.length - 1); } if(this.options.transformTagName) { tagName = this.options.transformTagName(tagName); } const childNode = new xmlNode(tagName); if(tagName !== tagExp && attrExpPresent){ childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName); } this.addChild(currentNode, childNode, jPath) jPath = jPath.substr(0, jPath.lastIndexOf(".")); } //opening tag else{ const childNode = new xmlNode( tagName); this.tagsNodeStack.push(currentNode); if(tagName !== tagExp && attrExpPresent){ childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName); } this.addChild(currentNode, childNode, jPath) currentNode = childNode; } textData = ""; i = closeIndex; } } }else{ textData += xmlData[i]; } } return xmlObj.child; } function addChild(currentNode, childNode, jPath){ const result = this.options.updateTag(childNode.tagname, jPath, childNode[":@"]) if(result === false){ }else if(typeof result === "string"){ childNode.tagname = result currentNode.addChild(childNode); }else{ currentNode.addChild(childNode); } } const replaceEntitiesValue = function(val){ if(this.options.processEntities){ for(let entityName in this.docTypeEntities){ const entity = this.docTypeEntities[entityName]; val = val.replace( entity.regx, entity.val); } for(let entityName in this.lastEntities){ const entity = this.lastEntities[entityName]; val = val.replace( entity.regex, entity.val); } if(this.options.htmlEntities){ for(let entityName in this.htmlEntities){ const entity = this.htmlEntities[entityName]; val = val.replace( entity.regex, entity.val); } } val = val.replace( this.ampEntity.regex, this.ampEntity.val); } return val; } function saveTextToParentTag(textData, currentNode, jPath, isLeafNode) { if (textData) { //store previously collected data as textNode if(isLeafNode === undefined) isLeafNode = Object.keys(currentNode.child).length === 0 textData = this.parseTextData(textData, currentNode.tagname, jPath, false, currentNode[":@"] ? Object.keys(currentNode[":@"]).length !== 0 : false, isLeafNode); if (textData !== undefined && textData !== "") currentNode.add(this.options.textNodeName, textData); textData = ""; } return textData; } //TODO: use jPath to simplify the logic /** * * @param {string[]} stopNodes * @param {string} jPath * @param {string} currentTagName */ function isItStopNode(stopNodes, jPath, currentTagName){ const allNodesExp = "*." + currentTagName; for (const stopNodePath in stopNodes) { const stopNodeExp = stopNodes[stopNodePath]; if( allNodesExp === stopNodeExp || jPath === stopNodeExp ) return true; } return false; } /** * Returns the tag Expression and where it is ending handling single-double quotes situation * @param {string} xmlData * @param {number} i starting index * @returns */ function tagExpWithClosingIndex(xmlData, i, closingChar = ">"){ let attrBoundary; let tagExp = ""; for (let index = i; index < xmlData.length; index++) { let ch = xmlData[index]; if (attrBoundary) { if (ch === attrBoundary) attrBoundary = "";//reset } else if (ch === '"' || ch === "'") { attrBoundary = ch; } else if (ch === closingChar[0]) { if(closingChar[1]){ if(xmlData[index + 1] === closingChar[1]){ return { data: tagExp, index: index } } }else{ return { data: tagExp, index: index } } } else if (ch === '\t') { ch = " " } tagExp += ch; } } function findClosingIndex(xmlData, str, i, errMsg){ const closingIndex = xmlData.indexOf(str, i); if(closingIndex === -1){ throw new Error(errMsg) }else{ return closingIndex + str.length - 1; } } function readTagExp(xmlData,i, removeNSPrefix, closingChar = ">"){ const result = tagExpWithClosingIndex(xmlData, i+1, closingChar); if(!result) return; let tagExp = result.data; const closeIndex = result.index; const separatorIndex = tagExp.search(/\s/); let tagName = tagExp; let attrExpPresent = true; if(separatorIndex !== -1){//separate tag name and attributes expression tagName = tagExp.substring(0, separatorIndex); tagExp = tagExp.substring(separatorIndex + 1).trimStart(); } const rawTagName = tagName; if(removeNSPrefix){ const colonIndex = tagName.indexOf(":"); if(colonIndex !== -1){ tagName = tagName.substr(colonIndex+1); attrExpPresent = tagName !== result.data.substr(colonIndex + 1); } } return { tagName: tagName, tagExp: tagExp, closeIndex: closeIndex, attrExpPresent: attrExpPresent, rawTagName: rawTagName, } } /** * find paired tag for a stop node * @param {string} xmlData * @param {string} tagName * @param {number} i */ function readStopNodeData(xmlData, tagName, i){ const startIndex = i; // Starting at 1 since we already have an open tag let openTagCount = 1; for (; i < xmlData.length; i++) { if( xmlData[i] === "<"){ if (xmlData[i+1] === "/") {//close tag const closeIndex = findClosingIndex(xmlData, ">", i, `${tagName} is not closed`); let closeTagName = xmlData.substring(i+2,closeIndex).trim(); if(closeTagName === tagName){ openTagCount--; if (openTagCount === 0) { return { tagContent: xmlData.substring(startIndex, i), i : closeIndex } } } i=closeIndex; } else if(xmlData[i+1] === '?') { const closeIndex = findClosingIndex(xmlData, "?>", i+1, "StopNode is not closed.") i=closeIndex; } else if(xmlData.substr(i + 1, 3) === '!--') { const closeIndex = findClosingIndex(xmlData, "-->", i+3, "StopNode is not closed.") i=closeIndex; } else if(xmlData.substr(i + 1, 2) === '![') { const closeIndex = findClosingIndex(xmlData, "]]>", i, "StopNode is not closed.") - 2; i=closeIndex; } else { const tagData = readTagExp(xmlData, i, '>') if (tagData) { const openTagName = tagData && tagData.tagName; if (openTagName === tagName && tagData.tagExp[tagData.tagExp.length-1] !== "/") { openTagCount++; } i=tagData.closeIndex; } } } }//end for loop } function parseValue(val, shouldParse, options) { if (shouldParse && typeof val === 'string') { //console.log(options) const newval = val.trim(); if(newval === 'true' ) return true; else if(newval === 'false' ) return false; else return toNumber(val, options); } else { if (util.isExist(val)) { return val; } else { return ''; } } } module.exports = OrderedObjParser; /***/ }), /***/ 42380: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { buildOptions} = __nccwpck_require__(86993); const OrderedObjParser = __nccwpck_require__(25832); const { prettify} = __nccwpck_require__(42882); const validator = __nccwpck_require__(61739); class XMLParser{ constructor(options){ this.externalEntities = {}; this.options = buildOptions(options); } /** * Parse XML dats to JS object * @param {string|Buffer} xmlData * @param {boolean|Object} validationOption */ parse(xmlData,validationOption){ if(typeof xmlData === "string"){ }else if( xmlData.toString){ xmlData = xmlData.toString(); }else{ throw new Error("XML data is accepted in String or Bytes[] form.") } if( validationOption){ if(validationOption === true) validationOption = {}; //validate with default options const result = validator.validate(xmlData, validationOption); if (result !== true) { throw Error( `${result.err.msg}:${result.err.line}:${result.err.col}` ) } } const orderedObjParser = new OrderedObjParser(this.options); orderedObjParser.addExternalEntities(this.externalEntities); const orderedResult = orderedObjParser.parseXml(xmlData); if(this.options.preserveOrder || orderedResult === undefined) return orderedResult; else return prettify(orderedResult, this.options); } /** * Add Entity which is not by default supported by this library * @param {string} key * @param {string} value */ addEntity(key, value){ if(value.indexOf("&") !== -1){ throw new Error("Entity value can't have '&'") }else if(key.indexOf("&") !== -1 || key.indexOf(";") !== -1){ throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for ' '") }else if(value === "&"){ throw new Error("An entity with value '&' is not permitted"); }else{ this.externalEntities[key] = value; } } } module.exports = XMLParser; /***/ }), /***/ 42882: /***/ ((__unused_webpack_module, exports) => { "use strict"; /** * * @param {array} node * @param {any} options * @returns */ function prettify(node, options){ return compress( node, options); } /** * * @param {array} arr * @param {object} options * @param {string} jPath * @returns object */ function compress(arr, options, jPath){ let text; const compressedObj = {}; for (let i = 0; i < arr.length; i++) { const tagObj = arr[i]; const property = propName(tagObj); let newJpath = ""; if(jPath === undefined) newJpath = property; else newJpath = jPath + "." + property; if(property === options.textNodeName){ if(text === undefined) text = tagObj[property]; else text += "" + tagObj[property]; }else if(property === undefined){ continue; }else if(tagObj[property]){ let val = compress(tagObj[property], options, newJpath); const isLeaf = isLeafTag(val, options); if(tagObj[":@"]){ assignAttributes( val, tagObj[":@"], newJpath, options); }else if(Object.keys(val).length === 1 && val[options.textNodeName] !== undefined && !options.alwaysCreateTextNode){ val = val[options.textNodeName]; }else if(Object.keys(val).length === 0){ if(options.alwaysCreateTextNode) val[options.textNodeName] = ""; else val = ""; } if(compressedObj[property] !== undefined && compressedObj.hasOwnProperty(property)) { if(!Array.isArray(compressedObj[property])) { compressedObj[property] = [ compressedObj[property] ]; } compressedObj[property].push(val); }else{ //TODO: if a node is not an array, then check if it should be an array //also determine if it is a leaf node if (options.isArray(property, newJpath, isLeaf )) { compressedObj[property] = [val]; }else{ compressedObj[property] = val; } } } } // if(text && text.length > 0) compressedObj[options.textNodeName] = text; if(typeof text === "string"){ if(text.length > 0) compressedObj[options.textNodeName] = text; }else if(text !== undefined) compressedObj[options.textNodeName] = text; return compressedObj; } function propName(obj){ const keys = Object.keys(obj); for (let i = 0; i < keys.length; i++) { const key = keys[i]; if(key !== ":@") return key; } } function assignAttributes(obj, attrMap, jpath, options){ if (attrMap) { const keys = Object.keys(attrMap); const len = keys.length; //don't make it inline for (let i = 0; i < len; i++) { const atrrName = keys[i]; if (options.isArray(atrrName, jpath + "." + atrrName, true, true)) { obj[atrrName] = [ attrMap[atrrName] ]; } else { obj[atrrName] = attrMap[atrrName]; } } } } function isLeafTag(obj, options){ const { textNodeName } = options; const propCount = Object.keys(obj).length; if (propCount === 0) { return true; } if ( propCount === 1 && (obj[textNodeName] || typeof obj[textNodeName] === "boolean" || obj[textNodeName] === 0) ) { return true; } return false; } exports.prettify = prettify; /***/ }), /***/ 7462: /***/ ((module) => { "use strict"; class XmlNode{ constructor(tagname) { this.tagname = tagname; this.child = []; //nested tags, text, cdata, comments in order this[":@"] = {}; //attributes map } add(key,val){ // this.child.push( {name : key, val: val, isCdata: isCdata }); if(key === "__proto__") key = "#__proto__"; this.child.push( {[key]: val }); } addChild(node) { if(node.tagname === "__proto__") node.tagname = "#__proto__"; if(node[":@"] && Object.keys(node[":@"]).length > 0){ this.child.push( { [node.tagname]: node.child, [":@"]: node[":@"] }); }else{ this.child.push( { [node.tagname]: node.child }); } }; }; module.exports = XmlNode; /***/ }), /***/ 47568: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { module.exports = ForeverAgent ForeverAgent.SSL = ForeverAgentSSL var util = __nccwpck_require__(73837) , Agent = (__nccwpck_require__(13685).Agent) , net = __nccwpck_require__(41808) , tls = __nccwpck_require__(24404) , AgentSSL = (__nccwpck_require__(95687).Agent) function getConnectionName(host, port) { var name = '' if (typeof host === 'string') { name = host + ':' + port } else { // For node.js v012.0 and iojs-v1.5.1, host is an object. And any existing localAddress is part of the connection name. name = host.host + ':' + host.port + ':' + (host.localAddress ? (host.localAddress + ':') : ':') } return name } function ForeverAgent(options) { var self = this self.options = options || {} self.requests = {} self.sockets = {} self.freeSockets = {} self.maxSockets = self.options.maxSockets || Agent.defaultMaxSockets self.minSockets = self.options.minSockets || ForeverAgent.defaultMinSockets self.on('free', function(socket, host, port) { var name = getConnectionName(host, port) if (self.requests[name] && self.requests[name].length) { self.requests[name].shift().onSocket(socket) } else if (self.sockets[name].length < self.minSockets) { if (!self.freeSockets[name]) self.freeSockets[name] = [] self.freeSockets[name].push(socket) // if an error happens while we don't use the socket anyway, meh, throw the socket away var onIdleError = function() { socket.destroy() } socket._onIdleError = onIdleError socket.on('error', onIdleError) } else { // If there are no pending requests just destroy the // socket and it will get removed from the pool. This // gets us out of timeout issues and allows us to // default to Connection:keep-alive. socket.destroy() } }) } util.inherits(ForeverAgent, Agent) ForeverAgent.defaultMinSockets = 5 ForeverAgent.prototype.createConnection = net.createConnection ForeverAgent.prototype.addRequestNoreuse = Agent.prototype.addRequest ForeverAgent.prototype.addRequest = function(req, host, port) { var name = getConnectionName(host, port) if (typeof host !== 'string') { var options = host port = options.port host = options.host } if (this.freeSockets[name] && this.freeSockets[name].length > 0 && !req.useChunkedEncodingByDefault) { var idleSocket = this.freeSockets[name].pop() idleSocket.removeListener('error', idleSocket._onIdleError) delete idleSocket._onIdleError req._reusedSocket = true req.onSocket(idleSocket) } else { this.addRequestNoreuse(req, host, port) } } ForeverAgent.prototype.removeSocket = function(s, name, host, port) { if (this.sockets[name]) { var index = this.sockets[name].indexOf(s) if (index !== -1) { this.sockets[name].splice(index, 1) } } else if (this.sockets[name] && this.sockets[name].length === 0) { // don't leak delete this.sockets[name] delete this.requests[name] } if (this.freeSockets[name]) { var index = this.freeSockets[name].indexOf(s) if (index !== -1) { this.freeSockets[name].splice(index, 1) if (this.freeSockets[name].length === 0) { delete this.freeSockets[name] } } } if (this.requests[name] && this.requests[name].length) { // 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(name, host, port).emit('free') } } function ForeverAgentSSL (options) { ForeverAgent.call(this, options) } util.inherits(ForeverAgentSSL, ForeverAgent) ForeverAgentSSL.prototype.createConnection = createConnectionSSL ForeverAgentSSL.prototype.addRequestNoreuse = AgentSSL.prototype.addRequest function createConnectionSSL (port, host, options) { if (typeof port === 'object') { options = port; } else if (typeof host === 'object') { options = host; } else if (typeof options === 'object') { options = options; } else { options = {}; } if (typeof port === 'number') { options.port = port; } if (typeof host === 'string') { options.host = host; } return tls.connect(options); } /***/ }), /***/ 27714: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; const MiniPass = __nccwpck_require__(41077) const EE = (__nccwpck_require__(82361).EventEmitter) const fs = __nccwpck_require__(57147) let writev = fs.writev /* istanbul ignore next */ if (!writev) { // This entire block can be removed if support for earlier than Node.js // 12.9.0 is not needed. const binding = process.binding('fs') const FSReqWrap = binding.FSReqWrap || binding.FSReqCallback writev = (fd, iovec, pos, cb) => { const done = (er, bw) => cb(er, bw, iovec) const req = new FSReqWrap() req.oncomplete = done binding.writeBuffers(fd, iovec, pos, req) } } const _autoClose = Symbol('_autoClose') const _close = Symbol('_close') const _ended = Symbol('_ended') const _fd = Symbol('_fd') const _finished = Symbol('_finished') const _flags = Symbol('_flags') const _flush = Symbol('_flush') const _handleChunk = Symbol('_handleChunk') const _makeBuf = Symbol('_makeBuf') const _mode = Symbol('_mode') const _needDrain = Symbol('_needDrain') const _onerror = Symbol('_onerror') const _onopen = Symbol('_onopen') const _onread = Symbol('_onread') const _onwrite = Symbol('_onwrite') const _open = Symbol('_open') const _path = Symbol('_path') const _pos = Symbol('_pos') const _queue = Symbol('_queue') const _read = Symbol('_read') const _readSize = Symbol('_readSize') const _reading = Symbol('_reading') const _remain = Symbol('_remain') const _size = Symbol('_size') const _write = Symbol('_write') const _writing = Symbol('_writing') const _defaultFlag = Symbol('_defaultFlag') const _errored = Symbol('_errored') class ReadStream extends MiniPass { constructor (path, opt) { opt = opt || {} super(opt) this.readable = true this.writable = false if (typeof path !== 'string') throw new TypeError('path must be a string') this[_errored] = false this[_fd] = typeof opt.fd === 'number' ? opt.fd : null this[_path] = path this[_readSize] = opt.readSize || 16*1024*1024 this[_reading] = false this[_size] = typeof opt.size === 'number' ? opt.size : Infinity this[_remain] = this[_size] this[_autoClose] = typeof opt.autoClose === 'boolean' ? opt.autoClose : true if (typeof this[_fd] === 'number') this[_read]() else this[_open]() } get fd () { return this[_fd] } get path () { return this[_path] } write () { throw new TypeError('this is a readable stream') } end () { throw new TypeError('this is a readable stream') } [_open] () { fs.open(this[_path], 'r', (er, fd) => this[_onopen](er, fd)) } [_onopen] (er, fd) { if (er) this[_onerror](er) else { this[_fd] = fd this.emit('open', fd) this[_read]() } } [_makeBuf] () { return Buffer.allocUnsafe(Math.min(this[_readSize], this[_remain])) } [_read] () { if (!this[_reading]) { this[_reading] = true const buf = this[_makeBuf]() /* istanbul ignore if */ if (buf.length === 0) return process.nextTick(() => this[_onread](null, 0, buf)) fs.read(this[_fd], buf, 0, buf.length, null, (er, br, buf) => this[_onread](er, br, buf)) } } [_onread] (er, br, buf) { this[_reading] = false if (er) this[_onerror](er) else if (this[_handleChunk](br, buf)) this[_read]() } [_close] () { if (this[_autoClose] && typeof this[_fd] === 'number') { const fd = this[_fd] this[_fd] = null fs.close(fd, er => er ? this.emit('error', er) : this.emit('close')) } } [_onerror] (er) { this[_reading] = true this[_close]() this.emit('error', er) } [_handleChunk] (br, buf) { let ret = false // no effect if infinite this[_remain] -= br if (br > 0) ret = super.write(br < buf.length ? buf.slice(0, br) : buf) if (br === 0 || this[_remain] <= 0) { ret = false this[_close]() super.end() } return ret } emit (ev, data) { switch (ev) { case 'prefinish': case 'finish': break case 'drain': if (typeof this[_fd] === 'number') this[_read]() break case 'error': if (this[_errored]) return this[_errored] = true return super.emit(ev, data) default: return super.emit(ev, data) } } } class ReadStreamSync extends ReadStream { [_open] () { let threw = true try { this[_onopen](null, fs.openSync(this[_path], 'r')) threw = false } finally { if (threw) this[_close]() } } [_read] () { let threw = true try { if (!this[_reading]) { this[_reading] = true do { const buf = this[_makeBuf]() /* istanbul ignore next */ const br = buf.length === 0 ? 0 : fs.readSync(this[_fd], buf, 0, buf.length, null) if (!this[_handleChunk](br, buf)) break } while (true) this[_reading] = false } threw = false } finally { if (threw) this[_close]() } } [_close] () { if (this[_autoClose] && typeof this[_fd] === 'number') { const fd = this[_fd] this[_fd] = null fs.closeSync(fd) this.emit('close') } } } class WriteStream extends EE { constructor (path, opt) { opt = opt || {} super(opt) this.readable = false this.writable = true this[_errored] = false this[_writing] = false this[_ended] = false this[_needDrain] = false this[_queue] = [] this[_path] = path this[_fd] = typeof opt.fd === 'number' ? opt.fd : null this[_mode] = opt.mode === undefined ? 0o666 : opt.mode this[_pos] = typeof opt.start === 'number' ? opt.start : null this[_autoClose] = typeof opt.autoClose === 'boolean' ? opt.autoClose : true // truncating makes no sense when writing into the middle const defaultFlag = this[_pos] !== null ? 'r+' : 'w' this[_defaultFlag] = opt.flags === undefined this[_flags] = this[_defaultFlag] ? defaultFlag : opt.flags if (this[_fd] === null) this[_open]() } emit (ev, data) { if (ev === 'error') { if (this[_errored]) return this[_errored] = true } return super.emit(ev, data) } get fd () { return this[_fd] } get path () { return this[_path] } [_onerror] (er) { this[_close]() this[_writing] = true this.emit('error', er) } [_open] () { fs.open(this[_path], this[_flags], this[_mode], (er, fd) => this[_onopen](er, fd)) } [_onopen] (er, fd) { if (this[_defaultFlag] && this[_flags] === 'r+' && er && er.code === 'ENOENT') { this[_flags] = 'w' this[_open]() } else if (er) this[_onerror](er) else { this[_fd] = fd this.emit('open', fd) this[_flush]() } } end (buf, enc) { if (buf) this.write(buf, enc) this[_ended] = true // synthetic after-write logic, where drain/finish live if (!this[_writing] && !this[_queue].length && typeof this[_fd] === 'number') this[_onwrite](null, 0) return this } write (buf, enc) { if (typeof buf === 'string') buf = Buffer.from(buf, enc) if (this[_ended]) { this.emit('error', new Error('write() after end()')) return false } if (this[_fd] === null || this[_writing] || this[_queue].length) { this[_queue].push(buf) this[_needDrain] = true return false } this[_writing] = true this[_write](buf) return true } [_write] (buf) { fs.write(this[_fd], buf, 0, buf.length, this[_pos], (er, bw) => this[_onwrite](er, bw)) } [_onwrite] (er, bw) { if (er) this[_onerror](er) else { if (this[_pos] !== null) this[_pos] += bw if (this[_queue].length) this[_flush]() else { this[_writing] = false if (this[_ended] && !this[_finished]) { this[_finished] = true this[_close]() this.emit('finish') } else if (this[_needDrain]) { this[_needDrain] = false this.emit('drain') } } } } [_flush] () { if (this[_queue].length === 0) { if (this[_ended]) this[_onwrite](null, 0) } else if (this[_queue].length === 1) this[_write](this[_queue].pop()) else { const iovec = this[_queue] this[_queue] = [] writev(this[_fd], iovec, this[_pos], (er, bw) => this[_onwrite](er, bw)) } } [_close] () { if (this[_autoClose] && typeof this[_fd] === 'number') { const fd = this[_fd] this[_fd] = null fs.close(fd, er => er ? this.emit('error', er) : this.emit('close')) } } } class WriteStreamSync extends WriteStream { [_open] () { let fd // only wrap in a try{} block if we know we'll retry, to avoid // the rethrow obscuring the error's source frame in most cases. if (this[_defaultFlag] && this[_flags] === 'r+') { try { fd = fs.openSync(this[_path], this[_flags], this[_mode]) } catch (er) { if (er.code === 'ENOENT') { this[_flags] = 'w' return this[_open]() } else throw er } } else fd = fs.openSync(this[_path], this[_flags], this[_mode]) this[_onopen](null, fd) } [_close] () { if (this[_autoClose] && typeof this[_fd] === 'number') { const fd = this[_fd] this[_fd] = null fs.closeSync(fd) this.emit('close') } } [_write] (buf) { // throw the original, but try to close if it fails let threw = true try { this[_onwrite](null, fs.writeSync(this[_fd], buf, 0, buf.length, this[_pos])) threw = false } finally { if (threw) try { this[_close]() } catch (_) {} } } } exports.ReadStream = ReadStream exports.ReadStreamSync = ReadStreamSync exports.WriteStream = WriteStream exports.WriteStreamSync = WriteStreamSync /***/ }), /***/ 46863: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { module.exports = realpath realpath.realpath = realpath realpath.sync = realpathSync realpath.realpathSync = realpathSync realpath.monkeypatch = monkeypatch realpath.unmonkeypatch = unmonkeypatch var fs = __nccwpck_require__(57147) var origRealpath = fs.realpath var origRealpathSync = fs.realpathSync var version = process.version var ok = /^v[0-5]\./.test(version) var old = __nccwpck_require__(71734) function newError (er) { return er && er.syscall === 'realpath' && ( er.code === 'ELOOP' || er.code === 'ENOMEM' || er.code === 'ENAMETOOLONG' ) } function realpath (p, cache, cb) { if (ok) { return origRealpath(p, cache, cb) } if (typeof cache === 'function') { cb = cache cache = null } origRealpath(p, cache, function (er, result) { if (newError(er)) { old.realpath(p, cache, cb) } else { cb(er, result) } }) } function realpathSync (p, cache) { if (ok) { return origRealpathSync(p, cache) } try { return origRealpathSync(p, cache) } catch (er) { if (newError(er)) { return old.realpathSync(p, cache) } else { throw er } } } function monkeypatch () { fs.realpath = realpath fs.realpathSync = realpathSync } function unmonkeypatch () { fs.realpath = origRealpath fs.realpathSync = origRealpathSync } /***/ }), /***/ 71734: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { // Copyright Joyent, Inc. and other Node contributors. // // 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. var pathModule = __nccwpck_require__(71017); var isWindows = process.platform === 'win32'; var fs = __nccwpck_require__(57147); // JavaScript implementation of realpath, ported from node pre-v6 var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG); function rethrow() { // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and // is fairly slow to generate. var callback; if (DEBUG) { var backtrace = new Error; callback = debugCallback; } else callback = missingCallback; return callback; function debugCallback(err) { if (err) { backtrace.message = err.message; err = backtrace; missingCallback(err); } } function missingCallback(err) { if (err) { if (process.throwDeprecation) throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs else if (!process.noDeprecation) { var msg = 'fs: missing callback ' + (err.stack || err.message); if (process.traceDeprecation) console.trace(msg); else console.error(msg); } } } } function maybeCallback(cb) { return typeof cb === 'function' ? cb : rethrow(); } var normalize = pathModule.normalize; // Regexp that finds the next partion of a (partial) path // result is [base_with_slash, base], e.g. ['somedir/', 'somedir'] if (isWindows) { var nextPartRe = /(.*?)(?:[\/\\]+|$)/g; } else { var nextPartRe = /(.*?)(?:[\/]+|$)/g; } // Regex to find the device root, including trailing slash. E.g. 'c:\\'. if (isWindows) { var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/; } else { var splitRootRe = /^[\/]*/; } exports.realpathSync = function realpathSync(p, cache) { // make p is absolute p = pathModule.resolve(p); if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { return cache[p]; } var original = p, seenLinks = {}, knownHard = {}; // current character position in p var pos; // the partial path so far, including a trailing slash if any var current; // the partial path without a trailing slash (except when pointing at a root) var base; // the partial path scanned in the previous round, with slash var previous; start(); function start() { // Skip over roots var m = splitRootRe.exec(p); pos = m[0].length; current = m[0]; base = m[0]; previous = ''; // On windows, check that the root exists. On unix there is no need. if (isWindows && !knownHard[base]) { fs.lstatSync(base); knownHard[base] = true; } } // walk down the path, swapping out linked pathparts for their real // values // NB: p.length changes. while (pos < p.length) { // find the next part nextPartRe.lastIndex = pos; var result = nextPartRe.exec(p); previous = current; current += result[0]; base = previous + result[1]; pos = nextPartRe.lastIndex; // continue if not a symlink if (knownHard[base] || (cache && cache[base] === base)) { continue; } var resolvedLink; if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { // some known symbolic link. no need to stat again. resolvedLink = cache[base]; } else { var stat = fs.lstatSync(base); if (!stat.isSymbolicLink()) { knownHard[base] = true; if (cache) cache[base] = base; continue; } // read the link if it wasn't read before // dev/ino always return 0 on windows, so skip the check. var linkTarget = null; if (!isWindows) { var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); if (seenLinks.hasOwnProperty(id)) { linkTarget = seenLinks[id]; } } if (linkTarget === null) { fs.statSync(base); linkTarget = fs.readlinkSync(base); } resolvedLink = pathModule.resolve(previous, linkTarget); // track this, if given a cache. if (cache) cache[base] = resolvedLink; if (!isWindows) seenLinks[id] = linkTarget; } // resolve the link, then start over p = pathModule.resolve(resolvedLink, p.slice(pos)); start(); } if (cache) cache[original] = p; return p; }; exports.realpath = function realpath(p, cache, cb) { if (typeof cb !== 'function') { cb = maybeCallback(cache); cache = null; } // make p is absolute p = pathModule.resolve(p); if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { return process.nextTick(cb.bind(null, null, cache[p])); } var original = p, seenLinks = {}, knownHard = {}; // current character position in p var pos; // the partial path so far, including a trailing slash if any var current; // the partial path without a trailing slash (except when pointing at a root) var base; // the partial path scanned in the previous round, with slash var previous; start(); function start() { // Skip over roots var m = splitRootRe.exec(p); pos = m[0].length; current = m[0]; base = m[0]; previous = ''; // On windows, check that the root exists. On unix there is no need. if (isWindows && !knownHard[base]) { fs.lstat(base, function(err) { if (err) return cb(err); knownHard[base] = true; LOOP(); }); } else { process.nextTick(LOOP); } } // walk down the path, swapping out linked pathparts for their real // values function LOOP() { // stop if scanned past end of path if (pos >= p.length) { if (cache) cache[original] = p; return cb(null, p); } // find the next part nextPartRe.lastIndex = pos; var result = nextPartRe.exec(p); previous = current; current += result[0]; base = previous + result[1]; pos = nextPartRe.lastIndex; // continue if not a symlink if (knownHard[base] || (cache && cache[base] === base)) { return process.nextTick(LOOP); } if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { // known symbolic link. no need to stat again. return gotResolvedLink(cache[base]); } return fs.lstat(base, gotStat); } function gotStat(err, stat) { if (err) return cb(err); // if not a symlink, skip to the next path part if (!stat.isSymbolicLink()) { knownHard[base] = true; if (cache) cache[base] = base; return process.nextTick(LOOP); } // stat & read the link if not read before // call gotTarget as soon as the link target is known // dev/ino always return 0 on windows, so skip the check. if (!isWindows) { var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); if (seenLinks.hasOwnProperty(id)) { return gotTarget(null, seenLinks[id], base); } } fs.stat(base, function(err) { if (err) return cb(err); fs.readlink(base, function(err, target) { if (!isWindows) seenLinks[id] = target; gotTarget(err, target); }); }); } function gotTarget(err, target, base) { if (err) return cb(err); var resolvedLink = pathModule.resolve(previous, target); if (cache) cache[base] = resolvedLink; gotResolvedLink(resolvedLink); } function gotResolvedLink(resolvedLink) { // resolve the link, then start over p = pathModule.resolve(resolvedLink, p.slice(pos)); start(); } }; /***/ }), /***/ 91585: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const {PassThrough: PassThroughStream} = __nccwpck_require__(12781); module.exports = options => { options = {...options}; const {array} = options; let {encoding} = options; const isBuffer = encoding === 'buffer'; let objectMode = false; if (array) { objectMode = !(encoding || isBuffer); } else { encoding = encoding || 'utf8'; } if (isBuffer) { encoding = null; } const stream = new PassThroughStream({objectMode}); if (encoding) { stream.setEncoding(encoding); } let length = 0; const chunks = []; stream.on('data', chunk => { chunks.push(chunk); if (objectMode) { length = chunks.length; } else { length += chunk.length; } }); stream.getBufferedValue = () => { if (array) { return chunks; } return isBuffer ? Buffer.concat(chunks, length) : chunks.join(''); }; stream.getBufferedLength = () => length; return stream; }; /***/ }), /***/ 21766: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const {constants: BufferConstants} = __nccwpck_require__(14300); const stream = __nccwpck_require__(12781); const {promisify} = __nccwpck_require__(73837); const bufferStream = __nccwpck_require__(91585); const streamPipelinePromisified = promisify(stream.pipeline); class MaxBufferError extends Error { constructor() { super('maxBuffer exceeded'); this.name = 'MaxBufferError'; } } async function getStream(inputStream, options) { if (!inputStream) { throw new Error('Expected a stream'); } options = { maxBuffer: Infinity, ...options }; const {maxBuffer} = options; const stream = bufferStream(options); await new Promise((resolve, reject) => { const rejectPromise = error => { // Don't retrieve an oversized buffer. if (error && stream.getBufferedLength() <= BufferConstants.MAX_LENGTH) { error.bufferedData = stream.getBufferedValue(); } reject(error); }; (async () => { try { await streamPipelinePromisified(inputStream, stream); resolve(); } catch (error) { rejectPromise(error); } })(); stream.on('data', () => { if (stream.getBufferedLength() > maxBuffer) { rejectPromise(new MaxBufferError()); } }); }); return stream.getBufferedValue(); } module.exports = getStream; module.exports.buffer = (stream, options) => getStream(stream, {...options, encoding: 'buffer'}); module.exports.array = (stream, options) => getStream(stream, {...options, array: true}); module.exports.MaxBufferError = MaxBufferError; /***/ }), /***/ 47625: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { exports.setopts = setopts exports.ownProp = ownProp exports.makeAbs = makeAbs exports.finish = finish exports.mark = mark exports.isIgnored = isIgnored exports.childrenIgnored = childrenIgnored function ownProp (obj, field) { return Object.prototype.hasOwnProperty.call(obj, field) } var fs = __nccwpck_require__(57147) var path = __nccwpck_require__(71017) var minimatch = __nccwpck_require__(83973) var isAbsolute = __nccwpck_require__(38714) var Minimatch = minimatch.Minimatch function alphasort (a, b) { return a.localeCompare(b, 'en') } function setupIgnores (self, options) { self.ignore = options.ignore || [] if (!Array.isArray(self.ignore)) self.ignore = [self.ignore] if (self.ignore.length) { self.ignore = self.ignore.map(ignoreMap) } } // ignore patterns are always in dot:true mode. function ignoreMap (pattern) { var gmatcher = null if (pattern.slice(-3) === '/**') { var gpattern = pattern.replace(/(\/\*\*)+$/, '') gmatcher = new Minimatch(gpattern, { dot: true }) } return { matcher: new Minimatch(pattern, { dot: true }), gmatcher: gmatcher } } function setopts (self, pattern, options) { if (!options) options = {} // base-matching: just use globstar for that. if (options.matchBase && -1 === pattern.indexOf("/")) { if (options.noglobstar) { throw new Error("base matching requires globstar") } pattern = "**/" + pattern } self.silent = !!options.silent self.pattern = pattern self.strict = options.strict !== false self.realpath = !!options.realpath self.realpathCache = options.realpathCache || Object.create(null) self.follow = !!options.follow self.dot = !!options.dot self.mark = !!options.mark self.nodir = !!options.nodir if (self.nodir) self.mark = true self.sync = !!options.sync self.nounique = !!options.nounique self.nonull = !!options.nonull self.nosort = !!options.nosort self.nocase = !!options.nocase self.stat = !!options.stat self.noprocess = !!options.noprocess self.absolute = !!options.absolute self.fs = options.fs || fs self.maxLength = options.maxLength || Infinity self.cache = options.cache || Object.create(null) self.statCache = options.statCache || Object.create(null) self.symlinks = options.symlinks || Object.create(null) setupIgnores(self, options) self.changedCwd = false var cwd = process.cwd() if (!ownProp(options, "cwd")) self.cwd = cwd else { self.cwd = path.resolve(options.cwd) self.changedCwd = self.cwd !== cwd } self.root = options.root || path.resolve(self.cwd, "/") self.root = path.resolve(self.root) if (process.platform === "win32") self.root = self.root.replace(/\\/g, "/") // TODO: is an absolute `cwd` supposed to be resolved against `root`? // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test') self.cwdAbs = isAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd) if (process.platform === "win32") self.cwdAbs = self.cwdAbs.replace(/\\/g, "/") self.nomount = !!options.nomount // disable comments and negation in Minimatch. // Note that they are not supported in Glob itself anyway. options.nonegate = true options.nocomment = true // always treat \ in patterns as escapes, not path separators options.allowWindowsEscape = false self.minimatch = new Minimatch(pattern, options) self.options = self.minimatch.options } function finish (self) { var nou = self.nounique var all = nou ? [] : Object.create(null) for (var i = 0, l = self.matches.length; i < l; i ++) { var matches = self.matches[i] if (!matches || Object.keys(matches).length === 0) { if (self.nonull) { // do like the shell, and spit out the literal glob var literal = self.minimatch.globSet[i] if (nou) all.push(literal) else all[literal] = true } } else { // had matches var m = Object.keys(matches) if (nou) all.push.apply(all, m) else m.forEach(function (m) { all[m] = true }) } } if (!nou) all = Object.keys(all) if (!self.nosort) all = all.sort(alphasort) // at *some* point we statted all of these if (self.mark) { for (var i = 0; i < all.length; i++) { all[i] = self._mark(all[i]) } if (self.nodir) { all = all.filter(function (e) { var notDir = !(/\/$/.test(e)) var c = self.cache[e] || self.cache[makeAbs(self, e)] if (notDir && c) notDir = c !== 'DIR' && !Array.isArray(c) return notDir }) } } if (self.ignore.length) all = all.filter(function(m) { return !isIgnored(self, m) }) self.found = all } function mark (self, p) { var abs = makeAbs(self, p) var c = self.cache[abs] var m = p if (c) { var isDir = c === 'DIR' || Array.isArray(c) var slash = p.slice(-1) === '/' if (isDir && !slash) m += '/' else if (!isDir && slash) m = m.slice(0, -1) if (m !== p) { var mabs = makeAbs(self, m) self.statCache[mabs] = self.statCache[abs] self.cache[mabs] = self.cache[abs] } } return m } // lotta situps... function makeAbs (self, f) { var abs = f if (f.charAt(0) === '/') { abs = path.join(self.root, f) } else if (isAbsolute(f) || f === '') { abs = f } else if (self.changedCwd) { abs = path.resolve(self.cwd, f) } else { abs = path.resolve(f) } if (process.platform === 'win32') abs = abs.replace(/\\/g, '/') return abs } // Return true, if pattern ends with globstar '**', for the accompanying parent directory. // Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents function isIgnored (self, path) { if (!self.ignore.length) return false return self.ignore.some(function(item) { return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path)) }) } function childrenIgnored (self, path) { if (!self.ignore.length) return false return self.ignore.some(function(item) { return !!(item.gmatcher && item.gmatcher.match(path)) }) } /***/ }), /***/ 91957: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // Approach: // // 1. Get the minimatch set // 2. For each pattern in the set, PROCESS(pattern, false) // 3. Store matches per-set, then uniq them // // PROCESS(pattern, inGlobStar) // Get the first [n] items from pattern that are all strings // Join these together. This is PREFIX. // If there is no more remaining, then stat(PREFIX) and // add to matches if it succeeds. END. // // If inGlobStar and PREFIX is symlink and points to dir // set ENTRIES = [] // else readdir(PREFIX) as ENTRIES // If fail, END // // with ENTRIES // If pattern[n] is GLOBSTAR // // handle the case where the globstar match is empty // // by pruning it out, and testing the resulting pattern // PROCESS(pattern[0..n] + pattern[n+1 .. $], false) // // handle other cases. // for ENTRY in ENTRIES (not dotfiles) // // attach globstar + tail onto the entry // // Mark that this entry is a globstar match // PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true) // // else // not globstar // for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot) // Test ENTRY against pattern[n] // If fails, continue // If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $]) // // Caveat: // Cache all stats and readdirs results to minimize syscall. Since all // we ever care about is existence and directory-ness, we can just keep // `true` for files, and [children,...] for directories, or `false` for // things that don't exist. module.exports = glob var rp = __nccwpck_require__(46863) var minimatch = __nccwpck_require__(83973) var Minimatch = minimatch.Minimatch var inherits = __nccwpck_require__(44124) var EE = (__nccwpck_require__(82361).EventEmitter) var path = __nccwpck_require__(71017) var assert = __nccwpck_require__(39491) var isAbsolute = __nccwpck_require__(38714) var globSync = __nccwpck_require__(29010) var common = __nccwpck_require__(47625) var setopts = common.setopts var ownProp = common.ownProp var inflight = __nccwpck_require__(52492) var util = __nccwpck_require__(73837) var childrenIgnored = common.childrenIgnored var isIgnored = common.isIgnored var once = __nccwpck_require__(1223) function glob (pattern, options, cb) { if (typeof options === 'function') cb = options, options = {} if (!options) options = {} if (options.sync) { if (cb) throw new TypeError('callback provided to sync glob') return globSync(pattern, options) } return new Glob(pattern, options, cb) } glob.sync = globSync var GlobSync = glob.GlobSync = globSync.GlobSync // old api surface glob.glob = glob function extend (origin, add) { if (add === null || typeof add !== 'object') { return origin } var keys = Object.keys(add) var i = keys.length while (i--) { origin[keys[i]] = add[keys[i]] } return origin } glob.hasMagic = function (pattern, options_) { var options = extend({}, options_) options.noprocess = true var g = new Glob(pattern, options) var set = g.minimatch.set if (!pattern) return false if (set.length > 1) return true for (var j = 0; j < set[0].length; j++) { if (typeof set[0][j] !== 'string') return true } return false } glob.Glob = Glob inherits(Glob, EE) function Glob (pattern, options, cb) { if (typeof options === 'function') { cb = options options = null } if (options && options.sync) { if (cb) throw new TypeError('callback provided to sync glob') return new GlobSync(pattern, options) } if (!(this instanceof Glob)) return new Glob(pattern, options, cb) setopts(this, pattern, options) this._didRealPath = false // process each pattern in the minimatch set var n = this.minimatch.set.length // The matches are stored as {: true,...} so that // duplicates are automagically pruned. // Later, we do an Object.keys() on these. // Keep them as a list so we can fill in when nonull is set. this.matches = new Array(n) if (typeof cb === 'function') { cb = once(cb) this.on('error', cb) this.on('end', function (matches) { cb(null, matches) }) } var self = this this._processing = 0 this._emitQueue = [] this._processQueue = [] this.paused = false if (this.noprocess) return this if (n === 0) return done() var sync = true for (var i = 0; i < n; i ++) { this._process(this.minimatch.set[i], i, false, done) } sync = false function done () { --self._processing if (self._processing <= 0) { if (sync) { process.nextTick(function () { self._finish() }) } else { self._finish() } } } } Glob.prototype._finish = function () { assert(this instanceof Glob) if (this.aborted) return if (this.realpath && !this._didRealpath) return this._realpath() common.finish(this) this.emit('end', this.found) } Glob.prototype._realpath = function () { if (this._didRealpath) return this._didRealpath = true var n = this.matches.length if (n === 0) return this._finish() var self = this for (var i = 0; i < this.matches.length; i++) this._realpathSet(i, next) function next () { if (--n === 0) self._finish() } } Glob.prototype._realpathSet = function (index, cb) { var matchset = this.matches[index] if (!matchset) return cb() var found = Object.keys(matchset) var self = this var n = found.length if (n === 0) return cb() var set = this.matches[index] = Object.create(null) found.forEach(function (p, i) { // If there's a problem with the stat, then it means that // one or more of the links in the realpath couldn't be // resolved. just return the abs value in that case. p = self._makeAbs(p) rp.realpath(p, self.realpathCache, function (er, real) { if (!er) set[real] = true else if (er.syscall === 'stat') set[p] = true else self.emit('error', er) // srsly wtf right here if (--n === 0) { self.matches[index] = set cb() } }) }) } Glob.prototype._mark = function (p) { return common.mark(this, p) } Glob.prototype._makeAbs = function (f) { return common.makeAbs(this, f) } Glob.prototype.abort = function () { this.aborted = true this.emit('abort') } Glob.prototype.pause = function () { if (!this.paused) { this.paused = true this.emit('pause') } } Glob.prototype.resume = function () { if (this.paused) { this.emit('resume') this.paused = false if (this._emitQueue.length) { var eq = this._emitQueue.slice(0) this._emitQueue.length = 0 for (var i = 0; i < eq.length; i ++) { var e = eq[i] this._emitMatch(e[0], e[1]) } } if (this._processQueue.length) { var pq = this._processQueue.slice(0) this._processQueue.length = 0 for (var i = 0; i < pq.length; i ++) { var p = pq[i] this._processing-- this._process(p[0], p[1], p[2], p[3]) } } } } Glob.prototype._process = function (pattern, index, inGlobStar, cb) { assert(this instanceof Glob) assert(typeof cb === 'function') if (this.aborted) return this._processing++ if (this.paused) { this._processQueue.push([pattern, index, inGlobStar, cb]) return } //console.error('PROCESS %d', this._processing, pattern) // Get the first [n] parts of pattern that are all strings. var n = 0 while (typeof pattern[n] === 'string') { n ++ } // now n is the index of the first one that is *not* a string. // see if there's anything else var prefix switch (n) { // if not, then this is rather simple case pattern.length: this._processSimple(pattern.join('/'), index, cb) return case 0: // pattern *starts* with some non-trivial item. // going to readdir(cwd), but not include the prefix in matches. prefix = null break default: // pattern has some string bits in the front. // whatever it starts with, whether that's 'absolute' like /foo/bar, // or 'relative' like '../baz' prefix = pattern.slice(0, n).join('/') break } var remain = pattern.slice(n) // get the list of entries. var read if (prefix === null) read = '.' else if (isAbsolute(prefix) || isAbsolute(pattern.map(function (p) { return typeof p === 'string' ? p : '[*]' }).join('/'))) { if (!prefix || !isAbsolute(prefix)) prefix = '/' + prefix read = prefix } else read = prefix var abs = this._makeAbs(read) //if ignored, skip _processing if (childrenIgnored(this, read)) return cb() var isGlobStar = remain[0] === minimatch.GLOBSTAR if (isGlobStar) this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb) else this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb) } Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) { var self = this this._readdir(abs, inGlobStar, function (er, entries) { return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb) }) } Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { // if the abs isn't a dir, then nothing can match! if (!entries) return cb() // It will only match dot entries if it starts with a dot, or if // dot is set. Stuff like @(.foo|.bar) isn't allowed. var pn = remain[0] var negate = !!this.minimatch.negate var rawGlob = pn._glob var dotOk = this.dot || rawGlob.charAt(0) === '.' var matchedEntries = [] for (var i = 0; i < entries.length; i++) { var e = entries[i] if (e.charAt(0) !== '.' || dotOk) { var m if (negate && !prefix) { m = !e.match(pn) } else { m = e.match(pn) } if (m) matchedEntries.push(e) } } //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries) var len = matchedEntries.length // If there are no matched entries, then nothing matches. if (len === 0) return cb() // if this is the last remaining pattern bit, then no need for // an additional stat *unless* the user has specified mark or // stat explicitly. We know they exist, since readdir returned // them. if (remain.length === 1 && !this.mark && !this.stat) { if (!this.matches[index]) this.matches[index] = Object.create(null) for (var i = 0; i < len; i ++) { var e = matchedEntries[i] if (prefix) { if (prefix !== '/') e = prefix + '/' + e else e = prefix + e } if (e.charAt(0) === '/' && !this.nomount) { e = path.join(this.root, e) } this._emitMatch(index, e) } // This was the last one, and no stats were needed return cb() } // now test all matched entries as stand-ins for that part // of the pattern. remain.shift() for (var i = 0; i < len; i ++) { var e = matchedEntries[i] var newPattern if (prefix) { if (prefix !== '/') e = prefix + '/' + e else e = prefix + e } this._process([e].concat(remain), index, inGlobStar, cb) } cb() } Glob.prototype._emitMatch = function (index, e) { if (this.aborted) return if (isIgnored(this, e)) return if (this.paused) { this._emitQueue.push([index, e]) return } var abs = isAbsolute(e) ? e : this._makeAbs(e) if (this.mark) e = this._mark(e) if (this.absolute) e = abs if (this.matches[index][e]) return if (this.nodir) { var c = this.cache[abs] if (c === 'DIR' || Array.isArray(c)) return } this.matches[index][e] = true var st = this.statCache[abs] if (st) this.emit('stat', e, st) this.emit('match', e) } Glob.prototype._readdirInGlobStar = function (abs, cb) { if (this.aborted) return // follow all symlinked directories forever // just proceed as if this is a non-globstar situation if (this.follow) return this._readdir(abs, false, cb) var lstatkey = 'lstat\0' + abs var self = this var lstatcb = inflight(lstatkey, lstatcb_) if (lstatcb) self.fs.lstat(abs, lstatcb) function lstatcb_ (er, lstat) { if (er && er.code === 'ENOENT') return cb() var isSym = lstat && lstat.isSymbolicLink() self.symlinks[abs] = isSym // If it's not a symlink or a dir, then it's definitely a regular file. // don't bother doing a readdir in that case. if (!isSym && lstat && !lstat.isDirectory()) { self.cache[abs] = 'FILE' cb() } else self._readdir(abs, false, cb) } } Glob.prototype._readdir = function (abs, inGlobStar, cb) { if (this.aborted) return cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb) if (!cb) return //console.error('RD %j %j', +inGlobStar, abs) if (inGlobStar && !ownProp(this.symlinks, abs)) return this._readdirInGlobStar(abs, cb) if (ownProp(this.cache, abs)) { var c = this.cache[abs] if (!c || c === 'FILE') return cb() if (Array.isArray(c)) return cb(null, c) } var self = this self.fs.readdir(abs, readdirCb(this, abs, cb)) } function readdirCb (self, abs, cb) { return function (er, entries) { if (er) self._readdirError(abs, er, cb) else self._readdirEntries(abs, entries, cb) } } Glob.prototype._readdirEntries = function (abs, entries, cb) { if (this.aborted) return // if we haven't asked to stat everything, then just // assume that everything in there exists, so we can avoid // having to stat it a second time. if (!this.mark && !this.stat) { for (var i = 0; i < entries.length; i ++) { var e = entries[i] if (abs === '/') e = abs + e else e = abs + '/' + e this.cache[e] = true } } this.cache[abs] = entries return cb(null, entries) } Glob.prototype._readdirError = function (f, er, cb) { if (this.aborted) return // handle errors, and cache the information switch (er.code) { case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 case 'ENOTDIR': // totally normal. means it *does* exist. var abs = this._makeAbs(f) this.cache[abs] = 'FILE' if (abs === this.cwdAbs) { var error = new Error(er.code + ' invalid cwd ' + this.cwd) error.path = this.cwd error.code = er.code this.emit('error', error) this.abort() } break case 'ENOENT': // not terribly unusual case 'ELOOP': case 'ENAMETOOLONG': case 'UNKNOWN': this.cache[this._makeAbs(f)] = false break default: // some unusual error. Treat as failure. this.cache[this._makeAbs(f)] = false if (this.strict) { this.emit('error', er) // If the error is handled, then we abort // if not, we threw out of here this.abort() } if (!this.silent) console.error('glob error', er) break } return cb() } Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) { var self = this this._readdir(abs, inGlobStar, function (er, entries) { self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb) }) } Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { //console.error('pgs2', prefix, remain[0], entries) // no entries means not a dir, so it can never have matches // foo.txt/** doesn't match foo.txt if (!entries) return cb() // test without the globstar, and with every child both below // and replacing the globstar. var remainWithoutGlobStar = remain.slice(1) var gspref = prefix ? [ prefix ] : [] var noGlobStar = gspref.concat(remainWithoutGlobStar) // the noGlobStar pattern exits the inGlobStar state this._process(noGlobStar, index, false, cb) var isSym = this.symlinks[abs] var len = entries.length // If it's a symlink, and we're in a globstar, then stop if (isSym && inGlobStar) return cb() for (var i = 0; i < len; i++) { var e = entries[i] if (e.charAt(0) === '.' && !this.dot) continue // these two cases enter the inGlobStar state var instead = gspref.concat(entries[i], remainWithoutGlobStar) this._process(instead, index, true, cb) var below = gspref.concat(entries[i], remain) this._process(below, index, true, cb) } cb() } Glob.prototype._processSimple = function (prefix, index, cb) { // XXX review this. Shouldn't it be doing the mounting etc // before doing stat? kinda weird? var self = this this._stat(prefix, function (er, exists) { self._processSimple2(prefix, index, er, exists, cb) }) } Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) { //console.error('ps2', prefix, exists) if (!this.matches[index]) this.matches[index] = Object.create(null) // If it doesn't exist, then just mark the lack of results if (!exists) return cb() if (prefix && isAbsolute(prefix) && !this.nomount) { var trail = /[\/\\]$/.test(prefix) if (prefix.charAt(0) === '/') { prefix = path.join(this.root, prefix) } else { prefix = path.resolve(this.root, prefix) if (trail) prefix += '/' } } if (process.platform === 'win32') prefix = prefix.replace(/\\/g, '/') // Mark this as a match this._emitMatch(index, prefix) cb() } // Returns either 'DIR', 'FILE', or false Glob.prototype._stat = function (f, cb) { var abs = this._makeAbs(f) var needDir = f.slice(-1) === '/' if (f.length > this.maxLength) return cb() if (!this.stat && ownProp(this.cache, abs)) { var c = this.cache[abs] if (Array.isArray(c)) c = 'DIR' // It exists, but maybe not how we need it if (!needDir || c === 'DIR') return cb(null, c) if (needDir && c === 'FILE') return cb() // otherwise we have to stat, because maybe c=true // if we know it exists, but not what it is. } var exists var stat = this.statCache[abs] if (stat !== undefined) { if (stat === false) return cb(null, stat) else { var type = stat.isDirectory() ? 'DIR' : 'FILE' if (needDir && type === 'FILE') return cb() else return cb(null, type, stat) } } var self = this var statcb = inflight('stat\0' + abs, lstatcb_) if (statcb) self.fs.lstat(abs, statcb) function lstatcb_ (er, lstat) { if (lstat && lstat.isSymbolicLink()) { // If it's a symlink, then treat it as the target, unless // the target does not exist, then treat it as a file. return self.fs.stat(abs, function (er, stat) { if (er) self._stat2(f, abs, null, lstat, cb) else self._stat2(f, abs, er, stat, cb) }) } else { self._stat2(f, abs, er, lstat, cb) } } } Glob.prototype._stat2 = function (f, abs, er, stat, cb) { if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { this.statCache[abs] = false return cb() } var needDir = f.slice(-1) === '/' this.statCache[abs] = stat if (abs.slice(-1) === '/' && stat && !stat.isDirectory()) return cb(null, false, stat) var c = true if (stat) c = stat.isDirectory() ? 'DIR' : 'FILE' this.cache[abs] = this.cache[abs] || c if (needDir && c === 'FILE') return cb() return cb(null, c, stat) } /***/ }), /***/ 29010: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { module.exports = globSync globSync.GlobSync = GlobSync var rp = __nccwpck_require__(46863) var minimatch = __nccwpck_require__(83973) var Minimatch = minimatch.Minimatch var Glob = (__nccwpck_require__(91957).Glob) var util = __nccwpck_require__(73837) var path = __nccwpck_require__(71017) var assert = __nccwpck_require__(39491) var isAbsolute = __nccwpck_require__(38714) var common = __nccwpck_require__(47625) var setopts = common.setopts var ownProp = common.ownProp var childrenIgnored = common.childrenIgnored var isIgnored = common.isIgnored function globSync (pattern, options) { if (typeof options === 'function' || arguments.length === 3) throw new TypeError('callback provided to sync glob\n'+ 'See: https://github.com/isaacs/node-glob/issues/167') return new GlobSync(pattern, options).found } function GlobSync (pattern, options) { if (!pattern) throw new Error('must provide pattern') if (typeof options === 'function' || arguments.length === 3) throw new TypeError('callback provided to sync glob\n'+ 'See: https://github.com/isaacs/node-glob/issues/167') if (!(this instanceof GlobSync)) return new GlobSync(pattern, options) setopts(this, pattern, options) if (this.noprocess) return this var n = this.minimatch.set.length this.matches = new Array(n) for (var i = 0; i < n; i ++) { this._process(this.minimatch.set[i], i, false) } this._finish() } GlobSync.prototype._finish = function () { assert.ok(this instanceof GlobSync) if (this.realpath) { var self = this this.matches.forEach(function (matchset, index) { var set = self.matches[index] = Object.create(null) for (var p in matchset) { try { p = self._makeAbs(p) var real = rp.realpathSync(p, self.realpathCache) set[real] = true } catch (er) { if (er.syscall === 'stat') set[self._makeAbs(p)] = true else throw er } } }) } common.finish(this) } GlobSync.prototype._process = function (pattern, index, inGlobStar) { assert.ok(this instanceof GlobSync) // Get the first [n] parts of pattern that are all strings. var n = 0 while (typeof pattern[n] === 'string') { n ++ } // now n is the index of the first one that is *not* a string. // See if there's anything else var prefix switch (n) { // if not, then this is rather simple case pattern.length: this._processSimple(pattern.join('/'), index) return case 0: // pattern *starts* with some non-trivial item. // going to readdir(cwd), but not include the prefix in matches. prefix = null break default: // pattern has some string bits in the front. // whatever it starts with, whether that's 'absolute' like /foo/bar, // or 'relative' like '../baz' prefix = pattern.slice(0, n).join('/') break } var remain = pattern.slice(n) // get the list of entries. var read if (prefix === null) read = '.' else if (isAbsolute(prefix) || isAbsolute(pattern.map(function (p) { return typeof p === 'string' ? p : '[*]' }).join('/'))) { if (!prefix || !isAbsolute(prefix)) prefix = '/' + prefix read = prefix } else read = prefix var abs = this._makeAbs(read) //if ignored, skip processing if (childrenIgnored(this, read)) return var isGlobStar = remain[0] === minimatch.GLOBSTAR if (isGlobStar) this._processGlobStar(prefix, read, abs, remain, index, inGlobStar) else this._processReaddir(prefix, read, abs, remain, index, inGlobStar) } GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) { var entries = this._readdir(abs, inGlobStar) // if the abs isn't a dir, then nothing can match! if (!entries) return // It will only match dot entries if it starts with a dot, or if // dot is set. Stuff like @(.foo|.bar) isn't allowed. var pn = remain[0] var negate = !!this.minimatch.negate var rawGlob = pn._glob var dotOk = this.dot || rawGlob.charAt(0) === '.' var matchedEntries = [] for (var i = 0; i < entries.length; i++) { var e = entries[i] if (e.charAt(0) !== '.' || dotOk) { var m if (negate && !prefix) { m = !e.match(pn) } else { m = e.match(pn) } if (m) matchedEntries.push(e) } } var len = matchedEntries.length // If there are no matched entries, then nothing matches. if (len === 0) return // if this is the last remaining pattern bit, then no need for // an additional stat *unless* the user has specified mark or // stat explicitly. We know they exist, since readdir returned // them. if (remain.length === 1 && !this.mark && !this.stat) { if (!this.matches[index]) this.matches[index] = Object.create(null) for (var i = 0; i < len; i ++) { var e = matchedEntries[i] if (prefix) { if (prefix.slice(-1) !== '/') e = prefix + '/' + e else e = prefix + e } if (e.charAt(0) === '/' && !this.nomount) { e = path.join(this.root, e) } this._emitMatch(index, e) } // This was the last one, and no stats were needed return } // now test all matched entries as stand-ins for that part // of the pattern. remain.shift() for (var i = 0; i < len; i ++) { var e = matchedEntries[i] var newPattern if (prefix) newPattern = [prefix, e] else newPattern = [e] this._process(newPattern.concat(remain), index, inGlobStar) } } GlobSync.prototype._emitMatch = function (index, e) { if (isIgnored(this, e)) return var abs = this._makeAbs(e) if (this.mark) e = this._mark(e) if (this.absolute) { e = abs } if (this.matches[index][e]) return if (this.nodir) { var c = this.cache[abs] if (c === 'DIR' || Array.isArray(c)) return } this.matches[index][e] = true if (this.stat) this._stat(e) } GlobSync.prototype._readdirInGlobStar = function (abs) { // follow all symlinked directories forever // just proceed as if this is a non-globstar situation if (this.follow) return this._readdir(abs, false) var entries var lstat var stat try { lstat = this.fs.lstatSync(abs) } catch (er) { if (er.code === 'ENOENT') { // lstat failed, doesn't exist return null } } var isSym = lstat && lstat.isSymbolicLink() this.symlinks[abs] = isSym // If it's not a symlink or a dir, then it's definitely a regular file. // don't bother doing a readdir in that case. if (!isSym && lstat && !lstat.isDirectory()) this.cache[abs] = 'FILE' else entries = this._readdir(abs, false) return entries } GlobSync.prototype._readdir = function (abs, inGlobStar) { var entries if (inGlobStar && !ownProp(this.symlinks, abs)) return this._readdirInGlobStar(abs) if (ownProp(this.cache, abs)) { var c = this.cache[abs] if (!c || c === 'FILE') return null if (Array.isArray(c)) return c } try { return this._readdirEntries(abs, this.fs.readdirSync(abs)) } catch (er) { this._readdirError(abs, er) return null } } GlobSync.prototype._readdirEntries = function (abs, entries) { // if we haven't asked to stat everything, then just // assume that everything in there exists, so we can avoid // having to stat it a second time. if (!this.mark && !this.stat) { for (var i = 0; i < entries.length; i ++) { var e = entries[i] if (abs === '/') e = abs + e else e = abs + '/' + e this.cache[e] = true } } this.cache[abs] = entries // mark and cache dir-ness return entries } GlobSync.prototype._readdirError = function (f, er) { // handle errors, and cache the information switch (er.code) { case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 case 'ENOTDIR': // totally normal. means it *does* exist. var abs = this._makeAbs(f) this.cache[abs] = 'FILE' if (abs === this.cwdAbs) { var error = new Error(er.code + ' invalid cwd ' + this.cwd) error.path = this.cwd error.code = er.code throw error } break case 'ENOENT': // not terribly unusual case 'ELOOP': case 'ENAMETOOLONG': case 'UNKNOWN': this.cache[this._makeAbs(f)] = false break default: // some unusual error. Treat as failure. this.cache[this._makeAbs(f)] = false if (this.strict) throw er if (!this.silent) console.error('glob error', er) break } } GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) { var entries = this._readdir(abs, inGlobStar) // no entries means not a dir, so it can never have matches // foo.txt/** doesn't match foo.txt if (!entries) return // test without the globstar, and with every child both below // and replacing the globstar. var remainWithoutGlobStar = remain.slice(1) var gspref = prefix ? [ prefix ] : [] var noGlobStar = gspref.concat(remainWithoutGlobStar) // the noGlobStar pattern exits the inGlobStar state this._process(noGlobStar, index, false) var len = entries.length var isSym = this.symlinks[abs] // If it's a symlink, and we're in a globstar, then stop if (isSym && inGlobStar) return for (var i = 0; i < len; i++) { var e = entries[i] if (e.charAt(0) === '.' && !this.dot) continue // these two cases enter the inGlobStar state var instead = gspref.concat(entries[i], remainWithoutGlobStar) this._process(instead, index, true) var below = gspref.concat(entries[i], remain) this._process(below, index, true) } } GlobSync.prototype._processSimple = function (prefix, index) { // XXX review this. Shouldn't it be doing the mounting etc // before doing stat? kinda weird? var exists = this._stat(prefix) if (!this.matches[index]) this.matches[index] = Object.create(null) // If it doesn't exist, then just mark the lack of results if (!exists) return if (prefix && isAbsolute(prefix) && !this.nomount) { var trail = /[\/\\]$/.test(prefix) if (prefix.charAt(0) === '/') { prefix = path.join(this.root, prefix) } else { prefix = path.resolve(this.root, prefix) if (trail) prefix += '/' } } if (process.platform === 'win32') prefix = prefix.replace(/\\/g, '/') // Mark this as a match this._emitMatch(index, prefix) } // Returns either 'DIR', 'FILE', or false GlobSync.prototype._stat = function (f) { var abs = this._makeAbs(f) var needDir = f.slice(-1) === '/' if (f.length > this.maxLength) return false if (!this.stat && ownProp(this.cache, abs)) { var c = this.cache[abs] if (Array.isArray(c)) c = 'DIR' // It exists, but maybe not how we need it if (!needDir || c === 'DIR') return c if (needDir && c === 'FILE') return false // otherwise we have to stat, because maybe c=true // if we know it exists, but not what it is. } var exists var stat = this.statCache[abs] if (!stat) { var lstat try { lstat = this.fs.lstatSync(abs) } catch (er) { if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { this.statCache[abs] = false return false } } if (lstat && lstat.isSymbolicLink()) { try { stat = this.fs.statSync(abs) } catch (er) { stat = lstat } } else { stat = lstat } } this.statCache[abs] = stat var c = true if (stat) c = stat.isDirectory() ? 'DIR' : 'FILE' this.cache[abs] = this.cache[abs] || c if (needDir && c === 'FILE') return false return c } GlobSync.prototype._mark = function (p) { return common.mark(this, p) } GlobSync.prototype._makeAbs = function (f) { return common.makeAbs(this, f) } /***/ }), /***/ 26457: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const types_1 = __nccwpck_require__(64597); function createRejection(error, ...beforeErrorGroups) { const promise = (async () => { if (error instanceof types_1.RequestError) { try { for (const hooks of beforeErrorGroups) { if (hooks) { for (const hook of hooks) { // eslint-disable-next-line no-await-in-loop error = await hook(error); } } } } catch (error_) { error = error_; } } throw error; })(); const returnPromise = () => promise; promise.json = returnPromise; promise.text = returnPromise; promise.buffer = returnPromise; promise.on = returnPromise; return promise; } exports["default"] = createRejection; /***/ }), /***/ 36056: /***/ (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; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __exportStar = (this && this.__exportStar) || function(m, exports) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); }; Object.defineProperty(exports, "__esModule", ({ value: true })); const events_1 = __nccwpck_require__(82361); const is_1 = __nccwpck_require__(68977); const PCancelable = __nccwpck_require__(19072); const types_1 = __nccwpck_require__(64597); const parse_body_1 = __nccwpck_require__(88220); const core_1 = __nccwpck_require__(60094); const proxy_events_1 = __nccwpck_require__(53021); const get_buffer_1 = __nccwpck_require__(34500); const is_response_ok_1 = __nccwpck_require__(49298); const proxiedRequestEvents = [ 'request', 'response', 'redirect', 'uploadProgress', 'downloadProgress' ]; function asPromise(normalizedOptions) { let globalRequest; let globalResponse; const emitter = new events_1.EventEmitter(); const promise = new PCancelable((resolve, reject, onCancel) => { const makeRequest = (retryCount) => { const request = new core_1.default(undefined, normalizedOptions); request.retryCount = retryCount; request._noPipe = true; onCancel(() => request.destroy()); onCancel.shouldReject = false; onCancel(() => reject(new types_1.CancelError(request))); globalRequest = request; request.once('response', async (response) => { var _a; response.retryCount = retryCount; if (response.request.aborted) { // Canceled while downloading - will throw a `CancelError` or `TimeoutError` error return; } // Download body let rawBody; try { rawBody = await get_buffer_1.default(request); response.rawBody = rawBody; } catch (_b) { // The same error is caught below. // See request.once('error') return; } if (request._isAboutToError) { return; } // Parse body const contentEncoding = ((_a = response.headers['content-encoding']) !== null && _a !== void 0 ? _a : '').toLowerCase(); const isCompressed = ['gzip', 'deflate', 'br'].includes(contentEncoding); const { options } = request; if (isCompressed && !options.decompress) { response.body = rawBody; } else { try { response.body = parse_body_1.default(response, options.responseType, options.parseJson, options.encoding); } catch (error) { // Fallback to `utf8` response.body = rawBody.toString(); if (is_response_ok_1.isResponseOk(response)) { request._beforeError(error); return; } } } try { for (const [index, hook] of options.hooks.afterResponse.entries()) { // @ts-expect-error TS doesn't notice that CancelableRequest is a Promise // eslint-disable-next-line no-await-in-loop response = await hook(response, async (updatedOptions) => { const typedOptions = core_1.default.normalizeArguments(undefined, { ...updatedOptions, retry: { calculateDelay: () => 0 }, throwHttpErrors: false, resolveBodyOnly: false }, options); // Remove any further hooks for that request, because we'll call them anyway. // The loop continues. We don't want duplicates (asPromise recursion). typedOptions.hooks.afterResponse = typedOptions.hooks.afterResponse.slice(0, index); for (const hook of typedOptions.hooks.beforeRetry) { // eslint-disable-next-line no-await-in-loop await hook(typedOptions); } const promise = asPromise(typedOptions); onCancel(() => { promise.catch(() => { }); promise.cancel(); }); return promise; }); } } catch (error) { request._beforeError(new types_1.RequestError(error.message, error, request)); return; } globalResponse = response; if (!is_response_ok_1.isResponseOk(response)) { request._beforeError(new types_1.HTTPError(response)); return; } request.destroy(); resolve(request.options.resolveBodyOnly ? response.body : response); }); const onError = (error) => { if (promise.isCanceled) { return; } const { options } = request; if (error instanceof types_1.HTTPError && !options.throwHttpErrors) { const { response } = error; resolve(request.options.resolveBodyOnly ? response.body : response); return; } reject(error); }; request.once('error', onError); const previousBody = request.options.body; request.once('retry', (newRetryCount, error) => { var _a, _b; if (previousBody === ((_a = error.request) === null || _a === void 0 ? void 0 : _a.options.body) && is_1.default.nodeStream((_b = error.request) === null || _b === void 0 ? void 0 : _b.options.body)) { onError(error); return; } makeRequest(newRetryCount); }); proxy_events_1.default(request, emitter, proxiedRequestEvents); }; makeRequest(0); }); promise.on = (event, fn) => { emitter.on(event, fn); return promise; }; const shortcut = (responseType) => { const newPromise = (async () => { // Wait until downloading has ended await promise; const { options } = globalResponse.request; return parse_body_1.default(globalResponse, responseType, options.parseJson, options.encoding); })(); Object.defineProperties(newPromise, Object.getOwnPropertyDescriptors(promise)); return newPromise; }; promise.json = () => { const { headers } = globalRequest.options; if (!globalRequest.writableFinished && headers.accept === undefined) { headers.accept = 'application/json'; } return shortcut('json'); }; promise.buffer = () => shortcut('buffer'); promise.text = () => shortcut('text'); return promise; } exports["default"] = asPromise; __exportStar(__nccwpck_require__(64597), exports); /***/ }), /***/ 41048: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const is_1 = __nccwpck_require__(68977); const normalizeArguments = (options, defaults) => { if (is_1.default.null_(options.encoding)) { throw new TypeError('To get a Buffer, set `options.responseType` to `buffer` instead'); } is_1.assert.any([is_1.default.string, is_1.default.undefined], options.encoding); is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.resolveBodyOnly); is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.methodRewriting); is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.isStream); is_1.assert.any([is_1.default.string, is_1.default.undefined], options.responseType); // `options.responseType` if (options.responseType === undefined) { options.responseType = 'text'; } // `options.retry` const { retry } = options; if (defaults) { options.retry = { ...defaults.retry }; } else { options.retry = { calculateDelay: retryObject => retryObject.computedValue, limit: 0, methods: [], statusCodes: [], errorCodes: [], maxRetryAfter: undefined }; } if (is_1.default.object(retry)) { options.retry = { ...options.retry, ...retry }; options.retry.methods = [...new Set(options.retry.methods.map(method => method.toUpperCase()))]; options.retry.statusCodes = [...new Set(options.retry.statusCodes)]; options.retry.errorCodes = [...new Set(options.retry.errorCodes)]; } else if (is_1.default.number(retry)) { options.retry.limit = retry; } if (is_1.default.undefined(options.retry.maxRetryAfter)) { options.retry.maxRetryAfter = Math.min( // TypeScript is not smart enough to handle `.filter(x => is.number(x))`. // eslint-disable-next-line unicorn/no-fn-reference-in-iterator ...[options.timeout.request, options.timeout.connect].filter(is_1.default.number)); } // `options.pagination` if (is_1.default.object(options.pagination)) { if (defaults) { options.pagination = { ...defaults.pagination, ...options.pagination }; } const { pagination } = options; if (!is_1.default.function_(pagination.transform)) { throw new Error('`options.pagination.transform` must be implemented'); } if (!is_1.default.function_(pagination.shouldContinue)) { throw new Error('`options.pagination.shouldContinue` must be implemented'); } if (!is_1.default.function_(pagination.filter)) { throw new TypeError('`options.pagination.filter` must be implemented'); } if (!is_1.default.function_(pagination.paginate)) { throw new Error('`options.pagination.paginate` must be implemented'); } } // JSON mode if (options.responseType === 'json' && options.headers.accept === undefined) { options.headers.accept = 'application/json'; } return options; }; exports["default"] = normalizeArguments; /***/ }), /***/ 88220: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const types_1 = __nccwpck_require__(64597); const parseBody = (response, responseType, parseJson, encoding) => { const { rawBody } = response; try { if (responseType === 'text') { return rawBody.toString(encoding); } if (responseType === 'json') { return rawBody.length === 0 ? '' : parseJson(rawBody.toString()); } if (responseType === 'buffer') { return rawBody; } throw new types_1.ParseError({ message: `Unknown body type '${responseType}'`, name: 'Error' }, response); } catch (error) { throw new types_1.ParseError(error, response); } }; exports["default"] = parseBody; /***/ }), /***/ 64597: /***/ (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; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __exportStar = (this && this.__exportStar) || function(m, exports) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CancelError = exports.ParseError = void 0; const core_1 = __nccwpck_require__(60094); /** An error to be thrown when server response code is 2xx, and parsing body fails. Includes a `response` property. */ class ParseError extends core_1.RequestError { constructor(error, response) { const { options } = response.request; super(`${error.message} in "${options.url.toString()}"`, error, response.request); this.name = 'ParseError'; this.code = this.code === 'ERR_GOT_REQUEST_ERROR' ? 'ERR_BODY_PARSE_FAILURE' : this.code; } } exports.ParseError = ParseError; /** An error to be thrown when the request is aborted with `.cancel()`. */ class CancelError extends core_1.RequestError { constructor(request) { super('Promise was canceled', {}, request); this.name = 'CancelError'; this.code = 'ERR_CANCELED'; } get isCanceled() { return true; } } exports.CancelError = CancelError; __exportStar(__nccwpck_require__(60094), exports); /***/ }), /***/ 93462: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.retryAfterStatusCodes = void 0; exports.retryAfterStatusCodes = new Set([413, 429, 503]); const calculateRetryDelay = ({ attemptCount, retryOptions, error, retryAfter }) => { if (attemptCount > retryOptions.limit) { return 0; } const hasMethod = retryOptions.methods.includes(error.options.method); const hasErrorCode = retryOptions.errorCodes.includes(error.code); const hasStatusCode = error.response && retryOptions.statusCodes.includes(error.response.statusCode); if (!hasMethod || (!hasErrorCode && !hasStatusCode)) { return 0; } if (error.response) { if (retryAfter) { if (retryOptions.maxRetryAfter === undefined || retryAfter > retryOptions.maxRetryAfter) { return 0; } return retryAfter; } if (error.response.statusCode === 413) { return 0; } } const noise = Math.random() * 100; return ((2 ** (attemptCount - 1)) * 1000) + noise; }; exports["default"] = calculateRetryDelay; /***/ }), /***/ 60094: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.UnsupportedProtocolError = exports.ReadError = exports.TimeoutError = exports.UploadError = exports.CacheError = exports.HTTPError = exports.MaxRedirectsError = exports.RequestError = exports.setNonEnumerableProperties = exports.knownHookEvents = exports.withoutBody = exports.kIsNormalizedAlready = void 0; const util_1 = __nccwpck_require__(73837); const stream_1 = __nccwpck_require__(12781); const fs_1 = __nccwpck_require__(57147); const url_1 = __nccwpck_require__(57310); const http = __nccwpck_require__(13685); const http_1 = __nccwpck_require__(13685); const https = __nccwpck_require__(95687); const http_timer_1 = __nccwpck_require__(76234); const cacheable_lookup_1 = __nccwpck_require__(2286); const CacheableRequest = __nccwpck_require__(69016); const decompressResponse = __nccwpck_require__(22490); // @ts-expect-error Missing types const http2wrapper = __nccwpck_require__(54645); const lowercaseKeys = __nccwpck_require__(9662); const is_1 = __nccwpck_require__(68977); const get_body_size_1 = __nccwpck_require__(94564); const is_form_data_1 = __nccwpck_require__(90040); const proxy_events_1 = __nccwpck_require__(53021); const timed_out_1 = __nccwpck_require__(52454); const url_to_options_1 = __nccwpck_require__(8026); const options_to_url_1 = __nccwpck_require__(9219); const weakable_map_1 = __nccwpck_require__(7288); const get_buffer_1 = __nccwpck_require__(34500); const dns_ip_version_1 = __nccwpck_require__(94993); const is_response_ok_1 = __nccwpck_require__(49298); const deprecation_warning_1 = __nccwpck_require__(397); const normalize_arguments_1 = __nccwpck_require__(41048); const calculate_retry_delay_1 = __nccwpck_require__(93462); let globalDnsCache; const kRequest = Symbol('request'); const kResponse = Symbol('response'); const kResponseSize = Symbol('responseSize'); const kDownloadedSize = Symbol('downloadedSize'); const kBodySize = Symbol('bodySize'); const kUploadedSize = Symbol('uploadedSize'); const kServerResponsesPiped = Symbol('serverResponsesPiped'); const kUnproxyEvents = Symbol('unproxyEvents'); const kIsFromCache = Symbol('isFromCache'); const kCancelTimeouts = Symbol('cancelTimeouts'); const kStartedReading = Symbol('startedReading'); const kStopReading = Symbol('stopReading'); const kTriggerRead = Symbol('triggerRead'); const kBody = Symbol('body'); const kJobs = Symbol('jobs'); const kOriginalResponse = Symbol('originalResponse'); const kRetryTimeout = Symbol('retryTimeout'); exports.kIsNormalizedAlready = Symbol('isNormalizedAlready'); const supportsBrotli = is_1.default.string(process.versions.brotli); exports.withoutBody = new Set(['GET', 'HEAD']); exports.knownHookEvents = [ 'init', 'beforeRequest', 'beforeRedirect', 'beforeError', 'beforeRetry', // Promise-Only 'afterResponse' ]; function validateSearchParameters(searchParameters) { // eslint-disable-next-line guard-for-in for (const key in searchParameters) { const value = searchParameters[key]; if (!is_1.default.string(value) && !is_1.default.number(value) && !is_1.default.boolean(value) && !is_1.default.null_(value) && !is_1.default.undefined(value)) { throw new TypeError(`The \`searchParams\` value '${String(value)}' must be a string, number, boolean or null`); } } } function isClientRequest(clientRequest) { return is_1.default.object(clientRequest) && !('statusCode' in clientRequest); } const cacheableStore = new weakable_map_1.default(); const waitForOpenFile = async (file) => new Promise((resolve, reject) => { const onError = (error) => { reject(error); }; // Node.js 12 has incomplete types if (!file.pending) { resolve(); } file.once('error', onError); file.once('ready', () => { file.off('error', onError); resolve(); }); }); const redirectCodes = new Set([300, 301, 302, 303, 304, 307, 308]); const nonEnumerableProperties = [ 'context', 'body', 'json', 'form' ]; exports.setNonEnumerableProperties = (sources, to) => { // Non enumerable properties shall not be merged const properties = {}; for (const source of sources) { if (!source) { continue; } for (const name of nonEnumerableProperties) { if (!(name in source)) { continue; } properties[name] = { writable: true, configurable: true, enumerable: false, // @ts-expect-error TS doesn't see the check above value: source[name] }; } } Object.defineProperties(to, properties); }; /** An error to be thrown when a request fails. Contains a `code` property with error class code, like `ECONNREFUSED`. */ class RequestError extends Error { constructor(message, error, self) { var _a, _b; super(message); Error.captureStackTrace(this, this.constructor); this.name = 'RequestError'; this.code = (_a = error.code) !== null && _a !== void 0 ? _a : 'ERR_GOT_REQUEST_ERROR'; if (self instanceof Request) { Object.defineProperty(this, 'request', { enumerable: false, value: self }); Object.defineProperty(this, 'response', { enumerable: false, value: self[kResponse] }); Object.defineProperty(this, 'options', { // This fails because of TS 3.7.2 useDefineForClassFields // Ref: https://github.com/microsoft/TypeScript/issues/34972 enumerable: false, value: self.options }); } else { Object.defineProperty(this, 'options', { // This fails because of TS 3.7.2 useDefineForClassFields // Ref: https://github.com/microsoft/TypeScript/issues/34972 enumerable: false, value: self }); } this.timings = (_b = this.request) === null || _b === void 0 ? void 0 : _b.timings; // Recover the original stacktrace if (is_1.default.string(error.stack) && is_1.default.string(this.stack)) { const indexOfMessage = this.stack.indexOf(this.message) + this.message.length; const thisStackTrace = this.stack.slice(indexOfMessage).split('\n').reverse(); const errorStackTrace = error.stack.slice(error.stack.indexOf(error.message) + error.message.length).split('\n').reverse(); // Remove duplicated traces while (errorStackTrace.length !== 0 && errorStackTrace[0] === thisStackTrace[0]) { thisStackTrace.shift(); } this.stack = `${this.stack.slice(0, indexOfMessage)}${thisStackTrace.reverse().join('\n')}${errorStackTrace.reverse().join('\n')}`; } } } exports.RequestError = RequestError; /** An error to be thrown when the server redirects you more than ten times. Includes a `response` property. */ class MaxRedirectsError extends RequestError { constructor(request) { super(`Redirected ${request.options.maxRedirects} times. Aborting.`, {}, request); this.name = 'MaxRedirectsError'; this.code = 'ERR_TOO_MANY_REDIRECTS'; } } exports.MaxRedirectsError = MaxRedirectsError; /** An error to be thrown when the server response code is not 2xx nor 3xx if `options.followRedirect` is `true`, but always except for 304. Includes a `response` property. */ class HTTPError extends RequestError { constructor(response) { super(`Response code ${response.statusCode} (${response.statusMessage})`, {}, response.request); this.name = 'HTTPError'; this.code = 'ERR_NON_2XX_3XX_RESPONSE'; } } exports.HTTPError = HTTPError; /** An error to be thrown when a cache method fails. For example, if the database goes down or there's a filesystem error. */ class CacheError extends RequestError { constructor(error, request) { super(error.message, error, request); this.name = 'CacheError'; this.code = this.code === 'ERR_GOT_REQUEST_ERROR' ? 'ERR_CACHE_ACCESS' : this.code; } } exports.CacheError = CacheError; /** An error to be thrown when the request body is a stream and an error occurs while reading from that stream. */ class UploadError extends RequestError { constructor(error, request) { super(error.message, error, request); this.name = 'UploadError'; this.code = this.code === 'ERR_GOT_REQUEST_ERROR' ? 'ERR_UPLOAD' : this.code; } } exports.UploadError = UploadError; /** An error to be thrown when the request is aborted due to a timeout. Includes an `event` and `timings` property. */ class TimeoutError extends RequestError { constructor(error, timings, request) { super(error.message, error, request); this.name = 'TimeoutError'; this.event = error.event; this.timings = timings; } } exports.TimeoutError = TimeoutError; /** An error to be thrown when reading from response stream fails. */ class ReadError extends RequestError { constructor(error, request) { super(error.message, error, request); this.name = 'ReadError'; this.code = this.code === 'ERR_GOT_REQUEST_ERROR' ? 'ERR_READING_RESPONSE_STREAM' : this.code; } } exports.ReadError = ReadError; /** An error to be thrown when given an unsupported protocol. */ class UnsupportedProtocolError extends RequestError { constructor(options) { super(`Unsupported protocol "${options.url.protocol}"`, {}, options); this.name = 'UnsupportedProtocolError'; this.code = 'ERR_UNSUPPORTED_PROTOCOL'; } } exports.UnsupportedProtocolError = UnsupportedProtocolError; const proxiedRequestEvents = [ 'socket', 'connect', 'continue', 'information', 'upgrade', 'timeout' ]; class Request extends stream_1.Duplex { constructor(url, options = {}, defaults) { super({ // This must be false, to enable throwing after destroy // It is used for retry logic in Promise API autoDestroy: false, // It needs to be zero because we're just proxying the data to another stream highWaterMark: 0 }); this[kDownloadedSize] = 0; this[kUploadedSize] = 0; this.requestInitialized = false; this[kServerResponsesPiped] = new Set(); this.redirects = []; this[kStopReading] = false; this[kTriggerRead] = false; this[kJobs] = []; this.retryCount = 0; // TODO: Remove this when targeting Node.js >= 12 this._progressCallbacks = []; const unlockWrite = () => this._unlockWrite(); const lockWrite = () => this._lockWrite(); this.on('pipe', (source) => { source.prependListener('data', unlockWrite); source.on('data', lockWrite); source.prependListener('end', unlockWrite); source.on('end', lockWrite); }); this.on('unpipe', (source) => { source.off('data', unlockWrite); source.off('data', lockWrite); source.off('end', unlockWrite); source.off('end', lockWrite); }); this.on('pipe', source => { if (source instanceof http_1.IncomingMessage) { this.options.headers = { ...source.headers, ...this.options.headers }; } }); const { json, body, form } = options; if (json || body || form) { this._lockWrite(); } if (exports.kIsNormalizedAlready in options) { this.options = options; } else { try { // @ts-expect-error Common TypeScript bug saying that `this.constructor` is not accessible this.options = this.constructor.normalizeArguments(url, options, defaults); } catch (error) { // TODO: Move this to `_destroy()` if (is_1.default.nodeStream(options.body)) { options.body.destroy(); } this.destroy(error); return; } } (async () => { var _a; try { if (this.options.body instanceof fs_1.ReadStream) { await waitForOpenFile(this.options.body); } const { url: normalizedURL } = this.options; if (!normalizedURL) { throw new TypeError('Missing `url` property'); } this.requestUrl = normalizedURL.toString(); decodeURI(this.requestUrl); await this._finalizeBody(); await this._makeRequest(); if (this.destroyed) { (_a = this[kRequest]) === null || _a === void 0 ? void 0 : _a.destroy(); return; } // Queued writes etc. for (const job of this[kJobs]) { job(); } // Prevent memory leak this[kJobs].length = 0; this.requestInitialized = true; } catch (error) { if (error instanceof RequestError) { this._beforeError(error); return; } // This is a workaround for https://github.com/nodejs/node/issues/33335 if (!this.destroyed) { this.destroy(error); } } })(); } static normalizeArguments(url, options, defaults) { var _a, _b, _c, _d, _e; const rawOptions = options; if (is_1.default.object(url) && !is_1.default.urlInstance(url)) { options = { ...defaults, ...url, ...options }; } else { if (url && options && options.url !== undefined) { throw new TypeError('The `url` option is mutually exclusive with the `input` argument'); } options = { ...defaults, ...options }; if (url !== undefined) { options.url = url; } if (is_1.default.urlInstance(options.url)) { options.url = new url_1.URL(options.url.toString()); } } // TODO: Deprecate URL options in Got 12. // Support extend-specific options if (options.cache === false) { options.cache = undefined; } if (options.dnsCache === false) { options.dnsCache = undefined; } // Nice type assertions is_1.assert.any([is_1.default.string, is_1.default.undefined], options.method); is_1.assert.any([is_1.default.object, is_1.default.undefined], options.headers); is_1.assert.any([is_1.default.string, is_1.default.urlInstance, is_1.default.undefined], options.prefixUrl); is_1.assert.any([is_1.default.object, is_1.default.undefined], options.cookieJar); is_1.assert.any([is_1.default.object, is_1.default.string, is_1.default.undefined], options.searchParams); is_1.assert.any([is_1.default.object, is_1.default.string, is_1.default.undefined], options.cache); is_1.assert.any([is_1.default.object, is_1.default.number, is_1.default.undefined], options.timeout); is_1.assert.any([is_1.default.object, is_1.default.undefined], options.context); is_1.assert.any([is_1.default.object, is_1.default.undefined], options.hooks); is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.decompress); is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.ignoreInvalidCookies); is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.followRedirect); is_1.assert.any([is_1.default.number, is_1.default.undefined], options.maxRedirects); is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.throwHttpErrors); is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.http2); is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.allowGetBody); is_1.assert.any([is_1.default.string, is_1.default.undefined], options.localAddress); is_1.assert.any([dns_ip_version_1.isDnsLookupIpVersion, is_1.default.undefined], options.dnsLookupIpVersion); is_1.assert.any([is_1.default.object, is_1.default.undefined], options.https); is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.rejectUnauthorized); if (options.https) { is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.https.rejectUnauthorized); is_1.assert.any([is_1.default.function_, is_1.default.undefined], options.https.checkServerIdentity); is_1.assert.any([is_1.default.string, is_1.default.object, is_1.default.array, is_1.default.undefined], options.https.certificateAuthority); is_1.assert.any([is_1.default.string, is_1.default.object, is_1.default.array, is_1.default.undefined], options.https.key); is_1.assert.any([is_1.default.string, is_1.default.object, is_1.default.array, is_1.default.undefined], options.https.certificate); is_1.assert.any([is_1.default.string, is_1.default.undefined], options.https.passphrase); is_1.assert.any([is_1.default.string, is_1.default.buffer, is_1.default.array, is_1.default.undefined], options.https.pfx); } is_1.assert.any([is_1.default.object, is_1.default.undefined], options.cacheOptions); // `options.method` if (is_1.default.string(options.method)) { options.method = options.method.toUpperCase(); } else { options.method = 'GET'; } // `options.headers` if (options.headers === (defaults === null || defaults === void 0 ? void 0 : defaults.headers)) { options.headers = { ...options.headers }; } else { options.headers = lowercaseKeys({ ...(defaults === null || defaults === void 0 ? void 0 : defaults.headers), ...options.headers }); } // Disallow legacy `url.Url` if ('slashes' in options) { throw new TypeError('The legacy `url.Url` has been deprecated. Use `URL` instead.'); } // `options.auth` if ('auth' in options) { throw new TypeError('Parameter `auth` is deprecated. Use `username` / `password` instead.'); } // `options.searchParams` if ('searchParams' in options) { if (options.searchParams && options.searchParams !== (defaults === null || defaults === void 0 ? void 0 : defaults.searchParams)) { let searchParameters; if (is_1.default.string(options.searchParams) || (options.searchParams instanceof url_1.URLSearchParams)) { searchParameters = new url_1.URLSearchParams(options.searchParams); } else { validateSearchParameters(options.searchParams); searchParameters = new url_1.URLSearchParams(); // eslint-disable-next-line guard-for-in for (const key in options.searchParams) { const value = options.searchParams[key]; if (value === null) { searchParameters.append(key, ''); } else if (value !== undefined) { searchParameters.append(key, value); } } } // `normalizeArguments()` is also used to merge options (_a = defaults === null || defaults === void 0 ? void 0 : defaults.searchParams) === null || _a === void 0 ? void 0 : _a.forEach((value, key) => { // Only use default if one isn't already defined if (!searchParameters.has(key)) { searchParameters.append(key, value); } }); options.searchParams = searchParameters; } } // `options.username` & `options.password` options.username = (_b = options.username) !== null && _b !== void 0 ? _b : ''; options.password = (_c = options.password) !== null && _c !== void 0 ? _c : ''; // `options.prefixUrl` & `options.url` if (is_1.default.undefined(options.prefixUrl)) { options.prefixUrl = (_d = defaults === null || defaults === void 0 ? void 0 : defaults.prefixUrl) !== null && _d !== void 0 ? _d : ''; } else { options.prefixUrl = options.prefixUrl.toString(); if (options.prefixUrl !== '' && !options.prefixUrl.endsWith('/')) { options.prefixUrl += '/'; } } if (is_1.default.string(options.url)) { if (options.url.startsWith('/')) { throw new Error('`input` must not start with a slash when using `prefixUrl`'); } options.url = options_to_url_1.default(options.prefixUrl + options.url, options); } else if ((is_1.default.undefined(options.url) && options.prefixUrl !== '') || options.protocol) { options.url = options_to_url_1.default(options.prefixUrl, options); } if (options.url) { if ('port' in options) { delete options.port; } // Make it possible to change `options.prefixUrl` let { prefixUrl } = options; Object.defineProperty(options, 'prefixUrl', { set: (value) => { const url = options.url; if (!url.href.startsWith(value)) { throw new Error(`Cannot change \`prefixUrl\` from ${prefixUrl} to ${value}: ${url.href}`); } options.url = new url_1.URL(value + url.href.slice(prefixUrl.length)); prefixUrl = value; }, get: () => prefixUrl }); // Support UNIX sockets let { protocol } = options.url; if (protocol === 'unix:') { protocol = 'http:'; options.url = new url_1.URL(`http://unix${options.url.pathname}${options.url.search}`); } // Set search params if (options.searchParams) { // eslint-disable-next-line @typescript-eslint/no-base-to-string options.url.search = options.searchParams.toString(); } // Protocol check if (protocol !== 'http:' && protocol !== 'https:') { throw new UnsupportedProtocolError(options); } // Update `username` if (options.username === '') { options.username = options.url.username; } else { options.url.username = options.username; } // Update `password` if (options.password === '') { options.password = options.url.password; } else { options.url.password = options.password; } } // `options.cookieJar` const { cookieJar } = options; if (cookieJar) { let { setCookie, getCookieString } = cookieJar; is_1.assert.function_(setCookie); is_1.assert.function_(getCookieString); /* istanbul ignore next: Horrible `tough-cookie` v3 check */ if (setCookie.length === 4 && getCookieString.length === 0) { setCookie = util_1.promisify(setCookie.bind(options.cookieJar)); getCookieString = util_1.promisify(getCookieString.bind(options.cookieJar)); options.cookieJar = { setCookie, getCookieString: getCookieString }; } } // `options.cache` const { cache } = options; if (cache) { if (!cacheableStore.has(cache)) { cacheableStore.set(cache, new CacheableRequest(((requestOptions, handler) => { const result = requestOptions[kRequest](requestOptions, handler); // TODO: remove this when `cacheable-request` supports async request functions. if (is_1.default.promise(result)) { // @ts-expect-error // We only need to implement the error handler in order to support HTTP2 caching. // The result will be a promise anyway. result.once = (event, handler) => { if (event === 'error') { result.catch(handler); } else if (event === 'abort') { // The empty catch is needed here in case when // it rejects before it's `await`ed in `_makeRequest`. (async () => { try { const request = (await result); request.once('abort', handler); } catch (_a) { } })(); } else { /* istanbul ignore next: safety check */ throw new Error(`Unknown HTTP2 promise event: ${event}`); } return result; }; } return result; }), cache)); } } // `options.cacheOptions` options.cacheOptions = { ...options.cacheOptions }; // `options.dnsCache` if (options.dnsCache === true) { if (!globalDnsCache) { globalDnsCache = new cacheable_lookup_1.default(); } options.dnsCache = globalDnsCache; } else if (!is_1.default.undefined(options.dnsCache) && !options.dnsCache.lookup) { throw new TypeError(`Parameter \`dnsCache\` must be a CacheableLookup instance or a boolean, got ${is_1.default(options.dnsCache)}`); } // `options.timeout` if (is_1.default.number(options.timeout)) { options.timeout = { request: options.timeout }; } else if (defaults && options.timeout !== defaults.timeout) { options.timeout = { ...defaults.timeout, ...options.timeout }; } else { options.timeout = { ...options.timeout }; } // `options.context` if (!options.context) { options.context = {}; } // `options.hooks` const areHooksDefault = options.hooks === (defaults === null || defaults === void 0 ? void 0 : defaults.hooks); options.hooks = { ...options.hooks }; for (const event of exports.knownHookEvents) { if (event in options.hooks) { if (is_1.default.array(options.hooks[event])) { // See https://github.com/microsoft/TypeScript/issues/31445#issuecomment-576929044 options.hooks[event] = [...options.hooks[event]]; } else { throw new TypeError(`Parameter \`${event}\` must be an Array, got ${is_1.default(options.hooks[event])}`); } } else { options.hooks[event] = []; } } if (defaults && !areHooksDefault) { for (const event of exports.knownHookEvents) { const defaultHooks = defaults.hooks[event]; if (defaultHooks.length > 0) { // See https://github.com/microsoft/TypeScript/issues/31445#issuecomment-576929044 options.hooks[event] = [ ...defaults.hooks[event], ...options.hooks[event] ]; } } } // DNS options if ('family' in options) { deprecation_warning_1.default('"options.family" was never documented, please use "options.dnsLookupIpVersion"'); } // HTTPS options if (defaults === null || defaults === void 0 ? void 0 : defaults.https) { options.https = { ...defaults.https, ...options.https }; } if ('rejectUnauthorized' in options) { deprecation_warning_1.default('"options.rejectUnauthorized" is now deprecated, please use "options.https.rejectUnauthorized"'); } if ('checkServerIdentity' in options) { deprecation_warning_1.default('"options.checkServerIdentity" was never documented, please use "options.https.checkServerIdentity"'); } if ('ca' in options) { deprecation_warning_1.default('"options.ca" was never documented, please use "options.https.certificateAuthority"'); } if ('key' in options) { deprecation_warning_1.default('"options.key" was never documented, please use "options.https.key"'); } if ('cert' in options) { deprecation_warning_1.default('"options.cert" was never documented, please use "options.https.certificate"'); } if ('passphrase' in options) { deprecation_warning_1.default('"options.passphrase" was never documented, please use "options.https.passphrase"'); } if ('pfx' in options) { deprecation_warning_1.default('"options.pfx" was never documented, please use "options.https.pfx"'); } // Other options if ('followRedirects' in options) { throw new TypeError('The `followRedirects` option does not exist. Use `followRedirect` instead.'); } if (options.agent) { for (const key in options.agent) { if (key !== 'http' && key !== 'https' && key !== 'http2') { throw new TypeError(`Expected the \`options.agent\` properties to be \`http\`, \`https\` or \`http2\`, got \`${key}\``); } } } options.maxRedirects = (_e = options.maxRedirects) !== null && _e !== void 0 ? _e : 0; // Set non-enumerable properties exports.setNonEnumerableProperties([defaults, rawOptions], options); return normalize_arguments_1.default(options, defaults); } _lockWrite() { const onLockedWrite = () => { throw new TypeError('The payload has been already provided'); }; this.write = onLockedWrite; this.end = onLockedWrite; } _unlockWrite() { this.write = super.write; this.end = super.end; } async _finalizeBody() { const { options } = this; const { headers } = options; const isForm = !is_1.default.undefined(options.form); const isJSON = !is_1.default.undefined(options.json); const isBody = !is_1.default.undefined(options.body); const hasPayload = isForm || isJSON || isBody; const cannotHaveBody = exports.withoutBody.has(options.method) && !(options.method === 'GET' && options.allowGetBody); this._cannotHaveBody = cannotHaveBody; if (hasPayload) { if (cannotHaveBody) { throw new TypeError(`The \`${options.method}\` method cannot be used with a body`); } if ([isBody, isForm, isJSON].filter(isTrue => isTrue).length > 1) { throw new TypeError('The `body`, `json` and `form` options are mutually exclusive'); } if (isBody && !(options.body instanceof stream_1.Readable) && !is_1.default.string(options.body) && !is_1.default.buffer(options.body) && !is_form_data_1.default(options.body)) { throw new TypeError('The `body` option must be a stream.Readable, string or Buffer'); } if (isForm && !is_1.default.object(options.form)) { throw new TypeError('The `form` option must be an Object'); } { // Serialize body const noContentType = !is_1.default.string(headers['content-type']); if (isBody) { // Special case for https://github.com/form-data/form-data if (is_form_data_1.default(options.body) && noContentType) { headers['content-type'] = `multipart/form-data; boundary=${options.body.getBoundary()}`; } this[kBody] = options.body; } else if (isForm) { if (noContentType) { headers['content-type'] = 'application/x-www-form-urlencoded'; } this[kBody] = (new url_1.URLSearchParams(options.form)).toString(); } else { if (noContentType) { headers['content-type'] = 'application/json'; } this[kBody] = options.stringifyJson(options.json); } const uploadBodySize = await get_body_size_1.default(this[kBody], options.headers); // See https://tools.ietf.org/html/rfc7230#section-3.3.2 // A user agent SHOULD send a Content-Length in a request message when // no Transfer-Encoding is sent and the request method defines a meaning // for an enclosed payload body. For example, a Content-Length header // field is normally sent in a POST request even when the value is 0 // (indicating an empty payload body). A user agent SHOULD NOT send a // Content-Length header field when the request message does not contain // a payload body and the method semantics do not anticipate such a // body. if (is_1.default.undefined(headers['content-length']) && is_1.default.undefined(headers['transfer-encoding'])) { if (!cannotHaveBody && !is_1.default.undefined(uploadBodySize)) { headers['content-length'] = String(uploadBodySize); } } } } else if (cannotHaveBody) { this._lockWrite(); } else { this._unlockWrite(); } this[kBodySize] = Number(headers['content-length']) || undefined; } async _onResponseBase(response) { const { options } = this; const { url } = options; this[kOriginalResponse] = response; if (options.decompress) { response = decompressResponse(response); } const statusCode = response.statusCode; const typedResponse = response; typedResponse.statusMessage = typedResponse.statusMessage ? typedResponse.statusMessage : http.STATUS_CODES[statusCode]; typedResponse.url = options.url.toString(); typedResponse.requestUrl = this.requestUrl; typedResponse.redirectUrls = this.redirects; typedResponse.request = this; typedResponse.isFromCache = response.fromCache || false; typedResponse.ip = this.ip; typedResponse.retryCount = this.retryCount; this[kIsFromCache] = typedResponse.isFromCache; this[kResponseSize] = Number(response.headers['content-length']) || undefined; this[kResponse] = response; response.once('end', () => { this[kResponseSize] = this[kDownloadedSize]; this.emit('downloadProgress', this.downloadProgress); }); response.once('error', (error) => { // Force clean-up, because some packages don't do this. // TODO: Fix decompress-response response.destroy(); this._beforeError(new ReadError(error, this)); }); response.once('aborted', () => { this._beforeError(new ReadError({ name: 'Error', message: 'The server aborted pending request', code: 'ECONNRESET' }, this)); }); this.emit('downloadProgress', this.downloadProgress); const rawCookies = response.headers['set-cookie']; if (is_1.default.object(options.cookieJar) && rawCookies) { let promises = rawCookies.map(async (rawCookie) => options.cookieJar.setCookie(rawCookie, url.toString())); if (options.ignoreInvalidCookies) { promises = promises.map(async (p) => p.catch(() => { })); } try { await Promise.all(promises); } catch (error) { this._beforeError(error); return; } } if (options.followRedirect && response.headers.location && redirectCodes.has(statusCode)) { // We're being redirected, we don't care about the response. // It'd be best to abort the request, but we can't because // we would have to sacrifice the TCP connection. We don't want that. response.resume(); if (this[kRequest]) { this[kCancelTimeouts](); // eslint-disable-next-line @typescript-eslint/no-dynamic-delete delete this[kRequest]; this[kUnproxyEvents](); } const shouldBeGet = statusCode === 303 && options.method !== 'GET' && options.method !== 'HEAD'; if (shouldBeGet || !options.methodRewriting) { // Server responded with "see other", indicating that the resource exists at another location, // and the client should request it from that location via GET or HEAD. options.method = 'GET'; if ('body' in options) { delete options.body; } if ('json' in options) { delete options.json; } if ('form' in options) { delete options.form; } this[kBody] = undefined; delete options.headers['content-length']; } if (this.redirects.length >= options.maxRedirects) { this._beforeError(new MaxRedirectsError(this)); return; } try { // Do not remove. See https://github.com/sindresorhus/got/pull/214 const redirectBuffer = Buffer.from(response.headers.location, 'binary').toString(); // Handles invalid URLs. See https://github.com/sindresorhus/got/issues/604 const redirectUrl = new url_1.URL(redirectBuffer, url); const redirectString = redirectUrl.toString(); decodeURI(redirectString); // eslint-disable-next-line no-inner-declarations function isUnixSocketURL(url) { return url.protocol === 'unix:' || url.hostname === 'unix'; } if (!isUnixSocketURL(url) && isUnixSocketURL(redirectUrl)) { this._beforeError(new RequestError('Cannot redirect to UNIX socket', {}, this)); return; } // Redirecting to a different site, clear sensitive data. if (redirectUrl.hostname !== url.hostname || redirectUrl.port !== url.port) { if ('host' in options.headers) { delete options.headers.host; } if ('cookie' in options.headers) { delete options.headers.cookie; } if ('authorization' in options.headers) { delete options.headers.authorization; } if (options.username || options.password) { options.username = ''; options.password = ''; } } else { redirectUrl.username = options.username; redirectUrl.password = options.password; } this.redirects.push(redirectString); options.url = redirectUrl; for (const hook of options.hooks.beforeRedirect) { // eslint-disable-next-line no-await-in-loop await hook(options, typedResponse); } this.emit('redirect', typedResponse, options); await this._makeRequest(); } catch (error) { this._beforeError(error); return; } return; } if (options.isStream && options.throwHttpErrors && !is_response_ok_1.isResponseOk(typedResponse)) { this._beforeError(new HTTPError(typedResponse)); return; } response.on('readable', () => { if (this[kTriggerRead]) { this._read(); } }); this.on('resume', () => { response.resume(); }); this.on('pause', () => { response.pause(); }); response.once('end', () => { this.push(null); }); this.emit('response', response); for (const destination of this[kServerResponsesPiped]) { if (destination.headersSent) { continue; } // eslint-disable-next-line guard-for-in for (const key in response.headers) { const isAllowed = options.decompress ? key !== 'content-encoding' : true; const value = response.headers[key]; if (isAllowed) { destination.setHeader(key, value); } } destination.statusCode = statusCode; } } async _onResponse(response) { try { await this._onResponseBase(response); } catch (error) { /* istanbul ignore next: better safe than sorry */ this._beforeError(error); } } _onRequest(request) { const { options } = this; const { timeout, url } = options; http_timer_1.default(request); this[kCancelTimeouts] = timed_out_1.default(request, timeout, url); const responseEventName = options.cache ? 'cacheableResponse' : 'response'; request.once(responseEventName, (response) => { void this._onResponse(response); }); request.once('error', (error) => { var _a; // Force clean-up, because some packages (e.g. nock) don't do this. request.destroy(); // Node.js <= 12.18.2 mistakenly emits the response `end` first. (_a = request.res) === null || _a === void 0 ? void 0 : _a.removeAllListeners('end'); error = error instanceof timed_out_1.TimeoutError ? new TimeoutError(error, this.timings, this) : new RequestError(error.message, error, this); this._beforeError(error); }); this[kUnproxyEvents] = proxy_events_1.default(request, this, proxiedRequestEvents); this[kRequest] = request; this.emit('uploadProgress', this.uploadProgress); // Send body const body = this[kBody]; const currentRequest = this.redirects.length === 0 ? this : request; if (is_1.default.nodeStream(body)) { body.pipe(currentRequest); body.once('error', (error) => { this._beforeError(new UploadError(error, this)); }); } else { this._unlockWrite(); if (!is_1.default.undefined(body)) { this._writeRequest(body, undefined, () => { }); currentRequest.end(); this._lockWrite(); } else if (this._cannotHaveBody || this._noPipe) { currentRequest.end(); this._lockWrite(); } } this.emit('request', request); } async _createCacheableRequest(url, options) { return new Promise((resolve, reject) => { // TODO: Remove `utils/url-to-options.ts` when `cacheable-request` is fixed Object.assign(options, url_to_options_1.default(url)); // `http-cache-semantics` checks this // TODO: Fix this ignore. // @ts-expect-error delete options.url; let request; // This is ugly const cacheRequest = cacheableStore.get(options.cache)(options, async (response) => { // TODO: Fix `cacheable-response` response._readableState.autoDestroy = false; if (request) { (await request).emit('cacheableResponse', response); } resolve(response); }); // Restore options options.url = url; cacheRequest.once('error', reject); cacheRequest.once('request', async (requestOrPromise) => { request = requestOrPromise; resolve(request); }); }); } async _makeRequest() { var _a, _b, _c, _d, _e; const { options } = this; const { headers } = options; for (const key in headers) { if (is_1.default.undefined(headers[key])) { // eslint-disable-next-line @typescript-eslint/no-dynamic-delete delete headers[key]; } else if (is_1.default.null_(headers[key])) { throw new TypeError(`Use \`undefined\` instead of \`null\` to delete the \`${key}\` header`); } } if (options.decompress && is_1.default.undefined(headers['accept-encoding'])) { headers['accept-encoding'] = supportsBrotli ? 'gzip, deflate, br' : 'gzip, deflate'; } // Set cookies if (options.cookieJar) { const cookieString = await options.cookieJar.getCookieString(options.url.toString()); if (is_1.default.nonEmptyString(cookieString)) { options.headers.cookie = cookieString; } } for (const hook of options.hooks.beforeRequest) { // eslint-disable-next-line no-await-in-loop const result = await hook(options); if (!is_1.default.undefined(result)) { // @ts-expect-error Skip the type mismatch to support abstract responses options.request = () => result; break; } } if (options.body && this[kBody] !== options.body) { this[kBody] = options.body; } const { agent, request, timeout, url } = options; if (options.dnsCache && !('lookup' in options)) { options.lookup = options.dnsCache.lookup; } // UNIX sockets if (url.hostname === 'unix') { const matches = /(?.+?):(?.+)/.exec(`${url.pathname}${url.search}`); if (matches === null || matches === void 0 ? void 0 : matches.groups) { const { socketPath, path } = matches.groups; Object.assign(options, { socketPath, path, host: '' }); } } const isHttps = url.protocol === 'https:'; // Fallback function let fallbackFn; if (options.http2) { fallbackFn = http2wrapper.auto; } else { fallbackFn = isHttps ? https.request : http.request; } const realFn = (_a = options.request) !== null && _a !== void 0 ? _a : fallbackFn; // Cache support const fn = options.cache ? this._createCacheableRequest : realFn; // Pass an agent directly when HTTP2 is disabled if (agent && !options.http2) { options.agent = agent[isHttps ? 'https' : 'http']; } // Prepare plain HTTP request options options[kRequest] = realFn; delete options.request; // TODO: Fix this ignore. // @ts-expect-error delete options.timeout; const requestOptions = options; requestOptions.shared = (_b = options.cacheOptions) === null || _b === void 0 ? void 0 : _b.shared; requestOptions.cacheHeuristic = (_c = options.cacheOptions) === null || _c === void 0 ? void 0 : _c.cacheHeuristic; requestOptions.immutableMinTimeToLive = (_d = options.cacheOptions) === null || _d === void 0 ? void 0 : _d.immutableMinTimeToLive; requestOptions.ignoreCargoCult = (_e = options.cacheOptions) === null || _e === void 0 ? void 0 : _e.ignoreCargoCult; // If `dnsLookupIpVersion` is not present do not override `family` if (options.dnsLookupIpVersion !== undefined) { try { requestOptions.family = dns_ip_version_1.dnsLookupIpVersionToFamily(options.dnsLookupIpVersion); } catch (_f) { throw new Error('Invalid `dnsLookupIpVersion` option value'); } } // HTTPS options remapping if (options.https) { if ('rejectUnauthorized' in options.https) { requestOptions.rejectUnauthorized = options.https.rejectUnauthorized; } if (options.https.checkServerIdentity) { requestOptions.checkServerIdentity = options.https.checkServerIdentity; } if (options.https.certificateAuthority) { requestOptions.ca = options.https.certificateAuthority; } if (options.https.certificate) { requestOptions.cert = options.https.certificate; } if (options.https.key) { requestOptions.key = options.https.key; } if (options.https.passphrase) { requestOptions.passphrase = options.https.passphrase; } if (options.https.pfx) { requestOptions.pfx = options.https.pfx; } } try { let requestOrResponse = await fn(url, requestOptions); if (is_1.default.undefined(requestOrResponse)) { requestOrResponse = fallbackFn(url, requestOptions); } // Restore options options.request = request; options.timeout = timeout; options.agent = agent; // HTTPS options restore if (options.https) { if ('rejectUnauthorized' in options.https) { delete requestOptions.rejectUnauthorized; } if (options.https.checkServerIdentity) { // @ts-expect-error - This one will be removed when we remove the alias. delete requestOptions.checkServerIdentity; } if (options.https.certificateAuthority) { delete requestOptions.ca; } if (options.https.certificate) { delete requestOptions.cert; } if (options.https.key) { delete requestOptions.key; } if (options.https.passphrase) { delete requestOptions.passphrase; } if (options.https.pfx) { delete requestOptions.pfx; } } if (isClientRequest(requestOrResponse)) { this._onRequest(requestOrResponse); // Emit the response after the stream has been ended } else if (this.writable) { this.once('finish', () => { void this._onResponse(requestOrResponse); }); this._unlockWrite(); this.end(); this._lockWrite(); } else { void this._onResponse(requestOrResponse); } } catch (error) { if (error instanceof CacheableRequest.CacheError) { throw new CacheError(error, this); } throw new RequestError(error.message, error, this); } } async _error(error) { try { for (const hook of this.options.hooks.beforeError) { // eslint-disable-next-line no-await-in-loop error = await hook(error); } } catch (error_) { error = new RequestError(error_.message, error_, this); } this.destroy(error); } _beforeError(error) { if (this[kStopReading]) { return; } const { options } = this; const retryCount = this.retryCount + 1; this[kStopReading] = true; if (!(error instanceof RequestError)) { error = new RequestError(error.message, error, this); } const typedError = error; const { response } = typedError; void (async () => { if (response && !response.body) { response.setEncoding(this._readableState.encoding); try { response.rawBody = await get_buffer_1.default(response); response.body = response.rawBody.toString(); } catch (_a) { } } if (this.listenerCount('retry') !== 0) { let backoff; try { let retryAfter; if (response && 'retry-after' in response.headers) { retryAfter = Number(response.headers['retry-after']); if (Number.isNaN(retryAfter)) { retryAfter = Date.parse(response.headers['retry-after']) - Date.now(); if (retryAfter <= 0) { retryAfter = 1; } } else { retryAfter *= 1000; } } backoff = await options.retry.calculateDelay({ attemptCount: retryCount, retryOptions: options.retry, error: typedError, retryAfter, computedValue: calculate_retry_delay_1.default({ attemptCount: retryCount, retryOptions: options.retry, error: typedError, retryAfter, computedValue: 0 }) }); } catch (error_) { void this._error(new RequestError(error_.message, error_, this)); return; } if (backoff) { const retry = async () => { try { for (const hook of this.options.hooks.beforeRetry) { // eslint-disable-next-line no-await-in-loop await hook(this.options, typedError, retryCount); } } catch (error_) { void this._error(new RequestError(error_.message, error, this)); return; } // Something forced us to abort the retry if (this.destroyed) { return; } this.destroy(); this.emit('retry', retryCount, error); }; this[kRetryTimeout] = setTimeout(retry, backoff); return; } } void this._error(typedError); })(); } _read() { this[kTriggerRead] = true; const response = this[kResponse]; if (response && !this[kStopReading]) { // We cannot put this in the `if` above // because `.read()` also triggers the `end` event if (response.readableLength) { this[kTriggerRead] = false; } let data; while ((data = response.read()) !== null) { this[kDownloadedSize] += data.length; this[kStartedReading] = true; const progress = this.downloadProgress; if (progress.percent < 1) { this.emit('downloadProgress', progress); } this.push(data); } } } // Node.js 12 has incorrect types, so the encoding must be a string _write(chunk, encoding, callback) { const write = () => { this._writeRequest(chunk, encoding, callback); }; if (this.requestInitialized) { write(); } else { this[kJobs].push(write); } } _writeRequest(chunk, encoding, callback) { if (this[kRequest].destroyed) { // Probably the `ClientRequest` instance will throw return; } this._progressCallbacks.push(() => { this[kUploadedSize] += Buffer.byteLength(chunk, encoding); const progress = this.uploadProgress; if (progress.percent < 1) { this.emit('uploadProgress', progress); } }); // TODO: What happens if it's from cache? Then this[kRequest] won't be defined. this[kRequest].write(chunk, encoding, (error) => { if (!error && this._progressCallbacks.length > 0) { this._progressCallbacks.shift()(); } callback(error); }); } _final(callback) { const endRequest = () => { // FIX: Node.js 10 calls the write callback AFTER the end callback! while (this._progressCallbacks.length !== 0) { this._progressCallbacks.shift()(); } // We need to check if `this[kRequest]` is present, // because it isn't when we use cache. if (!(kRequest in this)) { callback(); return; } if (this[kRequest].destroyed) { callback(); return; } this[kRequest].end((error) => { if (!error) { this[kBodySize] = this[kUploadedSize]; this.emit('uploadProgress', this.uploadProgress); this[kRequest].emit('upload-complete'); } callback(error); }); }; if (this.requestInitialized) { endRequest(); } else { this[kJobs].push(endRequest); } } _destroy(error, callback) { var _a; this[kStopReading] = true; // Prevent further retries clearTimeout(this[kRetryTimeout]); if (kRequest in this) { this[kCancelTimeouts](); // TODO: Remove the next `if` when these get fixed: // - https://github.com/nodejs/node/issues/32851 if (!((_a = this[kResponse]) === null || _a === void 0 ? void 0 : _a.complete)) { this[kRequest].destroy(); } } if (error !== null && !is_1.default.undefined(error) && !(error instanceof RequestError)) { error = new RequestError(error.message, error, this); } callback(error); } get _isAboutToError() { return this[kStopReading]; } /** The remote IP address. */ get ip() { var _a; return (_a = this.socket) === null || _a === void 0 ? void 0 : _a.remoteAddress; } /** Indicates whether the request has been aborted or not. */ get aborted() { var _a, _b, _c; return ((_b = (_a = this[kRequest]) === null || _a === void 0 ? void 0 : _a.destroyed) !== null && _b !== void 0 ? _b : this.destroyed) && !((_c = this[kOriginalResponse]) === null || _c === void 0 ? void 0 : _c.complete); } get socket() { var _a, _b; return (_b = (_a = this[kRequest]) === null || _a === void 0 ? void 0 : _a.socket) !== null && _b !== void 0 ? _b : undefined; } /** Progress event for downloading (receiving a response). */ get downloadProgress() { let percent; if (this[kResponseSize]) { percent = this[kDownloadedSize] / this[kResponseSize]; } else if (this[kResponseSize] === this[kDownloadedSize]) { percent = 1; } else { percent = 0; } return { percent, transferred: this[kDownloadedSize], total: this[kResponseSize] }; } /** Progress event for uploading (sending a request). */ get uploadProgress() { let percent; if (this[kBodySize]) { percent = this[kUploadedSize] / this[kBodySize]; } else if (this[kBodySize] === this[kUploadedSize]) { percent = 1; } else { percent = 0; } return { percent, transferred: this[kUploadedSize], total: this[kBodySize] }; } /** The object contains the following properties: - `start` - Time when the request started. - `socket` - Time when a socket was assigned to the request. - `lookup` - Time when the DNS lookup finished. - `connect` - Time when the socket successfully connected. - `secureConnect` - Time when the socket securely connected. - `upload` - Time when the request finished uploading. - `response` - Time when the request fired `response` event. - `end` - Time when the response fired `end` event. - `error` - Time when the request fired `error` event. - `abort` - Time when the request fired `abort` event. - `phases` - `wait` - `timings.socket - timings.start` - `dns` - `timings.lookup - timings.socket` - `tcp` - `timings.connect - timings.lookup` - `tls` - `timings.secureConnect - timings.connect` - `request` - `timings.upload - (timings.secureConnect || timings.connect)` - `firstByte` - `timings.response - timings.upload` - `download` - `timings.end - timings.response` - `total` - `(timings.end || timings.error || timings.abort) - timings.start` If something has not been measured yet, it will be `undefined`. __Note__: The time is a `number` representing the milliseconds elapsed since the UNIX epoch. */ get timings() { var _a; return (_a = this[kRequest]) === null || _a === void 0 ? void 0 : _a.timings; } /** Whether the response was retrieved from the cache. */ get isFromCache() { return this[kIsFromCache]; } pipe(destination, options) { if (this[kStartedReading]) { throw new Error('Failed to pipe. The response has been emitted already.'); } if (destination instanceof http_1.ServerResponse) { this[kServerResponsesPiped].add(destination); } return super.pipe(destination, options); } unpipe(destination) { if (destination instanceof http_1.ServerResponse) { this[kServerResponsesPiped].delete(destination); } super.unpipe(destination); return this; } } exports["default"] = Request; /***/ }), /***/ 94993: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.dnsLookupIpVersionToFamily = exports.isDnsLookupIpVersion = void 0; const conversionTable = { auto: 0, ipv4: 4, ipv6: 6 }; exports.isDnsLookupIpVersion = (value) => { return value in conversionTable; }; exports.dnsLookupIpVersionToFamily = (dnsLookupIpVersion) => { if (exports.isDnsLookupIpVersion(dnsLookupIpVersion)) { return conversionTable[dnsLookupIpVersion]; } throw new Error('Invalid DNS lookup IP version'); }; /***/ }), /***/ 94564: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const fs_1 = __nccwpck_require__(57147); const util_1 = __nccwpck_require__(73837); const is_1 = __nccwpck_require__(68977); const is_form_data_1 = __nccwpck_require__(90040); const statAsync = util_1.promisify(fs_1.stat); exports["default"] = async (body, headers) => { if (headers && 'content-length' in headers) { return Number(headers['content-length']); } if (!body) { return 0; } if (is_1.default.string(body)) { return Buffer.byteLength(body); } if (is_1.default.buffer(body)) { return body.length; } if (is_form_data_1.default(body)) { return util_1.promisify(body.getLength.bind(body))(); } if (body instanceof fs_1.ReadStream) { const { size } = await statAsync(body.path); if (size === 0) { return undefined; } return size; } return undefined; }; /***/ }), /***/ 34500: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); // TODO: Update https://github.com/sindresorhus/get-stream const getBuffer = async (stream) => { const chunks = []; let length = 0; for await (const chunk of stream) { chunks.push(chunk); length += Buffer.byteLength(chunk); } if (Buffer.isBuffer(chunks[0])) { return Buffer.concat(chunks, length); } return Buffer.from(chunks.join('')); }; exports["default"] = getBuffer; /***/ }), /***/ 90040: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const is_1 = __nccwpck_require__(68977); exports["default"] = (body) => is_1.default.nodeStream(body) && is_1.default.function_(body.getBoundary); /***/ }), /***/ 49298: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isResponseOk = void 0; exports.isResponseOk = (response) => { const { statusCode } = response; const limitStatusCode = response.request.options.followRedirect ? 299 : 399; return (statusCode >= 200 && statusCode <= limitStatusCode) || statusCode === 304; }; /***/ }), /***/ 9219: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /* istanbul ignore file: deprecated */ const url_1 = __nccwpck_require__(57310); const keys = [ 'protocol', 'host', 'hostname', 'port', 'pathname', 'search' ]; exports["default"] = (origin, options) => { var _a, _b; if (options.path) { if (options.pathname) { throw new TypeError('Parameters `path` and `pathname` are mutually exclusive.'); } if (options.search) { throw new TypeError('Parameters `path` and `search` are mutually exclusive.'); } if (options.searchParams) { throw new TypeError('Parameters `path` and `searchParams` are mutually exclusive.'); } } if (options.search && options.searchParams) { throw new TypeError('Parameters `search` and `searchParams` are mutually exclusive.'); } if (!origin) { if (!options.protocol) { throw new TypeError('No URL protocol specified'); } origin = `${options.protocol}//${(_b = (_a = options.hostname) !== null && _a !== void 0 ? _a : options.host) !== null && _b !== void 0 ? _b : ''}`; } const url = new url_1.URL(origin); if (options.path) { const searchIndex = options.path.indexOf('?'); if (searchIndex === -1) { options.pathname = options.path; } else { options.pathname = options.path.slice(0, searchIndex); options.search = options.path.slice(searchIndex + 1); } delete options.path; } for (const key of keys) { if (options[key]) { url[key] = options[key].toString(); } } return url; }; /***/ }), /***/ 53021: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); function default_1(from, to, events) { const fns = {}; for (const event of events) { fns[event] = (...args) => { to.emit(event, ...args); }; from.on(event, fns[event]); } return () => { for (const event of events) { from.off(event, fns[event]); } }; } exports["default"] = default_1; /***/ }), /***/ 52454: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.TimeoutError = void 0; const net = __nccwpck_require__(41808); const unhandle_1 = __nccwpck_require__(81593); const reentry = Symbol('reentry'); const noop = () => { }; class TimeoutError extends Error { constructor(threshold, event) { super(`Timeout awaiting '${event}' for ${threshold}ms`); this.event = event; this.name = 'TimeoutError'; this.code = 'ETIMEDOUT'; } } exports.TimeoutError = TimeoutError; exports["default"] = (request, delays, options) => { if (reentry in request) { return noop; } request[reentry] = true; const cancelers = []; const { once, unhandleAll } = unhandle_1.default(); const addTimeout = (delay, callback, event) => { var _a; const timeout = setTimeout(callback, delay, delay, event); (_a = timeout.unref) === null || _a === void 0 ? void 0 : _a.call(timeout); const cancel = () => { clearTimeout(timeout); }; cancelers.push(cancel); return cancel; }; const { host, hostname } = options; const timeoutHandler = (delay, event) => { request.destroy(new TimeoutError(delay, event)); }; const cancelTimeouts = () => { for (const cancel of cancelers) { cancel(); } unhandleAll(); }; request.once('error', error => { cancelTimeouts(); // Save original behavior /* istanbul ignore next */ if (request.listenerCount('error') === 0) { throw error; } }); request.once('close', cancelTimeouts); once(request, 'response', (response) => { once(response, 'end', cancelTimeouts); }); if (typeof delays.request !== 'undefined') { addTimeout(delays.request, timeoutHandler, 'request'); } if (typeof delays.socket !== 'undefined') { const socketTimeoutHandler = () => { timeoutHandler(delays.socket, 'socket'); }; request.setTimeout(delays.socket, socketTimeoutHandler); // `request.setTimeout(0)` causes a memory leak. // We can just remove the listener and forget about the timer - it's unreffed. // See https://github.com/sindresorhus/got/issues/690 cancelers.push(() => { request.removeListener('timeout', socketTimeoutHandler); }); } once(request, 'socket', (socket) => { var _a; const { socketPath } = request; /* istanbul ignore next: hard to test */ if (socket.connecting) { const hasPath = Boolean(socketPath !== null && socketPath !== void 0 ? socketPath : net.isIP((_a = hostname !== null && hostname !== void 0 ? hostname : host) !== null && _a !== void 0 ? _a : '') !== 0); if (typeof delays.lookup !== 'undefined' && !hasPath && typeof socket.address().address === 'undefined') { const cancelTimeout = addTimeout(delays.lookup, timeoutHandler, 'lookup'); once(socket, 'lookup', cancelTimeout); } if (typeof delays.connect !== 'undefined') { const timeConnect = () => addTimeout(delays.connect, timeoutHandler, 'connect'); if (hasPath) { once(socket, 'connect', timeConnect()); } else { once(socket, 'lookup', (error) => { if (error === null) { once(socket, 'connect', timeConnect()); } }); } } if (typeof delays.secureConnect !== 'undefined' && options.protocol === 'https:') { once(socket, 'connect', () => { const cancelTimeout = addTimeout(delays.secureConnect, timeoutHandler, 'secureConnect'); once(socket, 'secureConnect', cancelTimeout); }); } } if (typeof delays.send !== 'undefined') { const timeRequest = () => addTimeout(delays.send, timeoutHandler, 'send'); /* istanbul ignore next: hard to test */ if (socket.connecting) { once(socket, 'connect', () => { once(request, 'upload-complete', timeRequest()); }); } else { once(request, 'upload-complete', timeRequest()); } } }); if (typeof delays.response !== 'undefined') { once(request, 'upload-complete', () => { const cancelTimeout = addTimeout(delays.response, timeoutHandler, 'response'); once(request, 'response', cancelTimeout); }); } return cancelTimeouts; }; /***/ }), /***/ 81593: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); // When attaching listeners, it's very easy to forget about them. // Especially if you do error handling and set timeouts. // So instead of checking if it's proper to throw an error on every timeout ever, // use this simple tool which will remove all listeners you have attached. exports["default"] = () => { const handlers = []; return { once(origin, event, fn) { origin.once(event, fn); handlers.push({ origin, event, fn }); }, unhandleAll() { for (const handler of handlers) { const { origin, event, fn } = handler; origin.removeListener(event, fn); } handlers.length = 0; } }; }; /***/ }), /***/ 8026: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const is_1 = __nccwpck_require__(68977); exports["default"] = (url) => { // Cast to URL url = url; const options = { protocol: url.protocol, hostname: is_1.default.string(url.hostname) && url.hostname.startsWith('[') ? url.hostname.slice(1, -1) : url.hostname, host: url.host, hash: url.hash, search: url.search, pathname: url.pathname, href: url.href, path: `${url.pathname || ''}${url.search || ''}` }; if (is_1.default.string(url.port) && url.port.length > 0) { options.port = Number(url.port); } if (url.username || url.password) { options.auth = `${url.username || ''}:${url.password || ''}`; } return options; }; /***/ }), /***/ 7288: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); class WeakableMap { constructor() { this.weakMap = new WeakMap(); this.map = new Map(); } set(key, value) { if (typeof key === 'object') { this.weakMap.set(key, value); } else { this.map.set(key, value); } } get(key) { if (typeof key === 'object') { return this.weakMap.get(key); } return this.map.get(key); } has(key) { if (typeof key === 'object') { return this.weakMap.has(key); } return this.map.has(key); } } exports["default"] = WeakableMap; /***/ }), /***/ 34337: /***/ (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; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __exportStar = (this && this.__exportStar) || function(m, exports) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.defaultHandler = void 0; const is_1 = __nccwpck_require__(68977); const as_promise_1 = __nccwpck_require__(36056); const create_rejection_1 = __nccwpck_require__(26457); const core_1 = __nccwpck_require__(60094); const deep_freeze_1 = __nccwpck_require__(70285); const errors = { RequestError: as_promise_1.RequestError, CacheError: as_promise_1.CacheError, ReadError: as_promise_1.ReadError, HTTPError: as_promise_1.HTTPError, MaxRedirectsError: as_promise_1.MaxRedirectsError, TimeoutError: as_promise_1.TimeoutError, ParseError: as_promise_1.ParseError, CancelError: as_promise_1.CancelError, UnsupportedProtocolError: as_promise_1.UnsupportedProtocolError, UploadError: as_promise_1.UploadError }; // The `delay` package weighs 10KB (!) const delay = async (ms) => new Promise(resolve => { setTimeout(resolve, ms); }); const { normalizeArguments } = core_1.default; const mergeOptions = (...sources) => { let mergedOptions; for (const source of sources) { mergedOptions = normalizeArguments(undefined, source, mergedOptions); } return mergedOptions; }; const getPromiseOrStream = (options) => options.isStream ? new core_1.default(undefined, options) : as_promise_1.default(options); const isGotInstance = (value) => ('defaults' in value && 'options' in value.defaults); const aliases = [ 'get', 'post', 'put', 'patch', 'head', 'delete' ]; exports.defaultHandler = (options, next) => next(options); const callInitHooks = (hooks, options) => { if (hooks) { for (const hook of hooks) { hook(options); } } }; const create = (defaults) => { // Proxy properties from next handlers defaults._rawHandlers = defaults.handlers; defaults.handlers = defaults.handlers.map(fn => ((options, next) => { // This will be assigned by assigning result let root; const result = fn(options, newOptions => { root = next(newOptions); return root; }); if (result !== root && !options.isStream && root) { const typedResult = result; const { then: promiseThen, catch: promiseCatch, finally: promiseFianlly } = typedResult; Object.setPrototypeOf(typedResult, Object.getPrototypeOf(root)); Object.defineProperties(typedResult, Object.getOwnPropertyDescriptors(root)); // These should point to the new promise // eslint-disable-next-line promise/prefer-await-to-then typedResult.then = promiseThen; typedResult.catch = promiseCatch; typedResult.finally = promiseFianlly; } return result; })); // Got interface const got = ((url, options = {}, _defaults) => { var _a, _b; let iteration = 0; const iterateHandlers = (newOptions) => { return defaults.handlers[iteration++](newOptions, iteration === defaults.handlers.length ? getPromiseOrStream : iterateHandlers); }; // TODO: Remove this in Got 12. if (is_1.default.plainObject(url)) { const mergedOptions = { ...url, ...options }; core_1.setNonEnumerableProperties([url, options], mergedOptions); options = mergedOptions; url = undefined; } try { // Call `init` hooks let initHookError; try { callInitHooks(defaults.options.hooks.init, options); callInitHooks((_a = options.hooks) === null || _a === void 0 ? void 0 : _a.init, options); } catch (error) { initHookError = error; } // Normalize options & call handlers const normalizedOptions = normalizeArguments(url, options, _defaults !== null && _defaults !== void 0 ? _defaults : defaults.options); normalizedOptions[core_1.kIsNormalizedAlready] = true; if (initHookError) { throw new as_promise_1.RequestError(initHookError.message, initHookError, normalizedOptions); } return iterateHandlers(normalizedOptions); } catch (error) { if (options.isStream) { throw error; } else { return create_rejection_1.default(error, defaults.options.hooks.beforeError, (_b = options.hooks) === null || _b === void 0 ? void 0 : _b.beforeError); } } }); got.extend = (...instancesOrOptions) => { const optionsArray = [defaults.options]; let handlers = [...defaults._rawHandlers]; let isMutableDefaults; for (const value of instancesOrOptions) { if (isGotInstance(value)) { optionsArray.push(value.defaults.options); handlers.push(...value.defaults._rawHandlers); isMutableDefaults = value.defaults.mutableDefaults; } else { optionsArray.push(value); if ('handlers' in value) { handlers.push(...value.handlers); } isMutableDefaults = value.mutableDefaults; } } handlers = handlers.filter(handler => handler !== exports.defaultHandler); if (handlers.length === 0) { handlers.push(exports.defaultHandler); } return create({ options: mergeOptions(...optionsArray), handlers, mutableDefaults: Boolean(isMutableDefaults) }); }; // Pagination const paginateEach = (async function* (url, options) { // TODO: Remove this `@ts-expect-error` when upgrading to TypeScript 4. // Error: Argument of type 'Merge> | undefined' is not assignable to parameter of type 'Options | undefined'. // @ts-expect-error let normalizedOptions = normalizeArguments(url, options, defaults.options); normalizedOptions.resolveBodyOnly = false; const pagination = normalizedOptions.pagination; if (!is_1.default.object(pagination)) { throw new TypeError('`options.pagination` must be implemented'); } const all = []; let { countLimit } = pagination; let numberOfRequests = 0; while (numberOfRequests < pagination.requestLimit) { if (numberOfRequests !== 0) { // eslint-disable-next-line no-await-in-loop await delay(pagination.backoff); } // @ts-expect-error FIXME! // TODO: Throw when result is not an instance of Response // eslint-disable-next-line no-await-in-loop const result = (await got(undefined, undefined, normalizedOptions)); // eslint-disable-next-line no-await-in-loop const parsed = await pagination.transform(result); const current = []; for (const item of parsed) { if (pagination.filter(item, all, current)) { if (!pagination.shouldContinue(item, all, current)) { return; } yield item; if (pagination.stackAllItems) { all.push(item); } current.push(item); if (--countLimit <= 0) { return; } } } const optionsToMerge = pagination.paginate(result, all, current); if (optionsToMerge === false) { return; } if (optionsToMerge === result.request.options) { normalizedOptions = result.request.options; } else if (optionsToMerge !== undefined) { normalizedOptions = normalizeArguments(undefined, optionsToMerge, normalizedOptions); } numberOfRequests++; } }); got.paginate = paginateEach; got.paginate.all = (async (url, options) => { const results = []; for await (const item of paginateEach(url, options)) { results.push(item); } return results; }); // For those who like very descriptive names got.paginate.each = paginateEach; // Stream API got.stream = ((url, options) => got(url, { ...options, isStream: true })); // Shortcuts for (const method of aliases) { got[method] = ((url, options) => got(url, { ...options, method })); got.stream[method] = ((url, options) => { return got(url, { ...options, method, isStream: true }); }); } Object.assign(got, errors); Object.defineProperty(got, 'defaults', { value: defaults.mutableDefaults ? defaults : deep_freeze_1.default(defaults), writable: defaults.mutableDefaults, configurable: defaults.mutableDefaults, enumerable: true }); got.mergeOptions = mergeOptions; return got; }; exports["default"] = create; __exportStar(__nccwpck_require__(72613), exports); /***/ }), /***/ 93061: /***/ (function(module, exports, __nccwpck_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __exportStar = (this && this.__exportStar) || function(m, exports) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); }; Object.defineProperty(exports, "__esModule", ({ value: true })); const url_1 = __nccwpck_require__(57310); const create_1 = __nccwpck_require__(34337); const defaults = { options: { method: 'GET', retry: { limit: 2, methods: [ 'GET', 'PUT', 'HEAD', 'DELETE', 'OPTIONS', 'TRACE' ], statusCodes: [ 408, 413, 429, 500, 502, 503, 504, 521, 522, 524 ], errorCodes: [ 'ETIMEDOUT', 'ECONNRESET', 'EADDRINUSE', 'ECONNREFUSED', 'EPIPE', 'ENOTFOUND', 'ENETUNREACH', 'EAI_AGAIN' ], maxRetryAfter: undefined, calculateDelay: ({ computedValue }) => computedValue }, timeout: {}, headers: { 'user-agent': 'got (https://github.com/sindresorhus/got)' }, hooks: { init: [], beforeRequest: [], beforeRedirect: [], beforeRetry: [], beforeError: [], afterResponse: [] }, cache: undefined, dnsCache: undefined, decompress: true, throwHttpErrors: true, followRedirect: true, isStream: false, responseType: 'text', resolveBodyOnly: false, maxRedirects: 10, prefixUrl: '', methodRewriting: true, ignoreInvalidCookies: false, context: {}, // TODO: Set this to `true` when Got 12 gets released http2: false, allowGetBody: false, https: undefined, pagination: { transform: (response) => { if (response.request.options.responseType === 'json') { return response.body; } return JSON.parse(response.body); }, paginate: response => { if (!Reflect.has(response.headers, 'link')) { return false; } const items = response.headers.link.split(','); let next; for (const item of items) { const parsed = item.split(';'); if (parsed[1].includes('next')) { next = parsed[0].trimStart().trim(); next = next.slice(1, -1); break; } } if (next) { const options = { url: new url_1.URL(next) }; return options; } return false; }, filter: () => true, shouldContinue: () => true, countLimit: Infinity, backoff: 0, requestLimit: 10000, stackAllItems: true }, parseJson: (text) => JSON.parse(text), stringifyJson: (object) => JSON.stringify(object), cacheOptions: {} }, handlers: [create_1.defaultHandler], mutableDefaults: false }; const got = create_1.default(defaults); exports["default"] = got; // For CommonJS default export support module.exports = got; module.exports["default"] = got; module.exports.__esModule = true; // Workaround for TS issue: https://github.com/sindresorhus/got/pull/1267 __exportStar(__nccwpck_require__(34337), exports); __exportStar(__nccwpck_require__(36056), exports); /***/ }), /***/ 72613: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 70285: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const is_1 = __nccwpck_require__(68977); function deepFreeze(object) { for (const value of Object.values(object)) { if (is_1.default.plainObject(value) || is_1.default.array(value)) { deepFreeze(value); } } return Object.freeze(object); } exports["default"] = deepFreeze; /***/ }), /***/ 397: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const alreadyWarned = new Set(); exports["default"] = (message) => { if (alreadyWarned.has(message)) { return; } alreadyWarned.add(message); // @ts-expect-error Missing types. process.emitWarning(`Got: ${message}`, { type: 'DeprecationWarning' }); }; /***/ }), /***/ 68977: /***/ ((module, exports) => { "use strict"; /// /// /// Object.defineProperty(exports, "__esModule", ({ value: true })); const typedArrayTypeNames = [ 'Int8Array', 'Uint8Array', 'Uint8ClampedArray', 'Int16Array', 'Uint16Array', 'Int32Array', 'Uint32Array', 'Float32Array', 'Float64Array', 'BigInt64Array', 'BigUint64Array' ]; function isTypedArrayName(name) { return typedArrayTypeNames.includes(name); } const objectTypeNames = [ 'Function', 'Generator', 'AsyncGenerator', 'GeneratorFunction', 'AsyncGeneratorFunction', 'AsyncFunction', 'Observable', 'Array', 'Buffer', 'Blob', 'Object', 'RegExp', 'Date', 'Error', 'Map', 'Set', 'WeakMap', 'WeakSet', 'ArrayBuffer', 'SharedArrayBuffer', 'DataView', 'Promise', 'URL', 'FormData', 'URLSearchParams', 'HTMLElement', ...typedArrayTypeNames ]; function isObjectTypeName(name) { return objectTypeNames.includes(name); } const primitiveTypeNames = [ 'null', 'undefined', 'string', 'number', 'bigint', 'boolean', 'symbol' ]; function isPrimitiveTypeName(name) { return primitiveTypeNames.includes(name); } // eslint-disable-next-line @typescript-eslint/ban-types function isOfType(type) { return (value) => typeof value === type; } const { toString } = Object.prototype; const getObjectType = (value) => { const objectTypeName = toString.call(value).slice(8, -1); if (/HTML\w+Element/.test(objectTypeName) && is.domElement(value)) { return 'HTMLElement'; } if (isObjectTypeName(objectTypeName)) { return objectTypeName; } return undefined; }; const isObjectOfType = (type) => (value) => getObjectType(value) === type; function is(value) { if (value === null) { return 'null'; } switch (typeof value) { case 'undefined': return 'undefined'; case 'string': return 'string'; case 'number': return 'number'; case 'boolean': return 'boolean'; case 'function': return 'Function'; case 'bigint': return 'bigint'; case 'symbol': return 'symbol'; default: } if (is.observable(value)) { return 'Observable'; } if (is.array(value)) { return 'Array'; } if (is.buffer(value)) { return 'Buffer'; } const tagType = getObjectType(value); if (tagType) { return tagType; } if (value instanceof String || value instanceof Boolean || value instanceof Number) { throw new TypeError('Please don\'t use object wrappers for primitive types'); } return 'Object'; } is.undefined = isOfType('undefined'); is.string = isOfType('string'); const isNumberType = isOfType('number'); is.number = (value) => isNumberType(value) && !is.nan(value); is.bigint = isOfType('bigint'); // eslint-disable-next-line @typescript-eslint/ban-types is.function_ = isOfType('function'); is.null_ = (value) => value === null; is.class_ = (value) => is.function_(value) && value.toString().startsWith('class '); is.boolean = (value) => value === true || value === false; is.symbol = isOfType('symbol'); is.numericString = (value) => is.string(value) && !is.emptyStringOrWhitespace(value) && !Number.isNaN(Number(value)); is.array = (value, assertion) => { if (!Array.isArray(value)) { return false; } if (!is.function_(assertion)) { return true; } return value.every(assertion); }; is.buffer = (value) => { var _a, _b, _c, _d; return (_d = (_c = (_b = (_a = value) === null || _a === void 0 ? void 0 : _a.constructor) === null || _b === void 0 ? void 0 : _b.isBuffer) === null || _c === void 0 ? void 0 : _c.call(_b, value)) !== null && _d !== void 0 ? _d : false; }; is.blob = (value) => isObjectOfType('Blob')(value); is.nullOrUndefined = (value) => is.null_(value) || is.undefined(value); is.object = (value) => !is.null_(value) && (typeof value === 'object' || is.function_(value)); is.iterable = (value) => { var _a; return is.function_((_a = value) === null || _a === void 0 ? void 0 : _a[Symbol.iterator]); }; is.asyncIterable = (value) => { var _a; return is.function_((_a = value) === null || _a === void 0 ? void 0 : _a[Symbol.asyncIterator]); }; is.generator = (value) => { var _a, _b; return is.iterable(value) && is.function_((_a = value) === null || _a === void 0 ? void 0 : _a.next) && is.function_((_b = value) === null || _b === void 0 ? void 0 : _b.throw); }; is.asyncGenerator = (value) => is.asyncIterable(value) && is.function_(value.next) && is.function_(value.throw); is.nativePromise = (value) => isObjectOfType('Promise')(value); const hasPromiseAPI = (value) => { var _a, _b; return is.function_((_a = value) === null || _a === void 0 ? void 0 : _a.then) && is.function_((_b = value) === null || _b === void 0 ? void 0 : _b.catch); }; is.promise = (value) => is.nativePromise(value) || hasPromiseAPI(value); is.generatorFunction = isObjectOfType('GeneratorFunction'); is.asyncGeneratorFunction = (value) => getObjectType(value) === 'AsyncGeneratorFunction'; is.asyncFunction = (value) => getObjectType(value) === 'AsyncFunction'; // eslint-disable-next-line no-prototype-builtins, @typescript-eslint/ban-types is.boundFunction = (value) => is.function_(value) && !value.hasOwnProperty('prototype'); is.regExp = isObjectOfType('RegExp'); is.date = isObjectOfType('Date'); is.error = isObjectOfType('Error'); is.map = (value) => isObjectOfType('Map')(value); is.set = (value) => isObjectOfType('Set')(value); is.weakMap = (value) => isObjectOfType('WeakMap')(value); is.weakSet = (value) => isObjectOfType('WeakSet')(value); is.int8Array = isObjectOfType('Int8Array'); is.uint8Array = isObjectOfType('Uint8Array'); is.uint8ClampedArray = isObjectOfType('Uint8ClampedArray'); is.int16Array = isObjectOfType('Int16Array'); is.uint16Array = isObjectOfType('Uint16Array'); is.int32Array = isObjectOfType('Int32Array'); is.uint32Array = isObjectOfType('Uint32Array'); is.float32Array = isObjectOfType('Float32Array'); is.float64Array = isObjectOfType('Float64Array'); is.bigInt64Array = isObjectOfType('BigInt64Array'); is.bigUint64Array = isObjectOfType('BigUint64Array'); is.arrayBuffer = isObjectOfType('ArrayBuffer'); is.sharedArrayBuffer = isObjectOfType('SharedArrayBuffer'); is.dataView = isObjectOfType('DataView'); is.enumCase = (value, targetEnum) => Object.values(targetEnum).includes(value); is.directInstanceOf = (instance, class_) => Object.getPrototypeOf(instance) === class_.prototype; is.urlInstance = (value) => isObjectOfType('URL')(value); is.urlString = (value) => { if (!is.string(value)) { return false; } try { new URL(value); // eslint-disable-line no-new return true; } catch (_a) { return false; } }; // Example: `is.truthy = (value: unknown): value is (not false | not 0 | not '' | not undefined | not null) => Boolean(value);` is.truthy = (value) => Boolean(value); // Example: `is.falsy = (value: unknown): value is (not true | 0 | '' | undefined | null) => Boolean(value);` is.falsy = (value) => !value; is.nan = (value) => Number.isNaN(value); is.primitive = (value) => is.null_(value) || isPrimitiveTypeName(typeof value); is.integer = (value) => Number.isInteger(value); is.safeInteger = (value) => Number.isSafeInteger(value); is.plainObject = (value) => { // From: https://github.com/sindresorhus/is-plain-obj/blob/main/index.js if (toString.call(value) !== '[object Object]') { return false; } const prototype = Object.getPrototypeOf(value); return prototype === null || prototype === Object.getPrototypeOf({}); }; is.typedArray = (value) => isTypedArrayName(getObjectType(value)); const isValidLength = (value) => is.safeInteger(value) && value >= 0; is.arrayLike = (value) => !is.nullOrUndefined(value) && !is.function_(value) && isValidLength(value.length); is.inRange = (value, range) => { if (is.number(range)) { return value >= Math.min(0, range) && value <= Math.max(range, 0); } if (is.array(range) && range.length === 2) { return value >= Math.min(...range) && value <= Math.max(...range); } throw new TypeError(`Invalid range: ${JSON.stringify(range)}`); }; const NODE_TYPE_ELEMENT = 1; const DOM_PROPERTIES_TO_CHECK = [ 'innerHTML', 'ownerDocument', 'style', 'attributes', 'nodeValue' ]; is.domElement = (value) => { return is.object(value) && value.nodeType === NODE_TYPE_ELEMENT && is.string(value.nodeName) && !is.plainObject(value) && DOM_PROPERTIES_TO_CHECK.every(property => property in value); }; is.observable = (value) => { var _a, _b, _c, _d; if (!value) { return false; } // eslint-disable-next-line no-use-extend-native/no-use-extend-native if (value === ((_b = (_a = value)[Symbol.observable]) === null || _b === void 0 ? void 0 : _b.call(_a))) { return true; } if (value === ((_d = (_c = value)['@@observable']) === null || _d === void 0 ? void 0 : _d.call(_c))) { return true; } return false; }; is.nodeStream = (value) => is.object(value) && is.function_(value.pipe) && !is.observable(value); is.infinite = (value) => value === Infinity || value === -Infinity; const isAbsoluteMod2 = (remainder) => (value) => is.integer(value) && Math.abs(value % 2) === remainder; is.evenInteger = isAbsoluteMod2(0); is.oddInteger = isAbsoluteMod2(1); is.emptyArray = (value) => is.array(value) && value.length === 0; is.nonEmptyArray = (value) => is.array(value) && value.length > 0; is.emptyString = (value) => is.string(value) && value.length === 0; const isWhiteSpaceString = (value) => is.string(value) && !/\S/.test(value); is.emptyStringOrWhitespace = (value) => is.emptyString(value) || isWhiteSpaceString(value); // TODO: Use `not ''` when the `not` operator is available. is.nonEmptyString = (value) => is.string(value) && value.length > 0; // TODO: Use `not ''` when the `not` operator is available. is.nonEmptyStringAndNotWhitespace = (value) => is.string(value) && !is.emptyStringOrWhitespace(value); is.emptyObject = (value) => is.object(value) && !is.map(value) && !is.set(value) && Object.keys(value).length === 0; // TODO: Use `not` operator here to remove `Map` and `Set` from type guard: // - https://github.com/Microsoft/TypeScript/pull/29317 is.nonEmptyObject = (value) => is.object(value) && !is.map(value) && !is.set(value) && Object.keys(value).length > 0; is.emptySet = (value) => is.set(value) && value.size === 0; is.nonEmptySet = (value) => is.set(value) && value.size > 0; is.emptyMap = (value) => is.map(value) && value.size === 0; is.nonEmptyMap = (value) => is.map(value) && value.size > 0; // `PropertyKey` is any value that can be used as an object key (string, number, or symbol) is.propertyKey = (value) => is.any([is.string, is.number, is.symbol], value); is.formData = (value) => isObjectOfType('FormData')(value); is.urlSearchParams = (value) => isObjectOfType('URLSearchParams')(value); const predicateOnArray = (method, predicate, values) => { if (!is.function_(predicate)) { throw new TypeError(`Invalid predicate: ${JSON.stringify(predicate)}`); } if (values.length === 0) { throw new TypeError('Invalid number of values'); } return method.call(values, predicate); }; is.any = (predicate, ...values) => { const predicates = is.array(predicate) ? predicate : [predicate]; return predicates.some(singlePredicate => predicateOnArray(Array.prototype.some, singlePredicate, values)); }; is.all = (predicate, ...values) => predicateOnArray(Array.prototype.every, predicate, values); const assertType = (condition, description, value, options = {}) => { if (!condition) { const { multipleValues } = options; const valuesMessage = multipleValues ? `received values of types ${[ ...new Set(value.map(singleValue => `\`${is(singleValue)}\``)) ].join(', ')}` : `received value of type \`${is(value)}\``; throw new TypeError(`Expected value which is \`${description}\`, ${valuesMessage}.`); } }; exports.assert = { // Unknowns. undefined: (value) => assertType(is.undefined(value), 'undefined', value), string: (value) => assertType(is.string(value), 'string', value), number: (value) => assertType(is.number(value), 'number', value), bigint: (value) => assertType(is.bigint(value), 'bigint', value), // eslint-disable-next-line @typescript-eslint/ban-types function_: (value) => assertType(is.function_(value), 'Function', value), null_: (value) => assertType(is.null_(value), 'null', value), class_: (value) => assertType(is.class_(value), "Class" /* class_ */, value), boolean: (value) => assertType(is.boolean(value), 'boolean', value), symbol: (value) => assertType(is.symbol(value), 'symbol', value), numericString: (value) => assertType(is.numericString(value), "string with a number" /* numericString */, value), array: (value, assertion) => { const assert = assertType; assert(is.array(value), 'Array', value); if (assertion) { value.forEach(assertion); } }, buffer: (value) => assertType(is.buffer(value), 'Buffer', value), blob: (value) => assertType(is.blob(value), 'Blob', value), nullOrUndefined: (value) => assertType(is.nullOrUndefined(value), "null or undefined" /* nullOrUndefined */, value), object: (value) => assertType(is.object(value), 'Object', value), iterable: (value) => assertType(is.iterable(value), "Iterable" /* iterable */, value), asyncIterable: (value) => assertType(is.asyncIterable(value), "AsyncIterable" /* asyncIterable */, value), generator: (value) => assertType(is.generator(value), 'Generator', value), asyncGenerator: (value) => assertType(is.asyncGenerator(value), 'AsyncGenerator', value), nativePromise: (value) => assertType(is.nativePromise(value), "native Promise" /* nativePromise */, value), promise: (value) => assertType(is.promise(value), 'Promise', value), generatorFunction: (value) => assertType(is.generatorFunction(value), 'GeneratorFunction', value), asyncGeneratorFunction: (value) => assertType(is.asyncGeneratorFunction(value), 'AsyncGeneratorFunction', value), // eslint-disable-next-line @typescript-eslint/ban-types asyncFunction: (value) => assertType(is.asyncFunction(value), 'AsyncFunction', value), // eslint-disable-next-line @typescript-eslint/ban-types boundFunction: (value) => assertType(is.boundFunction(value), 'Function', value), regExp: (value) => assertType(is.regExp(value), 'RegExp', value), date: (value) => assertType(is.date(value), 'Date', value), error: (value) => assertType(is.error(value), 'Error', value), map: (value) => assertType(is.map(value), 'Map', value), set: (value) => assertType(is.set(value), 'Set', value), weakMap: (value) => assertType(is.weakMap(value), 'WeakMap', value), weakSet: (value) => assertType(is.weakSet(value), 'WeakSet', value), int8Array: (value) => assertType(is.int8Array(value), 'Int8Array', value), uint8Array: (value) => assertType(is.uint8Array(value), 'Uint8Array', value), uint8ClampedArray: (value) => assertType(is.uint8ClampedArray(value), 'Uint8ClampedArray', value), int16Array: (value) => assertType(is.int16Array(value), 'Int16Array', value), uint16Array: (value) => assertType(is.uint16Array(value), 'Uint16Array', value), int32Array: (value) => assertType(is.int32Array(value), 'Int32Array', value), uint32Array: (value) => assertType(is.uint32Array(value), 'Uint32Array', value), float32Array: (value) => assertType(is.float32Array(value), 'Float32Array', value), float64Array: (value) => assertType(is.float64Array(value), 'Float64Array', value), bigInt64Array: (value) => assertType(is.bigInt64Array(value), 'BigInt64Array', value), bigUint64Array: (value) => assertType(is.bigUint64Array(value), 'BigUint64Array', value), arrayBuffer: (value) => assertType(is.arrayBuffer(value), 'ArrayBuffer', value), sharedArrayBuffer: (value) => assertType(is.sharedArrayBuffer(value), 'SharedArrayBuffer', value), dataView: (value) => assertType(is.dataView(value), 'DataView', value), enumCase: (value, targetEnum) => assertType(is.enumCase(value, targetEnum), 'EnumCase', value), urlInstance: (value) => assertType(is.urlInstance(value), 'URL', value), urlString: (value) => assertType(is.urlString(value), "string with a URL" /* urlString */, value), truthy: (value) => assertType(is.truthy(value), "truthy" /* truthy */, value), falsy: (value) => assertType(is.falsy(value), "falsy" /* falsy */, value), nan: (value) => assertType(is.nan(value), "NaN" /* nan */, value), primitive: (value) => assertType(is.primitive(value), "primitive" /* primitive */, value), integer: (value) => assertType(is.integer(value), "integer" /* integer */, value), safeInteger: (value) => assertType(is.safeInteger(value), "integer" /* safeInteger */, value), plainObject: (value) => assertType(is.plainObject(value), "plain object" /* plainObject */, value), typedArray: (value) => assertType(is.typedArray(value), "TypedArray" /* typedArray */, value), arrayLike: (value) => assertType(is.arrayLike(value), "array-like" /* arrayLike */, value), domElement: (value) => assertType(is.domElement(value), "HTMLElement" /* domElement */, value), observable: (value) => assertType(is.observable(value), 'Observable', value), nodeStream: (value) => assertType(is.nodeStream(value), "Node.js Stream" /* nodeStream */, value), infinite: (value) => assertType(is.infinite(value), "infinite number" /* infinite */, value), emptyArray: (value) => assertType(is.emptyArray(value), "empty array" /* emptyArray */, value), nonEmptyArray: (value) => assertType(is.nonEmptyArray(value), "non-empty array" /* nonEmptyArray */, value), emptyString: (value) => assertType(is.emptyString(value), "empty string" /* emptyString */, value), emptyStringOrWhitespace: (value) => assertType(is.emptyStringOrWhitespace(value), "empty string or whitespace" /* emptyStringOrWhitespace */, value), nonEmptyString: (value) => assertType(is.nonEmptyString(value), "non-empty string" /* nonEmptyString */, value), nonEmptyStringAndNotWhitespace: (value) => assertType(is.nonEmptyStringAndNotWhitespace(value), "non-empty string and not whitespace" /* nonEmptyStringAndNotWhitespace */, value), emptyObject: (value) => assertType(is.emptyObject(value), "empty object" /* emptyObject */, value), nonEmptyObject: (value) => assertType(is.nonEmptyObject(value), "non-empty object" /* nonEmptyObject */, value), emptySet: (value) => assertType(is.emptySet(value), "empty set" /* emptySet */, value), nonEmptySet: (value) => assertType(is.nonEmptySet(value), "non-empty set" /* nonEmptySet */, value), emptyMap: (value) => assertType(is.emptyMap(value), "empty map" /* emptyMap */, value), nonEmptyMap: (value) => assertType(is.nonEmptyMap(value), "non-empty map" /* nonEmptyMap */, value), propertyKey: (value) => assertType(is.propertyKey(value), 'PropertyKey', value), formData: (value) => assertType(is.formData(value), 'FormData', value), urlSearchParams: (value) => assertType(is.urlSearchParams(value), 'URLSearchParams', value), // Numbers. evenInteger: (value) => assertType(is.evenInteger(value), "even integer" /* evenInteger */, value), oddInteger: (value) => assertType(is.oddInteger(value), "odd integer" /* oddInteger */, value), // Two arguments. directInstanceOf: (instance, class_) => assertType(is.directInstanceOf(instance, class_), "T" /* directInstanceOf */, instance), inRange: (value, range) => assertType(is.inRange(value, range), "in range" /* inRange */, value), // Variadic functions. any: (predicate, ...values) => { return assertType(is.any(predicate, ...values), "predicate returns truthy for any value" /* any */, values, { multipleValues: true }); }, all: (predicate, ...values) => assertType(is.all(predicate, ...values), "predicate returns truthy for all values" /* all */, values, { multipleValues: true }) }; // Some few keywords are reserved, but we'll populate them for Node.js users // See https://github.com/Microsoft/TypeScript/issues/2536 Object.defineProperties(is, { class: { value: is.class_ }, function: { value: is.function_ }, null: { value: is.null_ } }); Object.defineProperties(exports.assert, { class: { value: exports.assert.class_ }, function: { value: exports.assert.function_ }, null: { value: exports.assert.null_ } }); exports["default"] = is; // For CommonJS default export support module.exports = is; module.exports["default"] = is; module.exports.assert = exports.assert; /***/ }), /***/ 76234: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const defer_to_connect_1 = __nccwpck_require__(98183); const util_1 = __nccwpck_require__(73837); const nodejsMajorVersion = Number(process.versions.node.split('.')[0]); const timer = (request) => { if (request.timings) { return request.timings; } const timings = { start: Date.now(), socket: undefined, lookup: undefined, connect: undefined, secureConnect: undefined, upload: undefined, response: undefined, end: undefined, error: undefined, abort: undefined, phases: { wait: undefined, dns: undefined, tcp: undefined, tls: undefined, request: undefined, firstByte: undefined, download: undefined, total: undefined } }; request.timings = timings; const handleError = (origin) => { const emit = origin.emit.bind(origin); origin.emit = (event, ...args) => { // Catches the `error` event if (event === 'error') { timings.error = Date.now(); timings.phases.total = timings.error - timings.start; origin.emit = emit; } // Saves the original behavior return emit(event, ...args); }; }; handleError(request); const onAbort = () => { timings.abort = Date.now(); // Let the `end` response event be responsible for setting the total phase, // unless the Node.js major version is >= 13. if (!timings.response || nodejsMajorVersion >= 13) { timings.phases.total = Date.now() - timings.start; } }; request.prependOnceListener('abort', onAbort); const onSocket = (socket) => { timings.socket = Date.now(); timings.phases.wait = timings.socket - timings.start; if (util_1.types.isProxy(socket)) { return; } const lookupListener = () => { timings.lookup = Date.now(); timings.phases.dns = timings.lookup - timings.socket; }; socket.prependOnceListener('lookup', lookupListener); defer_to_connect_1.default(socket, { connect: () => { timings.connect = Date.now(); if (timings.lookup === undefined) { socket.removeListener('lookup', lookupListener); timings.lookup = timings.connect; timings.phases.dns = timings.lookup - timings.socket; } timings.phases.tcp = timings.connect - timings.lookup; // This callback is called before flushing any data, // so we don't need to set `timings.phases.request` here. }, secureConnect: () => { timings.secureConnect = Date.now(); timings.phases.tls = timings.secureConnect - timings.connect; } }); }; if (request.socket) { onSocket(request.socket); } else { request.prependOnceListener('socket', onSocket); } const onUpload = () => { var _a; timings.upload = Date.now(); timings.phases.request = timings.upload - ((_a = timings.secureConnect) !== null && _a !== void 0 ? _a : timings.connect); }; const writableFinished = () => { if (typeof request.writableFinished === 'boolean') { return request.writableFinished; } // Node.js doesn't have `request.writableFinished` property return request.finished && request.outputSize === 0 && (!request.socket || request.socket.writableLength === 0); }; if (writableFinished()) { onUpload(); } else { request.prependOnceListener('finish', onUpload); } request.prependOnceListener('response', (response) => { timings.response = Date.now(); timings.phases.firstByte = timings.response - timings.upload; response.timings = timings; handleError(response); response.prependOnceListener('end', () => { timings.end = Date.now(); timings.phases.download = timings.end - timings.response; timings.phases.total = timings.end - timings.start; }); response.prependOnceListener('aborted', onAbort); }); return timings; }; exports["default"] = timer; // For CommonJS default export support module.exports = timer; module.exports["default"] = timer; /***/ }), /***/ 69016: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const EventEmitter = __nccwpck_require__(82361); const urlLib = __nccwpck_require__(57310); const normalizeUrl = __nccwpck_require__(88580); const getStream = __nccwpck_require__(86741); const CachePolicy = __nccwpck_require__(61002); const Response = __nccwpck_require__(9004); const lowercaseKeys = __nccwpck_require__(9662); const cloneResponse = __nccwpck_require__(81312); const Keyv = __nccwpck_require__(94432); class CacheableRequest { constructor(request, cacheAdapter) { if (typeof request !== 'function') { throw new TypeError('Parameter `request` must be a function'); } this.cache = new Keyv({ uri: typeof cacheAdapter === 'string' && cacheAdapter, store: typeof cacheAdapter !== 'string' && cacheAdapter, namespace: 'cacheable-request' }); return this.createCacheableRequest(request); } createCacheableRequest(request) { return (opts, cb) => { let url; if (typeof opts === 'string') { url = normalizeUrlObject(urlLib.parse(opts)); opts = {}; } else if (opts instanceof urlLib.URL) { url = normalizeUrlObject(urlLib.parse(opts.toString())); opts = {}; } else { const [pathname, ...searchParts] = (opts.path || '').split('?'); const search = searchParts.length > 0 ? `?${searchParts.join('?')}` : ''; url = normalizeUrlObject({ ...opts, pathname, search }); } opts = { headers: {}, method: 'GET', cache: true, strictTtl: false, automaticFailover: false, ...opts, ...urlObjectToRequestOptions(url) }; opts.headers = lowercaseKeys(opts.headers); const ee = new EventEmitter(); const normalizedUrlString = normalizeUrl( urlLib.format(url), { stripWWW: false, removeTrailingSlash: false, stripAuthentication: false } ); const key = `${opts.method}:${normalizedUrlString}`; let revalidate = false; let madeRequest = false; const makeRequest = opts => { madeRequest = true; let requestErrored = false; let requestErrorCallback; const requestErrorPromise = new Promise(resolve => { requestErrorCallback = () => { if (!requestErrored) { requestErrored = true; resolve(); } }; }); const handler = response => { if (revalidate && !opts.forceRefresh) { response.status = response.statusCode; const revalidatedPolicy = CachePolicy.fromObject(revalidate.cachePolicy).revalidatedPolicy(opts, response); if (!revalidatedPolicy.modified) { const headers = revalidatedPolicy.policy.responseHeaders(); response = new Response(revalidate.statusCode, headers, revalidate.body, revalidate.url); response.cachePolicy = revalidatedPolicy.policy; response.fromCache = true; } } if (!response.fromCache) { response.cachePolicy = new CachePolicy(opts, response, opts); response.fromCache = false; } let clonedResponse; if (opts.cache && response.cachePolicy.storable()) { clonedResponse = cloneResponse(response); (async () => { try { const bodyPromise = getStream.buffer(response); await Promise.race([ requestErrorPromise, new Promise(resolve => response.once('end', resolve)) ]); if (requestErrored) { return; } const body = await bodyPromise; const value = { cachePolicy: response.cachePolicy.toObject(), url: response.url, statusCode: response.fromCache ? revalidate.statusCode : response.statusCode, body }; let ttl = opts.strictTtl ? response.cachePolicy.timeToLive() : undefined; if (opts.maxTtl) { ttl = ttl ? Math.min(ttl, opts.maxTtl) : opts.maxTtl; } await this.cache.set(key, value, ttl); } catch (error) { ee.emit('error', new CacheableRequest.CacheError(error)); } })(); } else if (opts.cache && revalidate) { (async () => { try { await this.cache.delete(key); } catch (error) { ee.emit('error', new CacheableRequest.CacheError(error)); } })(); } ee.emit('response', clonedResponse || response); if (typeof cb === 'function') { cb(clonedResponse || response); } }; try { const req = request(opts, handler); req.once('error', requestErrorCallback); req.once('abort', requestErrorCallback); ee.emit('request', req); } catch (error) { ee.emit('error', new CacheableRequest.RequestError(error)); } }; (async () => { const get = async opts => { await Promise.resolve(); const cacheEntry = opts.cache ? await this.cache.get(key) : undefined; if (typeof cacheEntry === 'undefined') { return makeRequest(opts); } const policy = CachePolicy.fromObject(cacheEntry.cachePolicy); if (policy.satisfiesWithoutRevalidation(opts) && !opts.forceRefresh) { const headers = policy.responseHeaders(); const response = new Response(cacheEntry.statusCode, headers, cacheEntry.body, cacheEntry.url); response.cachePolicy = policy; response.fromCache = true; ee.emit('response', response); if (typeof cb === 'function') { cb(response); } } else { revalidate = cacheEntry; opts.headers = policy.revalidationHeaders(opts); makeRequest(opts); } }; const errorHandler = error => ee.emit('error', new CacheableRequest.CacheError(error)); this.cache.once('error', errorHandler); ee.on('response', () => this.cache.removeListener('error', errorHandler)); try { await get(opts); } catch (error) { if (opts.automaticFailover && !madeRequest) { makeRequest(opts); } ee.emit('error', new CacheableRequest.CacheError(error)); } })(); return ee; }; } } function urlObjectToRequestOptions(url) { const options = { ...url }; options.path = `${url.pathname || '/'}${url.search || ''}`; delete options.pathname; delete options.search; return options; } function normalizeUrlObject(url) { // If url was parsed by url.parse or new URL: // - hostname will be set // - host will be hostname[:port] // - port will be set if it was explicit in the parsed string // Otherwise, url was from request options: // - hostname or host may be set // - host shall not have port encoded return { protocol: url.protocol, auth: url.auth, hostname: url.hostname || url.host || 'localhost', port: url.port, pathname: url.pathname, search: url.search }; } CacheableRequest.RequestError = class extends Error { constructor(error) { super(error.message); this.name = 'RequestError'; Object.assign(this, error); } }; CacheableRequest.CacheError = class extends Error { constructor(error) { super(error.message); this.name = 'CacheError'; Object.assign(this, error); } }; module.exports = CacheableRequest; /***/ }), /***/ 22490: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const {Transform, PassThrough} = __nccwpck_require__(12781); const zlib = __nccwpck_require__(59796); const mimicResponse = __nccwpck_require__(35039); module.exports = response => { const contentEncoding = (response.headers['content-encoding'] || '').toLowerCase(); if (!['gzip', 'deflate', 'br'].includes(contentEncoding)) { return response; } // TODO: Remove this when targeting Node.js 12. const isBrotli = contentEncoding === 'br'; if (isBrotli && typeof zlib.createBrotliDecompress !== 'function') { response.destroy(new Error('Brotli is not supported on Node.js < 12')); return response; } let isEmpty = true; const checker = new Transform({ transform(data, _encoding, callback) { isEmpty = false; callback(null, data); }, flush(callback) { callback(); } }); const finalStream = new PassThrough({ autoDestroy: false, destroy(error, callback) { response.destroy(); callback(error); } }); const decompressStream = isBrotli ? zlib.createBrotliDecompress() : zlib.createUnzip(); decompressStream.once('error', error => { if (isEmpty && !response.readable) { finalStream.end(); return; } finalStream.destroy(error); }); mimicResponse(response, finalStream); response.pipe(checker).pipe(decompressStream).pipe(finalStream); return finalStream; }; /***/ }), /***/ 98183: /***/ ((module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); function isTLSSocket(socket) { return socket.encrypted; } const deferToConnect = (socket, fn) => { let listeners; if (typeof fn === 'function') { const connect = fn; listeners = { connect }; } else { listeners = fn; } const hasConnectListener = typeof listeners.connect === 'function'; const hasSecureConnectListener = typeof listeners.secureConnect === 'function'; const hasCloseListener = typeof listeners.close === 'function'; const onConnect = () => { if (hasConnectListener) { listeners.connect(); } if (isTLSSocket(socket) && hasSecureConnectListener) { if (socket.authorized) { listeners.secureConnect(); } else if (!socket.authorizationError) { socket.once('secureConnect', listeners.secureConnect); } } if (hasCloseListener) { socket.once('close', listeners.close); } }; if (socket.writable && !socket.connecting) { onConnect(); } else if (socket.connecting) { socket.once('connect', onConnect); } else if (socket.destroyed && hasCloseListener) { listeners.close(socket._hadError); } }; exports["default"] = deferToConnect; // For CommonJS default export support module.exports = deferToConnect; module.exports["default"] = deferToConnect; /***/ }), /***/ 65066: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const {PassThrough: PassThroughStream} = __nccwpck_require__(12781); module.exports = options => { options = {...options}; const {array} = options; let {encoding} = options; const isBuffer = encoding === 'buffer'; let objectMode = false; if (array) { objectMode = !(encoding || isBuffer); } else { encoding = encoding || 'utf8'; } if (isBuffer) { encoding = null; } const stream = new PassThroughStream({objectMode}); if (encoding) { stream.setEncoding(encoding); } let length = 0; const chunks = []; stream.on('data', chunk => { chunks.push(chunk); if (objectMode) { length = chunks.length; } else { length += chunk.length; } }); stream.getBufferedValue = () => { if (array) { return chunks; } return isBuffer ? Buffer.concat(chunks, length) : chunks.join(''); }; stream.getBufferedLength = () => length; return stream; }; /***/ }), /***/ 86741: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const {constants: BufferConstants} = __nccwpck_require__(14300); const pump = __nccwpck_require__(18341); const bufferStream = __nccwpck_require__(65066); class MaxBufferError extends Error { constructor() { super('maxBuffer exceeded'); this.name = 'MaxBufferError'; } } async function getStream(inputStream, options) { if (!inputStream) { return Promise.reject(new Error('Expected a stream')); } options = { maxBuffer: Infinity, ...options }; const {maxBuffer} = options; let stream; await new Promise((resolve, reject) => { const rejectPromise = error => { // Don't retrieve an oversized buffer. if (error && stream.getBufferedLength() <= BufferConstants.MAX_LENGTH) { error.bufferedData = stream.getBufferedValue(); } reject(error); }; stream = pump(inputStream, bufferStream(options), error => { if (error) { rejectPromise(error); return; } resolve(); }); stream.on('data', () => { if (stream.getBufferedLength() > maxBuffer) { rejectPromise(new MaxBufferError()); } }); }); return stream.getBufferedValue(); } module.exports = getStream; // TODO: Remove this for the next major release module.exports["default"] = getStream; module.exports.buffer = (stream, options) => getStream(stream, {...options, encoding: 'buffer'}); module.exports.array = (stream, options) => getStream(stream, {...options, array: true}); module.exports.MaxBufferError = MaxBufferError; /***/ }), /***/ 11460: /***/ ((__unused_webpack_module, exports) => { //TODO: handle reviver/dehydrate function like normal //and handle indentation, like normal. //if anyone needs this... please send pull request. exports.stringify = function stringify (o) { if('undefined' == typeof o) return o if(o && Buffer.isBuffer(o)) return JSON.stringify(':base64:' + o.toString('base64')) if(o && o.toJSON) o = o.toJSON() if(o && 'object' === typeof o) { var s = '' var array = Array.isArray(o) s = array ? '[' : '{' var first = true for(var k in o) { var ignore = 'function' == typeof o[k] || (!array && 'undefined' === typeof o[k]) if(Object.hasOwnProperty.call(o, k) && !ignore) { if(!first) s += ',' first = false if (array) { if(o[k] == undefined) s += 'null' else s += stringify(o[k]) } else if (o[k] !== void(0)) { s += stringify(k) + ':' + stringify(o[k]) } } } s += array ? ']' : '}' return s } else if ('string' === typeof o) { return JSON.stringify(/^:/.test(o) ? ':' + o : o) } else if ('undefined' === typeof o) { return 'null'; } else return JSON.stringify(o) } exports.parse = function (s) { return JSON.parse(s, function (key, value) { if('string' === typeof value) { if(/^:base64:/.test(value)) return Buffer.from(value.substring(8), 'base64') else return /^:/.test(value) ? value.substring(1) : value } return value }) } /***/ }), /***/ 94432: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const EventEmitter = __nccwpck_require__(82361); const JSONB = __nccwpck_require__(11460); const loadStore = options => { const adapters = { redis: '@keyv/redis', rediss: '@keyv/redis', mongodb: '@keyv/mongo', mongo: '@keyv/mongo', sqlite: '@keyv/sqlite', postgresql: '@keyv/postgres', postgres: '@keyv/postgres', mysql: '@keyv/mysql', etcd: '@keyv/etcd', offline: '@keyv/offline', tiered: '@keyv/tiered', }; if (options.adapter || options.uri) { const adapter = options.adapter || /^[^:+]*/.exec(options.uri)[0]; return new (require(adapters[adapter]))(options); } return new Map(); }; const iterableAdapters = [ 'sqlite', 'postgres', 'mysql', 'mongo', 'redis', 'tiered', ]; class Keyv extends EventEmitter { constructor(uri, {emitErrors = true, ...options} = {}) { super(); this.opts = { namespace: 'keyv', serialize: JSONB.stringify, deserialize: JSONB.parse, ...((typeof uri === 'string') ? {uri} : uri), ...options, }; if (!this.opts.store) { const adapterOptions = {...this.opts}; this.opts.store = loadStore(adapterOptions); } if (this.opts.compression) { const compression = this.opts.compression; this.opts.serialize = compression.serialize.bind(compression); this.opts.deserialize = compression.deserialize.bind(compression); } if (typeof this.opts.store.on === 'function' && emitErrors) { this.opts.store.on('error', error => this.emit('error', error)); } this.opts.store.namespace = this.opts.namespace; const generateIterator = iterator => async function * () { for await (const [key, raw] of typeof iterator === 'function' ? iterator(this.opts.store.namespace) : iterator) { const data = await this.opts.deserialize(raw); if (this.opts.store.namespace && !key.includes(this.opts.store.namespace)) { continue; } if (typeof data.expires === 'number' && Date.now() > data.expires) { this.delete(key); continue; } yield [this._getKeyUnprefix(key), data.value]; } }; // Attach iterators if (typeof this.opts.store[Symbol.iterator] === 'function' && this.opts.store instanceof Map) { this.iterator = generateIterator(this.opts.store); } else if (typeof this.opts.store.iterator === 'function' && this.opts.store.opts && this._checkIterableAdaptar()) { this.iterator = generateIterator(this.opts.store.iterator.bind(this.opts.store)); } } _checkIterableAdaptar() { return iterableAdapters.includes(this.opts.store.opts.dialect) || iterableAdapters.findIndex(element => this.opts.store.opts.url.includes(element)) >= 0; } _getKeyPrefix(key) { return `${this.opts.namespace}:${key}`; } _getKeyPrefixArray(keys) { return keys.map(key => `${this.opts.namespace}:${key}`); } _getKeyUnprefix(key) { return key .split(':') .splice(1) .join(':'); } get(key, options) { const {store} = this.opts; const isArray = Array.isArray(key); const keyPrefixed = isArray ? this._getKeyPrefixArray(key) : this._getKeyPrefix(key); if (isArray && store.getMany === undefined) { const promises = []; for (const key of keyPrefixed) { promises.push(Promise.resolve() .then(() => store.get(key)) .then(data => (typeof data === 'string') ? this.opts.deserialize(data) : (this.opts.compression ? this.opts.deserialize(data) : data)) .then(data => { if (data === undefined || data === null) { return undefined; } if (typeof data.expires === 'number' && Date.now() > data.expires) { return this.delete(key).then(() => undefined); } return (options && options.raw) ? data : data.value; }), ); } return Promise.allSettled(promises) .then(values => { const data = []; for (const value of values) { data.push(value.value); } return data; }); } return Promise.resolve() .then(() => isArray ? store.getMany(keyPrefixed) : store.get(keyPrefixed)) .then(data => (typeof data === 'string') ? this.opts.deserialize(data) : (this.opts.compression ? this.opts.deserialize(data) : data)) .then(data => { if (data === undefined || data === null) { return undefined; } if (isArray) { const result = []; for (let row of data) { if ((typeof row === 'string')) { row = this.opts.deserialize(row); } if (row === undefined || row === null) { result.push(undefined); continue; } if (typeof row.expires === 'number' && Date.now() > row.expires) { this.delete(key).then(() => undefined); result.push(undefined); } else { result.push((options && options.raw) ? row : row.value); } } return result; } if (typeof data.expires === 'number' && Date.now() > data.expires) { return this.delete(key).then(() => undefined); } return (options && options.raw) ? data : data.value; }); } set(key, value, ttl) { const keyPrefixed = this._getKeyPrefix(key); if (typeof ttl === 'undefined') { ttl = this.opts.ttl; } if (ttl === 0) { ttl = undefined; } const {store} = this.opts; return Promise.resolve() .then(() => { const expires = (typeof ttl === 'number') ? (Date.now() + ttl) : null; if (typeof value === 'symbol') { this.emit('error', 'symbol cannot be serialized'); } value = {value, expires}; return this.opts.serialize(value); }) .then(value => store.set(keyPrefixed, value, ttl)) .then(() => true); } delete(key) { const {store} = this.opts; if (Array.isArray(key)) { const keyPrefixed = this._getKeyPrefixArray(key); if (store.deleteMany === undefined) { const promises = []; for (const key of keyPrefixed) { promises.push(store.delete(key)); } return Promise.allSettled(promises) .then(values => values.every(x => x.value === true)); } return Promise.resolve() .then(() => store.deleteMany(keyPrefixed)); } const keyPrefixed = this._getKeyPrefix(key); return Promise.resolve() .then(() => store.delete(keyPrefixed)); } clear() { const {store} = this.opts; return Promise.resolve() .then(() => store.clear()); } has(key) { const keyPrefixed = this._getKeyPrefix(key); const {store} = this.opts; return Promise.resolve() .then(async () => { if (typeof store.has === 'function') { return store.has(keyPrefixed); } const value = await store.get(keyPrefixed); return value !== undefined; }); } disconnect() { const {store} = this.opts; if (typeof store.disconnect === 'function') { return store.disconnect(); } } } module.exports = Keyv; /***/ }), /***/ 35039: /***/ ((module) => { "use strict"; // We define these manually to ensure they're always copied // even if they would move up the prototype chain // https://nodejs.org/api/http.html#http_class_http_incomingmessage const knownProperties = [ 'aborted', 'complete', 'headers', 'httpVersion', 'httpVersionMinor', 'httpVersionMajor', 'method', 'rawHeaders', 'rawTrailers', 'setTimeout', 'socket', 'statusCode', 'statusMessage', 'trailers', 'url' ]; module.exports = (fromStream, toStream) => { if (toStream._readableState.autoDestroy) { throw new Error('The second stream must have the `autoDestroy` option set to `false`'); } const fromProperties = new Set(Object.keys(fromStream).concat(knownProperties)); const properties = {}; for (const property of fromProperties) { // Don't overwrite existing properties. if (property in toStream) { continue; } properties[property] = { get() { const value = fromStream[property]; const isFunction = typeof value === 'function'; return isFunction ? value.bind(fromStream) : value; }, set(value) { fromStream[property] = value; }, enumerable: true, configurable: false }; } Object.defineProperties(toStream, properties); fromStream.once('aborted', () => { toStream.destroy(); toStream.emit('aborted'); }); fromStream.once('close', () => { if (fromStream.complete) { if (toStream.readable) { toStream.once('end', () => { toStream.emit('close'); }); } else { toStream.emit('close'); } } else { toStream.emit('close'); } }); return toStream; }; /***/ }), /***/ 88580: /***/ ((module) => { "use strict"; // https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs const DATA_URL_DEFAULT_MIME_TYPE = 'text/plain'; const DATA_URL_DEFAULT_CHARSET = 'us-ascii'; const testParameter = (name, filters) => { return filters.some(filter => filter instanceof RegExp ? filter.test(name) : filter === name); }; const normalizeDataURL = (urlString, {stripHash}) => { const match = /^data:(?[^,]*?),(?[^#]*?)(?:#(?.*))?$/.exec(urlString); if (!match) { throw new Error(`Invalid URL: ${urlString}`); } let {type, data, hash} = match.groups; const mediaType = type.split(';'); hash = stripHash ? '' : hash; let isBase64 = false; if (mediaType[mediaType.length - 1] === 'base64') { mediaType.pop(); isBase64 = true; } // Lowercase MIME type const mimeType = (mediaType.shift() || '').toLowerCase(); const attributes = mediaType .map(attribute => { let [key, value = ''] = attribute.split('=').map(string => string.trim()); // Lowercase `charset` if (key === 'charset') { value = value.toLowerCase(); if (value === DATA_URL_DEFAULT_CHARSET) { return ''; } } return `${key}${value ? `=${value}` : ''}`; }) .filter(Boolean); const normalizedMediaType = [ ...attributes ]; if (isBase64) { normalizedMediaType.push('base64'); } if (normalizedMediaType.length !== 0 || (mimeType && mimeType !== DATA_URL_DEFAULT_MIME_TYPE)) { normalizedMediaType.unshift(mimeType); } return `data:${normalizedMediaType.join(';')},${isBase64 ? data.trim() : data}${hash ? `#${hash}` : ''}`; }; const normalizeUrl = (urlString, options) => { options = { defaultProtocol: 'http:', normalizeProtocol: true, forceHttp: false, forceHttps: false, stripAuthentication: true, stripHash: false, stripTextFragment: true, stripWWW: true, removeQueryParameters: [/^utm_\w+/i], removeTrailingSlash: true, removeSingleSlash: true, removeDirectoryIndex: false, sortQueryParameters: true, ...options }; urlString = urlString.trim(); // Data URL if (/^data:/i.test(urlString)) { return normalizeDataURL(urlString, options); } if (/^view-source:/i.test(urlString)) { throw new Error('`view-source:` is not supported as it is a non-standard protocol'); } const hasRelativeProtocol = urlString.startsWith('//'); const isRelativeUrl = !hasRelativeProtocol && /^\.*\//.test(urlString); // Prepend protocol if (!isRelativeUrl) { urlString = urlString.replace(/^(?!(?:\w+:)?\/\/)|^\/\//, options.defaultProtocol); } const urlObj = new URL(urlString); if (options.forceHttp && options.forceHttps) { throw new Error('The `forceHttp` and `forceHttps` options cannot be used together'); } if (options.forceHttp && urlObj.protocol === 'https:') { urlObj.protocol = 'http:'; } if (options.forceHttps && urlObj.protocol === 'http:') { urlObj.protocol = 'https:'; } // Remove auth if (options.stripAuthentication) { urlObj.username = ''; urlObj.password = ''; } // Remove hash if (options.stripHash) { urlObj.hash = ''; } else if (options.stripTextFragment) { urlObj.hash = urlObj.hash.replace(/#?:~:text.*?$/i, ''); } // Remove duplicate slashes if not preceded by a protocol if (urlObj.pathname) { urlObj.pathname = urlObj.pathname.replace(/(? 0) { let pathComponents = urlObj.pathname.split('/'); const lastComponent = pathComponents[pathComponents.length - 1]; if (testParameter(lastComponent, options.removeDirectoryIndex)) { pathComponents = pathComponents.slice(0, pathComponents.length - 1); urlObj.pathname = pathComponents.slice(1).join('/') + '/'; } } if (urlObj.hostname) { // Remove trailing dot urlObj.hostname = urlObj.hostname.replace(/\.$/, ''); // Remove `www.` if (options.stripWWW && /^www\.(?!www\.)(?:[a-z\-\d]{1,63})\.(?:[a-z.\-\d]{2,63})$/.test(urlObj.hostname)) { // Each label should be max 63 at length (min: 1). // Source: https://en.wikipedia.org/wiki/Hostname#Restrictions_on_valid_host_names // Each TLD should be up to 63 characters long (min: 2). // It is technically possible to have a single character TLD, but none currently exist. urlObj.hostname = urlObj.hostname.replace(/^www\./, ''); } } // Remove query unwanted parameters if (Array.isArray(options.removeQueryParameters)) { for (const key of [...urlObj.searchParams.keys()]) { if (testParameter(key, options.removeQueryParameters)) { urlObj.searchParams.delete(key); } } } if (options.removeQueryParameters === true) { urlObj.search = ''; } // Sort query parameters if (options.sortQueryParameters) { urlObj.searchParams.sort(); } if (options.removeTrailingSlash) { urlObj.pathname = urlObj.pathname.replace(/\/$/, ''); } const oldUrlString = urlString; // Take advantage of many of the Node `url` normalizations urlString = urlObj.toString(); if (!options.removeSingleSlash && urlObj.pathname === '/' && !oldUrlString.endsWith('/') && urlObj.hash === '') { urlString = urlString.replace(/\/$/, ''); } // Remove ending `/` unless removeSingleSlash is false if ((options.removeTrailingSlash || urlObj.pathname === '/') && urlObj.hash === '' && options.removeSingleSlash) { urlString = urlString.replace(/\/$/, ''); } // Restore relative protocol, if applicable if (hasRelativeProtocol && !options.normalizeProtocol) { urlString = urlString.replace(/^http:\/\//, '//'); } // Remove http/https if (options.stripProtocol) { urlString = urlString.replace(/^(?:https?:)?\/\//, ''); } return urlString; }; module.exports = normalizeUrl; /***/ }), /***/ 13679: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; module.exports = { afterRequest: __nccwpck_require__(83932), beforeRequest: __nccwpck_require__(36136), browser: __nccwpck_require__(805), cache: __nccwpck_require__(51632), content: __nccwpck_require__(61567), cookie: __nccwpck_require__(25725), creator: __nccwpck_require__(47218), entry: __nccwpck_require__(74560), har: __nccwpck_require__(75579), header: __nccwpck_require__(75147), log: __nccwpck_require__(53013), page: __nccwpck_require__(34777), pageTimings: __nccwpck_require__(5538), postData: __nccwpck_require__(12096), query: __nccwpck_require__(21251), request: __nccwpck_require__(99646), response: __nccwpck_require__(9103), timings: __nccwpck_require__(22007) } /***/ }), /***/ 74944: /***/ ((module) => { function HARError (errors) { var message = 'validation failed' this.name = 'HARError' this.message = message this.errors = errors if (typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, this.constructor) } else { this.stack = (new Error(message)).stack } } HARError.prototype = Error.prototype module.exports = HARError /***/ }), /***/ 75697: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { var Ajv = __nccwpck_require__(64941) var HARError = __nccwpck_require__(74944) var schemas = __nccwpck_require__(13679) var ajv function createAjvInstance () { var ajv = new Ajv({ allErrors: true }) ajv.addMetaSchema(__nccwpck_require__(96273)) ajv.addSchema(schemas) return ajv } function validate (name, data) { data = data || {} // validator config ajv = ajv || createAjvInstance() var validate = ajv.getSchema(name + '.json') return new Promise(function (resolve, reject) { var valid = validate(data) !valid ? reject(new HARError(validate.errors)) : resolve(data) }) } exports.afterRequest = function (data) { return validate('afterRequest', data) } exports.beforeRequest = function (data) { return validate('beforeRequest', data) } exports.browser = function (data) { return validate('browser', data) } exports.cache = function (data) { return validate('cache', data) } exports.content = function (data) { return validate('content', data) } exports.cookie = function (data) { return validate('cookie', data) } exports.creator = function (data) { return validate('creator', data) } exports.entry = function (data) { return validate('entry', data) } exports.har = function (data) { return validate('har', data) } exports.header = function (data) { return validate('header', data) } exports.log = function (data) { return validate('log', data) } exports.page = function (data) { return validate('page', data) } exports.pageTimings = function (data) { return validate('pageTimings', data) } exports.postData = function (data) { return validate('postData', data) } exports.query = function (data) { return validate('query', data) } exports.request = function (data) { return validate('request', data) } exports.response = function (data) { return validate('response', data) } exports.timings = function (data) { return validate('timings', data) } /***/ }), /***/ 61002: /***/ ((module) => { "use strict"; // rfc7231 6.1 const statusCodeCacheableByDefault = new Set([ 200, 203, 204, 206, 300, 301, 308, 404, 405, 410, 414, 501, ]); // This implementation does not understand partial responses (206) const understoodStatuses = new Set([ 200, 203, 204, 300, 301, 302, 303, 307, 308, 404, 405, 410, 414, 501, ]); const errorStatusCodes = new Set([ 500, 502, 503, 504, ]); const hopByHopHeaders = { date: true, // included, because we add Age update Date connection: true, 'keep-alive': true, 'proxy-authenticate': true, 'proxy-authorization': true, te: true, trailer: true, 'transfer-encoding': true, upgrade: true, }; const excludedFromRevalidationUpdate = { // Since the old body is reused, it doesn't make sense to change properties of the body 'content-length': true, 'content-encoding': true, 'transfer-encoding': true, 'content-range': true, }; function toNumberOrZero(s) { const n = parseInt(s, 10); return isFinite(n) ? n : 0; } // RFC 5861 function isErrorResponse(response) { // consider undefined response as faulty if(!response) { return true } return errorStatusCodes.has(response.status); } function parseCacheControl(header) { const cc = {}; if (!header) return cc; // TODO: When there is more than one value present for a given directive (e.g., two Expires header fields, multiple Cache-Control: max-age directives), // the directive's value is considered invalid. Caches are encouraged to consider responses that have invalid freshness information to be stale const parts = header.trim().split(/,/); for (const part of parts) { const [k, v] = part.split(/=/, 2); cc[k.trim()] = v === undefined ? true : v.trim().replace(/^"|"$/g, ''); } return cc; } function formatCacheControl(cc) { let parts = []; for (const k in cc) { const v = cc[k]; parts.push(v === true ? k : k + '=' + v); } if (!parts.length) { return undefined; } return parts.join(', '); } module.exports = class CachePolicy { constructor( req, res, { shared, cacheHeuristic, immutableMinTimeToLive, ignoreCargoCult, _fromObject, } = {} ) { if (_fromObject) { this._fromObject(_fromObject); return; } if (!res || !res.headers) { throw Error('Response headers missing'); } this._assertRequestHasHeaders(req); this._responseTime = this.now(); this._isShared = shared !== false; this._cacheHeuristic = undefined !== cacheHeuristic ? cacheHeuristic : 0.1; // 10% matches IE this._immutableMinTtl = undefined !== immutableMinTimeToLive ? immutableMinTimeToLive : 24 * 3600 * 1000; this._status = 'status' in res ? res.status : 200; this._resHeaders = res.headers; this._rescc = parseCacheControl(res.headers['cache-control']); this._method = 'method' in req ? req.method : 'GET'; this._url = req.url; this._host = req.headers.host; this._noAuthorization = !req.headers.authorization; this._reqHeaders = res.headers.vary ? req.headers : null; // Don't keep all request headers if they won't be used this._reqcc = parseCacheControl(req.headers['cache-control']); // Assume that if someone uses legacy, non-standard uncecessary options they don't understand caching, // so there's no point stricly adhering to the blindly copy&pasted directives. if ( ignoreCargoCult && 'pre-check' in this._rescc && 'post-check' in this._rescc ) { delete this._rescc['pre-check']; delete this._rescc['post-check']; delete this._rescc['no-cache']; delete this._rescc['no-store']; delete this._rescc['must-revalidate']; this._resHeaders = Object.assign({}, this._resHeaders, { 'cache-control': formatCacheControl(this._rescc), }); delete this._resHeaders.expires; delete this._resHeaders.pragma; } // When the Cache-Control header field is not present in a request, caches MUST consider the no-cache request pragma-directive // as having the same effect as if "Cache-Control: no-cache" were present (see Section 5.2.1). if ( res.headers['cache-control'] == null && /no-cache/.test(res.headers.pragma) ) { this._rescc['no-cache'] = true; } } now() { return Date.now(); } storable() { // The "no-store" request directive indicates that a cache MUST NOT store any part of either this request or any response to it. return !!( !this._reqcc['no-store'] && // A cache MUST NOT store a response to any request, unless: // The request method is understood by the cache and defined as being cacheable, and ('GET' === this._method || 'HEAD' === this._method || ('POST' === this._method && this._hasExplicitExpiration())) && // the response status code is understood by the cache, and understoodStatuses.has(this._status) && // the "no-store" cache directive does not appear in request or response header fields, and !this._rescc['no-store'] && // the "private" response directive does not appear in the response, if the cache is shared, and (!this._isShared || !this._rescc.private) && // the Authorization header field does not appear in the request, if the cache is shared, (!this._isShared || this._noAuthorization || this._allowsStoringAuthenticated()) && // the response either: // contains an Expires header field, or (this._resHeaders.expires || // contains a max-age response directive, or // contains a s-maxage response directive and the cache is shared, or // contains a public response directive. this._rescc['max-age'] || (this._isShared && this._rescc['s-maxage']) || this._rescc.public || // has a status code that is defined as cacheable by default statusCodeCacheableByDefault.has(this._status)) ); } _hasExplicitExpiration() { // 4.2.1 Calculating Freshness Lifetime return ( (this._isShared && this._rescc['s-maxage']) || this._rescc['max-age'] || this._resHeaders.expires ); } _assertRequestHasHeaders(req) { if (!req || !req.headers) { throw Error('Request headers missing'); } } satisfiesWithoutRevalidation(req) { this._assertRequestHasHeaders(req); // When presented with a request, a cache MUST NOT reuse a stored response, unless: // the presented request does not contain the no-cache pragma (Section 5.4), nor the no-cache cache directive, // unless the stored response is successfully validated (Section 4.3), and const requestCC = parseCacheControl(req.headers['cache-control']); if (requestCC['no-cache'] || /no-cache/.test(req.headers.pragma)) { return false; } if (requestCC['max-age'] && this.age() > requestCC['max-age']) { return false; } if ( requestCC['min-fresh'] && this.timeToLive() < 1000 * requestCC['min-fresh'] ) { return false; } // the stored response is either: // fresh, or allowed to be served stale if (this.stale()) { const allowsStale = requestCC['max-stale'] && !this._rescc['must-revalidate'] && (true === requestCC['max-stale'] || requestCC['max-stale'] > this.age() - this.maxAge()); if (!allowsStale) { return false; } } return this._requestMatches(req, false); } _requestMatches(req, allowHeadMethod) { // The presented effective request URI and that of the stored response match, and return ( (!this._url || this._url === req.url) && this._host === req.headers.host && // the request method associated with the stored response allows it to be used for the presented request, and (!req.method || this._method === req.method || (allowHeadMethod && 'HEAD' === req.method)) && // selecting header fields nominated by the stored response (if any) match those presented, and this._varyMatches(req) ); } _allowsStoringAuthenticated() { // following Cache-Control response directives (Section 5.2.2) have such an effect: must-revalidate, public, and s-maxage. return ( this._rescc['must-revalidate'] || this._rescc.public || this._rescc['s-maxage'] ); } _varyMatches(req) { if (!this._resHeaders.vary) { return true; } // A Vary header field-value of "*" always fails to match if (this._resHeaders.vary === '*') { return false; } const fields = this._resHeaders.vary .trim() .toLowerCase() .split(/\s*,\s*/); for (const name of fields) { if (req.headers[name] !== this._reqHeaders[name]) return false; } return true; } _copyWithoutHopByHopHeaders(inHeaders) { const headers = {}; for (const name in inHeaders) { if (hopByHopHeaders[name]) continue; headers[name] = inHeaders[name]; } // 9.1. Connection if (inHeaders.connection) { const tokens = inHeaders.connection.trim().split(/\s*,\s*/); for (const name of tokens) { delete headers[name]; } } if (headers.warning) { const warnings = headers.warning.split(/,/).filter(warning => { return !/^\s*1[0-9][0-9]/.test(warning); }); if (!warnings.length) { delete headers.warning; } else { headers.warning = warnings.join(',').trim(); } } return headers; } responseHeaders() { const headers = this._copyWithoutHopByHopHeaders(this._resHeaders); const age = this.age(); // A cache SHOULD generate 113 warning if it heuristically chose a freshness // lifetime greater than 24 hours and the response's age is greater than 24 hours. if ( age > 3600 * 24 && !this._hasExplicitExpiration() && this.maxAge() > 3600 * 24 ) { headers.warning = (headers.warning ? `${headers.warning}, ` : '') + '113 - "rfc7234 5.5.4"'; } headers.age = `${Math.round(age)}`; headers.date = new Date(this.now()).toUTCString(); return headers; } /** * Value of the Date response header or current time if Date was invalid * @return timestamp */ date() { const serverDate = Date.parse(this._resHeaders.date); if (isFinite(serverDate)) { return serverDate; } return this._responseTime; } /** * Value of the Age header, in seconds, updated for the current time. * May be fractional. * * @return Number */ age() { let age = this._ageValue(); const residentTime = (this.now() - this._responseTime) / 1000; return age + residentTime; } _ageValue() { return toNumberOrZero(this._resHeaders.age); } /** * Value of applicable max-age (or heuristic equivalent) in seconds. This counts since response's `Date`. * * For an up-to-date value, see `timeToLive()`. * * @return Number */ maxAge() { if (!this.storable() || this._rescc['no-cache']) { return 0; } // Shared responses with cookies are cacheable according to the RFC, but IMHO it'd be unwise to do so by default // so this implementation requires explicit opt-in via public header if ( this._isShared && (this._resHeaders['set-cookie'] && !this._rescc.public && !this._rescc.immutable) ) { return 0; } if (this._resHeaders.vary === '*') { return 0; } if (this._isShared) { if (this._rescc['proxy-revalidate']) { return 0; } // if a response includes the s-maxage directive, a shared cache recipient MUST ignore the Expires field. if (this._rescc['s-maxage']) { return toNumberOrZero(this._rescc['s-maxage']); } } // If a response includes a Cache-Control field with the max-age directive, a recipient MUST ignore the Expires field. if (this._rescc['max-age']) { return toNumberOrZero(this._rescc['max-age']); } const defaultMinTtl = this._rescc.immutable ? this._immutableMinTtl : 0; const serverDate = this.date(); if (this._resHeaders.expires) { const expires = Date.parse(this._resHeaders.expires); // A cache recipient MUST interpret invalid date formats, especially the value "0", as representing a time in the past (i.e., "already expired"). if (Number.isNaN(expires) || expires < serverDate) { return 0; } return Math.max(defaultMinTtl, (expires - serverDate) / 1000); } if (this._resHeaders['last-modified']) { const lastModified = Date.parse(this._resHeaders['last-modified']); if (isFinite(lastModified) && serverDate > lastModified) { return Math.max( defaultMinTtl, ((serverDate - lastModified) / 1000) * this._cacheHeuristic ); } } return defaultMinTtl; } timeToLive() { const age = this.maxAge() - this.age(); const staleIfErrorAge = age + toNumberOrZero(this._rescc['stale-if-error']); const staleWhileRevalidateAge = age + toNumberOrZero(this._rescc['stale-while-revalidate']); return Math.max(0, age, staleIfErrorAge, staleWhileRevalidateAge) * 1000; } stale() { return this.maxAge() <= this.age(); } _useStaleIfError() { return this.maxAge() + toNumberOrZero(this._rescc['stale-if-error']) > this.age(); } useStaleWhileRevalidate() { return this.maxAge() + toNumberOrZero(this._rescc['stale-while-revalidate']) > this.age(); } static fromObject(obj) { return new this(undefined, undefined, { _fromObject: obj }); } _fromObject(obj) { if (this._responseTime) throw Error('Reinitialized'); if (!obj || obj.v !== 1) throw Error('Invalid serialization'); this._responseTime = obj.t; this._isShared = obj.sh; this._cacheHeuristic = obj.ch; this._immutableMinTtl = obj.imm !== undefined ? obj.imm : 24 * 3600 * 1000; this._status = obj.st; this._resHeaders = obj.resh; this._rescc = obj.rescc; this._method = obj.m; this._url = obj.u; this._host = obj.h; this._noAuthorization = obj.a; this._reqHeaders = obj.reqh; this._reqcc = obj.reqcc; } toObject() { return { v: 1, t: this._responseTime, sh: this._isShared, ch: this._cacheHeuristic, imm: this._immutableMinTtl, st: this._status, resh: this._resHeaders, rescc: this._rescc, m: this._method, u: this._url, h: this._host, a: this._noAuthorization, reqh: this._reqHeaders, reqcc: this._reqcc, }; } /** * Headers for sending to the origin server to revalidate stale response. * Allows server to return 304 to allow reuse of the previous response. * * Hop by hop headers are always stripped. * Revalidation headers may be added or removed, depending on request. */ revalidationHeaders(incomingReq) { this._assertRequestHasHeaders(incomingReq); const headers = this._copyWithoutHopByHopHeaders(incomingReq.headers); // This implementation does not understand range requests delete headers['if-range']; if (!this._requestMatches(incomingReq, true) || !this.storable()) { // revalidation allowed via HEAD // not for the same resource, or wasn't allowed to be cached anyway delete headers['if-none-match']; delete headers['if-modified-since']; return headers; } /* MUST send that entity-tag in any cache validation request (using If-Match or If-None-Match) if an entity-tag has been provided by the origin server. */ if (this._resHeaders.etag) { headers['if-none-match'] = headers['if-none-match'] ? `${headers['if-none-match']}, ${this._resHeaders.etag}` : this._resHeaders.etag; } // Clients MAY issue simple (non-subrange) GET requests with either weak validators or strong validators. Clients MUST NOT use weak validators in other forms of request. const forbidsWeakValidators = headers['accept-ranges'] || headers['if-match'] || headers['if-unmodified-since'] || (this._method && this._method != 'GET'); /* SHOULD send the Last-Modified value in non-subrange cache validation requests (using If-Modified-Since) if only a Last-Modified value has been provided by the origin server. Note: This implementation does not understand partial responses (206) */ if (forbidsWeakValidators) { delete headers['if-modified-since']; if (headers['if-none-match']) { const etags = headers['if-none-match'] .split(/,/) .filter(etag => { return !/^\s*W\//.test(etag); }); if (!etags.length) { delete headers['if-none-match']; } else { headers['if-none-match'] = etags.join(',').trim(); } } } else if ( this._resHeaders['last-modified'] && !headers['if-modified-since'] ) { headers['if-modified-since'] = this._resHeaders['last-modified']; } return headers; } /** * Creates new CachePolicy with information combined from the previews response, * and the new revalidation response. * * Returns {policy, modified} where modified is a boolean indicating * whether the response body has been modified, and old cached body can't be used. * * @return {Object} {policy: CachePolicy, modified: Boolean} */ revalidatedPolicy(request, response) { this._assertRequestHasHeaders(request); if(this._useStaleIfError() && isErrorResponse(response)) { // I consider the revalidation request unsuccessful return { modified: false, matches: false, policy: this, }; } if (!response || !response.headers) { throw Error('Response headers missing'); } // These aren't going to be supported exactly, since one CachePolicy object // doesn't know about all the other cached objects. let matches = false; if (response.status !== undefined && response.status != 304) { matches = false; } else if ( response.headers.etag && !/^\s*W\//.test(response.headers.etag) ) { // "All of the stored responses with the same strong validator are selected. // If none of the stored responses contain the same strong validator, // then the cache MUST NOT use the new response to update any stored responses." matches = this._resHeaders.etag && this._resHeaders.etag.replace(/^\s*W\//, '') === response.headers.etag; } else if (this._resHeaders.etag && response.headers.etag) { // "If the new response contains a weak validator and that validator corresponds // to one of the cache's stored responses, // then the most recent of those matching stored responses is selected for update." matches = this._resHeaders.etag.replace(/^\s*W\//, '') === response.headers.etag.replace(/^\s*W\//, ''); } else if (this._resHeaders['last-modified']) { matches = this._resHeaders['last-modified'] === response.headers['last-modified']; } else { // If the new response does not include any form of validator (such as in the case where // a client generates an If-Modified-Since request from a source other than the Last-Modified // response header field), and there is only one stored response, and that stored response also // lacks a validator, then that stored response is selected for update. if ( !this._resHeaders.etag && !this._resHeaders['last-modified'] && !response.headers.etag && !response.headers['last-modified'] ) { matches = true; } } if (!matches) { return { policy: new this.constructor(request, response), // Client receiving 304 without body, even if it's invalid/mismatched has no option // but to reuse a cached body. We don't have a good way to tell clients to do // error recovery in such case. modified: response.status != 304, matches: false, }; } // use other header fields provided in the 304 (Not Modified) response to replace all instances // of the corresponding header fields in the stored response. const headers = {}; for (const k in this._resHeaders) { headers[k] = k in response.headers && !excludedFromRevalidationUpdate[k] ? response.headers[k] : this._resHeaders[k]; } const newResponse = Object.assign({}, response, { status: this._status, method: this._method, headers, }); return { policy: new this.constructor(request, newResponse, { shared: this._isShared, cacheHeuristic: this._cacheHeuristic, immutableMinTimeToLive: this._immutableMinTtl, }), modified: false, matches: true, }; } }; /***/ }), /***/ 42479: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // Copyright 2015 Joyent, Inc. var parser = __nccwpck_require__(95086); var signer = __nccwpck_require__(38143); var verify = __nccwpck_require__(51227); var utils = __nccwpck_require__(65689); ///--- API module.exports = { parse: parser.parseRequest, parseRequest: parser.parseRequest, sign: signer.signRequest, signRequest: signer.signRequest, createSigner: signer.createSigner, isSigner: signer.isSigner, sshKeyToPEM: utils.sshKeyToPEM, sshKeyFingerprint: utils.fingerprint, pemToRsaSSHKey: utils.pemToRsaSSHKey, verify: verify.verifySignature, verifySignature: verify.verifySignature, verifyHMAC: verify.verifyHMAC }; /***/ }), /***/ 95086: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // Copyright 2012 Joyent, Inc. All rights reserved. var assert = __nccwpck_require__(66631); var util = __nccwpck_require__(73837); var utils = __nccwpck_require__(65689); ///--- Globals var HASH_ALGOS = utils.HASH_ALGOS; var PK_ALGOS = utils.PK_ALGOS; var HttpSignatureError = utils.HttpSignatureError; var InvalidAlgorithmError = utils.InvalidAlgorithmError; var validateAlgorithm = utils.validateAlgorithm; var State = { New: 0, Params: 1 }; var ParamsState = { Name: 0, Quote: 1, Value: 2, Comma: 3 }; ///--- Specific Errors function ExpiredRequestError(message) { HttpSignatureError.call(this, message, ExpiredRequestError); } util.inherits(ExpiredRequestError, HttpSignatureError); function InvalidHeaderError(message) { HttpSignatureError.call(this, message, InvalidHeaderError); } util.inherits(InvalidHeaderError, HttpSignatureError); function InvalidParamsError(message) { HttpSignatureError.call(this, message, InvalidParamsError); } util.inherits(InvalidParamsError, HttpSignatureError); function MissingHeaderError(message) { HttpSignatureError.call(this, message, MissingHeaderError); } util.inherits(MissingHeaderError, HttpSignatureError); function StrictParsingError(message) { HttpSignatureError.call(this, message, StrictParsingError); } util.inherits(StrictParsingError, HttpSignatureError); ///--- Exported API module.exports = { /** * Parses the 'Authorization' header out of an http.ServerRequest object. * * Note that this API will fully validate the Authorization header, and throw * on any error. It will not however check the signature, or the keyId format * as those are specific to your environment. You can use the options object * to pass in extra constraints. * * As a response object you can expect this: * * { * "scheme": "Signature", * "params": { * "keyId": "foo", * "algorithm": "rsa-sha256", * "headers": [ * "date" or "x-date", * "digest" * ], * "signature": "base64" * }, * "signingString": "ready to be passed to crypto.verify()" * } * * @param {Object} request an http.ServerRequest. * @param {Object} options an optional options object with: * - clockSkew: allowed clock skew in seconds (default 300). * - headers: required header names (def: date or x-date) * - algorithms: algorithms to support (default: all). * - strict: should enforce latest spec parsing * (default: false). * @return {Object} parsed out object (see above). * @throws {TypeError} on invalid input. * @throws {InvalidHeaderError} on an invalid Authorization header error. * @throws {InvalidParamsError} if the params in the scheme are invalid. * @throws {MissingHeaderError} if the params indicate a header not present, * either in the request headers from the params, * or not in the params from a required header * in options. * @throws {StrictParsingError} if old attributes are used in strict parsing * mode. * @throws {ExpiredRequestError} if the value of date or x-date exceeds skew. */ parseRequest: function parseRequest(request, options) { assert.object(request, 'request'); assert.object(request.headers, 'request.headers'); if (options === undefined) { options = {}; } if (options.headers === undefined) { options.headers = [request.headers['x-date'] ? 'x-date' : 'date']; } assert.object(options, 'options'); assert.arrayOfString(options.headers, 'options.headers'); assert.optionalFinite(options.clockSkew, 'options.clockSkew'); var authzHeaderName = options.authorizationHeaderName || 'authorization'; if (!request.headers[authzHeaderName]) { throw new MissingHeaderError('no ' + authzHeaderName + ' header ' + 'present in the request'); } options.clockSkew = options.clockSkew || 300; var i = 0; var state = State.New; var substate = ParamsState.Name; var tmpName = ''; var tmpValue = ''; var parsed = { scheme: '', params: {}, signingString: '' }; var authz = request.headers[authzHeaderName]; for (i = 0; i < authz.length; i++) { var c = authz.charAt(i); switch (Number(state)) { case State.New: if (c !== ' ') parsed.scheme += c; else state = State.Params; break; case State.Params: switch (Number(substate)) { case ParamsState.Name: var code = c.charCodeAt(0); // restricted name of A-Z / a-z if ((code >= 0x41 && code <= 0x5a) || // A-Z (code >= 0x61 && code <= 0x7a)) { // a-z tmpName += c; } else if (c === '=') { if (tmpName.length === 0) throw new InvalidHeaderError('bad param format'); substate = ParamsState.Quote; } else { throw new InvalidHeaderError('bad param format'); } break; case ParamsState.Quote: if (c === '"') { tmpValue = ''; substate = ParamsState.Value; } else { throw new InvalidHeaderError('bad param format'); } break; case ParamsState.Value: if (c === '"') { parsed.params[tmpName] = tmpValue; substate = ParamsState.Comma; } else { tmpValue += c; } break; case ParamsState.Comma: if (c === ',') { tmpName = ''; substate = ParamsState.Name; } else { throw new InvalidHeaderError('bad param format'); } break; default: throw new Error('Invalid substate'); } break; default: throw new Error('Invalid substate'); } } if (!parsed.params.headers || parsed.params.headers === '') { if (request.headers['x-date']) { parsed.params.headers = ['x-date']; } else { parsed.params.headers = ['date']; } } else { parsed.params.headers = parsed.params.headers.split(' '); } // Minimally validate the parsed object if (!parsed.scheme || parsed.scheme !== 'Signature') throw new InvalidHeaderError('scheme was not "Signature"'); if (!parsed.params.keyId) throw new InvalidHeaderError('keyId was not specified'); if (!parsed.params.algorithm) throw new InvalidHeaderError('algorithm was not specified'); if (!parsed.params.signature) throw new InvalidHeaderError('signature was not specified'); // Check the algorithm against the official list parsed.params.algorithm = parsed.params.algorithm.toLowerCase(); try { validateAlgorithm(parsed.params.algorithm); } catch (e) { if (e instanceof InvalidAlgorithmError) throw (new InvalidParamsError(parsed.params.algorithm + ' is not ' + 'supported')); else throw (e); } // Build the signingString for (i = 0; i < parsed.params.headers.length; i++) { var h = parsed.params.headers[i].toLowerCase(); parsed.params.headers[i] = h; if (h === 'request-line') { if (!options.strict) { /* * We allow headers from the older spec drafts if strict parsing isn't * specified in options. */ parsed.signingString += request.method + ' ' + request.url + ' HTTP/' + request.httpVersion; } else { /* Strict parsing doesn't allow older draft headers. */ throw (new StrictParsingError('request-line is not a valid header ' + 'with strict parsing enabled.')); } } else if (h === '(request-target)') { parsed.signingString += '(request-target): ' + request.method.toLowerCase() + ' ' + request.url; } else { var value = request.headers[h]; if (value === undefined) throw new MissingHeaderError(h + ' was not in the request'); parsed.signingString += h + ': ' + value; } if ((i + 1) < parsed.params.headers.length) parsed.signingString += '\n'; } // Check against the constraints var date; if (request.headers.date || request.headers['x-date']) { if (request.headers['x-date']) { date = new Date(request.headers['x-date']); } else { date = new Date(request.headers.date); } var now = new Date(); var skew = Math.abs(now.getTime() - date.getTime()); if (skew > options.clockSkew * 1000) { throw new ExpiredRequestError('clock skew of ' + (skew / 1000) + 's was greater than ' + options.clockSkew + 's'); } } options.headers.forEach(function (hdr) { // Remember that we already checked any headers in the params // were in the request, so if this passes we're good. if (parsed.params.headers.indexOf(hdr.toLowerCase()) < 0) throw new MissingHeaderError(hdr + ' was not a signed header'); }); if (options.algorithms) { if (options.algorithms.indexOf(parsed.params.algorithm) === -1) throw new InvalidParamsError(parsed.params.algorithm + ' is not a supported algorithm'); } parsed.algorithm = parsed.params.algorithm.toUpperCase(); parsed.keyId = parsed.params.keyId; return parsed; } }; /***/ }), /***/ 38143: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // Copyright 2012 Joyent, Inc. All rights reserved. var assert = __nccwpck_require__(66631); var crypto = __nccwpck_require__(6113); var http = __nccwpck_require__(13685); var util = __nccwpck_require__(73837); var sshpk = __nccwpck_require__(87022); var jsprim = __nccwpck_require__(6287); var utils = __nccwpck_require__(65689); var sprintf = (__nccwpck_require__(73837).format); var HASH_ALGOS = utils.HASH_ALGOS; var PK_ALGOS = utils.PK_ALGOS; var InvalidAlgorithmError = utils.InvalidAlgorithmError; var HttpSignatureError = utils.HttpSignatureError; var validateAlgorithm = utils.validateAlgorithm; ///--- Globals var AUTHZ_FMT = 'Signature keyId="%s",algorithm="%s",headers="%s",signature="%s"'; ///--- Specific Errors function MissingHeaderError(message) { HttpSignatureError.call(this, message, MissingHeaderError); } util.inherits(MissingHeaderError, HttpSignatureError); function StrictParsingError(message) { HttpSignatureError.call(this, message, StrictParsingError); } util.inherits(StrictParsingError, HttpSignatureError); /* See createSigner() */ function RequestSigner(options) { assert.object(options, 'options'); var alg = []; if (options.algorithm !== undefined) { assert.string(options.algorithm, 'options.algorithm'); alg = validateAlgorithm(options.algorithm); } this.rs_alg = alg; /* * RequestSigners come in two varieties: ones with an rs_signFunc, and ones * with an rs_signer. * * rs_signFunc-based RequestSigners have to build up their entire signing * string within the rs_lines array and give it to rs_signFunc as a single * concat'd blob. rs_signer-based RequestSigners can add a line at a time to * their signing state by using rs_signer.update(), thus only needing to * buffer the hash function state and one line at a time. */ if (options.sign !== undefined) { assert.func(options.sign, 'options.sign'); this.rs_signFunc = options.sign; } else if (alg[0] === 'hmac' && options.key !== undefined) { assert.string(options.keyId, 'options.keyId'); this.rs_keyId = options.keyId; if (typeof (options.key) !== 'string' && !Buffer.isBuffer(options.key)) throw (new TypeError('options.key for HMAC must be a string or Buffer')); /* * Make an rs_signer for HMACs, not a rs_signFunc -- HMACs digest their * data in chunks rather than requiring it all to be given in one go * at the end, so they are more similar to signers than signFuncs. */ this.rs_signer = crypto.createHmac(alg[1].toUpperCase(), options.key); this.rs_signer.sign = function () { var digest = this.digest('base64'); return ({ hashAlgorithm: alg[1], toString: function () { return (digest); } }); }; } else if (options.key !== undefined) { var key = options.key; if (typeof (key) === 'string' || Buffer.isBuffer(key)) key = sshpk.parsePrivateKey(key); assert.ok(sshpk.PrivateKey.isPrivateKey(key, [1, 2]), 'options.key must be a sshpk.PrivateKey'); this.rs_key = key; assert.string(options.keyId, 'options.keyId'); this.rs_keyId = options.keyId; if (!PK_ALGOS[key.type]) { throw (new InvalidAlgorithmError(key.type.toUpperCase() + ' type ' + 'keys are not supported')); } if (alg[0] !== undefined && key.type !== alg[0]) { throw (new InvalidAlgorithmError('options.key must be a ' + alg[0].toUpperCase() + ' key, was given a ' + key.type.toUpperCase() + ' key instead')); } this.rs_signer = key.createSign(alg[1]); } else { throw (new TypeError('options.sign (func) or options.key is required')); } this.rs_headers = []; this.rs_lines = []; } /** * Adds a header to be signed, with its value, into this signer. * * @param {String} header * @param {String} value * @return {String} value written */ RequestSigner.prototype.writeHeader = function (header, value) { assert.string(header, 'header'); header = header.toLowerCase(); assert.string(value, 'value'); this.rs_headers.push(header); if (this.rs_signFunc) { this.rs_lines.push(header + ': ' + value); } else { var line = header + ': ' + value; if (this.rs_headers.length > 0) line = '\n' + line; this.rs_signer.update(line); } return (value); }; /** * Adds a default Date header, returning its value. * * @return {String} */ RequestSigner.prototype.writeDateHeader = function () { return (this.writeHeader('date', jsprim.rfc1123(new Date()))); }; /** * Adds the request target line to be signed. * * @param {String} method, HTTP method (e.g. 'get', 'post', 'put') * @param {String} path */ RequestSigner.prototype.writeTarget = function (method, path) { assert.string(method, 'method'); assert.string(path, 'path'); method = method.toLowerCase(); this.writeHeader('(request-target)', method + ' ' + path); }; /** * Calculate the value for the Authorization header on this request * asynchronously. * * @param {Func} callback (err, authz) */ RequestSigner.prototype.sign = function (cb) { assert.func(cb, 'callback'); if (this.rs_headers.length < 1) throw (new Error('At least one header must be signed')); var alg, authz; if (this.rs_signFunc) { var data = this.rs_lines.join('\n'); var self = this; this.rs_signFunc(data, function (err, sig) { if (err) { cb(err); return; } try { assert.object(sig, 'signature'); assert.string(sig.keyId, 'signature.keyId'); assert.string(sig.algorithm, 'signature.algorithm'); assert.string(sig.signature, 'signature.signature'); alg = validateAlgorithm(sig.algorithm); authz = sprintf(AUTHZ_FMT, sig.keyId, sig.algorithm, self.rs_headers.join(' '), sig.signature); } catch (e) { cb(e); return; } cb(null, authz); }); } else { try { var sigObj = this.rs_signer.sign(); } catch (e) { cb(e); return; } alg = (this.rs_alg[0] || this.rs_key.type) + '-' + sigObj.hashAlgorithm; var signature = sigObj.toString(); authz = sprintf(AUTHZ_FMT, this.rs_keyId, alg, this.rs_headers.join(' '), signature); cb(null, authz); } }; ///--- Exported API module.exports = { /** * Identifies whether a given object is a request signer or not. * * @param {Object} object, the object to identify * @returns {Boolean} */ isSigner: function (obj) { if (typeof (obj) === 'object' && obj instanceof RequestSigner) return (true); return (false); }, /** * Creates a request signer, used to asynchronously build a signature * for a request (does not have to be an http.ClientRequest). * * @param {Object} options, either: * - {String} keyId * - {String|Buffer} key * - {String} algorithm (optional, required for HMAC) * or: * - {Func} sign (data, cb) * @return {RequestSigner} */ createSigner: function createSigner(options) { return (new RequestSigner(options)); }, /** * Adds an 'Authorization' header to an http.ClientRequest object. * * Note that this API will add a Date header if it's not already set. Any * other headers in the options.headers array MUST be present, or this * will throw. * * You shouldn't need to check the return type; it's just there if you want * to be pedantic. * * The optional flag indicates whether parsing should use strict enforcement * of the version draft-cavage-http-signatures-04 of the spec or beyond. * The default is to be loose and support * older versions for compatibility. * * @param {Object} request an instance of http.ClientRequest. * @param {Object} options signing parameters object: * - {String} keyId required. * - {String} key required (either a PEM or HMAC key). * - {Array} headers optional; defaults to ['date']. * - {String} algorithm optional (unless key is HMAC); * default is the same as the sshpk default * signing algorithm for the type of key given * - {String} httpVersion optional; defaults to '1.1'. * - {Boolean} strict optional; defaults to 'false'. * @return {Boolean} true if Authorization (and optionally Date) were added. * @throws {TypeError} on bad parameter types (input). * @throws {InvalidAlgorithmError} if algorithm was bad or incompatible with * the given key. * @throws {sshpk.KeyParseError} if key was bad. * @throws {MissingHeaderError} if a header to be signed was specified but * was not present. */ signRequest: function signRequest(request, options) { assert.object(request, 'request'); assert.object(options, 'options'); assert.optionalString(options.algorithm, 'options.algorithm'); assert.string(options.keyId, 'options.keyId'); assert.optionalArrayOfString(options.headers, 'options.headers'); assert.optionalString(options.httpVersion, 'options.httpVersion'); if (!request.getHeader('Date')) request.setHeader('Date', jsprim.rfc1123(new Date())); if (!options.headers) options.headers = ['date']; if (!options.httpVersion) options.httpVersion = '1.1'; var alg = []; if (options.algorithm) { options.algorithm = options.algorithm.toLowerCase(); alg = validateAlgorithm(options.algorithm); } var i; var stringToSign = ''; for (i = 0; i < options.headers.length; i++) { if (typeof (options.headers[i]) !== 'string') throw new TypeError('options.headers must be an array of Strings'); var h = options.headers[i].toLowerCase(); if (h === 'request-line') { if (!options.strict) { /** * We allow headers from the older spec drafts if strict parsing isn't * specified in options. */ stringToSign += request.method + ' ' + request.path + ' HTTP/' + options.httpVersion; } else { /* Strict parsing doesn't allow older draft headers. */ throw (new StrictParsingError('request-line is not a valid header ' + 'with strict parsing enabled.')); } } else if (h === '(request-target)') { stringToSign += '(request-target): ' + request.method.toLowerCase() + ' ' + request.path; } else { var value = request.getHeader(h); if (value === undefined || value === '') { throw new MissingHeaderError(h + ' was not in the request'); } stringToSign += h + ': ' + value; } if ((i + 1) < options.headers.length) stringToSign += '\n'; } /* This is just for unit tests. */ if (request.hasOwnProperty('_stringToSign')) { request._stringToSign = stringToSign; } var signature; if (alg[0] === 'hmac') { if (typeof (options.key) !== 'string' && !Buffer.isBuffer(options.key)) throw (new TypeError('options.key must be a string or Buffer')); var hmac = crypto.createHmac(alg[1].toUpperCase(), options.key); hmac.update(stringToSign); signature = hmac.digest('base64'); } else { var key = options.key; if (typeof (key) === 'string' || Buffer.isBuffer(key)) key = sshpk.parsePrivateKey(options.key); assert.ok(sshpk.PrivateKey.isPrivateKey(key, [1, 2]), 'options.key must be a sshpk.PrivateKey'); if (!PK_ALGOS[key.type]) { throw (new InvalidAlgorithmError(key.type.toUpperCase() + ' type ' + 'keys are not supported')); } if (alg[0] !== undefined && key.type !== alg[0]) { throw (new InvalidAlgorithmError('options.key must be a ' + alg[0].toUpperCase() + ' key, was given a ' + key.type.toUpperCase() + ' key instead')); } var signer = key.createSign(alg[1]); signer.update(stringToSign); var sigObj = signer.sign(); if (!HASH_ALGOS[sigObj.hashAlgorithm]) { throw (new InvalidAlgorithmError(sigObj.hashAlgorithm.toUpperCase() + ' is not a supported hash algorithm')); } options.algorithm = key.type + '-' + sigObj.hashAlgorithm; signature = sigObj.toString(); assert.notStrictEqual(signature, '', 'empty signature produced'); } var authzHeaderName = options.authorizationHeaderName || 'Authorization'; request.setHeader(authzHeaderName, sprintf(AUTHZ_FMT, options.keyId, options.algorithm, options.headers.join(' '), signature)); return true; } }; /***/ }), /***/ 65689: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // Copyright 2012 Joyent, Inc. All rights reserved. var assert = __nccwpck_require__(66631); var sshpk = __nccwpck_require__(87022); var util = __nccwpck_require__(73837); var HASH_ALGOS = { 'sha1': true, 'sha256': true, 'sha512': true }; var PK_ALGOS = { 'rsa': true, 'dsa': true, 'ecdsa': true }; function HttpSignatureError(message, caller) { if (Error.captureStackTrace) Error.captureStackTrace(this, caller || HttpSignatureError); this.message = message; this.name = caller.name; } util.inherits(HttpSignatureError, Error); function InvalidAlgorithmError(message) { HttpSignatureError.call(this, message, InvalidAlgorithmError); } util.inherits(InvalidAlgorithmError, HttpSignatureError); function validateAlgorithm(algorithm) { var alg = algorithm.toLowerCase().split('-'); if (alg.length !== 2) { throw (new InvalidAlgorithmError(alg[0].toUpperCase() + ' is not a ' + 'valid algorithm')); } if (alg[0] !== 'hmac' && !PK_ALGOS[alg[0]]) { throw (new InvalidAlgorithmError(alg[0].toUpperCase() + ' type keys ' + 'are not supported')); } if (!HASH_ALGOS[alg[1]]) { throw (new InvalidAlgorithmError(alg[1].toUpperCase() + ' is not a ' + 'supported hash algorithm')); } return (alg); } ///--- API module.exports = { HASH_ALGOS: HASH_ALGOS, PK_ALGOS: PK_ALGOS, HttpSignatureError: HttpSignatureError, InvalidAlgorithmError: InvalidAlgorithmError, validateAlgorithm: validateAlgorithm, /** * Converts an OpenSSH public key (rsa only) to a PKCS#8 PEM file. * * The intent of this module is to interoperate with OpenSSL only, * specifically the node crypto module's `verify` method. * * @param {String} key an OpenSSH public key. * @return {String} PEM encoded form of the RSA public key. * @throws {TypeError} on bad input. * @throws {Error} on invalid ssh key formatted data. */ sshKeyToPEM: function sshKeyToPEM(key) { assert.string(key, 'ssh_key'); var k = sshpk.parseKey(key, 'ssh'); return (k.toString('pem')); }, /** * Generates an OpenSSH fingerprint from an ssh public key. * * @param {String} key an OpenSSH public key. * @return {String} key fingerprint. * @throws {TypeError} on bad input. * @throws {Error} if what you passed doesn't look like an ssh public key. */ fingerprint: function fingerprint(key) { assert.string(key, 'ssh_key'); var k = sshpk.parseKey(key, 'ssh'); return (k.fingerprint('md5').toString('hex')); }, /** * Converts a PKGCS#8 PEM file to an OpenSSH public key (rsa) * * The reverse of the above function. */ pemToRsaSSHKey: function pemToRsaSSHKey(pem, comment) { assert.equal('string', typeof (pem), 'typeof pem'); var k = sshpk.parseKey(pem, 'pem'); k.comment = comment; return (k.toString('ssh')); } }; /***/ }), /***/ 51227: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // Copyright 2015 Joyent, Inc. var assert = __nccwpck_require__(66631); var crypto = __nccwpck_require__(6113); var sshpk = __nccwpck_require__(87022); var utils = __nccwpck_require__(65689); var HASH_ALGOS = utils.HASH_ALGOS; var PK_ALGOS = utils.PK_ALGOS; var InvalidAlgorithmError = utils.InvalidAlgorithmError; var HttpSignatureError = utils.HttpSignatureError; var validateAlgorithm = utils.validateAlgorithm; ///--- Exported API module.exports = { /** * Verify RSA/DSA signature against public key. You are expected to pass in * an object that was returned from `parse()`. * * @param {Object} parsedSignature the object you got from `parse`. * @param {String} pubkey RSA/DSA private key PEM. * @return {Boolean} true if valid, false otherwise. * @throws {TypeError} if you pass in bad arguments. * @throws {InvalidAlgorithmError} */ verifySignature: function verifySignature(parsedSignature, pubkey) { assert.object(parsedSignature, 'parsedSignature'); if (typeof (pubkey) === 'string' || Buffer.isBuffer(pubkey)) pubkey = sshpk.parseKey(pubkey); assert.ok(sshpk.Key.isKey(pubkey, [1, 1]), 'pubkey must be a sshpk.Key'); var alg = validateAlgorithm(parsedSignature.algorithm); if (alg[0] === 'hmac' || alg[0] !== pubkey.type) return (false); var v = pubkey.createVerify(alg[1]); v.update(parsedSignature.signingString); return (v.verify(parsedSignature.params.signature, 'base64')); }, /** * Verify HMAC against shared secret. You are expected to pass in an object * that was returned from `parse()`. * * @param {Object} parsedSignature the object you got from `parse`. * @param {String} secret HMAC shared secret. * @return {Boolean} true if valid, false otherwise. * @throws {TypeError} if you pass in bad arguments. * @throws {InvalidAlgorithmError} */ verifyHMAC: function verifyHMAC(parsedSignature, secret) { assert.object(parsedSignature, 'parsedHMAC'); assert.string(secret, 'secret'); var alg = validateAlgorithm(parsedSignature.algorithm); if (alg[0] !== 'hmac') return (false); var hashAlg = alg[1].toUpperCase(); var hmac = crypto.createHmac(hashAlg, secret); hmac.update(parsedSignature.signingString); /* * Now double-hash to avoid leaking timing information - there's * no easy constant-time compare in JS, so we use this approach * instead. See for more info: * https://www.isecpartners.com/blog/2011/february/double-hmac- * verification.aspx */ var h1 = crypto.createHmac(hashAlg, secret); h1.update(hmac.digest()); h1 = h1.digest(); var h2 = crypto.createHmac(hashAlg, secret); h2.update(new Buffer(parsedSignature.params.signature, 'base64')); h2 = h2.digest(); /* Node 0.8 returns strings from .digest(). */ if (typeof (h1) === 'string') return (h1 === h2); /* And node 0.10 lacks the .equals() method on Buffers. */ if (Buffer.isBuffer(h1) && !h1.equals) return (h1.toString('binary') === h2.toString('binary')); return (h1.equals(h2)); } }; /***/ }), /***/ 79898: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const EventEmitter = __nccwpck_require__(82361); const tls = __nccwpck_require__(24404); const http2 = __nccwpck_require__(85158); const QuickLRU = __nccwpck_require__(49273); const kCurrentStreamsCount = Symbol('currentStreamsCount'); const kRequest = Symbol('request'); const kOriginSet = Symbol('cachedOriginSet'); const kGracefullyClosing = Symbol('gracefullyClosing'); const nameKeys = [ // `http2.connect()` options 'maxDeflateDynamicTableSize', 'maxSessionMemory', 'maxHeaderListPairs', 'maxOutstandingPings', 'maxReservedRemoteStreams', 'maxSendHeaderBlockLength', 'paddingStrategy', // `tls.connect()` options 'localAddress', 'path', 'rejectUnauthorized', 'minDHSize', // `tls.createSecureContext()` options 'ca', 'cert', 'clientCertEngine', 'ciphers', 'key', 'pfx', 'servername', 'minVersion', 'maxVersion', 'secureProtocol', 'crl', 'honorCipherOrder', 'ecdhCurve', 'dhparam', 'secureOptions', 'sessionIdContext' ]; const getSortedIndex = (array, value, compare) => { let low = 0; let high = array.length; while (low < high) { const mid = (low + high) >>> 1; /* istanbul ignore next */ if (compare(array[mid], value)) { // This never gets called because we use descending sort. Better to have this anyway. low = mid + 1; } else { high = mid; } } return low; }; const compareSessions = (a, b) => { return a.remoteSettings.maxConcurrentStreams > b.remoteSettings.maxConcurrentStreams; }; // See https://tools.ietf.org/html/rfc8336 const closeCoveredSessions = (where, session) => { // Clients SHOULD NOT emit new requests on any connection whose Origin // Set is a proper subset of another connection's Origin Set, and they // SHOULD close it once all outstanding requests are satisfied. for (const coveredSession of where) { if ( // The set is a proper subset when its length is less than the other set. coveredSession[kOriginSet].length < session[kOriginSet].length && // And the other set includes all elements of the subset. coveredSession[kOriginSet].every(origin => session[kOriginSet].includes(origin)) && // Makes sure that the session can handle all requests from the covered session. coveredSession[kCurrentStreamsCount] + session[kCurrentStreamsCount] <= session.remoteSettings.maxConcurrentStreams ) { // This allows pending requests to finish and prevents making new requests. gracefullyClose(coveredSession); } } }; // This is basically inverted `closeCoveredSessions(...)`. const closeSessionIfCovered = (where, coveredSession) => { for (const session of where) { if ( coveredSession[kOriginSet].length < session[kOriginSet].length && coveredSession[kOriginSet].every(origin => session[kOriginSet].includes(origin)) && coveredSession[kCurrentStreamsCount] + session[kCurrentStreamsCount] <= session.remoteSettings.maxConcurrentStreams ) { gracefullyClose(coveredSession); } } }; const getSessions = ({agent, isFree}) => { const result = {}; // eslint-disable-next-line guard-for-in for (const normalizedOptions in agent.sessions) { const sessions = agent.sessions[normalizedOptions]; const filtered = sessions.filter(session => { const result = session[Agent.kCurrentStreamsCount] < session.remoteSettings.maxConcurrentStreams; return isFree ? result : !result; }); if (filtered.length !== 0) { result[normalizedOptions] = filtered; } } return result; }; const gracefullyClose = session => { session[kGracefullyClosing] = true; if (session[kCurrentStreamsCount] === 0) { session.close(); } }; class Agent extends EventEmitter { constructor({timeout = 60000, maxSessions = Infinity, maxFreeSessions = 10, maxCachedTlsSessions = 100} = {}) { super(); // A session is considered busy when its current streams count // is equal to or greater than the `maxConcurrentStreams` value. // A session is considered free when its current streams count // is less than the `maxConcurrentStreams` value. // SESSIONS[NORMALIZED_OPTIONS] = []; this.sessions = {}; // The queue for creating new sessions. It looks like this: // QUEUE[NORMALIZED_OPTIONS][NORMALIZED_ORIGIN] = ENTRY_FUNCTION // // The entry function has `listeners`, `completed` and `destroyed` properties. // `listeners` is an array of objects containing `resolve` and `reject` functions. // `completed` is a boolean. It's set to true after ENTRY_FUNCTION is executed. // `destroyed` is a boolean. If it's set to true, the session will be destroyed if hasn't connected yet. this.queue = {}; // Each session will use this timeout value. this.timeout = timeout; // Max sessions in total this.maxSessions = maxSessions; // Max free sessions in total // TODO: decreasing `maxFreeSessions` should close some sessions this.maxFreeSessions = maxFreeSessions; this._freeSessionsCount = 0; this._sessionsCount = 0; // We don't support push streams by default. this.settings = { enablePush: false }; // Reusing TLS sessions increases performance. this.tlsSessionCache = new QuickLRU({maxSize: maxCachedTlsSessions}); } static normalizeOrigin(url, servername) { if (typeof url === 'string') { url = new URL(url); } if (servername && url.hostname !== servername) { url.hostname = servername; } return url.origin; } normalizeOptions(options) { let normalized = ''; if (options) { for (const key of nameKeys) { if (options[key]) { normalized += `:${options[key]}`; } } } return normalized; } _tryToCreateNewSession(normalizedOptions, normalizedOrigin) { if (!(normalizedOptions in this.queue) || !(normalizedOrigin in this.queue[normalizedOptions])) { return; } const item = this.queue[normalizedOptions][normalizedOrigin]; // The entry function can be run only once. // BUG: The session may be never created when: // - the first condition is false AND // - this function is never called with the same arguments in the future. if (this._sessionsCount < this.maxSessions && !item.completed) { item.completed = true; item(); } } getSession(origin, options, listeners) { return new Promise((resolve, reject) => { if (Array.isArray(listeners)) { listeners = [...listeners]; // Resolve the current promise ASAP, we're just moving the listeners. // They will be executed at a different time. resolve(); } else { listeners = [{resolve, reject}]; } const normalizedOptions = this.normalizeOptions(options); const normalizedOrigin = Agent.normalizeOrigin(origin, options && options.servername); if (normalizedOrigin === undefined) { for (const {reject} of listeners) { reject(new TypeError('The `origin` argument needs to be a string or an URL object')); } return; } if (normalizedOptions in this.sessions) { const sessions = this.sessions[normalizedOptions]; let maxConcurrentStreams = -1; let currentStreamsCount = -1; let optimalSession; // We could just do this.sessions[normalizedOptions].find(...) but that isn't optimal. // Additionally, we are looking for session which has biggest current pending streams count. for (const session of sessions) { const sessionMaxConcurrentStreams = session.remoteSettings.maxConcurrentStreams; if (sessionMaxConcurrentStreams < maxConcurrentStreams) { break; } if (session[kOriginSet].includes(normalizedOrigin)) { const sessionCurrentStreamsCount = session[kCurrentStreamsCount]; if ( sessionCurrentStreamsCount >= sessionMaxConcurrentStreams || session[kGracefullyClosing] || // Unfortunately the `close` event isn't called immediately, // so `session.destroyed` is `true`, but `session.closed` is `false`. session.destroyed ) { continue; } // We only need set this once. if (!optimalSession) { maxConcurrentStreams = sessionMaxConcurrentStreams; } // We're looking for the session which has biggest current pending stream count, // in order to minimalize the amount of active sessions. if (sessionCurrentStreamsCount > currentStreamsCount) { optimalSession = session; currentStreamsCount = sessionCurrentStreamsCount; } } } if (optimalSession) { /* istanbul ignore next: safety check */ if (listeners.length !== 1) { for (const {reject} of listeners) { const error = new Error( `Expected the length of listeners to be 1, got ${listeners.length}.\n` + 'Please report this to https://github.com/szmarczak/http2-wrapper/' ); reject(error); } return; } listeners[0].resolve(optimalSession); return; } } if (normalizedOptions in this.queue) { if (normalizedOrigin in this.queue[normalizedOptions]) { // There's already an item in the queue, just attach ourselves to it. this.queue[normalizedOptions][normalizedOrigin].listeners.push(...listeners); // This shouldn't be executed here. // See the comment inside _tryToCreateNewSession. this._tryToCreateNewSession(normalizedOptions, normalizedOrigin); return; } } else { this.queue[normalizedOptions] = {}; } // The entry must be removed from the queue IMMEDIATELY when: // 1. the session connects successfully, // 2. an error occurs. const removeFromQueue = () => { // Our entry can be replaced. We cannot remove the new one. if (normalizedOptions in this.queue && this.queue[normalizedOptions][normalizedOrigin] === entry) { delete this.queue[normalizedOptions][normalizedOrigin]; if (Object.keys(this.queue[normalizedOptions]).length === 0) { delete this.queue[normalizedOptions]; } } }; // The main logic is here const entry = () => { const name = `${normalizedOrigin}:${normalizedOptions}`; let receivedSettings = false; try { const session = http2.connect(origin, { createConnection: this.createConnection, settings: this.settings, session: this.tlsSessionCache.get(name), ...options }); session[kCurrentStreamsCount] = 0; session[kGracefullyClosing] = false; const isFree = () => session[kCurrentStreamsCount] < session.remoteSettings.maxConcurrentStreams; let wasFree = true; session.socket.once('session', tlsSession => { this.tlsSessionCache.set(name, tlsSession); }); session.once('error', error => { // Listeners are empty when the session successfully connected. for (const {reject} of listeners) { reject(error); } // The connection got broken, purge the cache. this.tlsSessionCache.delete(name); }); session.setTimeout(this.timeout, () => { // Terminates all streams owned by this session. // TODO: Maybe the streams should have a "Session timed out" error? session.destroy(); }); session.once('close', () => { if (receivedSettings) { // 1. If it wasn't free then no need to decrease because // it has been decreased already in session.request(). // 2. `stream.once('close')` won't increment the count // because the session is already closed. if (wasFree) { this._freeSessionsCount--; } this._sessionsCount--; // This cannot be moved to the stream logic, // because there may be a session that hadn't made a single request. const where = this.sessions[normalizedOptions]; where.splice(where.indexOf(session), 1); if (where.length === 0) { delete this.sessions[normalizedOptions]; } } else { // Broken connection const error = new Error('Session closed without receiving a SETTINGS frame'); error.code = 'HTTP2WRAPPER_NOSETTINGS'; for (const {reject} of listeners) { reject(error); } removeFromQueue(); } // There may be another session awaiting. this._tryToCreateNewSession(normalizedOptions, normalizedOrigin); }); // Iterates over the queue and processes listeners. const processListeners = () => { if (!(normalizedOptions in this.queue) || !isFree()) { return; } for (const origin of session[kOriginSet]) { if (origin in this.queue[normalizedOptions]) { const {listeners} = this.queue[normalizedOptions][origin]; // Prevents session overloading. while (listeners.length !== 0 && isFree()) { // We assume `resolve(...)` calls `request(...)` *directly*, // otherwise the session will get overloaded. listeners.shift().resolve(session); } const where = this.queue[normalizedOptions]; if (where[origin].listeners.length === 0) { delete where[origin]; if (Object.keys(where).length === 0) { delete this.queue[normalizedOptions]; break; } } // We're no longer free, no point in continuing. if (!isFree()) { break; } } } }; // The Origin Set cannot shrink. No need to check if it suddenly became covered by another one. session.on('origin', () => { session[kOriginSet] = session.originSet; if (!isFree()) { // The session is full. return; } processListeners(); // Close covered sessions (if possible). closeCoveredSessions(this.sessions[normalizedOptions], session); }); session.once('remoteSettings', () => { // Fix Node.js bug preventing the process from exiting session.ref(); session.unref(); this._sessionsCount++; // The Agent could have been destroyed already. if (entry.destroyed) { const error = new Error('Agent has been destroyed'); for (const listener of listeners) { listener.reject(error); } session.destroy(); return; } session[kOriginSet] = session.originSet; { const where = this.sessions; if (normalizedOptions in where) { const sessions = where[normalizedOptions]; sessions.splice(getSortedIndex(sessions, session, compareSessions), 0, session); } else { where[normalizedOptions] = [session]; } } this._freeSessionsCount += 1; receivedSettings = true; this.emit('session', session); processListeners(); removeFromQueue(); // TODO: Close last recently used (or least used?) session if (session[kCurrentStreamsCount] === 0 && this._freeSessionsCount > this.maxFreeSessions) { session.close(); } // Check if we haven't managed to execute all listeners. if (listeners.length !== 0) { // Request for a new session with predefined listeners. this.getSession(normalizedOrigin, options, listeners); listeners.length = 0; } // `session.remoteSettings.maxConcurrentStreams` might get increased session.on('remoteSettings', () => { processListeners(); // In case the Origin Set changes closeCoveredSessions(this.sessions[normalizedOptions], session); }); }); // Shim `session.request()` in order to catch all streams session[kRequest] = session.request; session.request = (headers, streamOptions) => { if (session[kGracefullyClosing]) { throw new Error('The session is gracefully closing. No new streams are allowed.'); } const stream = session[kRequest](headers, streamOptions); // The process won't exit until the session is closed or all requests are gone. session.ref(); ++session[kCurrentStreamsCount]; if (session[kCurrentStreamsCount] === session.remoteSettings.maxConcurrentStreams) { this._freeSessionsCount--; } stream.once('close', () => { wasFree = isFree(); --session[kCurrentStreamsCount]; if (!session.destroyed && !session.closed) { closeSessionIfCovered(this.sessions[normalizedOptions], session); if (isFree() && !session.closed) { if (!wasFree) { this._freeSessionsCount++; wasFree = true; } const isEmpty = session[kCurrentStreamsCount] === 0; if (isEmpty) { session.unref(); } if ( isEmpty && ( this._freeSessionsCount > this.maxFreeSessions || session[kGracefullyClosing] ) ) { session.close(); } else { closeCoveredSessions(this.sessions[normalizedOptions], session); processListeners(); } } } }); return stream; }; } catch (error) { for (const listener of listeners) { listener.reject(error); } removeFromQueue(); } }; entry.listeners = listeners; entry.completed = false; entry.destroyed = false; this.queue[normalizedOptions][normalizedOrigin] = entry; this._tryToCreateNewSession(normalizedOptions, normalizedOrigin); }); } request(origin, options, headers, streamOptions) { return new Promise((resolve, reject) => { this.getSession(origin, options, [{ reject, resolve: session => { try { resolve(session.request(headers, streamOptions)); } catch (error) { reject(error); } } }]); }); } createConnection(origin, options) { return Agent.connect(origin, options); } static connect(origin, options) { options.ALPNProtocols = ['h2']; const port = origin.port || 443; const host = origin.hostname || origin.host; if (typeof options.servername === 'undefined') { options.servername = host; } return tls.connect(port, host, options); } closeFreeSessions() { for (const sessions of Object.values(this.sessions)) { for (const session of sessions) { if (session[kCurrentStreamsCount] === 0) { session.close(); } } } } destroy(reason) { for (const sessions of Object.values(this.sessions)) { for (const session of sessions) { session.destroy(reason); } } for (const entriesOfAuthority of Object.values(this.queue)) { for (const entry of Object.values(entriesOfAuthority)) { entry.destroyed = true; } } // New requests should NOT attach to destroyed sessions this.queue = {}; } get freeSessions() { return getSessions({agent: this, isFree: true}); } get busySessions() { return getSessions({agent: this, isFree: false}); } } Agent.kCurrentStreamsCount = kCurrentStreamsCount; Agent.kGracefullyClosing = kGracefullyClosing; module.exports = { Agent, globalAgent: new Agent() }; /***/ }), /***/ 97167: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const http = __nccwpck_require__(13685); const https = __nccwpck_require__(95687); const resolveALPN = __nccwpck_require__(46624); const QuickLRU = __nccwpck_require__(49273); const Http2ClientRequest = __nccwpck_require__(59632); const calculateServerName = __nccwpck_require__(51982); const urlToOptions = __nccwpck_require__(92686); const cache = new QuickLRU({maxSize: 100}); const queue = new Map(); const installSocket = (agent, socket, options) => { socket._httpMessage = {shouldKeepAlive: true}; const onFree = () => { agent.emit('free', socket, options); }; socket.on('free', onFree); const onClose = () => { agent.removeSocket(socket, options); }; socket.on('close', onClose); const onRemove = () => { agent.removeSocket(socket, options); socket.off('close', onClose); socket.off('free', onFree); socket.off('agentRemove', onRemove); }; socket.on('agentRemove', onRemove); agent.emit('free', socket, options); }; const resolveProtocol = async options => { const name = `${options.host}:${options.port}:${options.ALPNProtocols.sort()}`; if (!cache.has(name)) { if (queue.has(name)) { const result = await queue.get(name); return result.alpnProtocol; } const {path, agent} = options; options.path = options.socketPath; const resultPromise = resolveALPN(options); queue.set(name, resultPromise); try { const {socket, alpnProtocol} = await resultPromise; cache.set(name, alpnProtocol); options.path = path; if (alpnProtocol === 'h2') { // https://github.com/nodejs/node/issues/33343 socket.destroy(); } else { const {globalAgent} = https; const defaultCreateConnection = https.Agent.prototype.createConnection; if (agent) { if (agent.createConnection === defaultCreateConnection) { installSocket(agent, socket, options); } else { socket.destroy(); } } else if (globalAgent.createConnection === defaultCreateConnection) { installSocket(globalAgent, socket, options); } else { socket.destroy(); } } queue.delete(name); return alpnProtocol; } catch (error) { queue.delete(name); throw error; } } return cache.get(name); }; module.exports = async (input, options, callback) => { if (typeof input === 'string' || input instanceof URL) { input = urlToOptions(new URL(input)); } if (typeof options === 'function') { callback = options; options = undefined; } options = { ALPNProtocols: ['h2', 'http/1.1'], ...input, ...options, resolveSocket: true }; if (!Array.isArray(options.ALPNProtocols) || options.ALPNProtocols.length === 0) { throw new Error('The `ALPNProtocols` option must be an Array with at least one entry'); } options.protocol = options.protocol || 'https:'; const isHttps = options.protocol === 'https:'; options.host = options.hostname || options.host || 'localhost'; options.session = options.tlsSession; options.servername = options.servername || calculateServerName(options); options.port = options.port || (isHttps ? 443 : 80); options._defaultAgent = isHttps ? https.globalAgent : http.globalAgent; const agents = options.agent; if (agents) { if (agents.addRequest) { throw new Error('The `options.agent` object can contain only `http`, `https` or `http2` properties'); } options.agent = agents[isHttps ? 'https' : 'http']; } if (isHttps) { const protocol = await resolveProtocol(options); if (protocol === 'h2') { if (agents) { options.agent = agents.http2; } return new Http2ClientRequest(options, callback); } } return http.request(options, callback); }; module.exports.protocolCache = cache; /***/ }), /***/ 59632: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const http2 = __nccwpck_require__(85158); const {Writable} = __nccwpck_require__(12781); const {Agent, globalAgent} = __nccwpck_require__(79898); const IncomingMessage = __nccwpck_require__(82575); const urlToOptions = __nccwpck_require__(92686); const proxyEvents = __nccwpck_require__(81818); const isRequestPseudoHeader = __nccwpck_require__(11199); const { ERR_INVALID_ARG_TYPE, ERR_INVALID_PROTOCOL, ERR_HTTP_HEADERS_SENT, ERR_INVALID_HTTP_TOKEN, ERR_HTTP_INVALID_HEADER_VALUE, ERR_INVALID_CHAR } = __nccwpck_require__(7087); const { HTTP2_HEADER_STATUS, HTTP2_HEADER_METHOD, HTTP2_HEADER_PATH, HTTP2_METHOD_CONNECT } = http2.constants; const kHeaders = Symbol('headers'); const kOrigin = Symbol('origin'); const kSession = Symbol('session'); const kOptions = Symbol('options'); const kFlushedHeaders = Symbol('flushedHeaders'); const kJobs = Symbol('jobs'); const isValidHttpToken = /^[\^`\-\w!#$%&*+.|~]+$/; const isInvalidHeaderValue = /[^\t\u0020-\u007E\u0080-\u00FF]/; class ClientRequest extends Writable { constructor(input, options, callback) { super({ autoDestroy: false }); const hasInput = typeof input === 'string' || input instanceof URL; if (hasInput) { input = urlToOptions(input instanceof URL ? input : new URL(input)); } if (typeof options === 'function' || options === undefined) { // (options, callback) callback = options; options = hasInput ? input : {...input}; } else { // (input, options, callback) options = {...input, ...options}; } if (options.h2session) { this[kSession] = options.h2session; } else if (options.agent === false) { this.agent = new Agent({maxFreeSessions: 0}); } else if (typeof options.agent === 'undefined' || options.agent === null) { if (typeof options.createConnection === 'function') { // This is a workaround - we don't have to create the session on our own. this.agent = new Agent({maxFreeSessions: 0}); this.agent.createConnection = options.createConnection; } else { this.agent = globalAgent; } } else if (typeof options.agent.request === 'function') { this.agent = options.agent; } else { throw new ERR_INVALID_ARG_TYPE('options.agent', ['Agent-like Object', 'undefined', 'false'], options.agent); } if (options.protocol && options.protocol !== 'https:') { throw new ERR_INVALID_PROTOCOL(options.protocol, 'https:'); } const port = options.port || options.defaultPort || (this.agent && this.agent.defaultPort) || 443; const host = options.hostname || options.host || 'localhost'; // Don't enforce the origin via options. It may be changed in an Agent. delete options.hostname; delete options.host; delete options.port; const {timeout} = options; options.timeout = undefined; this[kHeaders] = Object.create(null); this[kJobs] = []; this.socket = null; this.connection = null; this.method = options.method || 'GET'; this.path = options.path; this.res = null; this.aborted = false; this.reusedSocket = false; if (options.headers) { for (const [header, value] of Object.entries(options.headers)) { this.setHeader(header, value); } } if (options.auth && !('authorization' in this[kHeaders])) { this[kHeaders].authorization = 'Basic ' + Buffer.from(options.auth).toString('base64'); } options.session = options.tlsSession; options.path = options.socketPath; this[kOptions] = options; // Clients that generate HTTP/2 requests directly SHOULD use the :authority pseudo-header field instead of the Host header field. if (port === 443) { this[kOrigin] = `https://${host}`; if (!(':authority' in this[kHeaders])) { this[kHeaders][':authority'] = host; } } else { this[kOrigin] = `https://${host}:${port}`; if (!(':authority' in this[kHeaders])) { this[kHeaders][':authority'] = `${host}:${port}`; } } if (timeout) { this.setTimeout(timeout); } if (callback) { this.once('response', callback); } this[kFlushedHeaders] = false; } get method() { return this[kHeaders][HTTP2_HEADER_METHOD]; } set method(value) { if (value) { this[kHeaders][HTTP2_HEADER_METHOD] = value.toUpperCase(); } } get path() { return this[kHeaders][HTTP2_HEADER_PATH]; } set path(value) { if (value) { this[kHeaders][HTTP2_HEADER_PATH] = value; } } get _mustNotHaveABody() { return this.method === 'GET' || this.method === 'HEAD' || this.method === 'DELETE'; } _write(chunk, encoding, callback) { // https://github.com/nodejs/node/blob/654df09ae0c5e17d1b52a900a545f0664d8c7627/lib/internal/http2/util.js#L148-L156 if (this._mustNotHaveABody) { callback(new Error('The GET, HEAD and DELETE methods must NOT have a body')); /* istanbul ignore next: Node.js 12 throws directly */ return; } this.flushHeaders(); const callWrite = () => this._request.write(chunk, encoding, callback); if (this._request) { callWrite(); } else { this[kJobs].push(callWrite); } } _final(callback) { if (this.destroyed) { return; } this.flushHeaders(); const callEnd = () => { // For GET, HEAD and DELETE if (this._mustNotHaveABody) { callback(); return; } this._request.end(callback); }; if (this._request) { callEnd(); } else { this[kJobs].push(callEnd); } } abort() { if (this.res && this.res.complete) { return; } if (!this.aborted) { process.nextTick(() => this.emit('abort')); } this.aborted = true; this.destroy(); } _destroy(error, callback) { if (this.res) { this.res._dump(); } if (this._request) { this._request.destroy(); } callback(error); } async flushHeaders() { if (this[kFlushedHeaders] || this.destroyed) { return; } this[kFlushedHeaders] = true; const isConnectMethod = this.method === HTTP2_METHOD_CONNECT; // The real magic is here const onStream = stream => { this._request = stream; if (this.destroyed) { stream.destroy(); return; } // Forwards `timeout`, `continue`, `close` and `error` events to this instance. if (!isConnectMethod) { proxyEvents(stream, this, ['timeout', 'continue', 'close', 'error']); } // Wait for the `finish` event. We don't want to emit the `response` event // before `request.end()` is called. const waitForEnd = fn => { return (...args) => { if (!this.writable && !this.destroyed) { fn(...args); } else { this.once('finish', () => { fn(...args); }); } }; }; // This event tells we are ready to listen for the data. stream.once('response', waitForEnd((headers, flags, rawHeaders) => { // If we were to emit raw request stream, it would be as fast as the native approach. // Note that wrapping the raw stream in a Proxy instance won't improve the performance (already tested it). const response = new IncomingMessage(this.socket, stream.readableHighWaterMark); this.res = response; response.req = this; response.statusCode = headers[HTTP2_HEADER_STATUS]; response.headers = headers; response.rawHeaders = rawHeaders; response.once('end', () => { if (this.aborted) { response.aborted = true; response.emit('aborted'); } else { response.complete = true; // Has no effect, just be consistent with the Node.js behavior response.socket = null; response.connection = null; } }); if (isConnectMethod) { response.upgrade = true; // The HTTP1 API says the socket is detached here, // but we can't do that so we pass the original HTTP2 request. if (this.emit('connect', response, stream, Buffer.alloc(0))) { this.emit('close'); } else { // No listeners attached, destroy the original request. stream.destroy(); } } else { // Forwards data stream.on('data', chunk => { if (!response._dumped && !response.push(chunk)) { stream.pause(); } }); stream.once('end', () => { response.push(null); }); if (!this.emit('response', response)) { // No listeners attached, dump the response. response._dump(); } } })); // Emits `information` event stream.once('headers', waitForEnd( headers => this.emit('information', {statusCode: headers[HTTP2_HEADER_STATUS]}) )); stream.once('trailers', waitForEnd((trailers, flags, rawTrailers) => { const {res} = this; // Assigns trailers to the response object. res.trailers = trailers; res.rawTrailers = rawTrailers; })); const {socket} = stream.session; this.socket = socket; this.connection = socket; for (const job of this[kJobs]) { job(); } this.emit('socket', this.socket); }; // Makes a HTTP2 request if (this[kSession]) { try { onStream(this[kSession].request(this[kHeaders])); } catch (error) { this.emit('error', error); } } else { this.reusedSocket = true; try { onStream(await this.agent.request(this[kOrigin], this[kOptions], this[kHeaders])); } catch (error) { this.emit('error', error); } } } getHeader(name) { if (typeof name !== 'string') { throw new ERR_INVALID_ARG_TYPE('name', 'string', name); } return this[kHeaders][name.toLowerCase()]; } get headersSent() { return this[kFlushedHeaders]; } removeHeader(name) { if (typeof name !== 'string') { throw new ERR_INVALID_ARG_TYPE('name', 'string', name); } if (this.headersSent) { throw new ERR_HTTP_HEADERS_SENT('remove'); } delete this[kHeaders][name.toLowerCase()]; } setHeader(name, value) { if (this.headersSent) { throw new ERR_HTTP_HEADERS_SENT('set'); } if (typeof name !== 'string' || (!isValidHttpToken.test(name) && !isRequestPseudoHeader(name))) { throw new ERR_INVALID_HTTP_TOKEN('Header name', name); } if (typeof value === 'undefined') { throw new ERR_HTTP_INVALID_HEADER_VALUE(value, name); } if (isInvalidHeaderValue.test(value)) { throw new ERR_INVALID_CHAR('header content', name); } this[kHeaders][name.toLowerCase()] = value; } setNoDelay() { // HTTP2 sockets cannot be malformed, do nothing. } setSocketKeepAlive() { // HTTP2 sockets cannot be malformed, do nothing. } setTimeout(ms, callback) { const applyTimeout = () => this._request.setTimeout(ms, callback); if (this._request) { applyTimeout(); } else { this[kJobs].push(applyTimeout); } return this; } get maxHeadersCount() { if (!this.destroyed && this._request) { return this._request.session.localSettings.maxHeaderListSize; } return undefined; } set maxHeadersCount(_value) { // Updating HTTP2 settings would affect all requests, do nothing. } } module.exports = ClientRequest; /***/ }), /***/ 82575: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const {Readable} = __nccwpck_require__(12781); class IncomingMessage extends Readable { constructor(socket, highWaterMark) { super({ highWaterMark, autoDestroy: false }); this.statusCode = null; this.statusMessage = ''; this.httpVersion = '2.0'; this.httpVersionMajor = 2; this.httpVersionMinor = 0; this.headers = {}; this.trailers = {}; this.req = null; this.aborted = false; this.complete = false; this.upgrade = null; this.rawHeaders = []; this.rawTrailers = []; this.socket = socket; this.connection = socket; this._dumped = false; } _destroy(error) { this.req._request.destroy(error); } setTimeout(ms, callback) { this.req.setTimeout(ms, callback); return this; } _dump() { if (!this._dumped) { this._dumped = true; this.removeAllListeners('data'); this.resume(); } } _read() { if (this.req) { this.req._request.resume(); } } } module.exports = IncomingMessage; /***/ }), /***/ 54645: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const http2 = __nccwpck_require__(85158); const agent = __nccwpck_require__(79898); const ClientRequest = __nccwpck_require__(59632); const IncomingMessage = __nccwpck_require__(82575); const auto = __nccwpck_require__(97167); const request = (url, options, callback) => { return new ClientRequest(url, options, callback); }; const get = (url, options, callback) => { // eslint-disable-next-line unicorn/prevent-abbreviations const req = new ClientRequest(url, options, callback); req.end(); return req; }; module.exports = { ...http2, ClientRequest, IncomingMessage, ...agent, request, get, auto }; /***/ }), /***/ 51982: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const net = __nccwpck_require__(41808); /* istanbul ignore file: https://github.com/nodejs/node/blob/v13.0.1/lib/_http_agent.js */ module.exports = options => { let servername = options.host; const hostHeader = options.headers && options.headers.host; if (hostHeader) { if (hostHeader.startsWith('[')) { const index = hostHeader.indexOf(']'); if (index === -1) { servername = hostHeader; } else { servername = hostHeader.slice(1, -1); } } else { servername = hostHeader.split(':', 1)[0]; } } if (net.isIP(servername)) { return ''; } return servername; }; /***/ }), /***/ 7087: /***/ ((module) => { "use strict"; /* istanbul ignore file: https://github.com/nodejs/node/blob/master/lib/internal/errors.js */ const makeError = (Base, key, getMessage) => { module.exports[key] = class NodeError extends Base { constructor(...args) { super(typeof getMessage === 'string' ? getMessage : getMessage(args)); this.name = `${super.name} [${key}]`; this.code = key; } }; }; makeError(TypeError, 'ERR_INVALID_ARG_TYPE', args => { const type = args[0].includes('.') ? 'property' : 'argument'; let valid = args[1]; const isManyTypes = Array.isArray(valid); if (isManyTypes) { valid = `${valid.slice(0, -1).join(', ')} or ${valid.slice(-1)}`; } return `The "${args[0]}" ${type} must be ${isManyTypes ? 'one of' : 'of'} type ${valid}. Received ${typeof args[2]}`; }); makeError(TypeError, 'ERR_INVALID_PROTOCOL', args => { return `Protocol "${args[0]}" not supported. Expected "${args[1]}"`; }); makeError(Error, 'ERR_HTTP_HEADERS_SENT', args => { return `Cannot ${args[0]} headers after they are sent to the client`; }); makeError(TypeError, 'ERR_INVALID_HTTP_TOKEN', args => { return `${args[0]} must be a valid HTTP token [${args[1]}]`; }); makeError(TypeError, 'ERR_HTTP_INVALID_HEADER_VALUE', args => { return `Invalid value "${args[0]} for header "${args[1]}"`; }); makeError(TypeError, 'ERR_INVALID_CHAR', args => { return `Invalid character in ${args[0]} [${args[1]}]`; }); /***/ }), /***/ 11199: /***/ ((module) => { "use strict"; module.exports = header => { switch (header) { case ':method': case ':scheme': case ':authority': case ':path': return true; default: return false; } }; /***/ }), /***/ 81818: /***/ ((module) => { "use strict"; module.exports = (from, to, events) => { for (const event of events) { from.on(event, (...args) => to.emit(event, ...args)); } }; /***/ }), /***/ 92686: /***/ ((module) => { "use strict"; /* istanbul ignore file: https://github.com/nodejs/node/blob/a91293d4d9ab403046ab5eb022332e4e3d249bd3/lib/internal/url.js#L1257 */ module.exports = url => { const options = { protocol: url.protocol, hostname: typeof url.hostname === 'string' && url.hostname.startsWith('[') ? url.hostname.slice(1, -1) : url.hostname, host: url.host, hash: url.hash, search: url.search, pathname: url.pathname, href: url.href, path: `${url.pathname || ''}${url.search || ''}` }; if (typeof url.port === 'string' && url.port.length !== 0) { options.port = Number(url.port); } if (url.username || url.password) { options.auth = `${url.username || ''}:${url.password || ''}`; } return options; }; /***/ }), /***/ 28213: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({value:true}));exports.SIGNALS=void 0; const SIGNALS=[ { name:"SIGHUP", number:1, action:"terminate", description:"Terminal closed", standard:"posix"}, { name:"SIGINT", number:2, action:"terminate", description:"User interruption with CTRL-C", standard:"ansi"}, { name:"SIGQUIT", number:3, action:"core", description:"User interruption with CTRL-\\", standard:"posix"}, { name:"SIGILL", number:4, action:"core", description:"Invalid machine instruction", standard:"ansi"}, { name:"SIGTRAP", number:5, action:"core", description:"Debugger breakpoint", standard:"posix"}, { name:"SIGABRT", number:6, action:"core", description:"Aborted", standard:"ansi"}, { name:"SIGIOT", number:6, action:"core", description:"Aborted", standard:"bsd"}, { name:"SIGBUS", number:7, action:"core", description: "Bus error due to misaligned, non-existing address or paging error", standard:"bsd"}, { name:"SIGEMT", number:7, action:"terminate", description:"Command should be emulated but is not implemented", standard:"other"}, { name:"SIGFPE", number:8, action:"core", description:"Floating point arithmetic error", standard:"ansi"}, { name:"SIGKILL", number:9, action:"terminate", description:"Forced termination", standard:"posix", forced:true}, { name:"SIGUSR1", number:10, action:"terminate", description:"Application-specific signal", standard:"posix"}, { name:"SIGSEGV", number:11, action:"core", description:"Segmentation fault", standard:"ansi"}, { name:"SIGUSR2", number:12, action:"terminate", description:"Application-specific signal", standard:"posix"}, { name:"SIGPIPE", number:13, action:"terminate", description:"Broken pipe or socket", standard:"posix"}, { name:"SIGALRM", number:14, action:"terminate", description:"Timeout or timer", standard:"posix"}, { name:"SIGTERM", number:15, action:"terminate", description:"Termination", standard:"ansi"}, { name:"SIGSTKFLT", number:16, action:"terminate", description:"Stack is empty or overflowed", standard:"other"}, { name:"SIGCHLD", number:17, action:"ignore", description:"Child process terminated, paused or unpaused", standard:"posix"}, { name:"SIGCLD", number:17, action:"ignore", description:"Child process terminated, paused or unpaused", standard:"other"}, { name:"SIGCONT", number:18, action:"unpause", description:"Unpaused", standard:"posix", forced:true}, { name:"SIGSTOP", number:19, action:"pause", description:"Paused", standard:"posix", forced:true}, { name:"SIGTSTP", number:20, action:"pause", description:"Paused using CTRL-Z or \"suspend\"", standard:"posix"}, { name:"SIGTTIN", number:21, action:"pause", description:"Background process cannot read terminal input", standard:"posix"}, { name:"SIGBREAK", number:21, action:"terminate", description:"User interruption with CTRL-BREAK", standard:"other"}, { name:"SIGTTOU", number:22, action:"pause", description:"Background process cannot write to terminal output", standard:"posix"}, { name:"SIGURG", number:23, action:"ignore", description:"Socket received out-of-band data", standard:"bsd"}, { name:"SIGXCPU", number:24, action:"core", description:"Process timed out", standard:"bsd"}, { name:"SIGXFSZ", number:25, action:"core", description:"File too big", standard:"bsd"}, { name:"SIGVTALRM", number:26, action:"terminate", description:"Timeout or timer", standard:"bsd"}, { name:"SIGPROF", number:27, action:"terminate", description:"Timeout or timer", standard:"bsd"}, { name:"SIGWINCH", number:28, action:"ignore", description:"Terminal window size changed", standard:"bsd"}, { name:"SIGIO", number:29, action:"terminate", description:"I/O is available", standard:"other"}, { name:"SIGPOLL", number:29, action:"terminate", description:"Watched event", standard:"other"}, { name:"SIGINFO", number:29, action:"ignore", description:"Request for process information", standard:"other"}, { name:"SIGPWR", number:30, action:"terminate", description:"Device running out of power", standard:"systemv"}, { name:"SIGSYS", number:31, action:"core", description:"Invalid system call", standard:"other"}, { name:"SIGUNUSED", number:31, action:"terminate", description:"Invalid system call", standard:"other"}];exports.SIGNALS=SIGNALS; //# sourceMappingURL=core.js.map /***/ }), /***/ 2779: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({value:true}));exports.signalsByNumber=exports.signalsByName=void 0;var _os=__nccwpck_require__(22037); var _signals=__nccwpck_require__(86435); var _realtime=__nccwpck_require__(25295); const getSignalsByName=function(){ const signals=(0,_signals.getSignals)(); return signals.reduce(getSignalByName,{}); }; const getSignalByName=function( signalByNameMemo, {name,number,description,supported,action,forced,standard}) { return{ ...signalByNameMemo, [name]:{name,number,description,supported,action,forced,standard}}; }; const signalsByName=getSignalsByName();exports.signalsByName=signalsByName; const getSignalsByNumber=function(){ const signals=(0,_signals.getSignals)(); const length=_realtime.SIGRTMAX+1; const signalsA=Array.from({length},(value,number)=> getSignalByNumber(number,signals)); return Object.assign({},...signalsA); }; const getSignalByNumber=function(number,signals){ const signal=findSignalByNumber(number,signals); if(signal===undefined){ return{}; } const{name,description,supported,action,forced,standard}=signal; return{ [number]:{ name, number, description, supported, action, forced, standard}}; }; const findSignalByNumber=function(number,signals){ const signal=signals.find(({name})=>_os.constants.signals[name]===number); if(signal!==undefined){ return signal; } return signals.find(signalA=>signalA.number===number); }; const signalsByNumber=getSignalsByNumber();exports.signalsByNumber=signalsByNumber; //# sourceMappingURL=main.js.map /***/ }), /***/ 25295: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({value:true}));exports.SIGRTMAX=exports.getRealtimeSignals=void 0; const getRealtimeSignals=function(){ const length=SIGRTMAX-SIGRTMIN+1; return Array.from({length},getRealtimeSignal); };exports.getRealtimeSignals=getRealtimeSignals; const getRealtimeSignal=function(value,index){ return{ name:`SIGRT${index+1}`, number:SIGRTMIN+index, action:"terminate", description:"Application-specific signal (realtime)", standard:"posix"}; }; const SIGRTMIN=34; const SIGRTMAX=64;exports.SIGRTMAX=SIGRTMAX; //# sourceMappingURL=realtime.js.map /***/ }), /***/ 86435: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({value:true}));exports.getSignals=void 0;var _os=__nccwpck_require__(22037); var _core=__nccwpck_require__(28213); var _realtime=__nccwpck_require__(25295); const getSignals=function(){ const realtimeSignals=(0,_realtime.getRealtimeSignals)(); const signals=[..._core.SIGNALS,...realtimeSignals].map(normalizeSignal); return signals; };exports.getSignals=getSignals; const normalizeSignal=function({ name, number:defaultNumber, description, action, forced=false, standard}) { const{ signals:{[name]:constantSignal}}= _os.constants; const supported=constantSignal!==undefined; const number=supported?constantSignal:defaultNumber; return{name,number,description,supported,action,forced,standard}; }; //# sourceMappingURL=signals.js.map /***/ }), /***/ 98043: /***/ ((module) => { "use strict"; module.exports = (string, count = 1, options) => { options = { indent: ' ', includeEmptyLines: false, ...options }; if (typeof string !== 'string') { throw new TypeError( `Expected \`input\` to be a \`string\`, got \`${typeof string}\`` ); } if (typeof count !== 'number') { throw new TypeError( `Expected \`count\` to be a \`number\`, got \`${typeof count}\`` ); } if (typeof options.indent !== 'string') { throw new TypeError( `Expected \`options.indent\` to be a \`string\`, got \`${typeof options.indent}\`` ); } if (count === 0) { return string; } const regex = options.includeEmptyLines ? /^/gm : /^(?!\s*$)/gm; return string.replace(regex, options.indent.repeat(count)); }; /***/ }), /***/ 52492: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var wrappy = __nccwpck_require__(62940) var reqs = Object.create(null) var once = __nccwpck_require__(1223) module.exports = wrappy(inflight) function inflight (key, cb) { if (reqs[key]) { reqs[key].push(cb) return null } else { reqs[key] = [cb] return makeres(key) } } function makeres (key) { return once(function RES () { var cbs = reqs[key] var len = cbs.length var args = slice(arguments) // XXX It's somewhat ambiguous whether a new callback added in this // pass should be queued for later execution if something in the // list of callbacks throws, or if it should just be discarded. // However, it's such an edge case that it hardly matters, and either // choice is likely as surprising as the other. // As it happens, we do go ahead and schedule it for later execution. try { for (var i = 0; i < len; i++) { cbs[i].apply(null, args) } } finally { if (cbs.length > len) { // added more in the interim. // de-zalgo, just in case, but don't call again. cbs.splice(0, len) process.nextTick(function () { RES.apply(null, args) }) } else { delete reqs[key] } } }) } function slice (args) { var length = args.length var array = [] for (var i = 0; i < length; i++) array[i] = args[i] return array } /***/ }), /***/ 44124: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { try { var util = __nccwpck_require__(73837); /* istanbul ignore next */ if (typeof util.inherits !== 'function') throw ''; module.exports = util.inherits; } catch (e) { /* istanbul ignore next */ module.exports = __nccwpck_require__(8544); } /***/ }), /***/ 8544: /***/ ((module) => { if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { if (superCtor) { ctor.super_ = superCtor ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }) } }; } else { // old school shim for old browsers module.exports = function inherits(ctor, superCtor) { if (superCtor) { ctor.super_ = superCtor var TempCtor = function () {} TempCtor.prototype = superCtor.prototype ctor.prototype = new TempCtor() ctor.prototype.constructor = ctor } } } /***/ }), /***/ 41554: /***/ ((module) => { "use strict"; const isStream = stream => stream !== null && typeof stream === 'object' && typeof stream.pipe === 'function'; isStream.writable = stream => isStream(stream) && stream.writable !== false && typeof stream._write === 'function' && typeof stream._writableState === 'object'; isStream.readable = stream => isStream(stream) && stream.readable !== false && typeof stream._read === 'function' && typeof stream._readableState === 'object'; isStream.duplex = stream => isStream.writable(stream) && isStream.readable(stream); isStream.transform = stream => isStream.duplex(stream) && typeof stream._transform === 'function'; module.exports = isStream; /***/ }), /***/ 10657: /***/ ((module) => { module.exports = isTypedArray isTypedArray.strict = isStrictTypedArray isTypedArray.loose = isLooseTypedArray var toString = Object.prototype.toString var names = { '[object Int8Array]': true , '[object Int16Array]': true , '[object Int32Array]': true , '[object Uint8Array]': true , '[object Uint8ClampedArray]': true , '[object Uint16Array]': true , '[object Uint32Array]': true , '[object Float32Array]': true , '[object Float64Array]': true } function isTypedArray(arr) { return ( isStrictTypedArray(arr) || isLooseTypedArray(arr) ) } function isStrictTypedArray(arr) { return ( arr instanceof Int8Array || arr instanceof Int16Array || arr instanceof Int32Array || arr instanceof Uint8Array || arr instanceof Uint8ClampedArray || arr instanceof Uint16Array || arr instanceof Uint32Array || arr instanceof Float32Array || arr instanceof Float64Array ) } function isLooseTypedArray(arr) { return names[toString.call(arr)] } /***/ }), /***/ 97126: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var fs = __nccwpck_require__(57147) var core if (process.platform === 'win32' || global.TESTING_WINDOWS) { core = __nccwpck_require__(42001) } else { core = __nccwpck_require__(9728) } module.exports = isexe isexe.sync = sync function isexe (path, options, cb) { if (typeof options === 'function') { cb = options options = {} } if (!cb) { if (typeof Promise !== 'function') { throw new TypeError('callback not provided') } return new Promise(function (resolve, reject) { isexe(path, options || {}, function (er, is) { if (er) { reject(er) } else { resolve(is) } }) }) } core(path, options || {}, function (er, is) { // ignore EACCES because that just means we aren't allowed to run it if (er) { if (er.code === 'EACCES' || options && options.ignoreErrors) { er = null is = false } } cb(er, is) }) } function sync (path, options) { // my kingdom for a filtered catch try { return core.sync(path, options || {}) } catch (er) { if (options && options.ignoreErrors || er.code === 'EACCES') { return false } else { throw er } } } /***/ }), /***/ 9728: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { module.exports = isexe isexe.sync = sync var fs = __nccwpck_require__(57147) function isexe (path, options, cb) { fs.stat(path, function (er, stat) { cb(er, er ? false : checkStat(stat, options)) }) } function sync (path, options) { return checkStat(fs.statSync(path), options) } function checkStat (stat, options) { return stat.isFile() && checkMode(stat, options) } function checkMode (stat, options) { var mod = stat.mode var uid = stat.uid var gid = stat.gid var myUid = options.uid !== undefined ? options.uid : process.getuid && process.getuid() var myGid = options.gid !== undefined ? options.gid : process.getgid && process.getgid() var u = parseInt('100', 8) var g = parseInt('010', 8) var o = parseInt('001', 8) var ug = u | g var ret = (mod & o) || (mod & g) && gid === myGid || (mod & u) && uid === myUid || (mod & ug) && myUid === 0 return ret } /***/ }), /***/ 42001: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { module.exports = isexe isexe.sync = sync var fs = __nccwpck_require__(57147) function checkPathExt (path, options) { var pathext = options.pathExt !== undefined ? options.pathExt : process.env.PATHEXT if (!pathext) { return true } pathext = pathext.split(';') if (pathext.indexOf('') !== -1) { return true } for (var i = 0; i < pathext.length; i++) { var p = pathext[i].toLowerCase() if (p && path.substr(-p.length).toLowerCase() === p) { return true } } return false } function checkStat (stat, path, options) { if (!stat.isSymbolicLink() && !stat.isFile()) { return false } return checkPathExt(path, options) } function isexe (path, options, cb) { fs.stat(path, function (er, stat) { cb(er, er ? false : checkStat(stat, path, options)) }) } function sync (path, options) { return checkStat(fs.statSync(path), path, options) } /***/ }), /***/ 64713: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; module.exports = __nccwpck_require__(88867); /***/ }), /***/ 83362: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var stream = __nccwpck_require__(12781) function isStream (obj) { return obj instanceof stream.Stream } function isReadable (obj) { return isStream(obj) && typeof obj._read == 'function' && typeof obj._readableState == 'object' } function isWritable (obj) { return isStream(obj) && typeof obj._write == 'function' && typeof obj._writableState == 'object' } function isDuplex (obj) { return isReadable(obj) && isWritable(obj) } module.exports = isStream module.exports.isReadable = isReadable module.exports.isWritable = isWritable module.exports.isDuplex = isDuplex /***/ }), /***/ 21917: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var loader = __nccwpck_require__(51161); var dumper = __nccwpck_require__(68866); function renamed(from, to) { return function () { throw new Error('Function yaml.' + from + ' is removed in js-yaml 4. ' + 'Use yaml.' + to + ' instead, which is now safe by default.'); }; } module.exports.Type = __nccwpck_require__(6073); module.exports.Schema = __nccwpck_require__(21082); module.exports.FAILSAFE_SCHEMA = __nccwpck_require__(28562); module.exports.JSON_SCHEMA = __nccwpck_require__(1035); module.exports.CORE_SCHEMA = __nccwpck_require__(12011); module.exports.DEFAULT_SCHEMA = __nccwpck_require__(18759); module.exports.load = loader.load; module.exports.loadAll = loader.loadAll; module.exports.dump = dumper.dump; module.exports.YAMLException = __nccwpck_require__(68179); // Re-export all types in case user wants to create custom schema module.exports.types = { binary: __nccwpck_require__(77900), float: __nccwpck_require__(42705), map: __nccwpck_require__(86150), null: __nccwpck_require__(20721), pairs: __nccwpck_require__(96860), set: __nccwpck_require__(79548), timestamp: __nccwpck_require__(99212), bool: __nccwpck_require__(64993), int: __nccwpck_require__(11615), merge: __nccwpck_require__(86104), omap: __nccwpck_require__(19046), seq: __nccwpck_require__(67283), str: __nccwpck_require__(23619) }; // Removed functions from JS-YAML 3.0.x module.exports.safeLoad = renamed('safeLoad', 'load'); module.exports.safeLoadAll = renamed('safeLoadAll', 'loadAll'); module.exports.safeDump = renamed('safeDump', 'dump'); /***/ }), /***/ 26829: /***/ ((module) => { "use strict"; function isNothing(subject) { return (typeof subject === 'undefined') || (subject === null); } function isObject(subject) { return (typeof subject === 'object') && (subject !== null); } function toArray(sequence) { if (Array.isArray(sequence)) return sequence; else if (isNothing(sequence)) return []; return [ sequence ]; } function extend(target, source) { var index, length, key, sourceKeys; if (source) { sourceKeys = Object.keys(source); for (index = 0, length = sourceKeys.length; index < length; index += 1) { key = sourceKeys[index]; target[key] = source[key]; } } return target; } function repeat(string, count) { var result = '', cycle; for (cycle = 0; cycle < count; cycle += 1) { result += string; } return result; } function isNegativeZero(number) { return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number); } module.exports.isNothing = isNothing; module.exports.isObject = isObject; module.exports.toArray = toArray; module.exports.repeat = repeat; module.exports.isNegativeZero = isNegativeZero; module.exports.extend = extend; /***/ }), /***/ 68866: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /*eslint-disable no-use-before-define*/ var common = __nccwpck_require__(26829); var YAMLException = __nccwpck_require__(68179); var DEFAULT_SCHEMA = __nccwpck_require__(18759); var _toString = Object.prototype.toString; var _hasOwnProperty = Object.prototype.hasOwnProperty; var CHAR_BOM = 0xFEFF; var CHAR_TAB = 0x09; /* Tab */ var CHAR_LINE_FEED = 0x0A; /* LF */ var CHAR_CARRIAGE_RETURN = 0x0D; /* CR */ var CHAR_SPACE = 0x20; /* Space */ var CHAR_EXCLAMATION = 0x21; /* ! */ var CHAR_DOUBLE_QUOTE = 0x22; /* " */ var CHAR_SHARP = 0x23; /* # */ var CHAR_PERCENT = 0x25; /* % */ var CHAR_AMPERSAND = 0x26; /* & */ var CHAR_SINGLE_QUOTE = 0x27; /* ' */ var CHAR_ASTERISK = 0x2A; /* * */ var CHAR_COMMA = 0x2C; /* , */ var CHAR_MINUS = 0x2D; /* - */ var CHAR_COLON = 0x3A; /* : */ var CHAR_EQUALS = 0x3D; /* = */ var CHAR_GREATER_THAN = 0x3E; /* > */ var CHAR_QUESTION = 0x3F; /* ? */ var CHAR_COMMERCIAL_AT = 0x40; /* @ */ var CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */ var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */ var CHAR_GRAVE_ACCENT = 0x60; /* ` */ var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */ var CHAR_VERTICAL_LINE = 0x7C; /* | */ var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */ var ESCAPE_SEQUENCES = {}; ESCAPE_SEQUENCES[0x00] = '\\0'; ESCAPE_SEQUENCES[0x07] = '\\a'; ESCAPE_SEQUENCES[0x08] = '\\b'; ESCAPE_SEQUENCES[0x09] = '\\t'; ESCAPE_SEQUENCES[0x0A] = '\\n'; ESCAPE_SEQUENCES[0x0B] = '\\v'; ESCAPE_SEQUENCES[0x0C] = '\\f'; ESCAPE_SEQUENCES[0x0D] = '\\r'; ESCAPE_SEQUENCES[0x1B] = '\\e'; ESCAPE_SEQUENCES[0x22] = '\\"'; ESCAPE_SEQUENCES[0x5C] = '\\\\'; ESCAPE_SEQUENCES[0x85] = '\\N'; ESCAPE_SEQUENCES[0xA0] = '\\_'; ESCAPE_SEQUENCES[0x2028] = '\\L'; ESCAPE_SEQUENCES[0x2029] = '\\P'; var DEPRECATED_BOOLEANS_SYNTAX = [ 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON', 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF' ]; var DEPRECATED_BASE60_SYNTAX = /^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/; function compileStyleMap(schema, map) { var result, keys, index, length, tag, style, type; if (map === null) return {}; result = {}; keys = Object.keys(map); for (index = 0, length = keys.length; index < length; index += 1) { tag = keys[index]; style = String(map[tag]); if (tag.slice(0, 2) === '!!') { tag = 'tag:yaml.org,2002:' + tag.slice(2); } type = schema.compiledTypeMap['fallback'][tag]; if (type && _hasOwnProperty.call(type.styleAliases, style)) { style = type.styleAliases[style]; } result[tag] = style; } return result; } function encodeHex(character) { var string, handle, length; string = character.toString(16).toUpperCase(); if (character <= 0xFF) { handle = 'x'; length = 2; } else if (character <= 0xFFFF) { handle = 'u'; length = 4; } else if (character <= 0xFFFFFFFF) { handle = 'U'; length = 8; } else { throw new YAMLException('code point within a string may not be greater than 0xFFFFFFFF'); } return '\\' + handle + common.repeat('0', length - string.length) + string; } var QUOTING_TYPE_SINGLE = 1, QUOTING_TYPE_DOUBLE = 2; function State(options) { this.schema = options['schema'] || DEFAULT_SCHEMA; this.indent = Math.max(1, (options['indent'] || 2)); this.noArrayIndent = options['noArrayIndent'] || false; this.skipInvalid = options['skipInvalid'] || false; this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']); this.styleMap = compileStyleMap(this.schema, options['styles'] || null); this.sortKeys = options['sortKeys'] || false; this.lineWidth = options['lineWidth'] || 80; this.noRefs = options['noRefs'] || false; this.noCompatMode = options['noCompatMode'] || false; this.condenseFlow = options['condenseFlow'] || false; this.quotingType = options['quotingType'] === '"' ? QUOTING_TYPE_DOUBLE : QUOTING_TYPE_SINGLE; this.forceQuotes = options['forceQuotes'] || false; this.replacer = typeof options['replacer'] === 'function' ? options['replacer'] : null; this.implicitTypes = this.schema.compiledImplicit; this.explicitTypes = this.schema.compiledExplicit; this.tag = null; this.result = ''; this.duplicates = []; this.usedDuplicates = null; } // Indents every line in a string. Empty lines (\n only) are not indented. function indentString(string, spaces) { var ind = common.repeat(' ', spaces), position = 0, next = -1, result = '', line, length = string.length; while (position < length) { next = string.indexOf('\n', position); if (next === -1) { line = string.slice(position); position = length; } else { line = string.slice(position, next + 1); position = next + 1; } if (line.length && line !== '\n') result += ind; result += line; } return result; } function generateNextLine(state, level) { return '\n' + common.repeat(' ', state.indent * level); } function testImplicitResolving(state, str) { var index, length, type; for (index = 0, length = state.implicitTypes.length; index < length; index += 1) { type = state.implicitTypes[index]; if (type.resolve(str)) { return true; } } return false; } // [33] s-white ::= s-space | s-tab function isWhitespace(c) { return c === CHAR_SPACE || c === CHAR_TAB; } // Returns true if the character can be printed without escaping. // From YAML 1.2: "any allowed characters known to be non-printable // should also be escaped. [However,] This isn’t mandatory" // Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029. function isPrintable(c) { return (0x00020 <= c && c <= 0x00007E) || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029) || ((0x0E000 <= c && c <= 0x00FFFD) && c !== CHAR_BOM) || (0x10000 <= c && c <= 0x10FFFF); } // [34] ns-char ::= nb-char - s-white // [27] nb-char ::= c-printable - b-char - c-byte-order-mark // [26] b-char ::= b-line-feed | b-carriage-return // Including s-white (for some reason, examples doesn't match specs in this aspect) // ns-char ::= c-printable - b-line-feed - b-carriage-return - c-byte-order-mark function isNsCharOrWhitespace(c) { return isPrintable(c) && c !== CHAR_BOM // - b-char && c !== CHAR_CARRIAGE_RETURN && c !== CHAR_LINE_FEED; } // [127] ns-plain-safe(c) ::= c = flow-out ⇒ ns-plain-safe-out // c = flow-in ⇒ ns-plain-safe-in // c = block-key ⇒ ns-plain-safe-out // c = flow-key ⇒ ns-plain-safe-in // [128] ns-plain-safe-out ::= ns-char // [129] ns-plain-safe-in ::= ns-char - c-flow-indicator // [130] ns-plain-char(c) ::= ( ns-plain-safe(c) - “:” - “#” ) // | ( /* An ns-char preceding */ “#” ) // | ( “:” /* Followed by an ns-plain-safe(c) */ ) function isPlainSafe(c, prev, inblock) { var cIsNsCharOrWhitespace = isNsCharOrWhitespace(c); var cIsNsChar = cIsNsCharOrWhitespace && !isWhitespace(c); return ( // ns-plain-safe inblock ? // c = flow-in cIsNsCharOrWhitespace : cIsNsCharOrWhitespace // - c-flow-indicator && c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET ) // ns-plain-char && c !== CHAR_SHARP // false on '#' && !(prev === CHAR_COLON && !cIsNsChar) // false on ': ' || (isNsCharOrWhitespace(prev) && !isWhitespace(prev) && c === CHAR_SHARP) // change to true on '[^ ]#' || (prev === CHAR_COLON && cIsNsChar); // change to true on ':[^ ]' } // Simplified test for values allowed as the first character in plain style. function isPlainSafeFirst(c) { // Uses a subset of ns-char - c-indicator // where ns-char = nb-char - s-white. // No support of ( ( “?” | “:” | “-” ) /* Followed by an ns-plain-safe(c)) */ ) part return isPrintable(c) && c !== CHAR_BOM && !isWhitespace(c) // - s-white // - (c-indicator ::= // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}” && c !== CHAR_MINUS && c !== CHAR_QUESTION && c !== CHAR_COLON && c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET // | “#” | “&” | “*” | “!” | “|” | “=” | “>” | “'” | “"” && c !== CHAR_SHARP && c !== CHAR_AMPERSAND && c !== CHAR_ASTERISK && c !== CHAR_EXCLAMATION && c !== CHAR_VERTICAL_LINE && c !== CHAR_EQUALS && c !== CHAR_GREATER_THAN && c !== CHAR_SINGLE_QUOTE && c !== CHAR_DOUBLE_QUOTE // | “%” | “@” | “`”) && c !== CHAR_PERCENT && c !== CHAR_COMMERCIAL_AT && c !== CHAR_GRAVE_ACCENT; } // Simplified test for values allowed as the last character in plain style. function isPlainSafeLast(c) { // just not whitespace or colon, it will be checked to be plain character later return !isWhitespace(c) && c !== CHAR_COLON; } // Same as 'string'.codePointAt(pos), but works in older browsers. function codePointAt(string, pos) { var first = string.charCodeAt(pos), second; if (first >= 0xD800 && first <= 0xDBFF && pos + 1 < string.length) { second = string.charCodeAt(pos + 1); if (second >= 0xDC00 && second <= 0xDFFF) { // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; } } return first; } // Determines whether block indentation indicator is required. function needIndentIndicator(string) { var leadingSpaceRe = /^\n* /; return leadingSpaceRe.test(string); } var STYLE_PLAIN = 1, STYLE_SINGLE = 2, STYLE_LITERAL = 3, STYLE_FOLDED = 4, STYLE_DOUBLE = 5; // Determines which scalar styles are possible and returns the preferred style. // lineWidth = -1 => no limit. // Pre-conditions: str.length > 0. // Post-conditions: // STYLE_PLAIN or STYLE_SINGLE => no \n are in the string. // STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1). // STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1). function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType, quotingType, forceQuotes, inblock) { var i; var char = 0; var prevChar = null; var hasLineBreak = false; var hasFoldableLine = false; // only checked if shouldTrackWidth var shouldTrackWidth = lineWidth !== -1; var previousLineBreak = -1; // count the first line correctly var plain = isPlainSafeFirst(codePointAt(string, 0)) && isPlainSafeLast(codePointAt(string, string.length - 1)); if (singleLineOnly || forceQuotes) { // Case: no block styles. // Check for disallowed characters to rule out plain and single. for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { char = codePointAt(string, i); if (!isPrintable(char)) { return STYLE_DOUBLE; } plain = plain && isPlainSafe(char, prevChar, inblock); prevChar = char; } } else { // Case: block styles permitted. for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { char = codePointAt(string, i); if (char === CHAR_LINE_FEED) { hasLineBreak = true; // Check if any line can be folded. if (shouldTrackWidth) { hasFoldableLine = hasFoldableLine || // Foldable line = too long, and not more-indented. (i - previousLineBreak - 1 > lineWidth && string[previousLineBreak + 1] !== ' '); previousLineBreak = i; } } else if (!isPrintable(char)) { return STYLE_DOUBLE; } plain = plain && isPlainSafe(char, prevChar, inblock); prevChar = char; } // in case the end is missing a \n hasFoldableLine = hasFoldableLine || (shouldTrackWidth && (i - previousLineBreak - 1 > lineWidth && string[previousLineBreak + 1] !== ' ')); } // Although every style can represent \n without escaping, prefer block styles // for multiline, since they're more readable and they don't add empty lines. // Also prefer folding a super-long line. if (!hasLineBreak && !hasFoldableLine) { // Strings interpretable as another type have to be quoted; // e.g. the string 'true' vs. the boolean true. if (plain && !forceQuotes && !testAmbiguousType(string)) { return STYLE_PLAIN; } return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE; } // Edge case: block indentation indicator can only have one digit. if (indentPerLevel > 9 && needIndentIndicator(string)) { return STYLE_DOUBLE; } // At this point we know block styles are valid. // Prefer literal style unless we want to fold. if (!forceQuotes) { return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL; } return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE; } // Note: line breaking/folding is implemented for only the folded style. // NB. We drop the last trailing newline (if any) of a returned block scalar // since the dumper adds its own newline. This always works: // • No ending newline => unaffected; already using strip "-" chomping. // • Ending newline => removed then restored. // Importantly, this keeps the "+" chomp indicator from gaining an extra line. function writeScalar(state, string, level, iskey, inblock) { state.dump = (function () { if (string.length === 0) { return state.quotingType === QUOTING_TYPE_DOUBLE ? '""' : "''"; } if (!state.noCompatMode) { if (DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1 || DEPRECATED_BASE60_SYNTAX.test(string)) { return state.quotingType === QUOTING_TYPE_DOUBLE ? ('"' + string + '"') : ("'" + string + "'"); } } var indent = state.indent * Math.max(1, level); // no 0-indent scalars // As indentation gets deeper, let the width decrease monotonically // to the lower bound min(state.lineWidth, 40). // Note that this implies // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound. // state.lineWidth > 40 + state.indent: width decreases until the lower bound. // This behaves better than a constant minimum width which disallows narrower options, // or an indent threshold which causes the width to suddenly increase. var lineWidth = state.lineWidth === -1 ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent); // Without knowing if keys are implicit/explicit, assume implicit for safety. var singleLineOnly = iskey // No block styles in flow mode. || (state.flowLevel > -1 && level >= state.flowLevel); function testAmbiguity(string) { return testImplicitResolving(state, string); } switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, testAmbiguity, state.quotingType, state.forceQuotes && !iskey, inblock)) { case STYLE_PLAIN: return string; case STYLE_SINGLE: return "'" + string.replace(/'/g, "''") + "'"; case STYLE_LITERAL: return '|' + blockHeader(string, state.indent) + dropEndingNewline(indentString(string, indent)); case STYLE_FOLDED: return '>' + blockHeader(string, state.indent) + dropEndingNewline(indentString(foldString(string, lineWidth), indent)); case STYLE_DOUBLE: return '"' + escapeString(string, lineWidth) + '"'; default: throw new YAMLException('impossible error: invalid scalar style'); } }()); } // Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9. function blockHeader(string, indentPerLevel) { var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : ''; // note the special case: the string '\n' counts as a "trailing" empty line. var clip = string[string.length - 1] === '\n'; var keep = clip && (string[string.length - 2] === '\n' || string === '\n'); var chomp = keep ? '+' : (clip ? '' : '-'); return indentIndicator + chomp + '\n'; } // (See the note for writeScalar.) function dropEndingNewline(string) { return string[string.length - 1] === '\n' ? string.slice(0, -1) : string; } // Note: a long line without a suitable break point will exceed the width limit. // Pre-conditions: every char in str isPrintable, str.length > 0, width > 0. function foldString(string, width) { // In folded style, $k$ consecutive newlines output as $k+1$ newlines— // unless they're before or after a more-indented line, or at the very // beginning or end, in which case $k$ maps to $k$. // Therefore, parse each chunk as newline(s) followed by a content line. var lineRe = /(\n+)([^\n]*)/g; // first line (possibly an empty line) var result = (function () { var nextLF = string.indexOf('\n'); nextLF = nextLF !== -1 ? nextLF : string.length; lineRe.lastIndex = nextLF; return foldLine(string.slice(0, nextLF), width); }()); // If we haven't reached the first content line yet, don't add an extra \n. var prevMoreIndented = string[0] === '\n' || string[0] === ' '; var moreIndented; // rest of the lines var match; while ((match = lineRe.exec(string))) { var prefix = match[1], line = match[2]; moreIndented = (line[0] === ' '); result += prefix + (!prevMoreIndented && !moreIndented && line !== '' ? '\n' : '') + foldLine(line, width); prevMoreIndented = moreIndented; } return result; } // Greedy line breaking. // Picks the longest line under the limit each time, // otherwise settles for the shortest line over the limit. // NB. More-indented lines *cannot* be folded, as that would add an extra \n. function foldLine(line, width) { if (line === '' || line[0] === ' ') return line; // Since a more-indented line adds a \n, breaks can't be followed by a space. var breakRe = / [^ ]/g; // note: the match index will always be <= length-2. var match; // start is an inclusive index. end, curr, and next are exclusive. var start = 0, end, curr = 0, next = 0; var result = ''; // Invariants: 0 <= start <= length-1. // 0 <= curr <= next <= max(0, length-2). curr - start <= width. // Inside the loop: // A match implies length >= 2, so curr and next are <= length-2. while ((match = breakRe.exec(line))) { next = match.index; // maintain invariant: curr - start <= width if (next - start > width) { end = (curr > start) ? curr : next; // derive end <= length-2 result += '\n' + line.slice(start, end); // skip the space that was output as \n start = end + 1; // derive start <= length-1 } curr = next; } // By the invariants, start <= length-1, so there is something left over. // It is either the whole string or a part starting from non-whitespace. result += '\n'; // Insert a break if the remainder is too long and there is a break available. if (line.length - start > width && curr > start) { result += line.slice(start, curr) + '\n' + line.slice(curr + 1); } else { result += line.slice(start); } return result.slice(1); // drop extra \n joiner } // Escapes a double-quoted string. function escapeString(string) { var result = ''; var char = 0; var escapeSeq; for (var i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { char = codePointAt(string, i); escapeSeq = ESCAPE_SEQUENCES[char]; if (!escapeSeq && isPrintable(char)) { result += string[i]; if (char >= 0x10000) result += string[i + 1]; } else { result += escapeSeq || encodeHex(char); } } return result; } function writeFlowSequence(state, level, object) { var _result = '', _tag = state.tag, index, length, value; for (index = 0, length = object.length; index < length; index += 1) { value = object[index]; if (state.replacer) { value = state.replacer.call(object, String(index), value); } // Write only valid elements, put null instead of invalid elements. if (writeNode(state, level, value, false, false) || (typeof value === 'undefined' && writeNode(state, level, null, false, false))) { if (_result !== '') _result += ',' + (!state.condenseFlow ? ' ' : ''); _result += state.dump; } } state.tag = _tag; state.dump = '[' + _result + ']'; } function writeBlockSequence(state, level, object, compact) { var _result = '', _tag = state.tag, index, length, value; for (index = 0, length = object.length; index < length; index += 1) { value = object[index]; if (state.replacer) { value = state.replacer.call(object, String(index), value); } // Write only valid elements, put null instead of invalid elements. if (writeNode(state, level + 1, value, true, true, false, true) || (typeof value === 'undefined' && writeNode(state, level + 1, null, true, true, false, true))) { if (!compact || _result !== '') { _result += generateNextLine(state, level); } if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { _result += '-'; } else { _result += '- '; } _result += state.dump; } } state.tag = _tag; state.dump = _result || '[]'; // Empty sequence if no valid values. } function writeFlowMapping(state, level, object) { var _result = '', _tag = state.tag, objectKeyList = Object.keys(object), index, length, objectKey, objectValue, pairBuffer; for (index = 0, length = objectKeyList.length; index < length; index += 1) { pairBuffer = ''; if (_result !== '') pairBuffer += ', '; if (state.condenseFlow) pairBuffer += '"'; objectKey = objectKeyList[index]; objectValue = object[objectKey]; if (state.replacer) { objectValue = state.replacer.call(object, objectKey, objectValue); } if (!writeNode(state, level, objectKey, false, false)) { continue; // Skip this pair because of invalid key; } if (state.dump.length > 1024) pairBuffer += '? '; pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' '); if (!writeNode(state, level, objectValue, false, false)) { continue; // Skip this pair because of invalid value. } pairBuffer += state.dump; // Both key and value are valid. _result += pairBuffer; } state.tag = _tag; state.dump = '{' + _result + '}'; } function writeBlockMapping(state, level, object, compact) { var _result = '', _tag = state.tag, objectKeyList = Object.keys(object), index, length, objectKey, objectValue, explicitPair, pairBuffer; // Allow sorting keys so that the output file is deterministic if (state.sortKeys === true) { // Default sorting objectKeyList.sort(); } else if (typeof state.sortKeys === 'function') { // Custom sort function objectKeyList.sort(state.sortKeys); } else if (state.sortKeys) { // Something is wrong throw new YAMLException('sortKeys must be a boolean or a function'); } for (index = 0, length = objectKeyList.length; index < length; index += 1) { pairBuffer = ''; if (!compact || _result !== '') { pairBuffer += generateNextLine(state, level); } objectKey = objectKeyList[index]; objectValue = object[objectKey]; if (state.replacer) { objectValue = state.replacer.call(object, objectKey, objectValue); } if (!writeNode(state, level + 1, objectKey, true, true, true)) { continue; // Skip this pair because of invalid key. } explicitPair = (state.tag !== null && state.tag !== '?') || (state.dump && state.dump.length > 1024); if (explicitPair) { if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { pairBuffer += '?'; } else { pairBuffer += '? '; } } pairBuffer += state.dump; if (explicitPair) { pairBuffer += generateNextLine(state, level); } if (!writeNode(state, level + 1, objectValue, true, explicitPair)) { continue; // Skip this pair because of invalid value. } if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { pairBuffer += ':'; } else { pairBuffer += ': '; } pairBuffer += state.dump; // Both key and value are valid. _result += pairBuffer; } state.tag = _tag; state.dump = _result || '{}'; // Empty mapping if no valid pairs. } function detectType(state, object, explicit) { var _result, typeList, index, length, type, style; typeList = explicit ? state.explicitTypes : state.implicitTypes; for (index = 0, length = typeList.length; index < length; index += 1) { type = typeList[index]; if ((type.instanceOf || type.predicate) && (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) && (!type.predicate || type.predicate(object))) { if (explicit) { if (type.multi && type.representName) { state.tag = type.representName(object); } else { state.tag = type.tag; } } else { state.tag = '?'; } if (type.represent) { style = state.styleMap[type.tag] || type.defaultStyle; if (_toString.call(type.represent) === '[object Function]') { _result = type.represent(object, style); } else if (_hasOwnProperty.call(type.represent, style)) { _result = type.represent[style](object, style); } else { throw new YAMLException('!<' + type.tag + '> tag resolver accepts not "' + style + '" style'); } state.dump = _result; } return true; } } return false; } // Serializes `object` and writes it to global `result`. // Returns true on success, or false on invalid object. // function writeNode(state, level, object, block, compact, iskey, isblockseq) { state.tag = null; state.dump = object; if (!detectType(state, object, false)) { detectType(state, object, true); } var type = _toString.call(state.dump); var inblock = block; var tagStr; if (block) { block = (state.flowLevel < 0 || state.flowLevel > level); } var objectOrArray = type === '[object Object]' || type === '[object Array]', duplicateIndex, duplicate; if (objectOrArray) { duplicateIndex = state.duplicates.indexOf(object); duplicate = duplicateIndex !== -1; } if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) { compact = false; } if (duplicate && state.usedDuplicates[duplicateIndex]) { state.dump = '*ref_' + duplicateIndex; } else { if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) { state.usedDuplicates[duplicateIndex] = true; } if (type === '[object Object]') { if (block && (Object.keys(state.dump).length !== 0)) { writeBlockMapping(state, level, state.dump, compact); if (duplicate) { state.dump = '&ref_' + duplicateIndex + state.dump; } } else { writeFlowMapping(state, level, state.dump); if (duplicate) { state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; } } } else if (type === '[object Array]') { if (block && (state.dump.length !== 0)) { if (state.noArrayIndent && !isblockseq && level > 0) { writeBlockSequence(state, level - 1, state.dump, compact); } else { writeBlockSequence(state, level, state.dump, compact); } if (duplicate) { state.dump = '&ref_' + duplicateIndex + state.dump; } } else { writeFlowSequence(state, level, state.dump); if (duplicate) { state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; } } } else if (type === '[object String]') { if (state.tag !== '?') { writeScalar(state, state.dump, level, iskey, inblock); } } else if (type === '[object Undefined]') { return false; } else { if (state.skipInvalid) return false; throw new YAMLException('unacceptable kind of an object to dump ' + type); } if (state.tag !== null && state.tag !== '?') { // Need to encode all characters except those allowed by the spec: // // [35] ns-dec-digit ::= [#x30-#x39] /* 0-9 */ // [36] ns-hex-digit ::= ns-dec-digit // | [#x41-#x46] /* A-F */ | [#x61-#x66] /* a-f */ // [37] ns-ascii-letter ::= [#x41-#x5A] /* A-Z */ | [#x61-#x7A] /* a-z */ // [38] ns-word-char ::= ns-dec-digit | ns-ascii-letter | “-” // [39] ns-uri-char ::= “%” ns-hex-digit ns-hex-digit | ns-word-char | “#” // | “;” | “/” | “?” | “:” | “@” | “&” | “=” | “+” | “$” | “,” // | “_” | “.” | “!” | “~” | “*” | “'” | “(” | “)” | “[” | “]” // // Also need to encode '!' because it has special meaning (end of tag prefix). // tagStr = encodeURI( state.tag[0] === '!' ? state.tag.slice(1) : state.tag ).replace(/!/g, '%21'); if (state.tag[0] === '!') { tagStr = '!' + tagStr; } else if (tagStr.slice(0, 18) === 'tag:yaml.org,2002:') { tagStr = '!!' + tagStr.slice(18); } else { tagStr = '!<' + tagStr + '>'; } state.dump = tagStr + ' ' + state.dump; } } return true; } function getDuplicateReferences(object, state) { var objects = [], duplicatesIndexes = [], index, length; inspectNode(object, objects, duplicatesIndexes); for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) { state.duplicates.push(objects[duplicatesIndexes[index]]); } state.usedDuplicates = new Array(length); } function inspectNode(object, objects, duplicatesIndexes) { var objectKeyList, index, length; if (object !== null && typeof object === 'object') { index = objects.indexOf(object); if (index !== -1) { if (duplicatesIndexes.indexOf(index) === -1) { duplicatesIndexes.push(index); } } else { objects.push(object); if (Array.isArray(object)) { for (index = 0, length = object.length; index < length; index += 1) { inspectNode(object[index], objects, duplicatesIndexes); } } else { objectKeyList = Object.keys(object); for (index = 0, length = objectKeyList.length; index < length; index += 1) { inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes); } } } } } function dump(input, options) { options = options || {}; var state = new State(options); if (!state.noRefs) getDuplicateReferences(input, state); var value = input; if (state.replacer) { value = state.replacer.call({ '': value }, '', value); } if (writeNode(state, 0, value, true, true)) return state.dump + '\n'; return ''; } module.exports.dump = dump; /***/ }), /***/ 68179: /***/ ((module) => { "use strict"; // YAML error class. http://stackoverflow.com/questions/8458984 // function formatError(exception, compact) { var where = '', message = exception.reason || '(unknown reason)'; if (!exception.mark) return message; if (exception.mark.name) { where += 'in "' + exception.mark.name + '" '; } where += '(' + (exception.mark.line + 1) + ':' + (exception.mark.column + 1) + ')'; if (!compact && exception.mark.snippet) { where += '\n\n' + exception.mark.snippet; } return message + ' ' + where; } function YAMLException(reason, mark) { // Super constructor Error.call(this); this.name = 'YAMLException'; this.reason = reason; this.mark = mark; this.message = formatError(this, false); // Include stack trace in error object if (Error.captureStackTrace) { // Chrome and NodeJS Error.captureStackTrace(this, this.constructor); } else { // FF, IE 10+ and Safari 6+. Fallback for others this.stack = (new Error()).stack || ''; } } // Inherit from Error YAMLException.prototype = Object.create(Error.prototype); YAMLException.prototype.constructor = YAMLException; YAMLException.prototype.toString = function toString(compact) { return this.name + ': ' + formatError(this, compact); }; module.exports = YAMLException; /***/ }), /***/ 51161: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /*eslint-disable max-len,no-use-before-define*/ var common = __nccwpck_require__(26829); var YAMLException = __nccwpck_require__(68179); var makeSnippet = __nccwpck_require__(96975); var DEFAULT_SCHEMA = __nccwpck_require__(18759); var _hasOwnProperty = Object.prototype.hasOwnProperty; var CONTEXT_FLOW_IN = 1; var CONTEXT_FLOW_OUT = 2; var CONTEXT_BLOCK_IN = 3; var CONTEXT_BLOCK_OUT = 4; var CHOMPING_CLIP = 1; var CHOMPING_STRIP = 2; var CHOMPING_KEEP = 3; var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/; var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/; var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i; var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i; function _class(obj) { return Object.prototype.toString.call(obj); } function is_EOL(c) { return (c === 0x0A/* LF */) || (c === 0x0D/* CR */); } function is_WHITE_SPACE(c) { return (c === 0x09/* Tab */) || (c === 0x20/* Space */); } function is_WS_OR_EOL(c) { return (c === 0x09/* Tab */) || (c === 0x20/* Space */) || (c === 0x0A/* LF */) || (c === 0x0D/* CR */); } function is_FLOW_INDICATOR(c) { return c === 0x2C/* , */ || c === 0x5B/* [ */ || c === 0x5D/* ] */ || c === 0x7B/* { */ || c === 0x7D/* } */; } function fromHexCode(c) { var lc; if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { return c - 0x30; } /*eslint-disable no-bitwise*/ lc = c | 0x20; if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) { return lc - 0x61 + 10; } return -1; } function escapedHexLen(c) { if (c === 0x78/* x */) { return 2; } if (c === 0x75/* u */) { return 4; } if (c === 0x55/* U */) { return 8; } return 0; } function fromDecimalCode(c) { if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { return c - 0x30; } return -1; } function simpleEscapeSequence(c) { /* eslint-disable indent */ return (c === 0x30/* 0 */) ? '\x00' : (c === 0x61/* a */) ? '\x07' : (c === 0x62/* b */) ? '\x08' : (c === 0x74/* t */) ? '\x09' : (c === 0x09/* Tab */) ? '\x09' : (c === 0x6E/* n */) ? '\x0A' : (c === 0x76/* v */) ? '\x0B' : (c === 0x66/* f */) ? '\x0C' : (c === 0x72/* r */) ? '\x0D' : (c === 0x65/* e */) ? '\x1B' : (c === 0x20/* Space */) ? ' ' : (c === 0x22/* " */) ? '\x22' : (c === 0x2F/* / */) ? '/' : (c === 0x5C/* \ */) ? '\x5C' : (c === 0x4E/* N */) ? '\x85' : (c === 0x5F/* _ */) ? '\xA0' : (c === 0x4C/* L */) ? '\u2028' : (c === 0x50/* P */) ? '\u2029' : ''; } function charFromCodepoint(c) { if (c <= 0xFFFF) { return String.fromCharCode(c); } // Encode UTF-16 surrogate pair // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF return String.fromCharCode( ((c - 0x010000) >> 10) + 0xD800, ((c - 0x010000) & 0x03FF) + 0xDC00 ); } var simpleEscapeCheck = new Array(256); // integer, for fast access var simpleEscapeMap = new Array(256); for (var i = 0; i < 256; i++) { simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0; simpleEscapeMap[i] = simpleEscapeSequence(i); } function State(input, options) { this.input = input; this.filename = options['filename'] || null; this.schema = options['schema'] || DEFAULT_SCHEMA; this.onWarning = options['onWarning'] || null; // (Hidden) Remove? makes the loader to expect YAML 1.1 documents // if such documents have no explicit %YAML directive this.legacy = options['legacy'] || false; this.json = options['json'] || false; this.listener = options['listener'] || null; this.implicitTypes = this.schema.compiledImplicit; this.typeMap = this.schema.compiledTypeMap; this.length = input.length; this.position = 0; this.line = 0; this.lineStart = 0; this.lineIndent = 0; // position of first leading tab in the current line, // used to make sure there are no tabs in the indentation this.firstTabInLine = -1; this.documents = []; /* this.version; this.checkLineBreaks; this.tagMap; this.anchorMap; this.tag; this.anchor; this.kind; this.result;*/ } function generateError(state, message) { var mark = { name: state.filename, buffer: state.input.slice(0, -1), // omit trailing \0 position: state.position, line: state.line, column: state.position - state.lineStart }; mark.snippet = makeSnippet(mark); return new YAMLException(message, mark); } function throwError(state, message) { throw generateError(state, message); } function throwWarning(state, message) { if (state.onWarning) { state.onWarning.call(null, generateError(state, message)); } } var directiveHandlers = { YAML: function handleYamlDirective(state, name, args) { var match, major, minor; if (state.version !== null) { throwError(state, 'duplication of %YAML directive'); } if (args.length !== 1) { throwError(state, 'YAML directive accepts exactly one argument'); } match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]); if (match === null) { throwError(state, 'ill-formed argument of the YAML directive'); } major = parseInt(match[1], 10); minor = parseInt(match[2], 10); if (major !== 1) { throwError(state, 'unacceptable YAML version of the document'); } state.version = args[0]; state.checkLineBreaks = (minor < 2); if (minor !== 1 && minor !== 2) { throwWarning(state, 'unsupported YAML version of the document'); } }, TAG: function handleTagDirective(state, name, args) { var handle, prefix; if (args.length !== 2) { throwError(state, 'TAG directive accepts exactly two arguments'); } handle = args[0]; prefix = args[1]; if (!PATTERN_TAG_HANDLE.test(handle)) { throwError(state, 'ill-formed tag handle (first argument) of the TAG directive'); } if (_hasOwnProperty.call(state.tagMap, handle)) { throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle'); } if (!PATTERN_TAG_URI.test(prefix)) { throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive'); } try { prefix = decodeURIComponent(prefix); } catch (err) { throwError(state, 'tag prefix is malformed: ' + prefix); } state.tagMap[handle] = prefix; } }; function captureSegment(state, start, end, checkJson) { var _position, _length, _character, _result; if (start < end) { _result = state.input.slice(start, end); if (checkJson) { for (_position = 0, _length = _result.length; _position < _length; _position += 1) { _character = _result.charCodeAt(_position); if (!(_character === 0x09 || (0x20 <= _character && _character <= 0x10FFFF))) { throwError(state, 'expected valid JSON character'); } } } else if (PATTERN_NON_PRINTABLE.test(_result)) { throwError(state, 'the stream contains non-printable characters'); } state.result += _result; } } function mergeMappings(state, destination, source, overridableKeys) { var sourceKeys, key, index, quantity; if (!common.isObject(source)) { throwError(state, 'cannot merge mappings; the provided source object is unacceptable'); } sourceKeys = Object.keys(source); for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) { key = sourceKeys[index]; if (!_hasOwnProperty.call(destination, key)) { destination[key] = source[key]; overridableKeys[key] = true; } } } function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startLineStart, startPos) { var index, quantity; // The output is a plain object here, so keys can only be strings. // We need to convert keyNode to a string, but doing so can hang the process // (deeply nested arrays that explode exponentially using aliases). if (Array.isArray(keyNode)) { keyNode = Array.prototype.slice.call(keyNode); for (index = 0, quantity = keyNode.length; index < quantity; index += 1) { if (Array.isArray(keyNode[index])) { throwError(state, 'nested arrays are not supported inside keys'); } if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') { keyNode[index] = '[object Object]'; } } } // Avoid code execution in load() via toString property // (still use its own toString for arrays, timestamps, // and whatever user schema extensions happen to have @@toStringTag) if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') { keyNode = '[object Object]'; } keyNode = String(keyNode); if (_result === null) { _result = {}; } if (keyTag === 'tag:yaml.org,2002:merge') { if (Array.isArray(valueNode)) { for (index = 0, quantity = valueNode.length; index < quantity; index += 1) { mergeMappings(state, _result, valueNode[index], overridableKeys); } } else { mergeMappings(state, _result, valueNode, overridableKeys); } } else { if (!state.json && !_hasOwnProperty.call(overridableKeys, keyNode) && _hasOwnProperty.call(_result, keyNode)) { state.line = startLine || state.line; state.lineStart = startLineStart || state.lineStart; state.position = startPos || state.position; throwError(state, 'duplicated mapping key'); } // used for this specific key only because Object.defineProperty is slow if (keyNode === '__proto__') { Object.defineProperty(_result, keyNode, { configurable: true, enumerable: true, writable: true, value: valueNode }); } else { _result[keyNode] = valueNode; } delete overridableKeys[keyNode]; } return _result; } function readLineBreak(state) { var ch; ch = state.input.charCodeAt(state.position); if (ch === 0x0A/* LF */) { state.position++; } else if (ch === 0x0D/* CR */) { state.position++; if (state.input.charCodeAt(state.position) === 0x0A/* LF */) { state.position++; } } else { throwError(state, 'a line break is expected'); } state.line += 1; state.lineStart = state.position; state.firstTabInLine = -1; } function skipSeparationSpace(state, allowComments, checkIndent) { var lineBreaks = 0, ch = state.input.charCodeAt(state.position); while (ch !== 0) { while (is_WHITE_SPACE(ch)) { if (ch === 0x09/* Tab */ && state.firstTabInLine === -1) { state.firstTabInLine = state.position; } ch = state.input.charCodeAt(++state.position); } if (allowComments && ch === 0x23/* # */) { do { ch = state.input.charCodeAt(++state.position); } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0); } if (is_EOL(ch)) { readLineBreak(state); ch = state.input.charCodeAt(state.position); lineBreaks++; state.lineIndent = 0; while (ch === 0x20/* Space */) { state.lineIndent++; ch = state.input.charCodeAt(++state.position); } } else { break; } } if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) { throwWarning(state, 'deficient indentation'); } return lineBreaks; } function testDocumentSeparator(state) { var _position = state.position, ch; ch = state.input.charCodeAt(_position); // Condition state.position === state.lineStart is tested // in parent on each call, for efficiency. No needs to test here again. if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) && ch === state.input.charCodeAt(_position + 1) && ch === state.input.charCodeAt(_position + 2)) { _position += 3; ch = state.input.charCodeAt(_position); if (ch === 0 || is_WS_OR_EOL(ch)) { return true; } } return false; } function writeFoldedLines(state, count) { if (count === 1) { state.result += ' '; } else if (count > 1) { state.result += common.repeat('\n', count - 1); } } function readPlainScalar(state, nodeIndent, withinFlowCollection) { var preceding, following, captureStart, captureEnd, hasPendingContent, _line, _lineStart, _lineIndent, _kind = state.kind, _result = state.result, ch; ch = state.input.charCodeAt(state.position); if (is_WS_OR_EOL(ch) || is_FLOW_INDICATOR(ch) || ch === 0x23/* # */ || ch === 0x26/* & */ || ch === 0x2A/* * */ || ch === 0x21/* ! */ || ch === 0x7C/* | */ || ch === 0x3E/* > */ || ch === 0x27/* ' */ || ch === 0x22/* " */ || ch === 0x25/* % */ || ch === 0x40/* @ */ || ch === 0x60/* ` */) { return false; } if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) { following = state.input.charCodeAt(state.position + 1); if (is_WS_OR_EOL(following) || withinFlowCollection && is_FLOW_INDICATOR(following)) { return false; } } state.kind = 'scalar'; state.result = ''; captureStart = captureEnd = state.position; hasPendingContent = false; while (ch !== 0) { if (ch === 0x3A/* : */) { following = state.input.charCodeAt(state.position + 1); if (is_WS_OR_EOL(following) || withinFlowCollection && is_FLOW_INDICATOR(following)) { break; } } else if (ch === 0x23/* # */) { preceding = state.input.charCodeAt(state.position - 1); if (is_WS_OR_EOL(preceding)) { break; } } else if ((state.position === state.lineStart && testDocumentSeparator(state)) || withinFlowCollection && is_FLOW_INDICATOR(ch)) { break; } else if (is_EOL(ch)) { _line = state.line; _lineStart = state.lineStart; _lineIndent = state.lineIndent; skipSeparationSpace(state, false, -1); if (state.lineIndent >= nodeIndent) { hasPendingContent = true; ch = state.input.charCodeAt(state.position); continue; } else { state.position = captureEnd; state.line = _line; state.lineStart = _lineStart; state.lineIndent = _lineIndent; break; } } if (hasPendingContent) { captureSegment(state, captureStart, captureEnd, false); writeFoldedLines(state, state.line - _line); captureStart = captureEnd = state.position; hasPendingContent = false; } if (!is_WHITE_SPACE(ch)) { captureEnd = state.position + 1; } ch = state.input.charCodeAt(++state.position); } captureSegment(state, captureStart, captureEnd, false); if (state.result) { return true; } state.kind = _kind; state.result = _result; return false; } function readSingleQuotedScalar(state, nodeIndent) { var ch, captureStart, captureEnd; ch = state.input.charCodeAt(state.position); if (ch !== 0x27/* ' */) { return false; } state.kind = 'scalar'; state.result = ''; state.position++; captureStart = captureEnd = state.position; while ((ch = state.input.charCodeAt(state.position)) !== 0) { if (ch === 0x27/* ' */) { captureSegment(state, captureStart, state.position, true); ch = state.input.charCodeAt(++state.position); if (ch === 0x27/* ' */) { captureStart = state.position; state.position++; captureEnd = state.position; } else { return true; } } else if (is_EOL(ch)) { captureSegment(state, captureStart, captureEnd, true); writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); captureStart = captureEnd = state.position; } else if (state.position === state.lineStart && testDocumentSeparator(state)) { throwError(state, 'unexpected end of the document within a single quoted scalar'); } else { state.position++; captureEnd = state.position; } } throwError(state, 'unexpected end of the stream within a single quoted scalar'); } function readDoubleQuotedScalar(state, nodeIndent) { var captureStart, captureEnd, hexLength, hexResult, tmp, ch; ch = state.input.charCodeAt(state.position); if (ch !== 0x22/* " */) { return false; } state.kind = 'scalar'; state.result = ''; state.position++; captureStart = captureEnd = state.position; while ((ch = state.input.charCodeAt(state.position)) !== 0) { if (ch === 0x22/* " */) { captureSegment(state, captureStart, state.position, true); state.position++; return true; } else if (ch === 0x5C/* \ */) { captureSegment(state, captureStart, state.position, true); ch = state.input.charCodeAt(++state.position); if (is_EOL(ch)) { skipSeparationSpace(state, false, nodeIndent); // TODO: rework to inline fn with no type cast? } else if (ch < 256 && simpleEscapeCheck[ch]) { state.result += simpleEscapeMap[ch]; state.position++; } else if ((tmp = escapedHexLen(ch)) > 0) { hexLength = tmp; hexResult = 0; for (; hexLength > 0; hexLength--) { ch = state.input.charCodeAt(++state.position); if ((tmp = fromHexCode(ch)) >= 0) { hexResult = (hexResult << 4) + tmp; } else { throwError(state, 'expected hexadecimal character'); } } state.result += charFromCodepoint(hexResult); state.position++; } else { throwError(state, 'unknown escape sequence'); } captureStart = captureEnd = state.position; } else if (is_EOL(ch)) { captureSegment(state, captureStart, captureEnd, true); writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); captureStart = captureEnd = state.position; } else if (state.position === state.lineStart && testDocumentSeparator(state)) { throwError(state, 'unexpected end of the document within a double quoted scalar'); } else { state.position++; captureEnd = state.position; } } throwError(state, 'unexpected end of the stream within a double quoted scalar'); } function readFlowCollection(state, nodeIndent) { var readNext = true, _line, _lineStart, _pos, _tag = state.tag, _result, _anchor = state.anchor, following, terminator, isPair, isExplicitPair, isMapping, overridableKeys = Object.create(null), keyNode, keyTag, valueNode, ch; ch = state.input.charCodeAt(state.position); if (ch === 0x5B/* [ */) { terminator = 0x5D;/* ] */ isMapping = false; _result = []; } else if (ch === 0x7B/* { */) { terminator = 0x7D;/* } */ isMapping = true; _result = {}; } else { return false; } if (state.anchor !== null) { state.anchorMap[state.anchor] = _result; } ch = state.input.charCodeAt(++state.position); while (ch !== 0) { skipSeparationSpace(state, true, nodeIndent); ch = state.input.charCodeAt(state.position); if (ch === terminator) { state.position++; state.tag = _tag; state.anchor = _anchor; state.kind = isMapping ? 'mapping' : 'sequence'; state.result = _result; return true; } else if (!readNext) { throwError(state, 'missed comma between flow collection entries'); } else if (ch === 0x2C/* , */) { // "flow collection entries can never be completely empty", as per YAML 1.2, section 7.4 throwError(state, "expected the node content, but found ','"); } keyTag = keyNode = valueNode = null; isPair = isExplicitPair = false; if (ch === 0x3F/* ? */) { following = state.input.charCodeAt(state.position + 1); if (is_WS_OR_EOL(following)) { isPair = isExplicitPair = true; state.position++; skipSeparationSpace(state, true, nodeIndent); } } _line = state.line; // Save the current line. _lineStart = state.lineStart; _pos = state.position; composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); keyTag = state.tag; keyNode = state.result; skipSeparationSpace(state, true, nodeIndent); ch = state.input.charCodeAt(state.position); if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) { isPair = true; ch = state.input.charCodeAt(++state.position); skipSeparationSpace(state, true, nodeIndent); composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); valueNode = state.result; } if (isMapping) { storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos); } else if (isPair) { _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos)); } else { _result.push(keyNode); } skipSeparationSpace(state, true, nodeIndent); ch = state.input.charCodeAt(state.position); if (ch === 0x2C/* , */) { readNext = true; ch = state.input.charCodeAt(++state.position); } else { readNext = false; } } throwError(state, 'unexpected end of the stream within a flow collection'); } function readBlockScalar(state, nodeIndent) { var captureStart, folding, chomping = CHOMPING_CLIP, didReadContent = false, detectedIndent = false, textIndent = nodeIndent, emptyLines = 0, atMoreIndented = false, tmp, ch; ch = state.input.charCodeAt(state.position); if (ch === 0x7C/* | */) { folding = false; } else if (ch === 0x3E/* > */) { folding = true; } else { return false; } state.kind = 'scalar'; state.result = ''; while (ch !== 0) { ch = state.input.charCodeAt(++state.position); if (ch === 0x2B/* + */ || ch === 0x2D/* - */) { if (CHOMPING_CLIP === chomping) { chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP; } else { throwError(state, 'repeat of a chomping mode identifier'); } } else if ((tmp = fromDecimalCode(ch)) >= 0) { if (tmp === 0) { throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one'); } else if (!detectedIndent) { textIndent = nodeIndent + tmp - 1; detectedIndent = true; } else { throwError(state, 'repeat of an indentation width identifier'); } } else { break; } } if (is_WHITE_SPACE(ch)) { do { ch = state.input.charCodeAt(++state.position); } while (is_WHITE_SPACE(ch)); if (ch === 0x23/* # */) { do { ch = state.input.charCodeAt(++state.position); } while (!is_EOL(ch) && (ch !== 0)); } } while (ch !== 0) { readLineBreak(state); state.lineIndent = 0; ch = state.input.charCodeAt(state.position); while ((!detectedIndent || state.lineIndent < textIndent) && (ch === 0x20/* Space */)) { state.lineIndent++; ch = state.input.charCodeAt(++state.position); } if (!detectedIndent && state.lineIndent > textIndent) { textIndent = state.lineIndent; } if (is_EOL(ch)) { emptyLines++; continue; } // End of the scalar. if (state.lineIndent < textIndent) { // Perform the chomping. if (chomping === CHOMPING_KEEP) { state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); } else if (chomping === CHOMPING_CLIP) { if (didReadContent) { // i.e. only if the scalar is not empty. state.result += '\n'; } } // Break this `while` cycle and go to the funciton's epilogue. break; } // Folded style: use fancy rules to handle line breaks. if (folding) { // Lines starting with white space characters (more-indented lines) are not folded. if (is_WHITE_SPACE(ch)) { atMoreIndented = true; // except for the first content line (cf. Example 8.1) state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); // End of more-indented block. } else if (atMoreIndented) { atMoreIndented = false; state.result += common.repeat('\n', emptyLines + 1); // Just one line break - perceive as the same line. } else if (emptyLines === 0) { if (didReadContent) { // i.e. only if we have already read some scalar content. state.result += ' '; } // Several line breaks - perceive as different lines. } else { state.result += common.repeat('\n', emptyLines); } // Literal style: just add exact number of line breaks between content lines. } else { // Keep all line breaks except the header line break. state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); } didReadContent = true; detectedIndent = true; emptyLines = 0; captureStart = state.position; while (!is_EOL(ch) && (ch !== 0)) { ch = state.input.charCodeAt(++state.position); } captureSegment(state, captureStart, state.position, false); } return true; } function readBlockSequence(state, nodeIndent) { var _line, _tag = state.tag, _anchor = state.anchor, _result = [], following, detected = false, ch; // there is a leading tab before this token, so it can't be a block sequence/mapping; // it can still be flow sequence/mapping or a scalar if (state.firstTabInLine !== -1) return false; if (state.anchor !== null) { state.anchorMap[state.anchor] = _result; } ch = state.input.charCodeAt(state.position); while (ch !== 0) { if (state.firstTabInLine !== -1) { state.position = state.firstTabInLine; throwError(state, 'tab characters must not be used in indentation'); } if (ch !== 0x2D/* - */) { break; } following = state.input.charCodeAt(state.position + 1); if (!is_WS_OR_EOL(following)) { break; } detected = true; state.position++; if (skipSeparationSpace(state, true, -1)) { if (state.lineIndent <= nodeIndent) { _result.push(null); ch = state.input.charCodeAt(state.position); continue; } } _line = state.line; composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true); _result.push(state.result); skipSeparationSpace(state, true, -1); ch = state.input.charCodeAt(state.position); if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { throwError(state, 'bad indentation of a sequence entry'); } else if (state.lineIndent < nodeIndent) { break; } } if (detected) { state.tag = _tag; state.anchor = _anchor; state.kind = 'sequence'; state.result = _result; return true; } return false; } function readBlockMapping(state, nodeIndent, flowIndent) { var following, allowCompact, _line, _keyLine, _keyLineStart, _keyPos, _tag = state.tag, _anchor = state.anchor, _result = {}, overridableKeys = Object.create(null), keyTag = null, keyNode = null, valueNode = null, atExplicitKey = false, detected = false, ch; // there is a leading tab before this token, so it can't be a block sequence/mapping; // it can still be flow sequence/mapping or a scalar if (state.firstTabInLine !== -1) return false; if (state.anchor !== null) { state.anchorMap[state.anchor] = _result; } ch = state.input.charCodeAt(state.position); while (ch !== 0) { if (!atExplicitKey && state.firstTabInLine !== -1) { state.position = state.firstTabInLine; throwError(state, 'tab characters must not be used in indentation'); } following = state.input.charCodeAt(state.position + 1); _line = state.line; // Save the current line. // // Explicit notation case. There are two separate blocks: // first for the key (denoted by "?") and second for the value (denoted by ":") // if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) { if (ch === 0x3F/* ? */) { if (atExplicitKey) { storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); keyTag = keyNode = valueNode = null; } detected = true; atExplicitKey = true; allowCompact = true; } else if (atExplicitKey) { // i.e. 0x3A/* : */ === character after the explicit key. atExplicitKey = false; allowCompact = true; } else { throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line'); } state.position += 1; ch = following; // // Implicit notation case. Flow-style node as the key first, then ":", and the value. // } else { _keyLine = state.line; _keyLineStart = state.lineStart; _keyPos = state.position; if (!composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) { // Neither implicit nor explicit notation. // Reading is done. Go to the epilogue. break; } if (state.line === _line) { ch = state.input.charCodeAt(state.position); while (is_WHITE_SPACE(ch)) { ch = state.input.charCodeAt(++state.position); } if (ch === 0x3A/* : */) { ch = state.input.charCodeAt(++state.position); if (!is_WS_OR_EOL(ch)) { throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping'); } if (atExplicitKey) { storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); keyTag = keyNode = valueNode = null; } detected = true; atExplicitKey = false; allowCompact = false; keyTag = state.tag; keyNode = state.result; } else if (detected) { throwError(state, 'can not read an implicit mapping pair; a colon is missed'); } else { state.tag = _tag; state.anchor = _anchor; return true; // Keep the result of `composeNode`. } } else if (detected) { throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key'); } else { state.tag = _tag; state.anchor = _anchor; return true; // Keep the result of `composeNode`. } } // // Common reading code for both explicit and implicit notations. // if (state.line === _line || state.lineIndent > nodeIndent) { if (atExplicitKey) { _keyLine = state.line; _keyLineStart = state.lineStart; _keyPos = state.position; } if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) { if (atExplicitKey) { keyNode = state.result; } else { valueNode = state.result; } } if (!atExplicitKey) { storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _keyLine, _keyLineStart, _keyPos); keyTag = keyNode = valueNode = null; } skipSeparationSpace(state, true, -1); ch = state.input.charCodeAt(state.position); } if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { throwError(state, 'bad indentation of a mapping entry'); } else if (state.lineIndent < nodeIndent) { break; } } // // Epilogue. // // Special case: last mapping's node contains only the key in explicit notation. if (atExplicitKey) { storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); } // Expose the resulting mapping. if (detected) { state.tag = _tag; state.anchor = _anchor; state.kind = 'mapping'; state.result = _result; } return detected; } function readTagProperty(state) { var _position, isVerbatim = false, isNamed = false, tagHandle, tagName, ch; ch = state.input.charCodeAt(state.position); if (ch !== 0x21/* ! */) return false; if (state.tag !== null) { throwError(state, 'duplication of a tag property'); } ch = state.input.charCodeAt(++state.position); if (ch === 0x3C/* < */) { isVerbatim = true; ch = state.input.charCodeAt(++state.position); } else if (ch === 0x21/* ! */) { isNamed = true; tagHandle = '!!'; ch = state.input.charCodeAt(++state.position); } else { tagHandle = '!'; } _position = state.position; if (isVerbatim) { do { ch = state.input.charCodeAt(++state.position); } while (ch !== 0 && ch !== 0x3E/* > */); if (state.position < state.length) { tagName = state.input.slice(_position, state.position); ch = state.input.charCodeAt(++state.position); } else { throwError(state, 'unexpected end of the stream within a verbatim tag'); } } else { while (ch !== 0 && !is_WS_OR_EOL(ch)) { if (ch === 0x21/* ! */) { if (!isNamed) { tagHandle = state.input.slice(_position - 1, state.position + 1); if (!PATTERN_TAG_HANDLE.test(tagHandle)) { throwError(state, 'named tag handle cannot contain such characters'); } isNamed = true; _position = state.position + 1; } else { throwError(state, 'tag suffix cannot contain exclamation marks'); } } ch = state.input.charCodeAt(++state.position); } tagName = state.input.slice(_position, state.position); if (PATTERN_FLOW_INDICATORS.test(tagName)) { throwError(state, 'tag suffix cannot contain flow indicator characters'); } } if (tagName && !PATTERN_TAG_URI.test(tagName)) { throwError(state, 'tag name cannot contain such characters: ' + tagName); } try { tagName = decodeURIComponent(tagName); } catch (err) { throwError(state, 'tag name is malformed: ' + tagName); } if (isVerbatim) { state.tag = tagName; } else if (_hasOwnProperty.call(state.tagMap, tagHandle)) { state.tag = state.tagMap[tagHandle] + tagName; } else if (tagHandle === '!') { state.tag = '!' + tagName; } else if (tagHandle === '!!') { state.tag = 'tag:yaml.org,2002:' + tagName; } else { throwError(state, 'undeclared tag handle "' + tagHandle + '"'); } return true; } function readAnchorProperty(state) { var _position, ch; ch = state.input.charCodeAt(state.position); if (ch !== 0x26/* & */) return false; if (state.anchor !== null) { throwError(state, 'duplication of an anchor property'); } ch = state.input.charCodeAt(++state.position); _position = state.position; while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { ch = state.input.charCodeAt(++state.position); } if (state.position === _position) { throwError(state, 'name of an anchor node must contain at least one character'); } state.anchor = state.input.slice(_position, state.position); return true; } function readAlias(state) { var _position, alias, ch; ch = state.input.charCodeAt(state.position); if (ch !== 0x2A/* * */) return false; ch = state.input.charCodeAt(++state.position); _position = state.position; while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { ch = state.input.charCodeAt(++state.position); } if (state.position === _position) { throwError(state, 'name of an alias node must contain at least one character'); } alias = state.input.slice(_position, state.position); if (!_hasOwnProperty.call(state.anchorMap, alias)) { throwError(state, 'unidentified alias "' + alias + '"'); } state.result = state.anchorMap[alias]; skipSeparationSpace(state, true, -1); return true; } function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) { var allowBlockStyles, allowBlockScalars, allowBlockCollections, indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this parentIndent) { indentStatus = 1; } else if (state.lineIndent === parentIndent) { indentStatus = 0; } else if (state.lineIndent < parentIndent) { indentStatus = -1; } } } if (indentStatus === 1) { while (readTagProperty(state) || readAnchorProperty(state)) { if (skipSeparationSpace(state, true, -1)) { atNewLine = true; allowBlockCollections = allowBlockStyles; if (state.lineIndent > parentIndent) { indentStatus = 1; } else if (state.lineIndent === parentIndent) { indentStatus = 0; } else if (state.lineIndent < parentIndent) { indentStatus = -1; } } else { allowBlockCollections = false; } } } if (allowBlockCollections) { allowBlockCollections = atNewLine || allowCompact; } if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) { if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) { flowIndent = parentIndent; } else { flowIndent = parentIndent + 1; } blockIndent = state.position - state.lineStart; if (indentStatus === 1) { if (allowBlockCollections && (readBlockSequence(state, blockIndent) || readBlockMapping(state, blockIndent, flowIndent)) || readFlowCollection(state, flowIndent)) { hasContent = true; } else { if ((allowBlockScalars && readBlockScalar(state, flowIndent)) || readSingleQuotedScalar(state, flowIndent) || readDoubleQuotedScalar(state, flowIndent)) { hasContent = true; } else if (readAlias(state)) { hasContent = true; if (state.tag !== null || state.anchor !== null) { throwError(state, 'alias node should not have any properties'); } } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) { hasContent = true; if (state.tag === null) { state.tag = '?'; } } if (state.anchor !== null) { state.anchorMap[state.anchor] = state.result; } } } else if (indentStatus === 0) { // Special case: block sequences are allowed to have same indentation level as the parent. // http://www.yaml.org/spec/1.2/spec.html#id2799784 hasContent = allowBlockCollections && readBlockSequence(state, blockIndent); } } if (state.tag === null) { if (state.anchor !== null) { state.anchorMap[state.anchor] = state.result; } } else if (state.tag === '?') { // Implicit resolving is not allowed for non-scalar types, and '?' // non-specific tag is only automatically assigned to plain scalars. // // We only need to check kind conformity in case user explicitly assigns '?' // tag, for example like this: "! [0]" // if (state.result !== null && state.kind !== 'scalar') { throwError(state, 'unacceptable node kind for ! tag; it should be "scalar", not "' + state.kind + '"'); } for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) { type = state.implicitTypes[typeIndex]; if (type.resolve(state.result)) { // `state.result` updated in resolver if matched state.result = type.construct(state.result); state.tag = type.tag; if (state.anchor !== null) { state.anchorMap[state.anchor] = state.result; } break; } } } else if (state.tag !== '!') { if (_hasOwnProperty.call(state.typeMap[state.kind || 'fallback'], state.tag)) { type = state.typeMap[state.kind || 'fallback'][state.tag]; } else { // looking for multi type type = null; typeList = state.typeMap.multi[state.kind || 'fallback']; for (typeIndex = 0, typeQuantity = typeList.length; typeIndex < typeQuantity; typeIndex += 1) { if (state.tag.slice(0, typeList[typeIndex].tag.length) === typeList[typeIndex].tag) { type = typeList[typeIndex]; break; } } } if (!type) { throwError(state, 'unknown tag !<' + state.tag + '>'); } if (state.result !== null && type.kind !== state.kind) { throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"'); } if (!type.resolve(state.result, state.tag)) { // `state.result` updated in resolver if matched throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag'); } else { state.result = type.construct(state.result, state.tag); if (state.anchor !== null) { state.anchorMap[state.anchor] = state.result; } } } if (state.listener !== null) { state.listener('close', state); } return state.tag !== null || state.anchor !== null || hasContent; } function readDocument(state) { var documentStart = state.position, _position, directiveName, directiveArgs, hasDirectives = false, ch; state.version = null; state.checkLineBreaks = state.legacy; state.tagMap = Object.create(null); state.anchorMap = Object.create(null); while ((ch = state.input.charCodeAt(state.position)) !== 0) { skipSeparationSpace(state, true, -1); ch = state.input.charCodeAt(state.position); if (state.lineIndent > 0 || ch !== 0x25/* % */) { break; } hasDirectives = true; ch = state.input.charCodeAt(++state.position); _position = state.position; while (ch !== 0 && !is_WS_OR_EOL(ch)) { ch = state.input.charCodeAt(++state.position); } directiveName = state.input.slice(_position, state.position); directiveArgs = []; if (directiveName.length < 1) { throwError(state, 'directive name must not be less than one character in length'); } while (ch !== 0) { while (is_WHITE_SPACE(ch)) { ch = state.input.charCodeAt(++state.position); } if (ch === 0x23/* # */) { do { ch = state.input.charCodeAt(++state.position); } while (ch !== 0 && !is_EOL(ch)); break; } if (is_EOL(ch)) break; _position = state.position; while (ch !== 0 && !is_WS_OR_EOL(ch)) { ch = state.input.charCodeAt(++state.position); } directiveArgs.push(state.input.slice(_position, state.position)); } if (ch !== 0) readLineBreak(state); if (_hasOwnProperty.call(directiveHandlers, directiveName)) { directiveHandlers[directiveName](state, directiveName, directiveArgs); } else { throwWarning(state, 'unknown document directive "' + directiveName + '"'); } } skipSeparationSpace(state, true, -1); if (state.lineIndent === 0 && state.input.charCodeAt(state.position) === 0x2D/* - */ && state.input.charCodeAt(state.position + 1) === 0x2D/* - */ && state.input.charCodeAt(state.position + 2) === 0x2D/* - */) { state.position += 3; skipSeparationSpace(state, true, -1); } else if (hasDirectives) { throwError(state, 'directives end mark is expected'); } composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true); skipSeparationSpace(state, true, -1); if (state.checkLineBreaks && PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) { throwWarning(state, 'non-ASCII line breaks are interpreted as content'); } state.documents.push(state.result); if (state.position === state.lineStart && testDocumentSeparator(state)) { if (state.input.charCodeAt(state.position) === 0x2E/* . */) { state.position += 3; skipSeparationSpace(state, true, -1); } return; } if (state.position < (state.length - 1)) { throwError(state, 'end of the stream or a document separator is expected'); } else { return; } } function loadDocuments(input, options) { input = String(input); options = options || {}; if (input.length !== 0) { // Add tailing `\n` if not exists if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ && input.charCodeAt(input.length - 1) !== 0x0D/* CR */) { input += '\n'; } // Strip BOM if (input.charCodeAt(0) === 0xFEFF) { input = input.slice(1); } } var state = new State(input, options); var nullpos = input.indexOf('\0'); if (nullpos !== -1) { state.position = nullpos; throwError(state, 'null byte is not allowed in input'); } // Use 0 as string terminator. That significantly simplifies bounds check. state.input += '\0'; while (state.input.charCodeAt(state.position) === 0x20/* Space */) { state.lineIndent += 1; state.position += 1; } while (state.position < (state.length - 1)) { readDocument(state); } return state.documents; } function loadAll(input, iterator, options) { if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') { options = iterator; iterator = null; } var documents = loadDocuments(input, options); if (typeof iterator !== 'function') { return documents; } for (var index = 0, length = documents.length; index < length; index += 1) { iterator(documents[index]); } } function load(input, options) { var documents = loadDocuments(input, options); if (documents.length === 0) { /*eslint-disable no-undefined*/ return undefined; } else if (documents.length === 1) { return documents[0]; } throw new YAMLException('expected a single document in the stream, but found more'); } module.exports.loadAll = loadAll; module.exports.load = load; /***/ }), /***/ 21082: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /*eslint-disable max-len*/ var YAMLException = __nccwpck_require__(68179); var Type = __nccwpck_require__(6073); function compileList(schema, name) { var result = []; schema[name].forEach(function (currentType) { var newIndex = result.length; result.forEach(function (previousType, previousIndex) { if (previousType.tag === currentType.tag && previousType.kind === currentType.kind && previousType.multi === currentType.multi) { newIndex = previousIndex; } }); result[newIndex] = currentType; }); return result; } function compileMap(/* lists... */) { var result = { scalar: {}, sequence: {}, mapping: {}, fallback: {}, multi: { scalar: [], sequence: [], mapping: [], fallback: [] } }, index, length; function collectType(type) { if (type.multi) { result.multi[type.kind].push(type); result.multi['fallback'].push(type); } else { result[type.kind][type.tag] = result['fallback'][type.tag] = type; } } for (index = 0, length = arguments.length; index < length; index += 1) { arguments[index].forEach(collectType); } return result; } function Schema(definition) { return this.extend(definition); } Schema.prototype.extend = function extend(definition) { var implicit = []; var explicit = []; if (definition instanceof Type) { // Schema.extend(type) explicit.push(definition); } else if (Array.isArray(definition)) { // Schema.extend([ type1, type2, ... ]) explicit = explicit.concat(definition); } else if (definition && (Array.isArray(definition.implicit) || Array.isArray(definition.explicit))) { // Schema.extend({ explicit: [ type1, type2, ... ], implicit: [ type1, type2, ... ] }) if (definition.implicit) implicit = implicit.concat(definition.implicit); if (definition.explicit) explicit = explicit.concat(definition.explicit); } else { throw new YAMLException('Schema.extend argument should be a Type, [ Type ], ' + 'or a schema definition ({ implicit: [...], explicit: [...] })'); } implicit.forEach(function (type) { if (!(type instanceof Type)) { throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.'); } if (type.loadKind && type.loadKind !== 'scalar') { throw new YAMLException('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.'); } if (type.multi) { throw new YAMLException('There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.'); } }); explicit.forEach(function (type) { if (!(type instanceof Type)) { throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.'); } }); var result = Object.create(Schema.prototype); result.implicit = (this.implicit || []).concat(implicit); result.explicit = (this.explicit || []).concat(explicit); result.compiledImplicit = compileList(result, 'implicit'); result.compiledExplicit = compileList(result, 'explicit'); result.compiledTypeMap = compileMap(result.compiledImplicit, result.compiledExplicit); return result; }; module.exports = Schema; /***/ }), /***/ 12011: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // Standard YAML's Core schema. // http://www.yaml.org/spec/1.2/spec.html#id2804923 // // NOTE: JS-YAML does not support schema-specific tag resolution restrictions. // So, Core schema has no distinctions from JSON schema is JS-YAML. module.exports = __nccwpck_require__(1035); /***/ }), /***/ 18759: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // JS-YAML's default schema for `safeLoad` function. // It is not described in the YAML specification. // // This schema is based on standard YAML's Core schema and includes most of // extra types described at YAML tag repository. (http://yaml.org/type/) module.exports = (__nccwpck_require__(12011).extend)({ implicit: [ __nccwpck_require__(99212), __nccwpck_require__(86104) ], explicit: [ __nccwpck_require__(77900), __nccwpck_require__(19046), __nccwpck_require__(96860), __nccwpck_require__(79548) ] }); /***/ }), /***/ 28562: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // Standard YAML's Failsafe schema. // http://www.yaml.org/spec/1.2/spec.html#id2802346 var Schema = __nccwpck_require__(21082); module.exports = new Schema({ explicit: [ __nccwpck_require__(23619), __nccwpck_require__(67283), __nccwpck_require__(86150) ] }); /***/ }), /***/ 1035: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // Standard YAML's JSON schema. // http://www.yaml.org/spec/1.2/spec.html#id2803231 // // NOTE: JS-YAML does not support schema-specific tag resolution restrictions. // So, this schema is not such strict as defined in the YAML specification. // It allows numbers in binary notaion, use `Null` and `NULL` as `null`, etc. module.exports = (__nccwpck_require__(28562).extend)({ implicit: [ __nccwpck_require__(20721), __nccwpck_require__(64993), __nccwpck_require__(11615), __nccwpck_require__(42705) ] }); /***/ }), /***/ 96975: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var common = __nccwpck_require__(26829); // get snippet for a single line, respecting maxLength function getLine(buffer, lineStart, lineEnd, position, maxLineLength) { var head = ''; var tail = ''; var maxHalfLength = Math.floor(maxLineLength / 2) - 1; if (position - lineStart > maxHalfLength) { head = ' ... '; lineStart = position - maxHalfLength + head.length; } if (lineEnd - position > maxHalfLength) { tail = ' ...'; lineEnd = position + maxHalfLength - tail.length; } return { str: head + buffer.slice(lineStart, lineEnd).replace(/\t/g, '→') + tail, pos: position - lineStart + head.length // relative position }; } function padStart(string, max) { return common.repeat(' ', max - string.length) + string; } function makeSnippet(mark, options) { options = Object.create(options || null); if (!mark.buffer) return null; if (!options.maxLength) options.maxLength = 79; if (typeof options.indent !== 'number') options.indent = 1; if (typeof options.linesBefore !== 'number') options.linesBefore = 3; if (typeof options.linesAfter !== 'number') options.linesAfter = 2; var re = /\r?\n|\r|\0/g; var lineStarts = [ 0 ]; var lineEnds = []; var match; var foundLineNo = -1; while ((match = re.exec(mark.buffer))) { lineEnds.push(match.index); lineStarts.push(match.index + match[0].length); if (mark.position <= match.index && foundLineNo < 0) { foundLineNo = lineStarts.length - 2; } } if (foundLineNo < 0) foundLineNo = lineStarts.length - 1; var result = '', i, line; var lineNoLength = Math.min(mark.line + options.linesAfter, lineEnds.length).toString().length; var maxLineLength = options.maxLength - (options.indent + lineNoLength + 3); for (i = 1; i <= options.linesBefore; i++) { if (foundLineNo - i < 0) break; line = getLine( mark.buffer, lineStarts[foundLineNo - i], lineEnds[foundLineNo - i], mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i]), maxLineLength ); result = common.repeat(' ', options.indent) + padStart((mark.line - i + 1).toString(), lineNoLength) + ' | ' + line.str + '\n' + result; } line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength); result += common.repeat(' ', options.indent) + padStart((mark.line + 1).toString(), lineNoLength) + ' | ' + line.str + '\n'; result += common.repeat('-', options.indent + lineNoLength + 3 + line.pos) + '^' + '\n'; for (i = 1; i <= options.linesAfter; i++) { if (foundLineNo + i >= lineEnds.length) break; line = getLine( mark.buffer, lineStarts[foundLineNo + i], lineEnds[foundLineNo + i], mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i]), maxLineLength ); result += common.repeat(' ', options.indent) + padStart((mark.line + i + 1).toString(), lineNoLength) + ' | ' + line.str + '\n'; } return result.replace(/\n$/, ''); } module.exports = makeSnippet; /***/ }), /***/ 6073: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var YAMLException = __nccwpck_require__(68179); var TYPE_CONSTRUCTOR_OPTIONS = [ 'kind', 'multi', 'resolve', 'construct', 'instanceOf', 'predicate', 'represent', 'representName', 'defaultStyle', 'styleAliases' ]; var YAML_NODE_KINDS = [ 'scalar', 'sequence', 'mapping' ]; function compileStyleAliases(map) { var result = {}; if (map !== null) { Object.keys(map).forEach(function (style) { map[style].forEach(function (alias) { result[String(alias)] = style; }); }); } return result; } function Type(tag, options) { options = options || {}; Object.keys(options).forEach(function (name) { if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) { throw new YAMLException('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.'); } }); // TODO: Add tag format check. this.options = options; // keep original options in case user wants to extend this type later this.tag = tag; this.kind = options['kind'] || null; this.resolve = options['resolve'] || function () { return true; }; this.construct = options['construct'] || function (data) { return data; }; this.instanceOf = options['instanceOf'] || null; this.predicate = options['predicate'] || null; this.represent = options['represent'] || null; this.representName = options['representName'] || null; this.defaultStyle = options['defaultStyle'] || null; this.multi = options['multi'] || false; this.styleAliases = compileStyleAliases(options['styleAliases'] || null); if (YAML_NODE_KINDS.indexOf(this.kind) === -1) { throw new YAMLException('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.'); } } module.exports = Type; /***/ }), /***/ 77900: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /*eslint-disable no-bitwise*/ var Type = __nccwpck_require__(6073); // [ 64, 65, 66 ] -> [ padding, CR, LF ] var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r'; function resolveYamlBinary(data) { if (data === null) return false; var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP; // Convert one by one. for (idx = 0; idx < max; idx++) { code = map.indexOf(data.charAt(idx)); // Skip CR/LF if (code > 64) continue; // Fail on illegal characters if (code < 0) return false; bitlen += 6; } // If there are any bits left, source was corrupted return (bitlen % 8) === 0; } function constructYamlBinary(data) { var idx, tailbits, input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan max = input.length, map = BASE64_MAP, bits = 0, result = []; // Collect by 6*4 bits (3 bytes) for (idx = 0; idx < max; idx++) { if ((idx % 4 === 0) && idx) { result.push((bits >> 16) & 0xFF); result.push((bits >> 8) & 0xFF); result.push(bits & 0xFF); } bits = (bits << 6) | map.indexOf(input.charAt(idx)); } // Dump tail tailbits = (max % 4) * 6; if (tailbits === 0) { result.push((bits >> 16) & 0xFF); result.push((bits >> 8) & 0xFF); result.push(bits & 0xFF); } else if (tailbits === 18) { result.push((bits >> 10) & 0xFF); result.push((bits >> 2) & 0xFF); } else if (tailbits === 12) { result.push((bits >> 4) & 0xFF); } return new Uint8Array(result); } function representYamlBinary(object /*, style*/) { var result = '', bits = 0, idx, tail, max = object.length, map = BASE64_MAP; // Convert every three bytes to 4 ASCII characters. for (idx = 0; idx < max; idx++) { if ((idx % 3 === 0) && idx) { result += map[(bits >> 18) & 0x3F]; result += map[(bits >> 12) & 0x3F]; result += map[(bits >> 6) & 0x3F]; result += map[bits & 0x3F]; } bits = (bits << 8) + object[idx]; } // Dump tail tail = max % 3; if (tail === 0) { result += map[(bits >> 18) & 0x3F]; result += map[(bits >> 12) & 0x3F]; result += map[(bits >> 6) & 0x3F]; result += map[bits & 0x3F]; } else if (tail === 2) { result += map[(bits >> 10) & 0x3F]; result += map[(bits >> 4) & 0x3F]; result += map[(bits << 2) & 0x3F]; result += map[64]; } else if (tail === 1) { result += map[(bits >> 2) & 0x3F]; result += map[(bits << 4) & 0x3F]; result += map[64]; result += map[64]; } return result; } function isBinary(obj) { return Object.prototype.toString.call(obj) === '[object Uint8Array]'; } module.exports = new Type('tag:yaml.org,2002:binary', { kind: 'scalar', resolve: resolveYamlBinary, construct: constructYamlBinary, predicate: isBinary, represent: representYamlBinary }); /***/ }), /***/ 64993: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var Type = __nccwpck_require__(6073); function resolveYamlBoolean(data) { if (data === null) return false; var max = data.length; return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) || (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE')); } function constructYamlBoolean(data) { return data === 'true' || data === 'True' || data === 'TRUE'; } function isBoolean(object) { return Object.prototype.toString.call(object) === '[object Boolean]'; } module.exports = new Type('tag:yaml.org,2002:bool', { kind: 'scalar', resolve: resolveYamlBoolean, construct: constructYamlBoolean, predicate: isBoolean, represent: { lowercase: function (object) { return object ? 'true' : 'false'; }, uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; }, camelcase: function (object) { return object ? 'True' : 'False'; } }, defaultStyle: 'lowercase' }); /***/ }), /***/ 42705: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var common = __nccwpck_require__(26829); var Type = __nccwpck_require__(6073); var YAML_FLOAT_PATTERN = new RegExp( // 2.5e4, 2.5 and integers '^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' + // .2e4, .2 // special case, seems not from spec '|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' + // .inf '|[-+]?\\.(?:inf|Inf|INF)' + // .nan '|\\.(?:nan|NaN|NAN))$'); function resolveYamlFloat(data) { if (data === null) return false; if (!YAML_FLOAT_PATTERN.test(data) || // Quick hack to not allow integers end with `_` // Probably should update regexp & check speed data[data.length - 1] === '_') { return false; } return true; } function constructYamlFloat(data) { var value, sign; value = data.replace(/_/g, '').toLowerCase(); sign = value[0] === '-' ? -1 : 1; if ('+-'.indexOf(value[0]) >= 0) { value = value.slice(1); } if (value === '.inf') { return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; } else if (value === '.nan') { return NaN; } return sign * parseFloat(value, 10); } var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/; function representYamlFloat(object, style) { var res; if (isNaN(object)) { switch (style) { case 'lowercase': return '.nan'; case 'uppercase': return '.NAN'; case 'camelcase': return '.NaN'; } } else if (Number.POSITIVE_INFINITY === object) { switch (style) { case 'lowercase': return '.inf'; case 'uppercase': return '.INF'; case 'camelcase': return '.Inf'; } } else if (Number.NEGATIVE_INFINITY === object) { switch (style) { case 'lowercase': return '-.inf'; case 'uppercase': return '-.INF'; case 'camelcase': return '-.Inf'; } } else if (common.isNegativeZero(object)) { return '-0.0'; } res = object.toString(10); // JS stringifier can build scientific format without dots: 5e-100, // while YAML requres dot: 5.e-100. Fix it with simple hack return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res; } function isFloat(object) { return (Object.prototype.toString.call(object) === '[object Number]') && (object % 1 !== 0 || common.isNegativeZero(object)); } module.exports = new Type('tag:yaml.org,2002:float', { kind: 'scalar', resolve: resolveYamlFloat, construct: constructYamlFloat, predicate: isFloat, represent: representYamlFloat, defaultStyle: 'lowercase' }); /***/ }), /***/ 11615: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var common = __nccwpck_require__(26829); var Type = __nccwpck_require__(6073); function isHexCode(c) { return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) || ((0x41/* A */ <= c) && (c <= 0x46/* F */)) || ((0x61/* a */ <= c) && (c <= 0x66/* f */)); } function isOctCode(c) { return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */)); } function isDecCode(c) { return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)); } function resolveYamlInteger(data) { if (data === null) return false; var max = data.length, index = 0, hasDigits = false, ch; if (!max) return false; ch = data[index]; // sign if (ch === '-' || ch === '+') { ch = data[++index]; } if (ch === '0') { // 0 if (index + 1 === max) return true; ch = data[++index]; // base 2, base 8, base 16 if (ch === 'b') { // base 2 index++; for (; index < max; index++) { ch = data[index]; if (ch === '_') continue; if (ch !== '0' && ch !== '1') return false; hasDigits = true; } return hasDigits && ch !== '_'; } if (ch === 'x') { // base 16 index++; for (; index < max; index++) { ch = data[index]; if (ch === '_') continue; if (!isHexCode(data.charCodeAt(index))) return false; hasDigits = true; } return hasDigits && ch !== '_'; } if (ch === 'o') { // base 8 index++; for (; index < max; index++) { ch = data[index]; if (ch === '_') continue; if (!isOctCode(data.charCodeAt(index))) return false; hasDigits = true; } return hasDigits && ch !== '_'; } } // base 10 (except 0) // value should not start with `_`; if (ch === '_') return false; for (; index < max; index++) { ch = data[index]; if (ch === '_') continue; if (!isDecCode(data.charCodeAt(index))) { return false; } hasDigits = true; } // Should have digits and should not end with `_` if (!hasDigits || ch === '_') return false; return true; } function constructYamlInteger(data) { var value = data, sign = 1, ch; if (value.indexOf('_') !== -1) { value = value.replace(/_/g, ''); } ch = value[0]; if (ch === '-' || ch === '+') { if (ch === '-') sign = -1; value = value.slice(1); ch = value[0]; } if (value === '0') return 0; if (ch === '0') { if (value[1] === 'b') return sign * parseInt(value.slice(2), 2); if (value[1] === 'x') return sign * parseInt(value.slice(2), 16); if (value[1] === 'o') return sign * parseInt(value.slice(2), 8); } return sign * parseInt(value, 10); } function isInteger(object) { return (Object.prototype.toString.call(object)) === '[object Number]' && (object % 1 === 0 && !common.isNegativeZero(object)); } module.exports = new Type('tag:yaml.org,2002:int', { kind: 'scalar', resolve: resolveYamlInteger, construct: constructYamlInteger, predicate: isInteger, represent: { binary: function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1); }, octal: function (obj) { return obj >= 0 ? '0o' + obj.toString(8) : '-0o' + obj.toString(8).slice(1); }, decimal: function (obj) { return obj.toString(10); }, /* eslint-disable max-len */ hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1); } }, defaultStyle: 'decimal', styleAliases: { binary: [ 2, 'bin' ], octal: [ 8, 'oct' ], decimal: [ 10, 'dec' ], hexadecimal: [ 16, 'hex' ] } }); /***/ }), /***/ 86150: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var Type = __nccwpck_require__(6073); module.exports = new Type('tag:yaml.org,2002:map', { kind: 'mapping', construct: function (data) { return data !== null ? data : {}; } }); /***/ }), /***/ 86104: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var Type = __nccwpck_require__(6073); function resolveYamlMerge(data) { return data === '<<' || data === null; } module.exports = new Type('tag:yaml.org,2002:merge', { kind: 'scalar', resolve: resolveYamlMerge }); /***/ }), /***/ 20721: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var Type = __nccwpck_require__(6073); function resolveYamlNull(data) { if (data === null) return true; var max = data.length; return (max === 1 && data === '~') || (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL')); } function constructYamlNull() { return null; } function isNull(object) { return object === null; } module.exports = new Type('tag:yaml.org,2002:null', { kind: 'scalar', resolve: resolveYamlNull, construct: constructYamlNull, predicate: isNull, represent: { canonical: function () { return '~'; }, lowercase: function () { return 'null'; }, uppercase: function () { return 'NULL'; }, camelcase: function () { return 'Null'; }, empty: function () { return ''; } }, defaultStyle: 'lowercase' }); /***/ }), /***/ 19046: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var Type = __nccwpck_require__(6073); var _hasOwnProperty = Object.prototype.hasOwnProperty; var _toString = Object.prototype.toString; function resolveYamlOmap(data) { if (data === null) return true; var objectKeys = [], index, length, pair, pairKey, pairHasKey, object = data; for (index = 0, length = object.length; index < length; index += 1) { pair = object[index]; pairHasKey = false; if (_toString.call(pair) !== '[object Object]') return false; for (pairKey in pair) { if (_hasOwnProperty.call(pair, pairKey)) { if (!pairHasKey) pairHasKey = true; else return false; } } if (!pairHasKey) return false; if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey); else return false; } return true; } function constructYamlOmap(data) { return data !== null ? data : []; } module.exports = new Type('tag:yaml.org,2002:omap', { kind: 'sequence', resolve: resolveYamlOmap, construct: constructYamlOmap }); /***/ }), /***/ 96860: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var Type = __nccwpck_require__(6073); var _toString = Object.prototype.toString; function resolveYamlPairs(data) { if (data === null) return true; var index, length, pair, keys, result, object = data; result = new Array(object.length); for (index = 0, length = object.length; index < length; index += 1) { pair = object[index]; if (_toString.call(pair) !== '[object Object]') return false; keys = Object.keys(pair); if (keys.length !== 1) return false; result[index] = [ keys[0], pair[keys[0]] ]; } return true; } function constructYamlPairs(data) { if (data === null) return []; var index, length, pair, keys, result, object = data; result = new Array(object.length); for (index = 0, length = object.length; index < length; index += 1) { pair = object[index]; keys = Object.keys(pair); result[index] = [ keys[0], pair[keys[0]] ]; } return result; } module.exports = new Type('tag:yaml.org,2002:pairs', { kind: 'sequence', resolve: resolveYamlPairs, construct: constructYamlPairs }); /***/ }), /***/ 67283: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var Type = __nccwpck_require__(6073); module.exports = new Type('tag:yaml.org,2002:seq', { kind: 'sequence', construct: function (data) { return data !== null ? data : []; } }); /***/ }), /***/ 79548: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var Type = __nccwpck_require__(6073); var _hasOwnProperty = Object.prototype.hasOwnProperty; function resolveYamlSet(data) { if (data === null) return true; var key, object = data; for (key in object) { if (_hasOwnProperty.call(object, key)) { if (object[key] !== null) return false; } } return true; } function constructYamlSet(data) { return data !== null ? data : {}; } module.exports = new Type('tag:yaml.org,2002:set', { kind: 'mapping', resolve: resolveYamlSet, construct: constructYamlSet }); /***/ }), /***/ 23619: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var Type = __nccwpck_require__(6073); module.exports = new Type('tag:yaml.org,2002:str', { kind: 'scalar', construct: function (data) { return data !== null ? data : ''; } }); /***/ }), /***/ 99212: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var Type = __nccwpck_require__(6073); var YAML_DATE_REGEXP = new RegExp( '^([0-9][0-9][0-9][0-9])' + // [1] year '-([0-9][0-9])' + // [2] month '-([0-9][0-9])$'); // [3] day var YAML_TIMESTAMP_REGEXP = new RegExp( '^([0-9][0-9][0-9][0-9])' + // [1] year '-([0-9][0-9]?)' + // [2] month '-([0-9][0-9]?)' + // [3] day '(?:[Tt]|[ \\t]+)' + // ... '([0-9][0-9]?)' + // [4] hour ':([0-9][0-9])' + // [5] minute ':([0-9][0-9])' + // [6] second '(?:\\.([0-9]*))?' + // [7] fraction '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour '(?::([0-9][0-9]))?))?$'); // [11] tz_minute function resolveYamlTimestamp(data) { if (data === null) return false; if (YAML_DATE_REGEXP.exec(data) !== null) return true; if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true; return false; } function constructYamlTimestamp(data) { var match, year, month, day, hour, minute, second, fraction = 0, delta = null, tz_hour, tz_minute, date; match = YAML_DATE_REGEXP.exec(data); if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data); if (match === null) throw new Error('Date resolve error'); // match: [1] year [2] month [3] day year = +(match[1]); month = +(match[2]) - 1; // JS month starts with 0 day = +(match[3]); if (!match[4]) { // no hour return new Date(Date.UTC(year, month, day)); } // match: [4] hour [5] minute [6] second [7] fraction hour = +(match[4]); minute = +(match[5]); second = +(match[6]); if (match[7]) { fraction = match[7].slice(0, 3); while (fraction.length < 3) { // milli-seconds fraction += '0'; } fraction = +fraction; } // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute if (match[9]) { tz_hour = +(match[10]); tz_minute = +(match[11] || 0); delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds if (match[9] === '-') delta = -delta; } date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction)); if (delta) date.setTime(date.getTime() - delta); return date; } function representYamlTimestamp(object /*, style*/) { return object.toISOString(); } module.exports = new Type('tag:yaml.org,2002:timestamp', { kind: 'scalar', resolve: resolveYamlTimestamp, construct: constructYamlTimestamp, instanceOf: Date, represent: representYamlTimestamp }); /***/ }), /***/ 85587: /***/ (function(module, exports) { (function(){ // Copyright (c) 2005 Tom Wu // All Rights Reserved. // See "LICENSE" for details. // Basic JavaScript BN library - subset useful for RSA encryption. // Bits per digit var dbits; // JavaScript engine analysis var canary = 0xdeadbeefcafe; var j_lm = ((canary&0xffffff)==0xefcafe); // (public) Constructor function BigInteger(a,b,c) { if(a != null) if("number" == typeof a) this.fromNumber(a,b,c); else if(b == null && "string" != typeof a) this.fromString(a,256); else this.fromString(a,b); } // return new, unset BigInteger function nbi() { return new BigInteger(null); } // am: Compute w_j += (x*this_i), propagate carries, // c is initial carry, returns final carry. // c < 3*dvalue, x < 2*dvalue, this_i < dvalue // We need to select the fastest one that works in this environment. // am1: use a single mult and divide to get the high bits, // max digit bits should be 26 because // max internal value = 2*dvalue^2-2*dvalue (< 2^53) function am1(i,x,w,j,c,n) { while(--n >= 0) { var v = x*this[i++]+w[j]+c; c = Math.floor(v/0x4000000); w[j++] = v&0x3ffffff; } return c; } // am2 avoids a big mult-and-extract completely. // Max digit bits should be <= 30 because we do bitwise ops // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) function am2(i,x,w,j,c,n) { var xl = x&0x7fff, xh = x>>15; while(--n >= 0) { var l = this[i]&0x7fff; var h = this[i++]>>15; var m = xh*l+h*xl; l = xl*l+((m&0x7fff)<<15)+w[j]+(c&0x3fffffff); c = (l>>>30)+(m>>>15)+xh*h+(c>>>30); w[j++] = l&0x3fffffff; } return c; } // Alternately, set max digit bits to 28 since some // browsers slow down when dealing with 32-bit numbers. function am3(i,x,w,j,c,n) { var xl = x&0x3fff, xh = x>>14; while(--n >= 0) { var l = this[i]&0x3fff; var h = this[i++]>>14; var m = xh*l+h*xl; l = xl*l+((m&0x3fff)<<14)+w[j]+c; c = (l>>28)+(m>>14)+xh*h; w[j++] = l&0xfffffff; } return c; } var inBrowser = typeof navigator !== "undefined"; if(inBrowser && j_lm && (navigator.appName == "Microsoft Internet Explorer")) { BigInteger.prototype.am = am2; dbits = 30; } else if(inBrowser && j_lm && (navigator.appName != "Netscape")) { BigInteger.prototype.am = am1; dbits = 26; } else { // Mozilla/Netscape seems to prefer am3 BigInteger.prototype.am = am3; dbits = 28; } BigInteger.prototype.DB = dbits; BigInteger.prototype.DM = ((1<= 0; --i) r[i] = this[i]; r.t = this.t; r.s = this.s; } // (protected) set from integer value x, -DV <= x < DV function bnpFromInt(x) { this.t = 1; this.s = (x<0)?-1:0; if(x > 0) this[0] = x; else if(x < -1) this[0] = x+this.DV; else this.t = 0; } // return bigint initialized to value function nbv(i) { var r = nbi(); r.fromInt(i); return r; } // (protected) set from string and radix function bnpFromString(s,b) { var k; if(b == 16) k = 4; else if(b == 8) k = 3; else if(b == 256) k = 8; // byte array else if(b == 2) k = 1; else if(b == 32) k = 5; else if(b == 4) k = 2; else { this.fromRadix(s,b); return; } this.t = 0; this.s = 0; var i = s.length, mi = false, sh = 0; while(--i >= 0) { var x = (k==8)?s[i]&0xff:intAt(s,i); if(x < 0) { if(s.charAt(i) == "-") mi = true; continue; } mi = false; if(sh == 0) this[this.t++] = x; else if(sh+k > this.DB) { this[this.t-1] |= (x&((1<<(this.DB-sh))-1))<>(this.DB-sh)); } else this[this.t-1] |= x<= this.DB) sh -= this.DB; } if(k == 8 && (s[0]&0x80) != 0) { this.s = -1; if(sh > 0) this[this.t-1] |= ((1<<(this.DB-sh))-1)< 0 && this[this.t-1] == c) --this.t; } // (public) return string representation in given radix function bnToString(b) { if(this.s < 0) return "-"+this.negate().toString(b); var k; if(b == 16) k = 4; else if(b == 8) k = 3; else if(b == 2) k = 1; else if(b == 32) k = 5; else if(b == 4) k = 2; else return this.toRadix(b); var km = (1< 0) { if(p < this.DB && (d = this[i]>>p) > 0) { m = true; r = int2char(d); } while(i >= 0) { if(p < k) { d = (this[i]&((1<>(p+=this.DB-k); } else { d = (this[i]>>(p-=k))&km; if(p <= 0) { p += this.DB; --i; } } if(d > 0) m = true; if(m) r += int2char(d); } } return m?r:"0"; } // (public) -this function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; } // (public) |this| function bnAbs() { return (this.s<0)?this.negate():this; } // (public) return + if this > a, - if this < a, 0 if equal function bnCompareTo(a) { var r = this.s-a.s; if(r != 0) return r; var i = this.t; r = i-a.t; if(r != 0) return (this.s<0)?-r:r; while(--i >= 0) if((r=this[i]-a[i]) != 0) return r; return 0; } // returns bit length of the integer x function nbits(x) { var r = 1, t; if((t=x>>>16) != 0) { x = t; r += 16; } if((t=x>>8) != 0) { x = t; r += 8; } if((t=x>>4) != 0) { x = t; r += 4; } if((t=x>>2) != 0) { x = t; r += 2; } if((t=x>>1) != 0) { x = t; r += 1; } return r; } // (public) return the number of bits in "this" function bnBitLength() { if(this.t <= 0) return 0; return this.DB*(this.t-1)+nbits(this[this.t-1]^(this.s&this.DM)); } // (protected) r = this << n*DB function bnpDLShiftTo(n,r) { var i; for(i = this.t-1; i >= 0; --i) r[i+n] = this[i]; for(i = n-1; i >= 0; --i) r[i] = 0; r.t = this.t+n; r.s = this.s; } // (protected) r = this >> n*DB function bnpDRShiftTo(n,r) { for(var i = n; i < this.t; ++i) r[i-n] = this[i]; r.t = Math.max(this.t-n,0); r.s = this.s; } // (protected) r = this << n function bnpLShiftTo(n,r) { var bs = n%this.DB; var cbs = this.DB-bs; var bm = (1<= 0; --i) { r[i+ds+1] = (this[i]>>cbs)|c; c = (this[i]&bm)<= 0; --i) r[i] = 0; r[ds] = c; r.t = this.t+ds+1; r.s = this.s; r.clamp(); } // (protected) r = this >> n function bnpRShiftTo(n,r) { r.s = this.s; var ds = Math.floor(n/this.DB); if(ds >= this.t) { r.t = 0; return; } var bs = n%this.DB; var cbs = this.DB-bs; var bm = (1<>bs; for(var i = ds+1; i < this.t; ++i) { r[i-ds-1] |= (this[i]&bm)<>bs; } if(bs > 0) r[this.t-ds-1] |= (this.s&bm)<>= this.DB; } if(a.t < this.t) { c -= a.s; while(i < this.t) { c += this[i]; r[i++] = c&this.DM; c >>= this.DB; } c += this.s; } else { c += this.s; while(i < a.t) { c -= a[i]; r[i++] = c&this.DM; c >>= this.DB; } c -= a.s; } r.s = (c<0)?-1:0; if(c < -1) r[i++] = this.DV+c; else if(c > 0) r[i++] = c; r.t = i; r.clamp(); } // (protected) r = this * a, r != this,a (HAC 14.12) // "this" should be the larger one if appropriate. function bnpMultiplyTo(a,r) { var x = this.abs(), y = a.abs(); var i = x.t; r.t = i+y.t; while(--i >= 0) r[i] = 0; for(i = 0; i < y.t; ++i) r[i+x.t] = x.am(0,y[i],r,i,0,x.t); r.s = 0; r.clamp(); if(this.s != a.s) BigInteger.ZERO.subTo(r,r); } // (protected) r = this^2, r != this (HAC 14.16) function bnpSquareTo(r) { var x = this.abs(); var i = r.t = 2*x.t; while(--i >= 0) r[i] = 0; for(i = 0; i < x.t-1; ++i) { var c = x.am(i,x[i],r,2*i,0,1); if((r[i+x.t]+=x.am(i+1,2*x[i],r,2*i+1,c,x.t-i-1)) >= x.DV) { r[i+x.t] -= x.DV; r[i+x.t+1] = 1; } } if(r.t > 0) r[r.t-1] += x.am(i,x[i],r,2*i,0,1); r.s = 0; r.clamp(); } // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) // r != q, this != m. q or r may be null. function bnpDivRemTo(m,q,r) { var pm = m.abs(); if(pm.t <= 0) return; var pt = this.abs(); if(pt.t < pm.t) { if(q != null) q.fromInt(0); if(r != null) this.copyTo(r); return; } if(r == null) r = nbi(); var y = nbi(), ts = this.s, ms = m.s; var nsh = this.DB-nbits(pm[pm.t-1]); // normalize modulus if(nsh > 0) { pm.lShiftTo(nsh,y); pt.lShiftTo(nsh,r); } else { pm.copyTo(y); pt.copyTo(r); } var ys = y.t; var y0 = y[ys-1]; if(y0 == 0) return; var yt = y0*(1<1)?y[ys-2]>>this.F2:0); var d1 = this.FV/yt, d2 = (1<= 0) { r[r.t++] = 1; r.subTo(t,r); } BigInteger.ONE.dlShiftTo(ys,t); t.subTo(y,y); // "negative" y so we can replace sub with am later while(y.t < ys) y[y.t++] = 0; while(--j >= 0) { // Estimate quotient digit var qd = (r[--i]==y0)?this.DM:Math.floor(r[i]*d1+(r[i-1]+e)*d2); if((r[i]+=y.am(0,qd,r,j,0,ys)) < qd) { // Try it out y.dlShiftTo(j,t); r.subTo(t,r); while(r[i] < --qd) r.subTo(t,r); } } if(q != null) { r.drShiftTo(ys,q); if(ts != ms) BigInteger.ZERO.subTo(q,q); } r.t = ys; r.clamp(); if(nsh > 0) r.rShiftTo(nsh,r); // Denormalize remainder if(ts < 0) BigInteger.ZERO.subTo(r,r); } // (public) this mod a function bnMod(a) { var r = nbi(); this.abs().divRemTo(a,null,r); if(this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r,r); return r; } // Modular reduction using "classic" algorithm function Classic(m) { this.m = m; } function cConvert(x) { if(x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m); else return x; } function cRevert(x) { return x; } function cReduce(x) { x.divRemTo(this.m,null,x); } function cMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } function cSqrTo(x,r) { x.squareTo(r); this.reduce(r); } Classic.prototype.convert = cConvert; Classic.prototype.revert = cRevert; Classic.prototype.reduce = cReduce; Classic.prototype.mulTo = cMulTo; Classic.prototype.sqrTo = cSqrTo; // (protected) return "-1/this % 2^DB"; useful for Mont. reduction // justification: // xy == 1 (mod m) // xy = 1+km // xy(2-xy) = (1+km)(1-km) // x[y(2-xy)] = 1-k^2m^2 // x[y(2-xy)] == 1 (mod m^2) // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 // should reduce x and y(2-xy) by m^2 at each step to keep size bounded. // JS multiply "overflows" differently from C/C++, so care is needed here. function bnpInvDigit() { if(this.t < 1) return 0; var x = this[0]; if((x&1) == 0) return 0; var y = x&3; // y == 1/x mod 2^2 y = (y*(2-(x&0xf)*y))&0xf; // y == 1/x mod 2^4 y = (y*(2-(x&0xff)*y))&0xff; // y == 1/x mod 2^8 y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff; // y == 1/x mod 2^16 // last step - calculate inverse mod DV directly; // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints y = (y*(2-x*y%this.DV))%this.DV; // y == 1/x mod 2^dbits // we really want the negative inverse, and -DV < y < DV return (y>0)?this.DV-y:-y; } // Montgomery reduction function Montgomery(m) { this.m = m; this.mp = m.invDigit(); this.mpl = this.mp&0x7fff; this.mph = this.mp>>15; this.um = (1<<(m.DB-15))-1; this.mt2 = 2*m.t; } // xR mod m function montConvert(x) { var r = nbi(); x.abs().dlShiftTo(this.m.t,r); r.divRemTo(this.m,null,r); if(x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r,r); return r; } // x/R mod m function montRevert(x) { var r = nbi(); x.copyTo(r); this.reduce(r); return r; } // x = x/R mod m (HAC 14.32) function montReduce(x) { while(x.t <= this.mt2) // pad x so am has enough room later x[x.t++] = 0; for(var i = 0; i < this.m.t; ++i) { // faster way of calculating u0 = x[i]*mp mod DV var j = x[i]&0x7fff; var u0 = (j*this.mpl+(((j*this.mph+(x[i]>>15)*this.mpl)&this.um)<<15))&x.DM; // use am to combine the multiply-shift-add into one call j = i+this.m.t; x[j] += this.m.am(0,u0,x,i,0,this.m.t); // propagate carry while(x[j] >= x.DV) { x[j] -= x.DV; x[++j]++; } } x.clamp(); x.drShiftTo(this.m.t,x); if(x.compareTo(this.m) >= 0) x.subTo(this.m,x); } // r = "x^2/R mod m"; x != r function montSqrTo(x,r) { x.squareTo(r); this.reduce(r); } // r = "xy/R mod m"; x,y != r function montMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } Montgomery.prototype.convert = montConvert; Montgomery.prototype.revert = montRevert; Montgomery.prototype.reduce = montReduce; Montgomery.prototype.mulTo = montMulTo; Montgomery.prototype.sqrTo = montSqrTo; // (protected) true iff this is even function bnpIsEven() { return ((this.t>0)?(this[0]&1):this.s) == 0; } // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79) function bnpExp(e,z) { if(e > 0xffffffff || e < 1) return BigInteger.ONE; var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e)-1; g.copyTo(r); while(--i >= 0) { z.sqrTo(r,r2); if((e&(1< 0) z.mulTo(r2,g,r); else { var t = r; r = r2; r2 = t; } } return z.revert(r); } // (public) this^e % m, 0 <= e < 2^32 function bnModPowInt(e,m) { var z; if(e < 256 || m.isEven()) z = new Classic(m); else z = new Montgomery(m); return this.exp(e,z); } // protected BigInteger.prototype.copyTo = bnpCopyTo; BigInteger.prototype.fromInt = bnpFromInt; BigInteger.prototype.fromString = bnpFromString; BigInteger.prototype.clamp = bnpClamp; BigInteger.prototype.dlShiftTo = bnpDLShiftTo; BigInteger.prototype.drShiftTo = bnpDRShiftTo; BigInteger.prototype.lShiftTo = bnpLShiftTo; BigInteger.prototype.rShiftTo = bnpRShiftTo; BigInteger.prototype.subTo = bnpSubTo; BigInteger.prototype.multiplyTo = bnpMultiplyTo; BigInteger.prototype.squareTo = bnpSquareTo; BigInteger.prototype.divRemTo = bnpDivRemTo; BigInteger.prototype.invDigit = bnpInvDigit; BigInteger.prototype.isEven = bnpIsEven; BigInteger.prototype.exp = bnpExp; // public BigInteger.prototype.toString = bnToString; BigInteger.prototype.negate = bnNegate; BigInteger.prototype.abs = bnAbs; BigInteger.prototype.compareTo = bnCompareTo; BigInteger.prototype.bitLength = bnBitLength; BigInteger.prototype.mod = bnMod; BigInteger.prototype.modPowInt = bnModPowInt; // "constants" BigInteger.ZERO = nbv(0); BigInteger.ONE = nbv(1); // Copyright (c) 2005-2009 Tom Wu // All Rights Reserved. // See "LICENSE" for details. // Extended JavaScript BN functions, required for RSA private ops. // Version 1.1: new BigInteger("0", 10) returns "proper" zero // Version 1.2: square() API, isProbablePrime fix // (public) function bnClone() { var r = nbi(); this.copyTo(r); return r; } // (public) return value as integer function bnIntValue() { if(this.s < 0) { if(this.t == 1) return this[0]-this.DV; else if(this.t == 0) return -1; } else if(this.t == 1) return this[0]; else if(this.t == 0) return 0; // assumes 16 < DB < 32 return ((this[1]&((1<<(32-this.DB))-1))<>24; } // (public) return value as short (assumes DB>=16) function bnShortValue() { return (this.t==0)?this.s:(this[0]<<16)>>16; } // (protected) return x s.t. r^x < DV function bnpChunkSize(r) { return Math.floor(Math.LN2*this.DB/Math.log(r)); } // (public) 0 if this == 0, 1 if this > 0 function bnSigNum() { if(this.s < 0) return -1; else if(this.t <= 0 || (this.t == 1 && this[0] <= 0)) return 0; else return 1; } // (protected) convert to radix string function bnpToRadix(b) { if(b == null) b = 10; if(this.signum() == 0 || b < 2 || b > 36) return "0"; var cs = this.chunkSize(b); var a = Math.pow(b,cs); var d = nbv(a), y = nbi(), z = nbi(), r = ""; this.divRemTo(d,y,z); while(y.signum() > 0) { r = (a+z.intValue()).toString(b).substr(1) + r; y.divRemTo(d,y,z); } return z.intValue().toString(b) + r; } // (protected) convert from radix string function bnpFromRadix(s,b) { this.fromInt(0); if(b == null) b = 10; var cs = this.chunkSize(b); var d = Math.pow(b,cs), mi = false, j = 0, w = 0; for(var i = 0; i < s.length; ++i) { var x = intAt(s,i); if(x < 0) { if(s.charAt(i) == "-" && this.signum() == 0) mi = true; continue; } w = b*w+x; if(++j >= cs) { this.dMultiply(d); this.dAddOffset(w,0); j = 0; w = 0; } } if(j > 0) { this.dMultiply(Math.pow(b,j)); this.dAddOffset(w,0); } if(mi) BigInteger.ZERO.subTo(this,this); } // (protected) alternate constructor function bnpFromNumber(a,b,c) { if("number" == typeof b) { // new BigInteger(int,int,RNG) if(a < 2) this.fromInt(1); else { this.fromNumber(a,c); if(!this.testBit(a-1)) // force MSB set this.bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,this); if(this.isEven()) this.dAddOffset(1,0); // force odd while(!this.isProbablePrime(b)) { this.dAddOffset(2,0); if(this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft(a-1),this); } } } else { // new BigInteger(int,RNG) var x = new Array(), t = a&7; x.length = (a>>3)+1; b.nextBytes(x); if(t > 0) x[0] &= ((1< 0) { if(p < this.DB && (d = this[i]>>p) != (this.s&this.DM)>>p) r[k++] = d|(this.s<<(this.DB-p)); while(i >= 0) { if(p < 8) { d = (this[i]&((1<>(p+=this.DB-8); } else { d = (this[i]>>(p-=8))&0xff; if(p <= 0) { p += this.DB; --i; } } if((d&0x80) != 0) d |= -256; if(k == 0 && (this.s&0x80) != (d&0x80)) ++k; if(k > 0 || d != this.s) r[k++] = d; } } return r; } function bnEquals(a) { return(this.compareTo(a)==0); } function bnMin(a) { return(this.compareTo(a)<0)?this:a; } function bnMax(a) { return(this.compareTo(a)>0)?this:a; } // (protected) r = this op a (bitwise) function bnpBitwiseTo(a,op,r) { var i, f, m = Math.min(a.t,this.t); for(i = 0; i < m; ++i) r[i] = op(this[i],a[i]); if(a.t < this.t) { f = a.s&this.DM; for(i = m; i < this.t; ++i) r[i] = op(this[i],f); r.t = this.t; } else { f = this.s&this.DM; for(i = m; i < a.t; ++i) r[i] = op(f,a[i]); r.t = a.t; } r.s = op(this.s,a.s); r.clamp(); } // (public) this & a function op_and(x,y) { return x&y; } function bnAnd(a) { var r = nbi(); this.bitwiseTo(a,op_and,r); return r; } // (public) this | a function op_or(x,y) { return x|y; } function bnOr(a) { var r = nbi(); this.bitwiseTo(a,op_or,r); return r; } // (public) this ^ a function op_xor(x,y) { return x^y; } function bnXor(a) { var r = nbi(); this.bitwiseTo(a,op_xor,r); return r; } // (public) this & ~a function op_andnot(x,y) { return x&~y; } function bnAndNot(a) { var r = nbi(); this.bitwiseTo(a,op_andnot,r); return r; } // (public) ~this function bnNot() { var r = nbi(); for(var i = 0; i < this.t; ++i) r[i] = this.DM&~this[i]; r.t = this.t; r.s = ~this.s; return r; } // (public) this << n function bnShiftLeft(n) { var r = nbi(); if(n < 0) this.rShiftTo(-n,r); else this.lShiftTo(n,r); return r; } // (public) this >> n function bnShiftRight(n) { var r = nbi(); if(n < 0) this.lShiftTo(-n,r); else this.rShiftTo(n,r); return r; } // return index of lowest 1-bit in x, x < 2^31 function lbit(x) { if(x == 0) return -1; var r = 0; if((x&0xffff) == 0) { x >>= 16; r += 16; } if((x&0xff) == 0) { x >>= 8; r += 8; } if((x&0xf) == 0) { x >>= 4; r += 4; } if((x&3) == 0) { x >>= 2; r += 2; } if((x&1) == 0) ++r; return r; } // (public) returns index of lowest 1-bit (or -1 if none) function bnGetLowestSetBit() { for(var i = 0; i < this.t; ++i) if(this[i] != 0) return i*this.DB+lbit(this[i]); if(this.s < 0) return this.t*this.DB; return -1; } // return number of 1 bits in x function cbit(x) { var r = 0; while(x != 0) { x &= x-1; ++r; } return r; } // (public) return number of set bits function bnBitCount() { var r = 0, x = this.s&this.DM; for(var i = 0; i < this.t; ++i) r += cbit(this[i]^x); return r; } // (public) true iff nth bit is set function bnTestBit(n) { var j = Math.floor(n/this.DB); if(j >= this.t) return(this.s!=0); return((this[j]&(1<<(n%this.DB)))!=0); } // (protected) this op (1<>= this.DB; } if(a.t < this.t) { c += a.s; while(i < this.t) { c += this[i]; r[i++] = c&this.DM; c >>= this.DB; } c += this.s; } else { c += this.s; while(i < a.t) { c += a[i]; r[i++] = c&this.DM; c >>= this.DB; } c += a.s; } r.s = (c<0)?-1:0; if(c > 0) r[i++] = c; else if(c < -1) r[i++] = this.DV+c; r.t = i; r.clamp(); } // (public) this + a function bnAdd(a) { var r = nbi(); this.addTo(a,r); return r; } // (public) this - a function bnSubtract(a) { var r = nbi(); this.subTo(a,r); return r; } // (public) this * a function bnMultiply(a) { var r = nbi(); this.multiplyTo(a,r); return r; } // (public) this^2 function bnSquare() { var r = nbi(); this.squareTo(r); return r; } // (public) this / a function bnDivide(a) { var r = nbi(); this.divRemTo(a,r,null); return r; } // (public) this % a function bnRemainder(a) { var r = nbi(); this.divRemTo(a,null,r); return r; } // (public) [this/a,this%a] function bnDivideAndRemainder(a) { var q = nbi(), r = nbi(); this.divRemTo(a,q,r); return new Array(q,r); } // (protected) this *= n, this >= 0, 1 < n < DV function bnpDMultiply(n) { this[this.t] = this.am(0,n-1,this,0,0,this.t); ++this.t; this.clamp(); } // (protected) this += n << w words, this >= 0 function bnpDAddOffset(n,w) { if(n == 0) return; while(this.t <= w) this[this.t++] = 0; this[w] += n; while(this[w] >= this.DV) { this[w] -= this.DV; if(++w >= this.t) this[this.t++] = 0; ++this[w]; } } // A "null" reducer function NullExp() {} function nNop(x) { return x; } function nMulTo(x,y,r) { x.multiplyTo(y,r); } function nSqrTo(x,r) { x.squareTo(r); } NullExp.prototype.convert = nNop; NullExp.prototype.revert = nNop; NullExp.prototype.mulTo = nMulTo; NullExp.prototype.sqrTo = nSqrTo; // (public) this^e function bnPow(e) { return this.exp(e,new NullExp()); } // (protected) r = lower n words of "this * a", a.t <= n // "this" should be the larger one if appropriate. function bnpMultiplyLowerTo(a,n,r) { var i = Math.min(this.t+a.t,n); r.s = 0; // assumes a,this >= 0 r.t = i; while(i > 0) r[--i] = 0; var j; for(j = r.t-this.t; i < j; ++i) r[i+this.t] = this.am(0,a[i],r,i,0,this.t); for(j = Math.min(a.t,n); i < j; ++i) this.am(0,a[i],r,i,0,n-i); r.clamp(); } // (protected) r = "this * a" without lower n words, n > 0 // "this" should be the larger one if appropriate. function bnpMultiplyUpperTo(a,n,r) { --n; var i = r.t = this.t+a.t-n; r.s = 0; // assumes a,this >= 0 while(--i >= 0) r[i] = 0; for(i = Math.max(n-this.t,0); i < a.t; ++i) r[this.t+i-n] = this.am(n-i,a[i],r,0,0,this.t+i-n); r.clamp(); r.drShiftTo(1,r); } // Barrett modular reduction function Barrett(m) { // setup Barrett this.r2 = nbi(); this.q3 = nbi(); BigInteger.ONE.dlShiftTo(2*m.t,this.r2); this.mu = this.r2.divide(m); this.m = m; } function barrettConvert(x) { if(x.s < 0 || x.t > 2*this.m.t) return x.mod(this.m); else if(x.compareTo(this.m) < 0) return x; else { var r = nbi(); x.copyTo(r); this.reduce(r); return r; } } function barrettRevert(x) { return x; } // x = x mod m (HAC 14.42) function barrettReduce(x) { x.drShiftTo(this.m.t-1,this.r2); if(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); } this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3); this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2); while(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1); x.subTo(this.r2,x); while(x.compareTo(this.m) >= 0) x.subTo(this.m,x); } // r = x^2 mod m; x != r function barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); } // r = x*y mod m; x,y != r function barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } Barrett.prototype.convert = barrettConvert; Barrett.prototype.revert = barrettRevert; Barrett.prototype.reduce = barrettReduce; Barrett.prototype.mulTo = barrettMulTo; Barrett.prototype.sqrTo = barrettSqrTo; // (public) this^e % m (HAC 14.85) function bnModPow(e,m) { var i = e.bitLength(), k, r = nbv(1), z; if(i <= 0) return r; else if(i < 18) k = 1; else if(i < 48) k = 3; else if(i < 144) k = 4; else if(i < 768) k = 5; else k = 6; if(i < 8) z = new Classic(m); else if(m.isEven()) z = new Barrett(m); else z = new Montgomery(m); // precomputation var g = new Array(), n = 3, k1 = k-1, km = (1< 1) { var g2 = nbi(); z.sqrTo(g[1],g2); while(n <= km) { g[n] = nbi(); z.mulTo(g2,g[n-2],g[n]); n += 2; } } var j = e.t-1, w, is1 = true, r2 = nbi(), t; i = nbits(e[j])-1; while(j >= 0) { if(i >= k1) w = (e[j]>>(i-k1))&km; else { w = (e[j]&((1<<(i+1))-1))<<(k1-i); if(j > 0) w |= e[j-1]>>(this.DB+i-k1); } n = k; while((w&1) == 0) { w >>= 1; --n; } if((i -= n) < 0) { i += this.DB; --j; } if(is1) { // ret == 1, don't bother squaring or multiplying it g[w].copyTo(r); is1 = false; } else { while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; } if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; } z.mulTo(r2,g[w],r); } while(j >= 0 && (e[j]&(1< 0) { x.rShiftTo(g,x); y.rShiftTo(g,y); } while(x.signum() > 0) { if((i = x.getLowestSetBit()) > 0) x.rShiftTo(i,x); if((i = y.getLowestSetBit()) > 0) y.rShiftTo(i,y); if(x.compareTo(y) >= 0) { x.subTo(y,x); x.rShiftTo(1,x); } else { y.subTo(x,y); y.rShiftTo(1,y); } } if(g > 0) y.lShiftTo(g,y); return y; } // (protected) this % n, n < 2^26 function bnpModInt(n) { if(n <= 0) return 0; var d = this.DV%n, r = (this.s<0)?n-1:0; if(this.t > 0) if(d == 0) r = this[0]%n; else for(var i = this.t-1; i >= 0; --i) r = (d*r+this[i])%n; return r; } // (public) 1/this % m (HAC 14.61) function bnModInverse(m) { var ac = m.isEven(); if((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO; var u = m.clone(), v = this.clone(); var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1); while(u.signum() != 0) { while(u.isEven()) { u.rShiftTo(1,u); if(ac) { if(!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); } a.rShiftTo(1,a); } else if(!b.isEven()) b.subTo(m,b); b.rShiftTo(1,b); } while(v.isEven()) { v.rShiftTo(1,v); if(ac) { if(!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); } c.rShiftTo(1,c); } else if(!d.isEven()) d.subTo(m,d); d.rShiftTo(1,d); } if(u.compareTo(v) >= 0) { u.subTo(v,u); if(ac) a.subTo(c,a); b.subTo(d,b); } else { v.subTo(u,v); if(ac) c.subTo(a,c); d.subTo(b,d); } } if(v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO; if(d.compareTo(m) >= 0) return d.subtract(m); if(d.signum() < 0) d.addTo(m,d); else return d; if(d.signum() < 0) return d.add(m); else return d; } var lowprimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997]; var lplim = (1<<26)/lowprimes[lowprimes.length-1]; // (public) test primality with certainty >= 1-.5^t function bnIsProbablePrime(t) { var i, x = this.abs(); if(x.t == 1 && x[0] <= lowprimes[lowprimes.length-1]) { for(i = 0; i < lowprimes.length; ++i) if(x[0] == lowprimes[i]) return true; return false; } if(x.isEven()) return false; i = 1; while(i < lowprimes.length) { var m = lowprimes[i], j = i+1; while(j < lowprimes.length && m < lplim) m *= lowprimes[j++]; m = x.modInt(m); while(i < j) if(m%lowprimes[i++] == 0) return false; } return x.millerRabin(t); } // (protected) true if probably prime (HAC 4.24, Miller-Rabin) function bnpMillerRabin(t) { var n1 = this.subtract(BigInteger.ONE); var k = n1.getLowestSetBit(); if(k <= 0) return false; var r = n1.shiftRight(k); t = (t+1)>>1; if(t > lowprimes.length) t = lowprimes.length; var a = nbi(); for(var i = 0; i < t; ++i) { //Pick bases at random, instead of starting at 2 a.fromInt(lowprimes[Math.floor(Math.random()*lowprimes.length)]); var y = a.modPow(r,this); if(y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { var j = 1; while(j++ < k && y.compareTo(n1) != 0) { y = y.modPowInt(2,this); if(y.compareTo(BigInteger.ONE) == 0) return false; } if(y.compareTo(n1) != 0) return false; } } return true; } // protected BigInteger.prototype.chunkSize = bnpChunkSize; BigInteger.prototype.toRadix = bnpToRadix; BigInteger.prototype.fromRadix = bnpFromRadix; BigInteger.prototype.fromNumber = bnpFromNumber; BigInteger.prototype.bitwiseTo = bnpBitwiseTo; BigInteger.prototype.changeBit = bnpChangeBit; BigInteger.prototype.addTo = bnpAddTo; BigInteger.prototype.dMultiply = bnpDMultiply; BigInteger.prototype.dAddOffset = bnpDAddOffset; BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo; BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo; BigInteger.prototype.modInt = bnpModInt; BigInteger.prototype.millerRabin = bnpMillerRabin; // public BigInteger.prototype.clone = bnClone; BigInteger.prototype.intValue = bnIntValue; BigInteger.prototype.byteValue = bnByteValue; BigInteger.prototype.shortValue = bnShortValue; BigInteger.prototype.signum = bnSigNum; BigInteger.prototype.toByteArray = bnToByteArray; BigInteger.prototype.equals = bnEquals; BigInteger.prototype.min = bnMin; BigInteger.prototype.max = bnMax; BigInteger.prototype.and = bnAnd; BigInteger.prototype.or = bnOr; BigInteger.prototype.xor = bnXor; BigInteger.prototype.andNot = bnAndNot; BigInteger.prototype.not = bnNot; BigInteger.prototype.shiftLeft = bnShiftLeft; BigInteger.prototype.shiftRight = bnShiftRight; BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit; BigInteger.prototype.bitCount = bnBitCount; BigInteger.prototype.testBit = bnTestBit; BigInteger.prototype.setBit = bnSetBit; BigInteger.prototype.clearBit = bnClearBit; BigInteger.prototype.flipBit = bnFlipBit; BigInteger.prototype.add = bnAdd; BigInteger.prototype.subtract = bnSubtract; BigInteger.prototype.multiply = bnMultiply; BigInteger.prototype.divide = bnDivide; BigInteger.prototype.remainder = bnRemainder; BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder; BigInteger.prototype.modPow = bnModPow; BigInteger.prototype.modInverse = bnModInverse; BigInteger.prototype.pow = bnPow; BigInteger.prototype.gcd = bnGCD; BigInteger.prototype.isProbablePrime = bnIsProbablePrime; // JSBN-specific extension BigInteger.prototype.square = bnSquare; // Expose the Barrett function BigInteger.prototype.Barrett = Barrett // BigInteger interfaces not implemented in jsbn: // BigInteger(int signum, byte[] magnitude) // double doubleValue() // float floatValue() // int hashCode() // long longValue() // static BigInteger valueOf(long val) // Random number generator - requires a PRNG backend, e.g. prng4.js // For best results, put code like // // in your main HTML document. var rng_state; var rng_pool; var rng_pptr; // Mix in a 32-bit integer into the pool function rng_seed_int(x) { rng_pool[rng_pptr++] ^= x & 255; rng_pool[rng_pptr++] ^= (x >> 8) & 255; rng_pool[rng_pptr++] ^= (x >> 16) & 255; rng_pool[rng_pptr++] ^= (x >> 24) & 255; if(rng_pptr >= rng_psize) rng_pptr -= rng_psize; } // Mix in the current time (w/milliseconds) into the pool function rng_seed_time() { rng_seed_int(new Date().getTime()); } // Initialize the pool with junk if needed. if(rng_pool == null) { rng_pool = new Array(); rng_pptr = 0; var t; if(typeof window !== "undefined" && window.crypto) { if (window.crypto.getRandomValues) { // Use webcrypto if available var ua = new Uint8Array(32); window.crypto.getRandomValues(ua); for(t = 0; t < 32; ++t) rng_pool[rng_pptr++] = ua[t]; } else if(navigator.appName == "Netscape" && navigator.appVersion < "5") { // Extract entropy (256 bits) from NS4 RNG if available var z = window.crypto.random(32); for(t = 0; t < z.length; ++t) rng_pool[rng_pptr++] = z.charCodeAt(t) & 255; } } while(rng_pptr < rng_psize) { // extract some randomness from Math.random() t = Math.floor(65536 * Math.random()); rng_pool[rng_pptr++] = t >>> 8; rng_pool[rng_pptr++] = t & 255; } rng_pptr = 0; rng_seed_time(); //rng_seed_int(window.screenX); //rng_seed_int(window.screenY); } function rng_get_byte() { if(rng_state == null) { rng_seed_time(); rng_state = prng_newstate(); rng_state.init(rng_pool); for(rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr) rng_pool[rng_pptr] = 0; rng_pptr = 0; //rng_pool = null; } // TODO: allow reseeding after first request return rng_state.next(); } function rng_get_bytes(ba) { var i; for(i = 0; i < ba.length; ++i) ba[i] = rng_get_byte(); } function SecureRandom() {} SecureRandom.prototype.nextBytes = rng_get_bytes; // prng4.js - uses Arcfour as a PRNG function Arcfour() { this.i = 0; this.j = 0; this.S = new Array(); } // Initialize arcfour context from key, an array of ints, each from [0..255] function ARC4init(key) { var i, j, t; for(i = 0; i < 256; ++i) this.S[i] = i; j = 0; for(i = 0; i < 256; ++i) { j = (j + this.S[i] + key[i % key.length]) & 255; t = this.S[i]; this.S[i] = this.S[j]; this.S[j] = t; } this.i = 0; this.j = 0; } function ARC4next() { var t; this.i = (this.i + 1) & 255; this.j = (this.j + this.S[this.i]) & 255; t = this.S[this.i]; this.S[this.i] = this.S[this.j]; this.S[this.j] = t; return this.S[(t + this.S[this.i]) & 255]; } Arcfour.prototype.init = ARC4init; Arcfour.prototype.next = ARC4next; // Plug in your RNG constructor here function prng_newstate() { return new Arcfour(); } // Pool size must be a multiple of 4 and greater than 32. // An array of bytes the size of the pool will be passed to init() var rng_psize = 256; BigInteger.SecureRandom = SecureRandom; BigInteger.BigInteger = BigInteger; if (true) { exports = module.exports = BigInteger; } else {} }).call(this); /***/ }), /***/ 52533: /***/ ((module) => { "use strict"; var traverse = module.exports = function (schema, opts, cb) { // Legacy support for v0.3.1 and earlier. if (typeof opts == 'function') { cb = opts; opts = {}; } cb = opts.cb || cb; var pre = (typeof cb == 'function') ? cb : cb.pre || function() {}; var post = cb.post || function() {}; _traverse(opts, pre, post, schema, '', schema); }; traverse.keywords = { additionalItems: true, items: true, contains: true, additionalProperties: true, propertyNames: true, not: true }; traverse.arrayKeywords = { items: true, allOf: true, anyOf: true, oneOf: true }; traverse.propsKeywords = { definitions: true, properties: true, patternProperties: true, dependencies: true }; traverse.skipKeywords = { default: true, enum: true, const: true, required: true, maximum: true, minimum: true, exclusiveMaximum: true, exclusiveMinimum: true, multipleOf: true, maxLength: true, minLength: true, pattern: true, format: true, maxItems: true, minItems: true, uniqueItems: true, maxProperties: true, minProperties: true }; function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) { if (schema && typeof schema == 'object' && !Array.isArray(schema)) { pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); for (var key in schema) { var sch = schema[key]; if (Array.isArray(sch)) { if (key in traverse.arrayKeywords) { for (var i=0; i schema.maxItems){ addError("There must be a maximum of " + schema.maxItems + " in the array"); } }else if(schema.properties || schema.additionalProperties){ errors.concat(checkObj(value, schema.properties, path, schema.additionalProperties)); } if(schema.pattern && typeof value == 'string' && !value.match(schema.pattern)){ addError("does not match the regex pattern " + schema.pattern); } if(schema.maxLength && typeof value == 'string' && value.length > schema.maxLength){ addError("may only be " + schema.maxLength + " characters long"); } if(schema.minLength && typeof value == 'string' && value.length < schema.minLength){ addError("must be at least " + schema.minLength + " characters long"); } if(typeof schema.minimum !== 'undefined' && typeof value == typeof schema.minimum && schema.minimum > value){ addError("must have a minimum value of " + schema.minimum); } if(typeof schema.maximum !== 'undefined' && typeof value == typeof schema.maximum && schema.maximum < value){ addError("must have a maximum value of " + schema.maximum); } if(schema['enum']){ var enumer = schema['enum']; l = enumer.length; var found; for(var j = 0; j < l; j++){ if(enumer[j]===value){ found=1; break; } } if(!found){ addError("does not have a value in the enumeration " + enumer.join(", ")); } } if(typeof schema.maxDecimal == 'number' && (value.toString().match(new RegExp("\\.[0-9]{" + (schema.maxDecimal + 1) + ",}")))){ addError("may only have " + schema.maxDecimal + " digits of decimal places"); } } } return null; } // validate an object against a schema function checkObj(instance,objTypeDef,path,additionalProp){ if(typeof objTypeDef =='object'){ if(typeof instance != 'object' || instance instanceof Array){ errors.push({property:path,message:"an object is required"}); } for(var i in objTypeDef){ if(objTypeDef.hasOwnProperty(i) && i != '__proto__' && i != 'constructor'){ var value = instance.hasOwnProperty(i) ? instance[i] : undefined; // skip _not_ specified properties if (value === undefined && options.existingOnly) continue; var propDef = objTypeDef[i]; // set default if(value === undefined && propDef["default"]){ value = instance[i] = propDef["default"]; } if(options.coerce && i in instance){ value = instance[i] = options.coerce(value, propDef); } checkProp(value,propDef,path,i); } } } for(i in instance){ if(instance.hasOwnProperty(i) && !(i.charAt(0) == '_' && i.charAt(1) == '_') && objTypeDef && !objTypeDef[i] && additionalProp===false){ if (options.filter) { delete instance[i]; continue; } else { errors.push({property:path,message:"The property " + i + " is not defined in the schema and the schema does not allow additional properties"}); } } var requires = objTypeDef && objTypeDef[i] && objTypeDef[i].requires; if(requires && !(requires in instance)){ errors.push({property:path,message:"the presence of the property " + i + " requires that " + requires + " also be present"}); } value = instance[i]; if(additionalProp && (!(objTypeDef && typeof objTypeDef == 'object') || !(i in objTypeDef))){ if(options.coerce){ value = instance[i] = options.coerce(value, additionalProp); } checkProp(value,additionalProp,path,i); } if(!_changing && value && value.$schema){ errors = errors.concat(checkProp(value,value.$schema,path,i)); } } return errors; } if(schema){ checkProp(instance,schema,'',_changing || ''); } if(!_changing && instance && instance.$schema){ checkProp(instance,instance.$schema,'',''); } return {valid:!errors.length,errors:errors}; }; exports.mustBeValid = function(result){ // summary: // This checks to ensure that the result is valid and will throw an appropriate error message if it is not // result: the result returned from checkPropertyChange or validate if(!result.valid){ throw new TypeError(result.errors.map(function(error){return "for property " + error.property + ': ' + error.message;}).join(", \n")); } } return exports; })); /***/ }), /***/ 57073: /***/ ((module, exports) => { exports = module.exports = stringify exports.getSerialize = serializer function stringify(obj, replacer, spaces, cycleReplacer) { return JSON.stringify(obj, serializer(replacer, cycleReplacer), spaces) } function serializer(replacer, cycleReplacer) { var stack = [], keys = [] if (cycleReplacer == null) cycleReplacer = function(key, value) { if (stack[0] === value) return "[Circular ~]" return "[Circular ~." + keys.slice(0, stack.indexOf(value)).join(".") + "]" } return function(key, value) { if (stack.length > 0) { var thisPos = stack.indexOf(this) ~thisPos ? stack.splice(thisPos + 1) : stack.push(this) ~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key) if (~stack.indexOf(value)) value = cycleReplacer.call(this, key, value) } else stack.push(value) return replacer == null ? value : replacer.call(this, key, value) } } /***/ }), /***/ 63269: /***/ (function(module, exports, __nccwpck_require__) { (function (global, factory) { true ? factory(exports) : 0; }(this, function (exports) { 'use strict'; function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function (obj) { return typeof obj; }; } else { _typeof = function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _construct(Parent, args, Class) { if (isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); } function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; } function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } /* eslint-disable no-eval */ var globalEval = eval; // eslint-disable-next-line import/no-commonjs var supportsNodeVM = true && Boolean(module.exports) && !(typeof navigator !== 'undefined' && navigator.product === 'ReactNative'); var allowedResultTypes = ['value', 'path', 'pointer', 'parent', 'parentProperty', 'all']; var hasOwnProp = Object.prototype.hasOwnProperty; /** * Copy items out of one array into another. * @param {Array} source Array with items to copy * @param {Array} target Array to which to copy * @param {Function} conditionCb Callback passed the current item; will move * item if evaluates to `true` * @returns {undefined} */ var moveToAnotherArray = function moveToAnotherArray(source, target, conditionCb) { var il = source.length; for (var i = 0; i < il; i++) { var item = source[i]; if (conditionCb(item)) { target.push(source.splice(i--, 1)[0]); } } }; var vm = supportsNodeVM ? __nccwpck_require__(26144) : { /** * @param {string} expr Expression to evaluate * @param {Object} context Object whose items will be added to evaluation * @returns {*} Result of evaluated code */ runInNewContext: function runInNewContext(expr, context) { var keys = Object.keys(context); var funcs = []; moveToAnotherArray(keys, funcs, function (key) { return typeof context[key] === 'function'; }); var code = funcs.reduce(function (s, func) { var fString = context[func].toString(); if (!/function/.exec(fString)) { fString = 'function ' + fString; } return 'var ' + func + '=' + fString + ';' + s; }, '') + keys.reduce(function (s, vr) { return 'var ' + vr + '=' + JSON.stringify(context[vr]).replace( // http://www.thespanner.co.uk/2011/07/25/the-json-specification-is-now-wrong/ /\u2028|\u2029/g, function (m) { return "\\u202" + (m === "\u2028" ? '8' : '9'); }) + ';' + s; }, expr); return globalEval(code); } }; /** * Copies array and then pushes item into it. * @param {Array} arr Array to copy and into which to push * @param {*} item Array item to add (to end) * @returns {Array} Copy of the original array */ function push(arr, item) { arr = arr.slice(); arr.push(item); return arr; } /** * Copies array and then unshifts item into it. * @param {*} item Array item to add (to beginning) * @param {Array} arr Array to copy and into which to unshift * @returns {Array} Copy of the original array */ function unshift(item, arr) { arr = arr.slice(); arr.unshift(item); return arr; } /** * Caught when JSONPath is used without `new` but rethrown if with `new` * @extends Error */ var NewError = /*#__PURE__*/ function (_Error) { _inherits(NewError, _Error); /** * @param {*} value The evaluated scalar value */ function NewError(value) { var _this; _classCallCheck(this, NewError); _this = _possibleConstructorReturn(this, _getPrototypeOf(NewError).call(this, 'JSONPath should not be called with "new" (it prevents return of (unwrapped) scalar values)')); _this.avoidNew = true; _this.value = value; _this.name = 'NewError'; return _this; } return NewError; }(_wrapNativeSuper(Error)); /** * @param {Object} [opts] If present, must be an object * @param {string} expr JSON path to evaluate * @param {JSON} obj JSON object to evaluate against * @param {Function} callback Passed 3 arguments: 1) desired payload per `resultType`, * 2) `"value"|"property"`, 3) Full returned object with all payloads * @param {Function} otherTypeCallback If `@other()` is at the end of one's query, this * will be invoked with the value of the item, its path, its parent, and its parent's * property name, and it should return a boolean indicating whether the supplied value * belongs to the "other" type or not (or it may handle transformations and return `false`). * @returns {JSONPath} * @class */ function JSONPath(opts, expr, obj, callback, otherTypeCallback) { // eslint-disable-next-line no-restricted-syntax if (!(this instanceof JSONPath)) { try { return new JSONPath(opts, expr, obj, callback, otherTypeCallback); } catch (e) { if (!e.avoidNew) { throw e; } return e.value; } } if (typeof opts === 'string') { otherTypeCallback = callback; callback = obj; obj = expr; expr = opts; opts = {}; } opts = opts || {}; var objArgs = hasOwnProp.call(opts, 'json') && hasOwnProp.call(opts, 'path'); this.json = opts.json || obj; this.path = opts.path || expr; this.resultType = opts.resultType && opts.resultType.toLowerCase() || 'value'; this.flatten = opts.flatten || false; this.wrap = hasOwnProp.call(opts, 'wrap') ? opts.wrap : true; this.sandbox = opts.sandbox || {}; this.preventEval = opts.preventEval || false; this.parent = opts.parent || null; this.parentProperty = opts.parentProperty || null; this.callback = opts.callback || callback || null; this.otherTypeCallback = opts.otherTypeCallback || otherTypeCallback || function () { throw new Error('You must supply an otherTypeCallback callback option with the @other() operator.'); }; if (opts.autostart !== false) { var ret = this.evaluate({ path: objArgs ? opts.path : expr, json: objArgs ? opts.json : obj }); if (!ret || _typeof(ret) !== 'object') { throw new NewError(ret); } return ret; } } // PUBLIC METHODS JSONPath.prototype.evaluate = function (expr, json, callback, otherTypeCallback) { var that = this; var currParent = this.parent, currParentProperty = this.parentProperty; var flatten = this.flatten, wrap = this.wrap; this.currResultType = this.resultType; this.currPreventEval = this.preventEval; this.currSandbox = this.sandbox; callback = callback || this.callback; this.currOtherTypeCallback = otherTypeCallback || this.otherTypeCallback; json = json || this.json; expr = expr || this.path; if (expr && _typeof(expr) === 'object') { if (!expr.path) { throw new Error('You must supply a "path" property when providing an object argument to JSONPath.evaluate().'); } json = hasOwnProp.call(expr, 'json') ? expr.json : json; flatten = hasOwnProp.call(expr, 'flatten') ? expr.flatten : flatten; this.currResultType = hasOwnProp.call(expr, 'resultType') ? expr.resultType : this.currResultType; this.currSandbox = hasOwnProp.call(expr, 'sandbox') ? expr.sandbox : this.currSandbox; wrap = hasOwnProp.call(expr, 'wrap') ? expr.wrap : wrap; this.currPreventEval = hasOwnProp.call(expr, 'preventEval') ? expr.preventEval : this.currPreventEval; callback = hasOwnProp.call(expr, 'callback') ? expr.callback : callback; this.currOtherTypeCallback = hasOwnProp.call(expr, 'otherTypeCallback') ? expr.otherTypeCallback : this.currOtherTypeCallback; currParent = hasOwnProp.call(expr, 'parent') ? expr.parent : currParent; currParentProperty = hasOwnProp.call(expr, 'parentProperty') ? expr.parentProperty : currParentProperty; expr = expr.path; } currParent = currParent || null; currParentProperty = currParentProperty || null; if (Array.isArray(expr)) { expr = JSONPath.toPathString(expr); } if (!expr || !json || !allowedResultTypes.includes(this.currResultType)) { return undefined; } this._obj = json; var exprList = JSONPath.toPathArray(expr); if (exprList[0] === '$' && exprList.length > 1) { exprList.shift(); } this._hasParentSelector = null; var result = this._trace(exprList, json, ['$'], currParent, currParentProperty, callback).filter(function (ea) { return ea && !ea.isParentSelector; }); if (!result.length) { return wrap ? [] : undefined; } if (result.length === 1 && !wrap && !Array.isArray(result[0].value)) { return this._getPreferredOutput(result[0]); } return result.reduce(function (rslt, ea) { var valOrPath = that._getPreferredOutput(ea); if (flatten && Array.isArray(valOrPath)) { rslt = rslt.concat(valOrPath); } else { rslt.push(valOrPath); } return rslt; }, []); }; // PRIVATE METHODS JSONPath.prototype._getPreferredOutput = function (ea) { var resultType = this.currResultType; switch (resultType) { default: throw new TypeError('Unknown result type'); case 'all': ea.pointer = JSONPath.toPointer(ea.path); ea.path = typeof ea.path === 'string' ? ea.path : JSONPath.toPathString(ea.path); return ea; case 'value': case 'parent': case 'parentProperty': return ea[resultType]; case 'path': return JSONPath.toPathString(ea[resultType]); case 'pointer': return JSONPath.toPointer(ea.path); } }; JSONPath.prototype._handleCallback = function (fullRetObj, callback, type) { if (callback) { var preferredOutput = this._getPreferredOutput(fullRetObj); fullRetObj.path = typeof fullRetObj.path === 'string' ? fullRetObj.path : JSONPath.toPathString(fullRetObj.path); // eslint-disable-next-line callback-return callback(preferredOutput, type, fullRetObj); } }; JSONPath.prototype._trace = function (expr, val, path, parent, parentPropName, callback, literalPriority) { // No expr to follow? return path and value as the result of this trace branch var retObj; var that = this; if (!expr.length) { retObj = { path: path, value: val, parent: parent, parentProperty: parentPropName }; this._handleCallback(retObj, callback, 'value'); return retObj; } var loc = expr[0], x = expr.slice(1); // We need to gather the return value of recursive trace calls in order to // do the parent sel computation. var ret = []; function addRet(elems) { if (Array.isArray(elems)) { // This was causing excessive stack size in Node (with or without Babel) against our performance test: `ret.push(...elems);` elems.forEach(function (t) { ret.push(t); }); } else { ret.push(elems); } } if ((typeof loc !== 'string' || literalPriority) && val && hasOwnProp.call(val, loc)) { // simple case--directly follow property addRet(this._trace(x, val[loc], push(path, loc), val, loc, callback)); } else if (loc === '*') { // all child properties // eslint-disable-next-line no-shadow this._walk(loc, x, val, path, parent, parentPropName, callback, function (m, l, x, v, p, par, pr, cb) { addRet(that._trace(unshift(m, x), v, p, par, pr, cb, true)); }); } else if (loc === '..') { // all descendent parent properties addRet(this._trace(x, val, path, parent, parentPropName, callback)); // Check remaining expression with val's immediate children // eslint-disable-next-line no-shadow this._walk(loc, x, val, path, parent, parentPropName, callback, function (m, l, x, v, p, par, pr, cb) { // We don't join m and x here because we only want parents, not scalar values if (_typeof(v[m]) === 'object') { // Keep going with recursive descent on val's object children addRet(that._trace(unshift(l, x), v[m], push(p, m), v, m, cb)); } }); // The parent sel computation is handled in the frame above using the // ancestor object of val } else if (loc === '^') { // This is not a final endpoint, so we do not invoke the callback here this._hasParentSelector = true; return path.length ? { path: path.slice(0, -1), expr: x, isParentSelector: true } : []; } else if (loc === '~') { // property name retObj = { path: push(path, loc), value: parentPropName, parent: parent, parentProperty: null }; this._handleCallback(retObj, callback, 'property'); return retObj; } else if (loc === '$') { // root only addRet(this._trace(x, val, path, null, null, callback)); } else if (/^(-?\d*):(-?\d*):?(\d*)$/.test(loc)) { // [start:end:step] Python slice syntax addRet(this._slice(loc, x, val, path, parent, parentPropName, callback)); } else if (loc.indexOf('?(') === 0) { // [?(expr)] (filtering) if (this.currPreventEval) { throw new Error('Eval [?(expr)] prevented in JSONPath expression.'); } // eslint-disable-next-line no-shadow this._walk(loc, x, val, path, parent, parentPropName, callback, function (m, l, x, v, p, par, pr, cb) { if (that._eval(l.replace(/^\?\((.*?)\)$/, '$1'), v[m], m, p, par, pr)) { addRet(that._trace(unshift(m, x), v, p, par, pr, cb)); } }); } else if (loc[0] === '(') { // [(expr)] (dynamic property/index) if (this.currPreventEval) { throw new Error('Eval [(expr)] prevented in JSONPath expression.'); } // As this will resolve to a property name (but we don't know it yet), property and parent information is relative to the parent of the property to which this expression will resolve addRet(this._trace(unshift(this._eval(loc, val, path[path.length - 1], path.slice(0, -1), parent, parentPropName), x), val, path, parent, parentPropName, callback)); } else if (loc[0] === '@') { // value type: @boolean(), etc. var addType = false; var valueType = loc.slice(1, -2); switch (valueType) { default: throw new TypeError('Unknown value type ' + valueType); case 'scalar': if (!val || !['object', 'function'].includes(_typeof(val))) { addType = true; } break; case 'boolean': case 'string': case 'undefined': case 'function': if (_typeof(val) === valueType) { // eslint-disable-line valid-typeof addType = true; } break; case 'number': if (_typeof(val) === valueType && isFinite(val)) { // eslint-disable-line valid-typeof addType = true; } break; case 'nonFinite': if (typeof val === 'number' && !isFinite(val)) { addType = true; } break; case 'object': if (val && _typeof(val) === valueType) { // eslint-disable-line valid-typeof addType = true; } break; case 'array': if (Array.isArray(val)) { addType = true; } break; case 'other': addType = this.currOtherTypeCallback(val, path, parent, parentPropName); break; case 'integer': if (val === Number(val) && isFinite(val) && !(val % 1)) { addType = true; } break; case 'null': if (val === null) { addType = true; } break; } if (addType) { retObj = { path: path, value: val, parent: parent, parentProperty: parentPropName }; this._handleCallback(retObj, callback, 'value'); return retObj; } } else if (loc[0] === '`' && val && hasOwnProp.call(val, loc.slice(1))) { // `-escaped property var locProp = loc.slice(1); addRet(this._trace(x, val[locProp], push(path, locProp), val, locProp, callback, true)); } else if (loc.includes(',')) { // [name1,name2,...] var parts = loc.split(','); var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = parts[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var part = _step.value; addRet(this._trace(unshift(part, x), val, path, parent, parentPropName, callback)); } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator["return"] != null) { _iterator["return"](); } } finally { if (_didIteratorError) { throw _iteratorError; } } } } else if (!literalPriority && val && hasOwnProp.call(val, loc)) { // simple case--directly follow property addRet(this._trace(x, val[loc], push(path, loc), val, loc, callback, true)); } // We check the resulting values for parent selections. For parent // selections we discard the value object and continue the trace with the // current val object if (this._hasParentSelector) { // eslint-disable-next-line unicorn/no-for-loop for (var t = 0; t < ret.length; t++) { var rett = ret[t]; if (rett.isParentSelector) { var tmp = that._trace(rett.expr, val, rett.path, parent, parentPropName, callback); if (Array.isArray(tmp)) { ret[t] = tmp[0]; var tl = tmp.length; for (var tt = 1; tt < tl; tt++) { t++; ret.splice(t, 0, tmp[tt]); } } else { ret[t] = tmp; } } } } return ret; }; JSONPath.prototype._walk = function (loc, expr, val, path, parent, parentPropName, callback, f) { if (Array.isArray(val)) { var n = val.length; for (var i = 0; i < n; i++) { f(i, loc, expr, val, path, parent, parentPropName, callback); } } else if (_typeof(val) === 'object') { for (var m in val) { if (hasOwnProp.call(val, m)) { f(m, loc, expr, val, path, parent, parentPropName, callback); } } } }; JSONPath.prototype._slice = function (loc, expr, val, path, parent, parentPropName, callback) { if (!Array.isArray(val)) { return undefined; } var len = val.length, parts = loc.split(':'), step = parts[2] && parseInt(parts[2]) || 1; var start = parts[0] && parseInt(parts[0]) || 0, end = parts[1] && parseInt(parts[1]) || len; start = start < 0 ? Math.max(0, start + len) : Math.min(len, start); end = end < 0 ? Math.max(0, end + len) : Math.min(len, end); var ret = []; for (var i = start; i < end; i += step) { var tmp = this._trace(unshift(i, expr), val, path, parent, parentPropName, callback); if (Array.isArray(tmp)) { // This was causing excessive stack size in Node (with or without Babel) against our performance test: `ret.push(...tmp);` tmp.forEach(function (t) { ret.push(t); }); } else { ret.push(tmp); } } return ret; }; JSONPath.prototype._eval = function (code, _v, _vname, path, parent, parentPropName) { if (!this._obj || !_v) { return false; } if (code.includes('@parentProperty')) { this.currSandbox._$_parentProperty = parentPropName; code = code.replace(/@parentProperty/g, '_$_parentProperty'); } if (code.includes('@parent')) { this.currSandbox._$_parent = parent; code = code.replace(/@parent/g, '_$_parent'); } if (code.includes('@property')) { this.currSandbox._$_property = _vname; code = code.replace(/@property/g, '_$_property'); } if (code.includes('@path')) { this.currSandbox._$_path = JSONPath.toPathString(path.concat([_vname])); code = code.replace(/@path/g, '_$_path'); } if (code.match(/@([.\s)[])/)) { this.currSandbox._$_v = _v; code = code.replace(/@([.\s)[])/g, '_$_v$1'); } try { return vm.runInNewContext(code, this.currSandbox); } catch (e) { // eslint-disable-next-line no-console console.log(e); throw new Error('jsonPath: ' + e.message + ': ' + code); } }; // PUBLIC CLASS PROPERTIES AND METHODS // Could store the cache object itself JSONPath.cache = {}; /** * @param {string[]} pathArr Array to convert * @returns {string} The path string */ JSONPath.toPathString = function (pathArr) { var x = pathArr, n = x.length; var p = '$'; for (var i = 1; i < n; i++) { if (!/^(~|\^|@.*?\(\))$/.test(x[i])) { p += /^[0-9*]+$/.test(x[i]) ? '[' + x[i] + ']' : "['" + x[i] + "']"; } } return p; }; /** * @param {string} pointer JSON Path * @returns {string} JSON Pointer */ JSONPath.toPointer = function (pointer) { var x = pointer, n = x.length; var p = ''; for (var i = 1; i < n; i++) { if (!/^(~|\^|@.*?\(\))$/.test(x[i])) { p += '/' + x[i].toString().replace(/~/g, '~0').replace(/\//g, '~1'); } } return p; }; /** * @param {string} expr Expression to convert * @returns {string[]} */ JSONPath.toPathArray = function (expr) { var cache = JSONPath.cache; if (cache[expr]) { return cache[expr].concat(); } var subx = []; var normalized = expr // Properties .replace(/@(?:null|boolean|number|string|integer|undefined|nonFinite|scalar|array|object|function|other)\(\)/g, ';$&;') // Parenthetical evaluations (filtering and otherwise), directly // within brackets or single quotes .replace(/[['](\??\(.*?\))[\]']/g, function ($0, $1) { return '[#' + (subx.push($1) - 1) + ']'; }) // Escape periods and tildes within properties .replace(/\['([^'\]]*)'\]/g, function ($0, prop) { return "['" + prop.replace(/\./g, '%@%').replace(/~/g, '%%@@%%') + "']"; }) // Properties operator .replace(/~/g, ';~;') // Split by property boundaries .replace(/'?\.'?(?![^[]*\])|\['?/g, ';') // Reinsert periods within properties .replace(/%@%/g, '.') // Reinsert tildes within properties .replace(/%%@@%%/g, '~') // Parent .replace(/(?:;)?(\^+)(?:;)?/g, function ($0, ups) { return ';' + ups.split('').join(';') + ';'; }) // Descendents .replace(/;;;|;;/g, ';..;') // Remove trailing .replace(/;$|'?\]|'$/g, ''); var exprList = normalized.split(';').map(function (exp) { var match = exp.match(/#(\d+)/); return !match || !match[1] ? exp : subx[match[1]]; }); cache[expr] = exprList; return cache[expr]; }; exports.JSONPath = JSONPath; Object.defineProperty(exports, '__esModule', { value: true }); })); /***/ }), /***/ 6287: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { /* * lib/jsprim.js: utilities for primitive JavaScript types */ var mod_assert = __nccwpck_require__(66631); var mod_util = __nccwpck_require__(73837); var mod_extsprintf = __nccwpck_require__(87264); var mod_verror = __nccwpck_require__(81692); var mod_jsonschema = __nccwpck_require__(21328); /* * Public interface */ exports.deepCopy = deepCopy; exports.deepEqual = deepEqual; exports.isEmpty = isEmpty; exports.hasKey = hasKey; exports.forEachKey = forEachKey; exports.pluck = pluck; exports.flattenObject = flattenObject; exports.flattenIter = flattenIter; exports.validateJsonObject = validateJsonObjectJS; exports.validateJsonObjectJS = validateJsonObjectJS; exports.randElt = randElt; exports.extraProperties = extraProperties; exports.mergeObjects = mergeObjects; exports.startsWith = startsWith; exports.endsWith = endsWith; exports.parseInteger = parseInteger; exports.iso8601 = iso8601; exports.rfc1123 = rfc1123; exports.parseDateTime = parseDateTime; exports.hrtimediff = hrtimeDiff; exports.hrtimeDiff = hrtimeDiff; exports.hrtimeAccum = hrtimeAccum; exports.hrtimeAdd = hrtimeAdd; exports.hrtimeNanosec = hrtimeNanosec; exports.hrtimeMicrosec = hrtimeMicrosec; exports.hrtimeMillisec = hrtimeMillisec; /* * Deep copy an acyclic *basic* Javascript object. This only handles basic * scalars (strings, numbers, booleans) and arbitrarily deep arrays and objects * containing these. This does *not* handle instances of other classes. */ function deepCopy(obj) { var ret, key; var marker = '__deepCopy'; if (obj && obj[marker]) throw (new Error('attempted deep copy of cyclic object')); if (obj && obj.constructor == Object) { ret = {}; obj[marker] = true; for (key in obj) { if (key == marker) continue; ret[key] = deepCopy(obj[key]); } delete (obj[marker]); return (ret); } if (obj && obj.constructor == Array) { ret = []; obj[marker] = true; for (key = 0; key < obj.length; key++) ret.push(deepCopy(obj[key])); delete (obj[marker]); return (ret); } /* * It must be a primitive type -- just return it. */ return (obj); } function deepEqual(obj1, obj2) { if (typeof (obj1) != typeof (obj2)) return (false); if (obj1 === null || obj2 === null || typeof (obj1) != 'object') return (obj1 === obj2); if (obj1.constructor != obj2.constructor) return (false); var k; for (k in obj1) { if (!obj2.hasOwnProperty(k)) return (false); if (!deepEqual(obj1[k], obj2[k])) return (false); } for (k in obj2) { if (!obj1.hasOwnProperty(k)) return (false); } return (true); } function isEmpty(obj) { var key; for (key in obj) return (false); return (true); } function hasKey(obj, key) { mod_assert.equal(typeof (key), 'string'); return (Object.prototype.hasOwnProperty.call(obj, key)); } function forEachKey(obj, callback) { for (var key in obj) { if (hasKey(obj, key)) { callback(key, obj[key]); } } } function pluck(obj, key) { mod_assert.equal(typeof (key), 'string'); return (pluckv(obj, key)); } function pluckv(obj, key) { if (obj === null || typeof (obj) !== 'object') return (undefined); if (obj.hasOwnProperty(key)) return (obj[key]); var i = key.indexOf('.'); if (i == -1) return (undefined); var key1 = key.substr(0, i); if (!obj.hasOwnProperty(key1)) return (undefined); return (pluckv(obj[key1], key.substr(i + 1))); } /* * Invoke callback(row) for each entry in the array that would be returned by * flattenObject(data, depth). This is just like flattenObject(data, * depth).forEach(callback), except that the intermediate array is never * created. */ function flattenIter(data, depth, callback) { doFlattenIter(data, depth, [], callback); } function doFlattenIter(data, depth, accum, callback) { var each; var key; if (depth === 0) { each = accum.slice(0); each.push(data); callback(each); return; } mod_assert.ok(data !== null); mod_assert.equal(typeof (data), 'object'); mod_assert.equal(typeof (depth), 'number'); mod_assert.ok(depth >= 0); for (key in data) { each = accum.slice(0); each.push(key); doFlattenIter(data[key], depth - 1, each, callback); } } function flattenObject(data, depth) { if (depth === 0) return ([ data ]); mod_assert.ok(data !== null); mod_assert.equal(typeof (data), 'object'); mod_assert.equal(typeof (depth), 'number'); mod_assert.ok(depth >= 0); var rv = []; var key; for (key in data) { flattenObject(data[key], depth - 1).forEach(function (p) { rv.push([ key ].concat(p)); }); } return (rv); } function startsWith(str, prefix) { return (str.substr(0, prefix.length) == prefix); } function endsWith(str, suffix) { return (str.substr( str.length - suffix.length, suffix.length) == suffix); } function iso8601(d) { if (typeof (d) == 'number') d = new Date(d); mod_assert.ok(d.constructor === Date); return (mod_extsprintf.sprintf('%4d-%02d-%02dT%02d:%02d:%02d.%03dZ', d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate(), d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds(), d.getUTCMilliseconds())); } var RFC1123_MONTHS = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; var RFC1123_DAYS = [ 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; function rfc1123(date) { return (mod_extsprintf.sprintf('%s, %02d %s %04d %02d:%02d:%02d GMT', RFC1123_DAYS[date.getUTCDay()], date.getUTCDate(), RFC1123_MONTHS[date.getUTCMonth()], date.getUTCFullYear(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds())); } /* * Parses a date expressed as a string, as either a number of milliseconds since * the epoch or any string format that Date accepts, giving preference to the * former where these two sets overlap (e.g., small numbers). */ function parseDateTime(str) { /* * This is irritatingly implicit, but significantly more concise than * alternatives. The "+str" will convert a string containing only a * number directly to a Number, or NaN for other strings. Thus, if the * conversion succeeds, we use it (this is the milliseconds-since-epoch * case). Otherwise, we pass the string directly to the Date * constructor to parse. */ var numeric = +str; if (!isNaN(numeric)) { return (new Date(numeric)); } else { return (new Date(str)); } } /* * Number.*_SAFE_INTEGER isn't present before node v0.12, so we hardcode * the ES6 definitions here, while allowing for them to someday be higher. */ var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991; var MIN_SAFE_INTEGER = Number.MIN_SAFE_INTEGER || -9007199254740991; /* * Default options for parseInteger(). */ var PI_DEFAULTS = { base: 10, allowSign: true, allowPrefix: false, allowTrailing: false, allowImprecise: false, trimWhitespace: false, leadingZeroIsOctal: false }; var CP_0 = 0x30; var CP_9 = 0x39; var CP_A = 0x41; var CP_B = 0x42; var CP_O = 0x4f; var CP_T = 0x54; var CP_X = 0x58; var CP_Z = 0x5a; var CP_a = 0x61; var CP_b = 0x62; var CP_o = 0x6f; var CP_t = 0x74; var CP_x = 0x78; var CP_z = 0x7a; var PI_CONV_DEC = 0x30; var PI_CONV_UC = 0x37; var PI_CONV_LC = 0x57; /* * A stricter version of parseInt() that provides options for changing what * is an acceptable string (for example, disallowing trailing characters). */ function parseInteger(str, uopts) { mod_assert.string(str, 'str'); mod_assert.optionalObject(uopts, 'options'); var baseOverride = false; var options = PI_DEFAULTS; if (uopts) { baseOverride = hasKey(uopts, 'base'); options = mergeObjects(options, uopts); mod_assert.number(options.base, 'options.base'); mod_assert.ok(options.base >= 2, 'options.base >= 2'); mod_assert.ok(options.base <= 36, 'options.base <= 36'); mod_assert.bool(options.allowSign, 'options.allowSign'); mod_assert.bool(options.allowPrefix, 'options.allowPrefix'); mod_assert.bool(options.allowTrailing, 'options.allowTrailing'); mod_assert.bool(options.allowImprecise, 'options.allowImprecise'); mod_assert.bool(options.trimWhitespace, 'options.trimWhitespace'); mod_assert.bool(options.leadingZeroIsOctal, 'options.leadingZeroIsOctal'); if (options.leadingZeroIsOctal) { mod_assert.ok(!baseOverride, '"base" and "leadingZeroIsOctal" are ' + 'mutually exclusive'); } } var c; var pbase = -1; var base = options.base; var start; var mult = 1; var value = 0; var idx = 0; var len = str.length; /* Trim any whitespace on the left side. */ if (options.trimWhitespace) { while (idx < len && isSpace(str.charCodeAt(idx))) { ++idx; } } /* Check the number for a leading sign. */ if (options.allowSign) { if (str[idx] === '-') { idx += 1; mult = -1; } else if (str[idx] === '+') { idx += 1; } } /* Parse the base-indicating prefix if there is one. */ if (str[idx] === '0') { if (options.allowPrefix) { pbase = prefixToBase(str.charCodeAt(idx + 1)); if (pbase !== -1 && (!baseOverride || pbase === base)) { base = pbase; idx += 2; } } if (pbase === -1 && options.leadingZeroIsOctal) { base = 8; } } /* Parse the actual digits. */ for (start = idx; idx < len; ++idx) { c = translateDigit(str.charCodeAt(idx)); if (c !== -1 && c < base) { value *= base; value += c; } else { break; } } /* If we didn't parse any digits, we have an invalid number. */ if (start === idx) { return (new Error('invalid number: ' + JSON.stringify(str))); } /* Trim any whitespace on the right side. */ if (options.trimWhitespace) { while (idx < len && isSpace(str.charCodeAt(idx))) { ++idx; } } /* Check for trailing characters. */ if (idx < len && !options.allowTrailing) { return (new Error('trailing characters after number: ' + JSON.stringify(str.slice(idx)))); } /* If our value is 0, we return now, to avoid returning -0. */ if (value === 0) { return (0); } /* Calculate our final value. */ var result = value * mult; /* * If the string represents a value that cannot be precisely represented * by JavaScript, then we want to check that: * * - We never increased the value past MAX_SAFE_INTEGER * - We don't make the result negative and below MIN_SAFE_INTEGER * * Because we only ever increment the value during parsing, there's no * chance of moving past MAX_SAFE_INTEGER and then dropping below it * again, losing precision in the process. This means that we only need * to do our checks here, at the end. */ if (!options.allowImprecise && (value > MAX_SAFE_INTEGER || result < MIN_SAFE_INTEGER)) { return (new Error('number is outside of the supported range: ' + JSON.stringify(str.slice(start, idx)))); } return (result); } /* * Interpret a character code as a base-36 digit. */ function translateDigit(d) { if (d >= CP_0 && d <= CP_9) { /* '0' to '9' -> 0 to 9 */ return (d - PI_CONV_DEC); } else if (d >= CP_A && d <= CP_Z) { /* 'A' - 'Z' -> 10 to 35 */ return (d - PI_CONV_UC); } else if (d >= CP_a && d <= CP_z) { /* 'a' - 'z' -> 10 to 35 */ return (d - PI_CONV_LC); } else { /* Invalid character code */ return (-1); } } /* * Test if a value matches the ECMAScript definition of trimmable whitespace. */ function isSpace(c) { return (c === 0x20) || (c >= 0x0009 && c <= 0x000d) || (c === 0x00a0) || (c === 0x1680) || (c === 0x180e) || (c >= 0x2000 && c <= 0x200a) || (c === 0x2028) || (c === 0x2029) || (c === 0x202f) || (c === 0x205f) || (c === 0x3000) || (c === 0xfeff); } /* * Determine which base a character indicates (e.g., 'x' indicates hex). */ function prefixToBase(c) { if (c === CP_b || c === CP_B) { /* 0b/0B (binary) */ return (2); } else if (c === CP_o || c === CP_O) { /* 0o/0O (octal) */ return (8); } else if (c === CP_t || c === CP_T) { /* 0t/0T (decimal) */ return (10); } else if (c === CP_x || c === CP_X) { /* 0x/0X (hexadecimal) */ return (16); } else { /* Not a meaningful character */ return (-1); } } function validateJsonObjectJS(schema, input) { var report = mod_jsonschema.validate(input, schema); if (report.errors.length === 0) return (null); /* Currently, we only do anything useful with the first error. */ var error = report.errors[0]; /* The failed property is given by a URI with an irrelevant prefix. */ var propname = error['property']; var reason = error['message'].toLowerCase(); var i, j; /* * There's at least one case where the property error message is * confusing at best. We work around this here. */ if ((i = reason.indexOf('the property ')) != -1 && (j = reason.indexOf(' is not defined in the schema and the ' + 'schema does not allow additional properties')) != -1) { i += 'the property '.length; if (propname === '') propname = reason.substr(i, j - i); else propname = propname + '.' + reason.substr(i, j - i); reason = 'unsupported property'; } var rv = new mod_verror.VError('property "%s": %s', propname, reason); rv.jsv_details = error; return (rv); } function randElt(arr) { mod_assert.ok(Array.isArray(arr) && arr.length > 0, 'randElt argument must be a non-empty array'); return (arr[Math.floor(Math.random() * arr.length)]); } function assertHrtime(a) { mod_assert.ok(a[0] >= 0 && a[1] >= 0, 'negative numbers not allowed in hrtimes'); mod_assert.ok(a[1] < 1e9, 'nanoseconds column overflow'); } /* * Compute the time elapsed between hrtime readings A and B, where A is later * than B. hrtime readings come from Node's process.hrtime(). There is no * defined way to represent negative deltas, so it's illegal to diff B from A * where the time denoted by B is later than the time denoted by A. If this * becomes valuable, we can define a representation and extend the * implementation to support it. */ function hrtimeDiff(a, b) { assertHrtime(a); assertHrtime(b); mod_assert.ok(a[0] > b[0] || (a[0] == b[0] && a[1] >= b[1]), 'negative differences not allowed'); var rv = [ a[0] - b[0], 0 ]; if (a[1] >= b[1]) { rv[1] = a[1] - b[1]; } else { rv[0]--; rv[1] = 1e9 - (b[1] - a[1]); } return (rv); } /* * Convert a hrtime reading from the array format returned by Node's * process.hrtime() into a scalar number of nanoseconds. */ function hrtimeNanosec(a) { assertHrtime(a); return (Math.floor(a[0] * 1e9 + a[1])); } /* * Convert a hrtime reading from the array format returned by Node's * process.hrtime() into a scalar number of microseconds. */ function hrtimeMicrosec(a) { assertHrtime(a); return (Math.floor(a[0] * 1e6 + a[1] / 1e3)); } /* * Convert a hrtime reading from the array format returned by Node's * process.hrtime() into a scalar number of milliseconds. */ function hrtimeMillisec(a) { assertHrtime(a); return (Math.floor(a[0] * 1e3 + a[1] / 1e6)); } /* * Add two hrtime readings A and B, overwriting A with the result of the * addition. This function is useful for accumulating several hrtime intervals * into a counter. Returns A. */ function hrtimeAccum(a, b) { assertHrtime(a); assertHrtime(b); /* * Accumulate the nanosecond component. */ a[1] += b[1]; if (a[1] >= 1e9) { /* * The nanosecond component overflowed, so carry to the seconds * field. */ a[0]++; a[1] -= 1e9; } /* * Accumulate the seconds component. */ a[0] += b[0]; return (a); } /* * Add two hrtime readings A and B, returning the result as a new hrtime array. * Does not modify either input argument. */ function hrtimeAdd(a, b) { assertHrtime(a); var rv = [ a[0], a[1] ]; return (hrtimeAccum(rv, b)); } /* * Check an object for unexpected properties. Accepts the object to check, and * an array of allowed property names (strings). Returns an array of key names * that were found on the object, but did not appear in the list of allowed * properties. If no properties were found, the returned array will be of * zero length. */ function extraProperties(obj, allowed) { mod_assert.ok(typeof (obj) === 'object' && obj !== null, 'obj argument must be a non-null object'); mod_assert.ok(Array.isArray(allowed), 'allowed argument must be an array of strings'); for (var i = 0; i < allowed.length; i++) { mod_assert.ok(typeof (allowed[i]) === 'string', 'allowed argument must be an array of strings'); } return (Object.keys(obj).filter(function (key) { return (allowed.indexOf(key) === -1); })); } /* * Given three sets of properties "provided" (may be undefined), "overrides" * (required), and "defaults" (may be undefined), construct an object containing * the union of these sets with "overrides" overriding "provided", and * "provided" overriding "defaults". None of the input objects are modified. */ function mergeObjects(provided, overrides, defaults) { var rv, k; rv = {}; if (defaults) { for (k in defaults) rv[k] = defaults[k]; } if (provided) { for (k in provided) rv[k] = provided[k]; } if (overrides) { for (k in overrides) rv[k] = overrides[k]; } return (rv); } /***/ }), /***/ 9662: /***/ ((module) => { "use strict"; module.exports = object => { const result = {}; for (const [key, value] of Object.entries(object)) { result[key.toLowerCase()] = value; } return result; }; /***/ }), /***/ 7129: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // A linked list to keep track of recently-used-ness const Yallist = __nccwpck_require__(40665) const MAX = Symbol('max') const LENGTH = Symbol('length') const LENGTH_CALCULATOR = Symbol('lengthCalculator') const ALLOW_STALE = Symbol('allowStale') const MAX_AGE = Symbol('maxAge') const DISPOSE = Symbol('dispose') const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet') const LRU_LIST = Symbol('lruList') const CACHE = Symbol('cache') const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet') const naiveLength = () => 1 // lruList is a yallist where the head is the youngest // item, and the tail is the oldest. the list contains the Hit // objects as the entries. // Each Hit object has a reference to its Yallist.Node. This // never changes. // // cache is a Map (or PseudoMap) that matches the keys to // the Yallist.Node object. class LRUCache { constructor (options) { if (typeof options === 'number') options = { max: options } if (!options) options = {} if (options.max && (typeof options.max !== 'number' || options.max < 0)) throw new TypeError('max must be a non-negative number') // Kind of weird to have a default max of Infinity, but oh well. const max = this[MAX] = options.max || Infinity const lc = options.length || naiveLength this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc this[ALLOW_STALE] = options.stale || false if (options.maxAge && typeof options.maxAge !== 'number') throw new TypeError('maxAge must be a number') this[MAX_AGE] = options.maxAge || 0 this[DISPOSE] = options.dispose this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false this.reset() } // resize the cache when the max changes. set max (mL) { if (typeof mL !== 'number' || mL < 0) throw new TypeError('max must be a non-negative number') this[MAX] = mL || Infinity trim(this) } get max () { return this[MAX] } set allowStale (allowStale) { this[ALLOW_STALE] = !!allowStale } get allowStale () { return this[ALLOW_STALE] } set maxAge (mA) { if (typeof mA !== 'number') throw new TypeError('maxAge must be a non-negative number') this[MAX_AGE] = mA trim(this) } get maxAge () { return this[MAX_AGE] } // resize the cache when the lengthCalculator changes. set lengthCalculator (lC) { if (typeof lC !== 'function') lC = naiveLength if (lC !== this[LENGTH_CALCULATOR]) { this[LENGTH_CALCULATOR] = lC this[LENGTH] = 0 this[LRU_LIST].forEach(hit => { hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key) this[LENGTH] += hit.length }) } trim(this) } get lengthCalculator () { return this[LENGTH_CALCULATOR] } get length () { return this[LENGTH] } get itemCount () { return this[LRU_LIST].length } rforEach (fn, thisp) { thisp = thisp || this for (let walker = this[LRU_LIST].tail; walker !== null;) { const prev = walker.prev forEachStep(this, fn, walker, thisp) walker = prev } } forEach (fn, thisp) { thisp = thisp || this for (let walker = this[LRU_LIST].head; walker !== null;) { const next = walker.next forEachStep(this, fn, walker, thisp) walker = next } } keys () { return this[LRU_LIST].toArray().map(k => k.key) } values () { return this[LRU_LIST].toArray().map(k => k.value) } reset () { if (this[DISPOSE] && this[LRU_LIST] && this[LRU_LIST].length) { this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value)) } this[CACHE] = new Map() // hash of items by key this[LRU_LIST] = new Yallist() // list of items in order of use recency this[LENGTH] = 0 // length of items in the list } dump () { return this[LRU_LIST].map(hit => isStale(this, hit) ? false : { k: hit.key, v: hit.value, e: hit.now + (hit.maxAge || 0) }).toArray().filter(h => h) } dumpLru () { return this[LRU_LIST] } set (key, value, maxAge) { maxAge = maxAge || this[MAX_AGE] if (maxAge && typeof maxAge !== 'number') throw new TypeError('maxAge must be a number') const now = maxAge ? Date.now() : 0 const len = this[LENGTH_CALCULATOR](value, key) if (this[CACHE].has(key)) { if (len > this[MAX]) { del(this, this[CACHE].get(key)) return false } const node = this[CACHE].get(key) const item = node.value // dispose of the old one before overwriting // split out into 2 ifs for better coverage tracking if (this[DISPOSE]) { if (!this[NO_DISPOSE_ON_SET]) this[DISPOSE](key, item.value) } item.now = now item.maxAge = maxAge item.value = value this[LENGTH] += len - item.length item.length = len this.get(key) trim(this) return true } const hit = new Entry(key, value, len, now, maxAge) // oversized objects fall out of cache automatically. if (hit.length > this[MAX]) { if (this[DISPOSE]) this[DISPOSE](key, value) return false } this[LENGTH] += hit.length this[LRU_LIST].unshift(hit) this[CACHE].set(key, this[LRU_LIST].head) trim(this) return true } has (key) { if (!this[CACHE].has(key)) return false const hit = this[CACHE].get(key).value return !isStale(this, hit) } get (key) { return get(this, key, true) } peek (key) { return get(this, key, false) } pop () { const node = this[LRU_LIST].tail if (!node) return null del(this, node) return node.value } del (key) { del(this, this[CACHE].get(key)) } load (arr) { // reset the cache this.reset() const now = Date.now() // A previous serialized cache has the most recent items first for (let l = arr.length - 1; l >= 0; l--) { const hit = arr[l] const expiresAt = hit.e || 0 if (expiresAt === 0) // the item was created without expiration in a non aged cache this.set(hit.k, hit.v) else { const maxAge = expiresAt - now // dont add already expired items if (maxAge > 0) { this.set(hit.k, hit.v, maxAge) } } } } prune () { this[CACHE].forEach((value, key) => get(this, key, false)) } } const get = (self, key, doUse) => { const node = self[CACHE].get(key) if (node) { const hit = node.value if (isStale(self, hit)) { del(self, node) if (!self[ALLOW_STALE]) return undefined } else { if (doUse) { if (self[UPDATE_AGE_ON_GET]) node.value.now = Date.now() self[LRU_LIST].unshiftNode(node) } } return hit.value } } const isStale = (self, hit) => { if (!hit || (!hit.maxAge && !self[MAX_AGE])) return false const diff = Date.now() - hit.now return hit.maxAge ? diff > hit.maxAge : self[MAX_AGE] && (diff > self[MAX_AGE]) } const trim = self => { if (self[LENGTH] > self[MAX]) { for (let walker = self[LRU_LIST].tail; self[LENGTH] > self[MAX] && walker !== null;) { // We know that we're about to delete this one, and also // what the next least recently used key will be, so just // go ahead and set it now. const prev = walker.prev del(self, walker) walker = prev } } } const del = (self, node) => { if (node) { const hit = node.value if (self[DISPOSE]) self[DISPOSE](hit.key, hit.value) self[LENGTH] -= hit.length self[CACHE].delete(hit.key) self[LRU_LIST].removeNode(node) } } class Entry { constructor (key, value, length, now, maxAge) { this.key = key this.value = value this.length = length this.now = now this.maxAge = maxAge || 0 } } const forEachStep = (self, fn, node, thisp) => { let hit = node.value if (isStale(self, hit)) { del(self, node) if (!self[ALLOW_STALE]) hit = undefined } if (hit) fn.call(thisp, hit.value, hit.key, self) } module.exports = LRUCache /***/ }), /***/ 21381: /***/ ((module, exports) => { "use strict"; // ISC @ Julien Fontanet // =================================================================== var construct = typeof Reflect !== "undefined" ? Reflect.construct : undefined; var defineProperty = Object.defineProperty; // ------------------------------------------------------------------- var captureStackTrace = Error.captureStackTrace; if (captureStackTrace === undefined) { captureStackTrace = function captureStackTrace(error) { var container = new Error(); defineProperty(error, "stack", { configurable: true, get: function getStack() { var stack = container.stack; // Replace property with value for faster future accesses. defineProperty(this, "stack", { configurable: true, value: stack, writable: true, }); return stack; }, set: function setStack(stack) { defineProperty(error, "stack", { configurable: true, value: stack, writable: true, }); }, }); }; } // ------------------------------------------------------------------- function BaseError(message) { if (message !== undefined) { defineProperty(this, "message", { configurable: true, value: message, writable: true, }); } var cname = this.constructor.name; if (cname !== undefined && cname !== this.name) { defineProperty(this, "name", { configurable: true, value: cname, writable: true, }); } captureStackTrace(this, this.constructor); } BaseError.prototype = Object.create(Error.prototype, { // See: https://github.com/JsCommunity/make-error/issues/4 constructor: { configurable: true, value: BaseError, writable: true, }, }); // ------------------------------------------------------------------- // Sets the name of a function if possible (depends of the JS engine). var setFunctionName = (function() { function setFunctionName(fn, name) { return defineProperty(fn, "name", { configurable: true, value: name, }); } try { var f = function() {}; setFunctionName(f, "foo"); if (f.name === "foo") { return setFunctionName; } } catch (_) {} })(); // ------------------------------------------------------------------- function makeError(constructor, super_) { if (super_ == null || super_ === Error) { super_ = BaseError; } else if (typeof super_ !== "function") { throw new TypeError("super_ should be a function"); } var name; if (typeof constructor === "string") { name = constructor; constructor = construct !== undefined ? function() { return construct(super_, arguments, this.constructor); } : function() { super_.apply(this, arguments); }; // If the name can be set, do it once and for all. if (setFunctionName !== undefined) { setFunctionName(constructor, name); name = undefined; } } else if (typeof constructor !== "function") { throw new TypeError("constructor should be either a string or a function"); } // Also register the super constructor also as `constructor.super_` just // like Node's `util.inherits()`. // // eslint-disable-next-line dot-notation constructor.super_ = constructor["super"] = super_; var properties = { constructor: { configurable: true, value: constructor, writable: true, }, }; // If the name could not be set on the constructor, set it on the // prototype. if (name !== undefined) { properties.name = { configurable: true, value: name, writable: true, }; } constructor.prototype = Object.create(super_.prototype, properties); return constructor; } exports = module.exports = makeError; exports.BaseError = BaseError; /***/ }), /***/ 2621: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { PassThrough } = __nccwpck_require__(12781); module.exports = function (/*streams...*/) { var sources = [] var output = new PassThrough({objectMode: true}) output.setMaxListeners(0) output.add = add output.isEmpty = isEmpty output.on('unpipe', remove) Array.prototype.slice.call(arguments).forEach(add) return output function add (source) { if (Array.isArray(source)) { source.forEach(add) return this } sources.push(source); source.once('end', remove.bind(null, source)) source.once('error', output.emit.bind(output, 'error')) source.pipe(output, {end: false}) return this } function isEmpty () { return sources.length == 0; } function remove (source) { sources = sources.filter(function (it) { return it !== source }) if (!sources.length && output.readable) { output.end() } } } /***/ }), /***/ 47426: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /*! * mime-db * Copyright(c) 2014 Jonathan Ong * Copyright(c) 2015-2022 Douglas Christopher Wilson * MIT Licensed */ /** * Module exports. */ module.exports = __nccwpck_require__(53765) /***/ }), /***/ 43583: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /*! * mime-types * Copyright(c) 2014 Jonathan Ong * Copyright(c) 2015 Douglas Christopher Wilson * MIT Licensed */ /** * Module dependencies. * @private */ var db = __nccwpck_require__(47426) var extname = (__nccwpck_require__(71017).extname) /** * Module variables. * @private */ var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/ var TEXT_TYPE_REGEXP = /^text\//i /** * Module exports. * @public */ exports.charset = charset exports.charsets = { lookup: charset } exports.contentType = contentType exports.extension = extension exports.extensions = Object.create(null) exports.lookup = lookup exports.types = Object.create(null) // Populate the extensions/types maps populateMaps(exports.extensions, exports.types) /** * Get the default charset for a MIME type. * * @param {string} type * @return {boolean|string} */ function charset (type) { if (!type || typeof type !== 'string') { return false } // TODO: use media-typer var match = EXTRACT_TYPE_REGEXP.exec(type) var mime = match && db[match[1].toLowerCase()] if (mime && mime.charset) { return mime.charset } // default text/* to utf-8 if (match && TEXT_TYPE_REGEXP.test(match[1])) { return 'UTF-8' } return false } /** * Create a full Content-Type header given a MIME type or extension. * * @param {string} str * @return {boolean|string} */ function contentType (str) { // TODO: should this even be in this module? if (!str || typeof str !== 'string') { return false } var mime = str.indexOf('/') === -1 ? exports.lookup(str) : str if (!mime) { return false } // TODO: use content-type or other module if (mime.indexOf('charset') === -1) { var charset = exports.charset(mime) if (charset) mime += '; charset=' + charset.toLowerCase() } return mime } /** * Get the default extension for a MIME type. * * @param {string} type * @return {boolean|string} */ function extension (type) { if (!type || typeof type !== 'string') { return false } // TODO: use media-typer var match = EXTRACT_TYPE_REGEXP.exec(type) // get extensions var exts = match && exports.extensions[match[1].toLowerCase()] if (!exts || !exts.length) { return false } return exts[0] } /** * Lookup the MIME type for a file path/extension. * * @param {string} path * @return {boolean|string} */ function lookup (path) { if (!path || typeof path !== 'string') { return false } // get the extension ("ext" or ".ext" or full path) var extension = extname('x.' + path) .toLowerCase() .substr(1) if (!extension) { return false } return exports.types[extension] || false } /** * Populate the extensions and types maps. * @private */ function populateMaps (extensions, types) { // source preference (least -> most) var preference = ['nginx', 'apache', undefined, 'iana'] Object.keys(db).forEach(function forEachMimeType (type) { var mime = db[type] var exts = mime.extensions if (!exts || !exts.length) { return } // mime -> extensions extensions[type] = exts // extension -> mime for (var i = 0; i < exts.length; i++) { var extension = exts[i] if (types[extension]) { var from = preference.indexOf(db[types[extension]].source) var to = preference.indexOf(mime.source) if (types[extension] !== 'application/octet-stream' && (from > to || (from === to && types[extension].substr(0, 12) === 'application/'))) { // skip the remapping continue } } // set the extension -> mime types[extension] = type } }) } /***/ }), /***/ 76047: /***/ ((module) => { "use strict"; const mimicFn = (to, from) => { for (const prop of Reflect.ownKeys(from)) { Object.defineProperty(to, prop, Object.getOwnPropertyDescriptor(from, prop)); } return to; }; module.exports = mimicFn; // TODO: Remove this for the next major release module.exports["default"] = mimicFn; /***/ }), /***/ 42610: /***/ ((module) => { "use strict"; // We define these manually to ensure they're always copied // even if they would move up the prototype chain // https://nodejs.org/api/http.html#http_class_http_incomingmessage const knownProps = [ 'destroy', 'setTimeout', 'socket', 'headers', 'trailers', 'rawHeaders', 'statusCode', 'httpVersion', 'httpVersionMinor', 'httpVersionMajor', 'rawTrailers', 'statusMessage' ]; module.exports = (fromStream, toStream) => { const fromProps = new Set(Object.keys(fromStream).concat(knownProps)); for (const prop of fromProps) { // Don't overwrite existing properties if (prop in toStream) { continue; } toStream[prop] = typeof fromStream[prop] === 'function' ? fromStream[prop].bind(fromStream) : fromStream[prop]; } }; /***/ }), /***/ 83973: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { module.exports = minimatch minimatch.Minimatch = Minimatch var path = (function () { try { return __nccwpck_require__(71017) } catch (e) {}}()) || { sep: '/' } minimatch.sep = path.sep var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {} var expand = __nccwpck_require__(33717) var plTypes = { '!': { open: '(?:(?!(?:', close: '))[^/]*?)'}, '?': { open: '(?:', close: ')?' }, '+': { open: '(?:', close: ')+' }, '*': { open: '(?:', close: ')*' }, '@': { open: '(?:', close: ')' } } // any single thing other than / // don't need to escape / when using new RegExp() var qmark = '[^/]' // * => any number of characters var star = qmark + '*?' // ** when dots are allowed. Anything goes, except .. and . // not (^ or / followed by one or two dots followed by $ or /), // followed by anything, any number of times. var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?' // not a ^ or / followed by a dot, // followed by anything, any number of times. var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?' // characters that need to be escaped in RegExp. var reSpecials = charSet('().*{}+?[]^$\\!') // "abc" -> { a:true, b:true, c:true } function charSet (s) { return s.split('').reduce(function (set, c) { set[c] = true return set }, {}) } // normalizes slashes. var slashSplit = /\/+/ minimatch.filter = filter function filter (pattern, options) { options = options || {} return function (p, i, list) { return minimatch(p, pattern, options) } } function ext (a, b) { b = b || {} var t = {} Object.keys(a).forEach(function (k) { t[k] = a[k] }) Object.keys(b).forEach(function (k) { t[k] = b[k] }) return t } minimatch.defaults = function (def) { if (!def || typeof def !== 'object' || !Object.keys(def).length) { return minimatch } var orig = minimatch var m = function minimatch (p, pattern, options) { return orig(p, pattern, ext(def, options)) } m.Minimatch = function Minimatch (pattern, options) { return new orig.Minimatch(pattern, ext(def, options)) } m.Minimatch.defaults = function defaults (options) { return orig.defaults(ext(def, options)).Minimatch } m.filter = function filter (pattern, options) { return orig.filter(pattern, ext(def, options)) } m.defaults = function defaults (options) { return orig.defaults(ext(def, options)) } m.makeRe = function makeRe (pattern, options) { return orig.makeRe(pattern, ext(def, options)) } m.braceExpand = function braceExpand (pattern, options) { return orig.braceExpand(pattern, ext(def, options)) } m.match = function (list, pattern, options) { return orig.match(list, pattern, ext(def, options)) } return m } Minimatch.defaults = function (def) { return minimatch.defaults(def).Minimatch } function minimatch (p, pattern, options) { assertValidPattern(pattern) if (!options) options = {} // shortcut: comments match nothing. if (!options.nocomment && pattern.charAt(0) === '#') { return false } return new Minimatch(pattern, options).match(p) } function Minimatch (pattern, options) { if (!(this instanceof Minimatch)) { return new Minimatch(pattern, options) } assertValidPattern(pattern) if (!options) options = {} pattern = pattern.trim() // windows support: need to use /, not \ if (!options.allowWindowsEscape && path.sep !== '/') { pattern = pattern.split(path.sep).join('/') } this.options = options this.set = [] this.pattern = pattern this.regexp = null this.negate = false this.comment = false this.empty = false this.partial = !!options.partial // make the set of regexps etc. this.make() } Minimatch.prototype.debug = function () {} Minimatch.prototype.make = make function make () { var pattern = this.pattern var options = this.options // empty patterns and comments match nothing. if (!options.nocomment && pattern.charAt(0) === '#') { this.comment = true return } if (!pattern) { this.empty = true return } // step 1: figure out negation, etc. this.parseNegate() // step 2: expand braces var set = this.globSet = this.braceExpand() if (options.debug) this.debug = function debug() { console.error.apply(console, arguments) } this.debug(this.pattern, set) // step 3: now we have a set, so turn each one into a series of path-portion // matching patterns. // These will be regexps, except in the case of "**", which is // set to the GLOBSTAR object for globstar behavior, // and will not contain any / characters set = this.globParts = set.map(function (s) { return s.split(slashSplit) }) this.debug(this.pattern, set) // glob --> regexps set = set.map(function (s, si, set) { return s.map(this.parse, this) }, this) this.debug(this.pattern, set) // filter out everything that didn't compile properly. set = set.filter(function (s) { return s.indexOf(false) === -1 }) this.debug(this.pattern, set) this.set = set } Minimatch.prototype.parseNegate = parseNegate function parseNegate () { var pattern = this.pattern var negate = false var options = this.options var negateOffset = 0 if (options.nonegate) return for (var i = 0, l = pattern.length ; i < l && pattern.charAt(i) === '!' ; i++) { negate = !negate negateOffset++ } if (negateOffset) this.pattern = pattern.substr(negateOffset) this.negate = negate } // Brace expansion: // a{b,c}d -> abd acd // a{b,}c -> abc ac // a{0..3}d -> a0d a1d a2d a3d // a{b,c{d,e}f}g -> abg acdfg acefg // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg // // Invalid sets are not expanded. // a{2..}b -> a{2..}b // a{b}c -> a{b}c minimatch.braceExpand = function (pattern, options) { return braceExpand(pattern, options) } Minimatch.prototype.braceExpand = braceExpand function braceExpand (pattern, options) { if (!options) { if (this instanceof Minimatch) { options = this.options } else { options = {} } } pattern = typeof pattern === 'undefined' ? this.pattern : pattern assertValidPattern(pattern) // Thanks to Yeting Li for // improving this regexp to avoid a ReDOS vulnerability. if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) { // shortcut. no need to expand. return [pattern] } return expand(pattern) } var MAX_PATTERN_LENGTH = 1024 * 64 var assertValidPattern = function (pattern) { if (typeof pattern !== 'string') { throw new TypeError('invalid pattern') } if (pattern.length > MAX_PATTERN_LENGTH) { throw new TypeError('pattern is too long') } } // parse a component of the expanded set. // At this point, no pattern may contain "/" in it // so we're going to return a 2d array, where each entry is the full // pattern, split on '/', and then turned into a regular expression. // A regexp is made at the end which joins each array with an // escaped /, and another full one which joins each regexp with |. // // Following the lead of Bash 4.1, note that "**" only has special meaning // when it is the *only* thing in a path portion. Otherwise, any series // of * is equivalent to a single *. Globstar behavior is enabled by // default, and can be disabled by setting options.noglobstar. Minimatch.prototype.parse = parse var SUBPARSE = {} function parse (pattern, isSub) { assertValidPattern(pattern) var options = this.options // shortcuts if (pattern === '**') { if (!options.noglobstar) return GLOBSTAR else pattern = '*' } if (pattern === '') return '' var re = '' var hasMagic = !!options.nocase var escaping = false // ? => one single character var patternListStack = [] var negativeLists = [] var stateChar var inClass = false var reClassStart = -1 var classStart = -1 // . and .. never match anything that doesn't start with ., // even when options.dot is set. var patternStart = pattern.charAt(0) === '.' ? '' // anything // not (start or / followed by . or .. followed by / or end) : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' : '(?!\\.)' var self = this function clearStateChar () { if (stateChar) { // we had some state-tracking character // that wasn't consumed by this pass. switch (stateChar) { case '*': re += star hasMagic = true break case '?': re += qmark hasMagic = true break default: re += '\\' + stateChar break } self.debug('clearStateChar %j %j', stateChar, re) stateChar = false } } for (var i = 0, len = pattern.length, c ; (i < len) && (c = pattern.charAt(i)) ; i++) { this.debug('%s\t%s %s %j', pattern, i, re, c) // skip over any that are escaped. if (escaping && reSpecials[c]) { re += '\\' + c escaping = false continue } switch (c) { /* istanbul ignore next */ case '/': { // completely not allowed, even escaped. // Should already be path-split by now. return false } case '\\': clearStateChar() escaping = true continue // the various stateChar values // for the "extglob" stuff. case '?': case '*': case '+': case '@': case '!': this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c) // all of those are literals inside a class, except that // the glob [!a] means [^a] in regexp if (inClass) { this.debug(' in class') if (c === '!' && i === classStart + 1) c = '^' re += c continue } // if we already have a stateChar, then it means // that there was something like ** or +? in there. // Handle the stateChar, then proceed with this one. self.debug('call clearStateChar %j', stateChar) clearStateChar() stateChar = c // if extglob is disabled, then +(asdf|foo) isn't a thing. // just clear the statechar *now*, rather than even diving into // the patternList stuff. if (options.noext) clearStateChar() continue case '(': if (inClass) { re += '(' continue } if (!stateChar) { re += '\\(' continue } patternListStack.push({ type: stateChar, start: i - 1, reStart: re.length, open: plTypes[stateChar].open, close: plTypes[stateChar].close }) // negation is (?:(?!js)[^/]*) re += stateChar === '!' ? '(?:(?!(?:' : '(?:' this.debug('plType %j %j', stateChar, re) stateChar = false continue case ')': if (inClass || !patternListStack.length) { re += '\\)' continue } clearStateChar() hasMagic = true var pl = patternListStack.pop() // negation is (?:(?!js)[^/]*) // The others are (?:) re += pl.close if (pl.type === '!') { negativeLists.push(pl) } pl.reEnd = re.length continue case '|': if (inClass || !patternListStack.length || escaping) { re += '\\|' escaping = false continue } clearStateChar() re += '|' continue // these are mostly the same in regexp and glob case '[': // swallow any state-tracking char before the [ clearStateChar() if (inClass) { re += '\\' + c continue } inClass = true classStart = i reClassStart = re.length re += c continue case ']': // a right bracket shall lose its special // meaning and represent itself in // a bracket expression if it occurs // first in the list. -- POSIX.2 2.8.3.2 if (i === classStart + 1 || !inClass) { re += '\\' + c escaping = false continue } // handle the case where we left a class open. // "[z-a]" is valid, equivalent to "\[z-a\]" // split where the last [ was, make sure we don't have // an invalid re. if so, re-walk the contents of the // would-be class to re-translate any characters that // were passed through as-is // TODO: It would probably be faster to determine this // without a try/catch and a new RegExp, but it's tricky // to do safely. For now, this is safe and works. var cs = pattern.substring(classStart + 1, i) try { RegExp('[' + cs + ']') } catch (er) { // not a valid class! var sp = this.parse(cs, SUBPARSE) re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]' hasMagic = hasMagic || sp[1] inClass = false continue } // finish up the class. hasMagic = true inClass = false re += c continue default: // swallow any state char that wasn't consumed clearStateChar() if (escaping) { // no need escaping = false } else if (reSpecials[c] && !(c === '^' && inClass)) { re += '\\' } re += c } // switch } // for // handle the case where we left a class open. // "[abc" is valid, equivalent to "\[abc" if (inClass) { // split where the last [ was, and escape it // this is a huge pita. We now have to re-walk // the contents of the would-be class to re-translate // any characters that were passed through as-is cs = pattern.substr(classStart + 1) sp = this.parse(cs, SUBPARSE) re = re.substr(0, reClassStart) + '\\[' + sp[0] hasMagic = hasMagic || sp[1] } // handle the case where we had a +( thing at the *end* // of the pattern. // each pattern list stack adds 3 chars, and we need to go through // and escape any | chars that were passed through as-is for the regexp. // Go through and escape them, taking care not to double-escape any // | chars that were already escaped. for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { var tail = re.slice(pl.reStart + pl.open.length) this.debug('setting tail', re, pl) // maybe some even number of \, then maybe 1 \, followed by a | tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) { if (!$2) { // the | isn't already escaped, so escape it. $2 = '\\' } // need to escape all those slashes *again*, without escaping the // one that we need for escaping the | character. As it works out, // escaping an even number of slashes can be done by simply repeating // it exactly after itself. That's why this trick works. // // I am sorry that you have to see this. return $1 + $1 + $2 + '|' }) this.debug('tail=%j\n %s', tail, tail, pl, re) var t = pl.type === '*' ? star : pl.type === '?' ? qmark : '\\' + pl.type hasMagic = true re = re.slice(0, pl.reStart) + t + '\\(' + tail } // handle trailing things that only matter at the very end. clearStateChar() if (escaping) { // trailing \\ re += '\\\\' } // only need to apply the nodot start if the re starts with // something that could conceivably capture a dot var addPatternStart = false switch (re.charAt(0)) { case '[': case '.': case '(': addPatternStart = true } // Hack to work around lack of negative lookbehind in JS // A pattern like: *.!(x).!(y|z) needs to ensure that a name // like 'a.xyz.yz' doesn't match. So, the first negative // lookahead, has to look ALL the way ahead, to the end of // the pattern. for (var n = negativeLists.length - 1; n > -1; n--) { var nl = negativeLists[n] var nlBefore = re.slice(0, nl.reStart) var nlFirst = re.slice(nl.reStart, nl.reEnd - 8) var nlLast = re.slice(nl.reEnd - 8, nl.reEnd) var nlAfter = re.slice(nl.reEnd) nlLast += nlAfter // Handle nested stuff like *(*.js|!(*.json)), where open parens // mean that we should *not* include the ) in the bit that is considered // "after" the negated section. var openParensBefore = nlBefore.split('(').length - 1 var cleanAfter = nlAfter for (i = 0; i < openParensBefore; i++) { cleanAfter = cleanAfter.replace(/\)[+*?]?/, '') } nlAfter = cleanAfter var dollar = '' if (nlAfter === '' && isSub !== SUBPARSE) { dollar = '$' } var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast re = newRe } // if the re is not "" at this point, then we need to make sure // it doesn't match against an empty path part. // Otherwise a/* will match a/, which it should not. if (re !== '' && hasMagic) { re = '(?=.)' + re } if (addPatternStart) { re = patternStart + re } // parsing just a piece of a larger pattern. if (isSub === SUBPARSE) { return [re, hasMagic] } // skip the regexp for non-magical patterns // unescape anything in it, though, so that it'll be // an exact match against a file etc. if (!hasMagic) { return globUnescape(pattern) } var flags = options.nocase ? 'i' : '' try { var regExp = new RegExp('^' + re + '$', flags) } catch (er) /* istanbul ignore next - should be impossible */ { // If it was an invalid regular expression, then it can't match // anything. This trick looks for a character after the end of // the string, which is of course impossible, except in multi-line // mode, but it's not a /m regex. return new RegExp('$.') } regExp._glob = pattern regExp._src = re return regExp } minimatch.makeRe = function (pattern, options) { return new Minimatch(pattern, options || {}).makeRe() } Minimatch.prototype.makeRe = makeRe function makeRe () { if (this.regexp || this.regexp === false) return this.regexp // at this point, this.set is a 2d array of partial // pattern strings, or "**". // // It's better to use .match(). This function shouldn't // be used, really, but it's pretty convenient sometimes, // when you just want to work with a regex. var set = this.set if (!set.length) { this.regexp = false return this.regexp } var options = this.options var twoStar = options.noglobstar ? star : options.dot ? twoStarDot : twoStarNoDot var flags = options.nocase ? 'i' : '' var re = set.map(function (pattern) { return pattern.map(function (p) { return (p === GLOBSTAR) ? twoStar : (typeof p === 'string') ? regExpEscape(p) : p._src }).join('\\\/') }).join('|') // must match entire pattern // ending in a * or ** will make it less strict. re = '^(?:' + re + ')$' // can match anything, as long as it's not this. if (this.negate) re = '^(?!' + re + ').*$' try { this.regexp = new RegExp(re, flags) } catch (ex) /* istanbul ignore next - should be impossible */ { this.regexp = false } return this.regexp } minimatch.match = function (list, pattern, options) { options = options || {} var mm = new Minimatch(pattern, options) list = list.filter(function (f) { return mm.match(f) }) if (mm.options.nonull && !list.length) { list.push(pattern) } return list } Minimatch.prototype.match = function match (f, partial) { if (typeof partial === 'undefined') partial = this.partial this.debug('match', f, this.pattern) // short-circuit in the case of busted things. // comments, etc. if (this.comment) return false if (this.empty) return f === '' if (f === '/' && partial) return true var options = this.options // windows: need to use /, not \ if (path.sep !== '/') { f = f.split(path.sep).join('/') } // treat the test path as a set of pathparts. f = f.split(slashSplit) this.debug(this.pattern, 'split', f) // just ONE of the pattern sets in this.set needs to match // in order for it to be valid. If negating, then just one // match means that we have failed. // Either way, return on the first hit. var set = this.set this.debug(this.pattern, 'set', set) // Find the basename of the path by looking for the last non-empty segment var filename var i for (i = f.length - 1; i >= 0; i--) { filename = f[i] if (filename) break } for (i = 0; i < set.length; i++) { var pattern = set[i] var file = f if (options.matchBase && pattern.length === 1) { file = [filename] } var hit = this.matchOne(file, pattern, partial) if (hit) { if (options.flipNegate) return true return !this.negate } } // didn't get any hits. this is success if it's a negative // pattern, failure otherwise. if (options.flipNegate) return false return this.negate } // set partial to true to test if, for example, // "/a/b" matches the start of "/*/b/*/d" // Partial means, if you run out of file before you run // out of pattern, then that's fine, as long as all // the parts match. Minimatch.prototype.matchOne = function (file, pattern, partial) { var options = this.options this.debug('matchOne', { 'this': this, file: file, pattern: pattern }) this.debug('matchOne', file.length, pattern.length) for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length ; (fi < fl) && (pi < pl) ; fi++, pi++) { this.debug('matchOne loop') var p = pattern[pi] var f = file[fi] this.debug(pattern, p, f) // should be impossible. // some invalid regexp stuff in the set. /* istanbul ignore if */ if (p === false) return false if (p === GLOBSTAR) { this.debug('GLOBSTAR', [pattern, p, f]) // "**" // a/**/b/**/c would match the following: // a/b/x/y/z/c // a/x/y/z/b/c // a/b/x/b/x/c // a/b/c // To do this, take the rest of the pattern after // the **, and see if it would match the file remainder. // If so, return success. // If not, the ** "swallows" a segment, and try again. // This is recursively awful. // // a/**/b/**/c matching a/b/x/y/z/c // - a matches a // - doublestar // - matchOne(b/x/y/z/c, b/**/c) // - b matches b // - doublestar // - matchOne(x/y/z/c, c) -> no // - matchOne(y/z/c, c) -> no // - matchOne(z/c, c) -> no // - matchOne(c, c) yes, hit var fr = fi var pr = pi + 1 if (pr === pl) { this.debug('** at the end') // a ** at the end will just swallow the rest. // We have found a match. // however, it will not swallow /.x, unless // options.dot is set. // . and .. are *never* matched by **, for explosively // exponential reasons. for (; fi < fl; fi++) { if (file[fi] === '.' || file[fi] === '..' || (!options.dot && file[fi].charAt(0) === '.')) return false } return true } // ok, let's see if we can swallow whatever we can. while (fr < fl) { var swallowee = file[fr] this.debug('\nglobstar while', file, fr, pattern, pr, swallowee) // XXX remove this slice. Just pass the start index. if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { this.debug('globstar found match!', fr, fl, swallowee) // found a match. return true } else { // can't swallow "." or ".." ever. // can only swallow ".foo" when explicitly asked. if (swallowee === '.' || swallowee === '..' || (!options.dot && swallowee.charAt(0) === '.')) { this.debug('dot detected!', file, fr, pattern, pr) break } // ** swallows a segment, and continue. this.debug('globstar swallow a segment, and continue') fr++ } } // no match was found. // However, in partial mode, we can't say this is necessarily over. // If there's more *pattern* left, then /* istanbul ignore if */ if (partial) { // ran out of file this.debug('\n>>> no match, partial?', file, fr, pattern, pr) if (fr === fl) return true } return false } // something other than ** // non-magic patterns just have to match exactly // patterns with magic have been turned into regexps. var hit if (typeof p === 'string') { hit = f === p this.debug('string match', p, f, hit) } else { hit = f.match(p) this.debug('pattern match', p, f, hit) } if (!hit) return false } // Note: ending in / means that we'll get a final "" // at the end of the pattern. This can only match a // corresponding "" at the end of the file. // If the file ends in /, then it can only match a // a pattern that ends in /, unless the pattern just // doesn't have any more for it. But, a/b/ should *not* // match "a/b/*", even though "" matches against the // [^/]*? pattern, except in partial mode, where it might // simply not be reached yet. // However, a/b/ should still satisfy a/* // now either we fell off the end of the pattern, or we're done. if (fi === fl && pi === pl) { // ran out of pattern and filename at the same time. // an exact hit! return true } else if (fi === fl) { // ran out of file, but still had pattern left. // this is ok if we're doing the match as part of // a glob fs traversal. return partial } else /* istanbul ignore else */ if (pi === pl) { // ran out of pattern, still have file left. // this is only acceptable if we're on the very last // empty segment of a file with a trailing slash. // a/* should match a/b/ return (fi === fl - 1) && (file[fi] === '') } // should be unreachable. /* istanbul ignore next */ throw new Error('wtf?') } // replace stuff like \* with * function globUnescape (s) { return s.replace(/\\(.)/g, '$1') } function regExpEscape (s) { return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') } /***/ }), /***/ 41077: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const proc = typeof process === 'object' && process ? process : { stdout: null, stderr: null, } const EE = __nccwpck_require__(82361) const Stream = __nccwpck_require__(12781) const SD = (__nccwpck_require__(71576).StringDecoder) const EOF = Symbol('EOF') const MAYBE_EMIT_END = Symbol('maybeEmitEnd') const EMITTED_END = Symbol('emittedEnd') const EMITTING_END = Symbol('emittingEnd') const EMITTED_ERROR = Symbol('emittedError') const CLOSED = Symbol('closed') const READ = Symbol('read') const FLUSH = Symbol('flush') const FLUSHCHUNK = Symbol('flushChunk') const ENCODING = Symbol('encoding') const DECODER = Symbol('decoder') const FLOWING = Symbol('flowing') const PAUSED = Symbol('paused') const RESUME = Symbol('resume') const BUFFERLENGTH = Symbol('bufferLength') const BUFFERPUSH = Symbol('bufferPush') const BUFFERSHIFT = Symbol('bufferShift') const OBJECTMODE = Symbol('objectMode') const DESTROYED = Symbol('destroyed') const EMITDATA = Symbol('emitData') const EMITEND = Symbol('emitEnd') const EMITEND2 = Symbol('emitEnd2') const ASYNC = Symbol('async') const defer = fn => Promise.resolve().then(fn) // TODO remove when Node v8 support drops const doIter = global._MP_NO_ITERATOR_SYMBOLS_ !== '1' const ASYNCITERATOR = doIter && Symbol.asyncIterator || Symbol('asyncIterator not implemented') const ITERATOR = doIter && Symbol.iterator || Symbol('iterator not implemented') // events that mean 'the stream is over' // these are treated specially, and re-emitted // if they are listened for after emitting. const isEndish = ev => ev === 'end' || ev === 'finish' || ev === 'prefinish' const isArrayBuffer = b => b instanceof ArrayBuffer || typeof b === 'object' && b.constructor && b.constructor.name === 'ArrayBuffer' && b.byteLength >= 0 const isArrayBufferView = b => !Buffer.isBuffer(b) && ArrayBuffer.isView(b) class Pipe { constructor (src, dest, opts) { this.src = src this.dest = dest this.opts = opts this.ondrain = () => src[RESUME]() dest.on('drain', this.ondrain) } unpipe () { this.dest.removeListener('drain', this.ondrain) } // istanbul ignore next - only here for the prototype proxyErrors () {} end () { this.unpipe() if (this.opts.end) this.dest.end() } } class PipeProxyErrors extends Pipe { unpipe () { this.src.removeListener('error', this.proxyErrors) super.unpipe() } constructor (src, dest, opts) { super(src, dest, opts) this.proxyErrors = er => dest.emit('error', er) src.on('error', this.proxyErrors) } } module.exports = class Minipass extends Stream { constructor (options) { super() this[FLOWING] = false // whether we're explicitly paused this[PAUSED] = false this.pipes = [] this.buffer = [] this[OBJECTMODE] = options && options.objectMode || false if (this[OBJECTMODE]) this[ENCODING] = null else this[ENCODING] = options && options.encoding || null if (this[ENCODING] === 'buffer') this[ENCODING] = null this[ASYNC] = options && !!options.async || false this[DECODER] = this[ENCODING] ? new SD(this[ENCODING]) : null this[EOF] = false this[EMITTED_END] = false this[EMITTING_END] = false this[CLOSED] = false this[EMITTED_ERROR] = null this.writable = true this.readable = true this[BUFFERLENGTH] = 0 this[DESTROYED] = false } get bufferLength () { return this[BUFFERLENGTH] } get encoding () { return this[ENCODING] } set encoding (enc) { if (this[OBJECTMODE]) throw new Error('cannot set encoding in objectMode') if (this[ENCODING] && enc !== this[ENCODING] && (this[DECODER] && this[DECODER].lastNeed || this[BUFFERLENGTH])) throw new Error('cannot change encoding') if (this[ENCODING] !== enc) { this[DECODER] = enc ? new SD(enc) : null if (this.buffer.length) this.buffer = this.buffer.map(chunk => this[DECODER].write(chunk)) } this[ENCODING] = enc } setEncoding (enc) { this.encoding = enc } get objectMode () { return this[OBJECTMODE] } set objectMode (om) { this[OBJECTMODE] = this[OBJECTMODE] || !!om } get ['async'] () { return this[ASYNC] } set ['async'] (a) { this[ASYNC] = this[ASYNC] || !!a } write (chunk, encoding, cb) { if (this[EOF]) throw new Error('write after end') if (this[DESTROYED]) { this.emit('error', Object.assign( new Error('Cannot call write after a stream was destroyed'), { code: 'ERR_STREAM_DESTROYED' } )) return true } if (typeof encoding === 'function') cb = encoding, encoding = 'utf8' if (!encoding) encoding = 'utf8' const fn = this[ASYNC] ? defer : f => f() // convert array buffers and typed array views into buffers // at some point in the future, we may want to do the opposite! // leave strings and buffers as-is // anything else switches us into object mode if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) { if (isArrayBufferView(chunk)) chunk = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength) else if (isArrayBuffer(chunk)) chunk = Buffer.from(chunk) else if (typeof chunk !== 'string') // use the setter so we throw if we have encoding set this.objectMode = true } // handle object mode up front, since it's simpler // this yields better performance, fewer checks later. if (this[OBJECTMODE]) { /* istanbul ignore if - maybe impossible? */ if (this.flowing && this[BUFFERLENGTH] !== 0) this[FLUSH](true) if (this.flowing) this.emit('data', chunk) else this[BUFFERPUSH](chunk) if (this[BUFFERLENGTH] !== 0) this.emit('readable') if (cb) fn(cb) return this.flowing } // at this point the chunk is a buffer or string // don't buffer it up or send it to the decoder if (!chunk.length) { if (this[BUFFERLENGTH] !== 0) this.emit('readable') if (cb) fn(cb) return this.flowing } // fast-path writing strings of same encoding to a stream with // an empty buffer, skipping the buffer/decoder dance if (typeof chunk === 'string' && // unless it is a string already ready for us to use !(encoding === this[ENCODING] && !this[DECODER].lastNeed)) { chunk = Buffer.from(chunk, encoding) } if (Buffer.isBuffer(chunk) && this[ENCODING]) chunk = this[DECODER].write(chunk) // Note: flushing CAN potentially switch us into not-flowing mode if (this.flowing && this[BUFFERLENGTH] !== 0) this[FLUSH](true) if (this.flowing) this.emit('data', chunk) else this[BUFFERPUSH](chunk) if (this[BUFFERLENGTH] !== 0) this.emit('readable') if (cb) fn(cb) return this.flowing } read (n) { if (this[DESTROYED]) return null if (this[BUFFERLENGTH] === 0 || n === 0 || n > this[BUFFERLENGTH]) { this[MAYBE_EMIT_END]() return null } if (this[OBJECTMODE]) n = null if (this.buffer.length > 1 && !this[OBJECTMODE]) { if (this.encoding) this.buffer = [this.buffer.join('')] else this.buffer = [Buffer.concat(this.buffer, this[BUFFERLENGTH])] } const ret = this[READ](n || null, this.buffer[0]) this[MAYBE_EMIT_END]() return ret } [READ] (n, chunk) { if (n === chunk.length || n === null) this[BUFFERSHIFT]() else { this.buffer[0] = chunk.slice(n) chunk = chunk.slice(0, n) this[BUFFERLENGTH] -= n } this.emit('data', chunk) if (!this.buffer.length && !this[EOF]) this.emit('drain') return chunk } end (chunk, encoding, cb) { if (typeof chunk === 'function') cb = chunk, chunk = null if (typeof encoding === 'function') cb = encoding, encoding = 'utf8' if (chunk) this.write(chunk, encoding) if (cb) this.once('end', cb) this[EOF] = true this.writable = false // if we haven't written anything, then go ahead and emit, // even if we're not reading. // we'll re-emit if a new 'end' listener is added anyway. // This makes MP more suitable to write-only use cases. if (this.flowing || !this[PAUSED]) this[MAYBE_EMIT_END]() return this } // don't let the internal resume be overwritten [RESUME] () { if (this[DESTROYED]) return this[PAUSED] = false this[FLOWING] = true this.emit('resume') if (this.buffer.length) this[FLUSH]() else if (this[EOF]) this[MAYBE_EMIT_END]() else this.emit('drain') } resume () { return this[RESUME]() } pause () { this[FLOWING] = false this[PAUSED] = true } get destroyed () { return this[DESTROYED] } get flowing () { return this[FLOWING] } get paused () { return this[PAUSED] } [BUFFERPUSH] (chunk) { if (this[OBJECTMODE]) this[BUFFERLENGTH] += 1 else this[BUFFERLENGTH] += chunk.length this.buffer.push(chunk) } [BUFFERSHIFT] () { if (this.buffer.length) { if (this[OBJECTMODE]) this[BUFFERLENGTH] -= 1 else this[BUFFERLENGTH] -= this.buffer[0].length } return this.buffer.shift() } [FLUSH] (noDrain) { do {} while (this[FLUSHCHUNK](this[BUFFERSHIFT]())) if (!noDrain && !this.buffer.length && !this[EOF]) this.emit('drain') } [FLUSHCHUNK] (chunk) { return chunk ? (this.emit('data', chunk), this.flowing) : false } pipe (dest, opts) { if (this[DESTROYED]) return const ended = this[EMITTED_END] opts = opts || {} if (dest === proc.stdout || dest === proc.stderr) opts.end = false else opts.end = opts.end !== false opts.proxyErrors = !!opts.proxyErrors // piping an ended stream ends immediately if (ended) { if (opts.end) dest.end() } else { this.pipes.push(!opts.proxyErrors ? new Pipe(this, dest, opts) : new PipeProxyErrors(this, dest, opts)) if (this[ASYNC]) defer(() => this[RESUME]()) else this[RESUME]() } return dest } unpipe (dest) { const p = this.pipes.find(p => p.dest === dest) if (p) { this.pipes.splice(this.pipes.indexOf(p), 1) p.unpipe() } } addListener (ev, fn) { return this.on(ev, fn) } on (ev, fn) { const ret = super.on(ev, fn) if (ev === 'data' && !this.pipes.length && !this.flowing) this[RESUME]() else if (ev === 'readable' && this[BUFFERLENGTH] !== 0) super.emit('readable') else if (isEndish(ev) && this[EMITTED_END]) { super.emit(ev) this.removeAllListeners(ev) } else if (ev === 'error' && this[EMITTED_ERROR]) { if (this[ASYNC]) defer(() => fn.call(this, this[EMITTED_ERROR])) else fn.call(this, this[EMITTED_ERROR]) } return ret } get emittedEnd () { return this[EMITTED_END] } [MAYBE_EMIT_END] () { if (!this[EMITTING_END] && !this[EMITTED_END] && !this[DESTROYED] && this.buffer.length === 0 && this[EOF]) { this[EMITTING_END] = true this.emit('end') this.emit('prefinish') this.emit('finish') if (this[CLOSED]) this.emit('close') this[EMITTING_END] = false } } emit (ev, data, ...extra) { // error and close are only events allowed after calling destroy() if (ev !== 'error' && ev !== 'close' && ev !== DESTROYED && this[DESTROYED]) return else if (ev === 'data') { return !data ? false : this[ASYNC] ? defer(() => this[EMITDATA](data)) : this[EMITDATA](data) } else if (ev === 'end') { return this[EMITEND]() } else if (ev === 'close') { this[CLOSED] = true // don't emit close before 'end' and 'finish' if (!this[EMITTED_END] && !this[DESTROYED]) return const ret = super.emit('close') this.removeAllListeners('close') return ret } else if (ev === 'error') { this[EMITTED_ERROR] = data const ret = super.emit('error', data) this[MAYBE_EMIT_END]() return ret } else if (ev === 'resume') { const ret = super.emit('resume') this[MAYBE_EMIT_END]() return ret } else if (ev === 'finish' || ev === 'prefinish') { const ret = super.emit(ev) this.removeAllListeners(ev) return ret } // Some other unknown event const ret = super.emit(ev, data, ...extra) this[MAYBE_EMIT_END]() return ret } [EMITDATA] (data) { for (const p of this.pipes) { if (p.dest.write(data) === false) this.pause() } const ret = super.emit('data', data) this[MAYBE_EMIT_END]() return ret } [EMITEND] () { if (this[EMITTED_END]) return this[EMITTED_END] = true this.readable = false if (this[ASYNC]) defer(() => this[EMITEND2]()) else this[EMITEND2]() } [EMITEND2] () { if (this[DECODER]) { const data = this[DECODER].end() if (data) { for (const p of this.pipes) { p.dest.write(data) } super.emit('data', data) } } for (const p of this.pipes) { p.end() } const ret = super.emit('end') this.removeAllListeners('end') return ret } // const all = await stream.collect() collect () { const buf = [] if (!this[OBJECTMODE]) buf.dataLength = 0 // set the promise first, in case an error is raised // by triggering the flow here. const p = this.promise() this.on('data', c => { buf.push(c) if (!this[OBJECTMODE]) buf.dataLength += c.length }) return p.then(() => buf) } // const data = await stream.concat() concat () { return this[OBJECTMODE] ? Promise.reject(new Error('cannot concat in objectMode')) : this.collect().then(buf => this[OBJECTMODE] ? Promise.reject(new Error('cannot concat in objectMode')) : this[ENCODING] ? buf.join('') : Buffer.concat(buf, buf.dataLength)) } // stream.promise().then(() => done, er => emitted error) promise () { return new Promise((resolve, reject) => { this.on(DESTROYED, () => reject(new Error('stream destroyed'))) this.on('error', er => reject(er)) this.on('end', () => resolve()) }) } // for await (let chunk of stream) [ASYNCITERATOR] () { const next = () => { const res = this.read() if (res !== null) return Promise.resolve({ done: false, value: res }) if (this[EOF]) return Promise.resolve({ done: true }) let resolve = null let reject = null const onerr = er => { this.removeListener('data', ondata) this.removeListener('end', onend) reject(er) } const ondata = value => { this.removeListener('error', onerr) this.removeListener('end', onend) this.pause() resolve({ value: value, done: !!this[EOF] }) } const onend = () => { this.removeListener('error', onerr) this.removeListener('data', ondata) resolve({ done: true }) } const ondestroy = () => onerr(new Error('stream destroyed')) return new Promise((res, rej) => { reject = rej resolve = res this.once(DESTROYED, ondestroy) this.once('error', onerr) this.once('end', onend) this.once('data', ondata) }) } return { next } } // for (let chunk of stream) [ITERATOR] () { const next = () => { const value = this.read() const done = value === null return { value, done } } return { next } } destroy (er) { if (this[DESTROYED]) { if (er) this.emit('error', er) else this.emit(DESTROYED) return this } this[DESTROYED] = true // throw away all buffered data, it's never coming out this.buffer.length = 0 this[BUFFERLENGTH] = 0 if (typeof this.close === 'function' && !this[CLOSED]) this.close() if (er) this.emit('error', er) else // if no error to emit, still reject pending promises this.emit(DESTROYED) return this } static isStream (s) { return !!s && (s instanceof Minipass || s instanceof Stream || s instanceof EE && ( typeof s.pipe === 'function' || // readable (typeof s.write === 'function' && typeof s.end === 'function') // writable )) } } /***/ }), /***/ 6769: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // Update with any zlib constants that are added or changed in the future. // Node v6 didn't export this, so we just hard code the version and rely // on all the other hard-coded values from zlib v4736. When node v6 // support drops, we can just export the realZlibConstants object. const realZlibConstants = (__nccwpck_require__(59796).constants) || /* istanbul ignore next */ { ZLIB_VERNUM: 4736 } module.exports = Object.freeze(Object.assign(Object.create(null), { Z_NO_FLUSH: 0, Z_PARTIAL_FLUSH: 1, Z_SYNC_FLUSH: 2, Z_FULL_FLUSH: 3, Z_FINISH: 4, Z_BLOCK: 5, Z_OK: 0, Z_STREAM_END: 1, Z_NEED_DICT: 2, Z_ERRNO: -1, Z_STREAM_ERROR: -2, Z_DATA_ERROR: -3, Z_MEM_ERROR: -4, Z_BUF_ERROR: -5, Z_VERSION_ERROR: -6, Z_NO_COMPRESSION: 0, Z_BEST_SPEED: 1, Z_BEST_COMPRESSION: 9, Z_DEFAULT_COMPRESSION: -1, Z_FILTERED: 1, Z_HUFFMAN_ONLY: 2, Z_RLE: 3, Z_FIXED: 4, Z_DEFAULT_STRATEGY: 0, DEFLATE: 1, INFLATE: 2, GZIP: 3, GUNZIP: 4, DEFLATERAW: 5, INFLATERAW: 6, UNZIP: 7, BROTLI_DECODE: 8, BROTLI_ENCODE: 9, Z_MIN_WINDOWBITS: 8, Z_MAX_WINDOWBITS: 15, Z_DEFAULT_WINDOWBITS: 15, Z_MIN_CHUNK: 64, Z_MAX_CHUNK: Infinity, Z_DEFAULT_CHUNK: 16384, Z_MIN_MEMLEVEL: 1, Z_MAX_MEMLEVEL: 9, Z_DEFAULT_MEMLEVEL: 8, Z_MIN_LEVEL: -1, Z_MAX_LEVEL: 9, Z_DEFAULT_LEVEL: -1, BROTLI_OPERATION_PROCESS: 0, BROTLI_OPERATION_FLUSH: 1, BROTLI_OPERATION_FINISH: 2, BROTLI_OPERATION_EMIT_METADATA: 3, BROTLI_MODE_GENERIC: 0, BROTLI_MODE_TEXT: 1, BROTLI_MODE_FONT: 2, BROTLI_DEFAULT_MODE: 0, BROTLI_MIN_QUALITY: 0, BROTLI_MAX_QUALITY: 11, BROTLI_DEFAULT_QUALITY: 11, BROTLI_MIN_WINDOW_BITS: 10, BROTLI_MAX_WINDOW_BITS: 24, BROTLI_LARGE_MAX_WINDOW_BITS: 30, BROTLI_DEFAULT_WINDOW: 22, BROTLI_MIN_INPUT_BLOCK_BITS: 16, BROTLI_MAX_INPUT_BLOCK_BITS: 24, BROTLI_PARAM_MODE: 0, BROTLI_PARAM_QUALITY: 1, BROTLI_PARAM_LGWIN: 2, BROTLI_PARAM_LGBLOCK: 3, BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING: 4, BROTLI_PARAM_SIZE_HINT: 5, BROTLI_PARAM_LARGE_WINDOW: 6, BROTLI_PARAM_NPOSTFIX: 7, BROTLI_PARAM_NDIRECT: 8, BROTLI_DECODER_RESULT_ERROR: 0, BROTLI_DECODER_RESULT_SUCCESS: 1, BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT: 2, BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT: 3, BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION: 0, BROTLI_DECODER_PARAM_LARGE_WINDOW: 1, BROTLI_DECODER_NO_ERROR: 0, BROTLI_DECODER_SUCCESS: 1, BROTLI_DECODER_NEEDS_MORE_INPUT: 2, BROTLI_DECODER_NEEDS_MORE_OUTPUT: 3, BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE: -1, BROTLI_DECODER_ERROR_FORMAT_RESERVED: -2, BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE: -3, BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET: -4, BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME: -5, BROTLI_DECODER_ERROR_FORMAT_CL_SPACE: -6, BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE: -7, BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT: -8, BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1: -9, BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2: -10, BROTLI_DECODER_ERROR_FORMAT_TRANSFORM: -11, BROTLI_DECODER_ERROR_FORMAT_DICTIONARY: -12, BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS: -13, BROTLI_DECODER_ERROR_FORMAT_PADDING_1: -14, BROTLI_DECODER_ERROR_FORMAT_PADDING_2: -15, BROTLI_DECODER_ERROR_FORMAT_DISTANCE: -16, BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET: -19, BROTLI_DECODER_ERROR_INVALID_ARGUMENTS: -20, BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES: -21, BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS: -22, BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP: -25, BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1: -26, BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2: -27, BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES: -30, BROTLI_DECODER_ERROR_UNREACHABLE: -31, }, realZlibConstants)) /***/ }), /***/ 33486: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; const assert = __nccwpck_require__(39491) const Buffer = (__nccwpck_require__(14300).Buffer) const realZlib = __nccwpck_require__(59796) const constants = exports.constants = __nccwpck_require__(6769) const Minipass = __nccwpck_require__(41077) const OriginalBufferConcat = Buffer.concat const _superWrite = Symbol('_superWrite') class ZlibError extends Error { constructor (err) { super('zlib: ' + err.message) this.code = err.code this.errno = err.errno /* istanbul ignore if */ if (!this.code) this.code = 'ZLIB_ERROR' this.message = 'zlib: ' + err.message Error.captureStackTrace(this, this.constructor) } get name () { return 'ZlibError' } } // the Zlib class they all inherit from // This thing manages the queue of requests, and returns // true or false if there is anything in the queue when // you call the .write() method. const _opts = Symbol('opts') const _flushFlag = Symbol('flushFlag') const _finishFlushFlag = Symbol('finishFlushFlag') const _fullFlushFlag = Symbol('fullFlushFlag') const _handle = Symbol('handle') const _onError = Symbol('onError') const _sawError = Symbol('sawError') const _level = Symbol('level') const _strategy = Symbol('strategy') const _ended = Symbol('ended') const _defaultFullFlush = Symbol('_defaultFullFlush') class ZlibBase extends Minipass { constructor (opts, mode) { if (!opts || typeof opts !== 'object') throw new TypeError('invalid options for ZlibBase constructor') super(opts) this[_sawError] = false this[_ended] = false this[_opts] = opts this[_flushFlag] = opts.flush this[_finishFlushFlag] = opts.finishFlush // this will throw if any options are invalid for the class selected try { this[_handle] = new realZlib[mode](opts) } catch (er) { // make sure that all errors get decorated properly throw new ZlibError(er) } this[_onError] = (err) => { // no sense raising multiple errors, since we abort on the first one. if (this[_sawError]) return this[_sawError] = true // there is no way to cleanly recover. // continuing only obscures problems. this.close() this.emit('error', err) } this[_handle].on('error', er => this[_onError](new ZlibError(er))) this.once('end', () => this.close) } close () { if (this[_handle]) { this[_handle].close() this[_handle] = null this.emit('close') } } reset () { if (!this[_sawError]) { assert(this[_handle], 'zlib binding closed') return this[_handle].reset() } } flush (flushFlag) { if (this.ended) return if (typeof flushFlag !== 'number') flushFlag = this[_fullFlushFlag] this.write(Object.assign(Buffer.alloc(0), { [_flushFlag]: flushFlag })) } end (chunk, encoding, cb) { if (chunk) this.write(chunk, encoding) this.flush(this[_finishFlushFlag]) this[_ended] = true return super.end(null, null, cb) } get ended () { return this[_ended] } write (chunk, encoding, cb) { // process the chunk using the sync process // then super.write() all the outputted chunks if (typeof encoding === 'function') cb = encoding, encoding = 'utf8' if (typeof chunk === 'string') chunk = Buffer.from(chunk, encoding) if (this[_sawError]) return assert(this[_handle], 'zlib binding closed') // _processChunk tries to .close() the native handle after it's done, so we // intercept that by temporarily making it a no-op. const nativeHandle = this[_handle]._handle const originalNativeClose = nativeHandle.close nativeHandle.close = () => {} const originalClose = this[_handle].close this[_handle].close = () => {} // It also calls `Buffer.concat()` at the end, which may be convenient // for some, but which we are not interested in as it slows us down. Buffer.concat = (args) => args let result try { const flushFlag = typeof chunk[_flushFlag] === 'number' ? chunk[_flushFlag] : this[_flushFlag] result = this[_handle]._processChunk(chunk, flushFlag) // if we don't throw, reset it back how it was Buffer.concat = OriginalBufferConcat } catch (err) { // or if we do, put Buffer.concat() back before we emit error // Error events call into user code, which may call Buffer.concat() Buffer.concat = OriginalBufferConcat this[_onError](new ZlibError(err)) } finally { if (this[_handle]) { // Core zlib resets `_handle` to null after attempting to close the // native handle. Our no-op handler prevented actual closure, but we // need to restore the `._handle` property. this[_handle]._handle = nativeHandle nativeHandle.close = originalNativeClose this[_handle].close = originalClose // `_processChunk()` adds an 'error' listener. If we don't remove it // after each call, these handlers start piling up. this[_handle].removeAllListeners('error') // make sure OUR error listener is still attached tho } } if (this[_handle]) this[_handle].on('error', er => this[_onError](new ZlibError(er))) let writeReturn if (result) { if (Array.isArray(result) && result.length > 0) { // The first buffer is always `handle._outBuffer`, which would be // re-used for later invocations; so, we always have to copy that one. writeReturn = this[_superWrite](Buffer.from(result[0])) for (let i = 1; i < result.length; i++) { writeReturn = this[_superWrite](result[i]) } } else { writeReturn = this[_superWrite](Buffer.from(result)) } } if (cb) cb() return writeReturn } [_superWrite] (data) { return super.write(data) } } class Zlib extends ZlibBase { constructor (opts, mode) { opts = opts || {} opts.flush = opts.flush || constants.Z_NO_FLUSH opts.finishFlush = opts.finishFlush || constants.Z_FINISH super(opts, mode) this[_fullFlushFlag] = constants.Z_FULL_FLUSH this[_level] = opts.level this[_strategy] = opts.strategy } params (level, strategy) { if (this[_sawError]) return if (!this[_handle]) throw new Error('cannot switch params when binding is closed') // no way to test this without also not supporting params at all /* istanbul ignore if */ if (!this[_handle].params) throw new Error('not supported in this implementation') if (this[_level] !== level || this[_strategy] !== strategy) { this.flush(constants.Z_SYNC_FLUSH) assert(this[_handle], 'zlib binding closed') // .params() calls .flush(), but the latter is always async in the // core zlib. We override .flush() temporarily to intercept that and // flush synchronously. const origFlush = this[_handle].flush this[_handle].flush = (flushFlag, cb) => { this.flush(flushFlag) cb() } try { this[_handle].params(level, strategy) } finally { this[_handle].flush = origFlush } /* istanbul ignore else */ if (this[_handle]) { this[_level] = level this[_strategy] = strategy } } } } // minimal 2-byte header class Deflate extends Zlib { constructor (opts) { super(opts, 'Deflate') } } class Inflate extends Zlib { constructor (opts) { super(opts, 'Inflate') } } // gzip - bigger header, same deflate compression const _portable = Symbol('_portable') class Gzip extends Zlib { constructor (opts) { super(opts, 'Gzip') this[_portable] = opts && !!opts.portable } [_superWrite] (data) { if (!this[_portable]) return super[_superWrite](data) // we'll always get the header emitted in one first chunk // overwrite the OS indicator byte with 0xFF this[_portable] = false data[9] = 255 return super[_superWrite](data) } } class Gunzip extends Zlib { constructor (opts) { super(opts, 'Gunzip') } } // raw - no header class DeflateRaw extends Zlib { constructor (opts) { super(opts, 'DeflateRaw') } } class InflateRaw extends Zlib { constructor (opts) { super(opts, 'InflateRaw') } } // auto-detect header. class Unzip extends Zlib { constructor (opts) { super(opts, 'Unzip') } } class Brotli extends ZlibBase { constructor (opts, mode) { opts = opts || {} opts.flush = opts.flush || constants.BROTLI_OPERATION_PROCESS opts.finishFlush = opts.finishFlush || constants.BROTLI_OPERATION_FINISH super(opts, mode) this[_fullFlushFlag] = constants.BROTLI_OPERATION_FLUSH } } class BrotliCompress extends Brotli { constructor (opts) { super(opts, 'BrotliCompress') } } class BrotliDecompress extends Brotli { constructor (opts) { super(opts, 'BrotliDecompress') } } exports.Deflate = Deflate exports.Inflate = Inflate exports.Gzip = Gzip exports.Gunzip = Gunzip exports.DeflateRaw = DeflateRaw exports.InflateRaw = InflateRaw exports.Unzip = Unzip /* istanbul ignore else */ if (typeof realZlib.BrotliCompress === 'function') { exports.BrotliCompress = BrotliCompress exports.BrotliDecompress = BrotliDecompress } else { exports.BrotliCompress = exports.BrotliDecompress = class { constructor () { throw new Error('Brotli is not supported in this version of Node.js') } } } /***/ }), /***/ 66186: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const optsArg = __nccwpck_require__(42853) const pathArg = __nccwpck_require__(12930) const {mkdirpNative, mkdirpNativeSync} = __nccwpck_require__(4983) const {mkdirpManual, mkdirpManualSync} = __nccwpck_require__(40356) const {useNative, useNativeSync} = __nccwpck_require__(54518) const mkdirp = (path, opts) => { path = pathArg(path) opts = optsArg(opts) return useNative(opts) ? mkdirpNative(path, opts) : mkdirpManual(path, opts) } const mkdirpSync = (path, opts) => { path = pathArg(path) opts = optsArg(opts) return useNativeSync(opts) ? mkdirpNativeSync(path, opts) : mkdirpManualSync(path, opts) } mkdirp.sync = mkdirpSync mkdirp.native = (path, opts) => mkdirpNative(pathArg(path), optsArg(opts)) mkdirp.manual = (path, opts) => mkdirpManual(pathArg(path), optsArg(opts)) mkdirp.nativeSync = (path, opts) => mkdirpNativeSync(pathArg(path), optsArg(opts)) mkdirp.manualSync = (path, opts) => mkdirpManualSync(pathArg(path), optsArg(opts)) module.exports = mkdirp /***/ }), /***/ 44992: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const {dirname} = __nccwpck_require__(71017) const findMade = (opts, parent, path = undefined) => { // we never want the 'made' return value to be a root directory if (path === parent) return Promise.resolve() return opts.statAsync(parent).then( st => st.isDirectory() ? path : undefined, // will fail later er => er.code === 'ENOENT' ? findMade(opts, dirname(parent), parent) : undefined ) } const findMadeSync = (opts, parent, path = undefined) => { if (path === parent) return undefined try { return opts.statSync(parent).isDirectory() ? path : undefined } catch (er) { return er.code === 'ENOENT' ? findMadeSync(opts, dirname(parent), parent) : undefined } } module.exports = {findMade, findMadeSync} /***/ }), /***/ 40356: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const {dirname} = __nccwpck_require__(71017) const mkdirpManual = (path, opts, made) => { opts.recursive = false const parent = dirname(path) if (parent === path) { return opts.mkdirAsync(path, opts).catch(er => { // swallowed by recursive implementation on posix systems // any other error is a failure if (er.code !== 'EISDIR') throw er }) } return opts.mkdirAsync(path, opts).then(() => made || path, er => { if (er.code === 'ENOENT') return mkdirpManual(parent, opts) .then(made => mkdirpManual(path, opts, made)) if (er.code !== 'EEXIST' && er.code !== 'EROFS') throw er return opts.statAsync(path).then(st => { if (st.isDirectory()) return made else throw er }, () => { throw er }) }) } const mkdirpManualSync = (path, opts, made) => { const parent = dirname(path) opts.recursive = false if (parent === path) { try { return opts.mkdirSync(path, opts) } catch (er) { // swallowed by recursive implementation on posix systems // any other error is a failure if (er.code !== 'EISDIR') throw er else return } } try { opts.mkdirSync(path, opts) return made || path } catch (er) { if (er.code === 'ENOENT') return mkdirpManualSync(path, opts, mkdirpManualSync(parent, opts, made)) if (er.code !== 'EEXIST' && er.code !== 'EROFS') throw er try { if (!opts.statSync(path).isDirectory()) throw er } catch (_) { throw er } } } module.exports = {mkdirpManual, mkdirpManualSync} /***/ }), /***/ 4983: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const {dirname} = __nccwpck_require__(71017) const {findMade, findMadeSync} = __nccwpck_require__(44992) const {mkdirpManual, mkdirpManualSync} = __nccwpck_require__(40356) const mkdirpNative = (path, opts) => { opts.recursive = true const parent = dirname(path) if (parent === path) return opts.mkdirAsync(path, opts) return findMade(opts, path).then(made => opts.mkdirAsync(path, opts).then(() => made) .catch(er => { if (er.code === 'ENOENT') return mkdirpManual(path, opts) else throw er })) } const mkdirpNativeSync = (path, opts) => { opts.recursive = true const parent = dirname(path) if (parent === path) return opts.mkdirSync(path, opts) const made = findMadeSync(opts, path) try { opts.mkdirSync(path, opts) return made } catch (er) { if (er.code === 'ENOENT') return mkdirpManualSync(path, opts) else throw er } } module.exports = {mkdirpNative, mkdirpNativeSync} /***/ }), /***/ 42853: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { promisify } = __nccwpck_require__(73837) const fs = __nccwpck_require__(57147) const optsArg = opts => { if (!opts) opts = { mode: 0o777, fs } else if (typeof opts === 'object') opts = { mode: 0o777, fs, ...opts } else if (typeof opts === 'number') opts = { mode: opts, fs } else if (typeof opts === 'string') opts = { mode: parseInt(opts, 8), fs } else throw new TypeError('invalid options argument') opts.mkdir = opts.mkdir || opts.fs.mkdir || fs.mkdir opts.mkdirAsync = promisify(opts.mkdir) opts.stat = opts.stat || opts.fs.stat || fs.stat opts.statAsync = promisify(opts.stat) opts.statSync = opts.statSync || opts.fs.statSync || fs.statSync opts.mkdirSync = opts.mkdirSync || opts.fs.mkdirSync || fs.mkdirSync return opts } module.exports = optsArg /***/ }), /***/ 12930: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const platform = process.env.__TESTING_MKDIRP_PLATFORM__ || process.platform const { resolve, parse } = __nccwpck_require__(71017) const pathArg = path => { if (/\0/.test(path)) { // simulate same failure that node raises throw Object.assign( new TypeError('path must be a string without null bytes'), { path, code: 'ERR_INVALID_ARG_VALUE', } ) } path = resolve(path) if (platform === 'win32') { const badWinChars = /[*|"<>?:]/ const {root} = parse(path) if (badWinChars.test(path.substr(root.length))) { throw Object.assign(new Error('Illegal characters in path.'), { path, code: 'EINVAL', }) } } return path } module.exports = pathArg /***/ }), /***/ 54518: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const fs = __nccwpck_require__(57147) const version = process.env.__TESTING_MKDIRP_NODE_VERSION__ || process.version const versArr = version.replace(/^v/, '').split('.') const hasNative = +versArr[0] > 10 || +versArr[0] === 10 && +versArr[1] >= 12 const useNative = !hasNative ? () => false : opts => opts.mkdir === fs.mkdir const useNativeSync = !hasNative ? () => false : opts => opts.mkdirSync === fs.mkdirSync module.exports = {useNative, useNativeSync} /***/ }), /***/ 80467: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } var Stream = _interopDefault(__nccwpck_require__(12781)); var http = _interopDefault(__nccwpck_require__(13685)); var Url = _interopDefault(__nccwpck_require__(57310)); var whatwgUrl = _interopDefault(__nccwpck_require__(73323)); var https = _interopDefault(__nccwpck_require__(95687)); var zlib = _interopDefault(__nccwpck_require__(59796)); // Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js // fix for "Readable" isn't a named export issue const Readable = Stream.Readable; const BUFFER = Symbol('buffer'); const TYPE = Symbol('type'); class Blob { constructor() { this[TYPE] = ''; const blobParts = arguments[0]; const options = arguments[1]; const buffers = []; let size = 0; if (blobParts) { const a = blobParts; const length = Number(a.length); for (let i = 0; i < length; i++) { const element = a[i]; let buffer; if (element instanceof Buffer) { buffer = element; } else if (ArrayBuffer.isView(element)) { buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength); } else if (element instanceof ArrayBuffer) { buffer = Buffer.from(element); } else if (element instanceof Blob) { buffer = element[BUFFER]; } else { buffer = Buffer.from(typeof element === 'string' ? element : String(element)); } size += buffer.length; buffers.push(buffer); } } this[BUFFER] = Buffer.concat(buffers); let type = options && options.type !== undefined && String(options.type).toLowerCase(); if (type && !/[^\u0020-\u007E]/.test(type)) { this[TYPE] = type; } } get size() { return this[BUFFER].length; } get type() { return this[TYPE]; } text() { return Promise.resolve(this[BUFFER].toString()); } arrayBuffer() { const buf = this[BUFFER]; const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); return Promise.resolve(ab); } stream() { const readable = new Readable(); readable._read = function () {}; readable.push(this[BUFFER]); readable.push(null); return readable; } toString() { return '[object Blob]'; } slice() { const size = this.size; const start = arguments[0]; const end = arguments[1]; let relativeStart, relativeEnd; if (start === undefined) { relativeStart = 0; } else if (start < 0) { relativeStart = Math.max(size + start, 0); } else { relativeStart = Math.min(start, size); } if (end === undefined) { relativeEnd = size; } else if (end < 0) { relativeEnd = Math.max(size + end, 0); } else { relativeEnd = Math.min(end, size); } const span = Math.max(relativeEnd - relativeStart, 0); const buffer = this[BUFFER]; const slicedBuffer = buffer.slice(relativeStart, relativeStart + span); const blob = new Blob([], { type: arguments[2] }); blob[BUFFER] = slicedBuffer; return blob; } } Object.defineProperties(Blob.prototype, { size: { enumerable: true }, type: { enumerable: true }, slice: { enumerable: true } }); Object.defineProperty(Blob.prototype, Symbol.toStringTag, { value: 'Blob', writable: false, enumerable: false, configurable: true }); /** * fetch-error.js * * FetchError interface for operational errors */ /** * Create FetchError instance * * @param String message Error message for human * @param String type Error type for machine * @param String systemError For Node.js system error * @return FetchError */ function FetchError(message, type, systemError) { Error.call(this, message); this.message = message; this.type = type; // when err.type is `system`, err.code contains system error code if (systemError) { this.code = this.errno = systemError.code; } // hide custom error implementation details from end-users Error.captureStackTrace(this, this.constructor); } FetchError.prototype = Object.create(Error.prototype); FetchError.prototype.constructor = FetchError; FetchError.prototype.name = 'FetchError'; let convert; try { convert = (__nccwpck_require__(22877).convert); } catch (e) {} const INTERNALS = Symbol('Body internals'); // fix an issue where "PassThrough" isn't a named export for node <10 const PassThrough = Stream.PassThrough; /** * Body mixin * * Ref: https://fetch.spec.whatwg.org/#body * * @param Stream body Readable stream * @param Object opts Response options * @return Void */ function Body(body) { var _this = this; var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, _ref$size = _ref.size; let size = _ref$size === undefined ? 0 : _ref$size; var _ref$timeout = _ref.timeout; let timeout = _ref$timeout === undefined ? 0 : _ref$timeout; if (body == null) { // body is undefined or null body = null; } else if (isURLSearchParams(body)) { // body is a URLSearchParams body = Buffer.from(body.toString()); } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { // body is ArrayBuffer body = Buffer.from(body); } else if (ArrayBuffer.isView(body)) { // body is ArrayBufferView body = Buffer.from(body.buffer, body.byteOffset, body.byteLength); } else if (body instanceof Stream) ; else { // none of the above // coerce to string then buffer body = Buffer.from(String(body)); } this[INTERNALS] = { body, disturbed: false, error: null }; this.size = size; this.timeout = timeout; if (body instanceof Stream) { body.on('error', function (err) { const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err); _this[INTERNALS].error = error; }); } } Body.prototype = { get body() { return this[INTERNALS].body; }, get bodyUsed() { return this[INTERNALS].disturbed; }, /** * Decode response as ArrayBuffer * * @return Promise */ arrayBuffer() { return consumeBody.call(this).then(function (buf) { return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); }); }, /** * Return raw response as Blob * * @return Promise */ blob() { let ct = this.headers && this.headers.get('content-type') || ''; return consumeBody.call(this).then(function (buf) { return Object.assign( // Prevent copying new Blob([], { type: ct.toLowerCase() }), { [BUFFER]: buf }); }); }, /** * Decode response as json * * @return Promise */ json() { var _this2 = this; return consumeBody.call(this).then(function (buffer) { try { return JSON.parse(buffer.toString()); } catch (err) { return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json')); } }); }, /** * Decode response as text * * @return Promise */ text() { return consumeBody.call(this).then(function (buffer) { return buffer.toString(); }); }, /** * Decode response as buffer (non-spec api) * * @return Promise */ buffer() { return consumeBody.call(this); }, /** * Decode response as text, while automatically detecting the encoding and * trying to decode to UTF-8 (non-spec api) * * @return Promise */ textConverted() { var _this3 = this; return consumeBody.call(this).then(function (buffer) { return convertBody(buffer, _this3.headers); }); } }; // In browsers, all properties are enumerable. Object.defineProperties(Body.prototype, { body: { enumerable: true }, bodyUsed: { enumerable: true }, arrayBuffer: { enumerable: true }, blob: { enumerable: true }, json: { enumerable: true }, text: { enumerable: true } }); Body.mixIn = function (proto) { for (const name of Object.getOwnPropertyNames(Body.prototype)) { // istanbul ignore else: future proof if (!(name in proto)) { const desc = Object.getOwnPropertyDescriptor(Body.prototype, name); Object.defineProperty(proto, name, desc); } } }; /** * Consume and convert an entire Body to a Buffer. * * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body * * @return Promise */ function consumeBody() { var _this4 = this; if (this[INTERNALS].disturbed) { return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`)); } this[INTERNALS].disturbed = true; if (this[INTERNALS].error) { return Body.Promise.reject(this[INTERNALS].error); } let body = this.body; // body is null if (body === null) { return Body.Promise.resolve(Buffer.alloc(0)); } // body is blob if (isBlob(body)) { body = body.stream(); } // body is buffer if (Buffer.isBuffer(body)) { return Body.Promise.resolve(body); } // istanbul ignore if: should never happen if (!(body instanceof Stream)) { return Body.Promise.resolve(Buffer.alloc(0)); } // body is stream // get ready to actually consume the body let accum = []; let accumBytes = 0; let abort = false; return new Body.Promise(function (resolve, reject) { let resTimeout; // allow timeout on slow response body if (_this4.timeout) { resTimeout = setTimeout(function () { abort = true; reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout')); }, _this4.timeout); } // handle stream errors body.on('error', function (err) { if (err.name === 'AbortError') { // if the request was aborted, reject with this Error abort = true; reject(err); } else { // other errors, such as incorrect content-encoding reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err)); } }); body.on('data', function (chunk) { if (abort || chunk === null) { return; } if (_this4.size && accumBytes + chunk.length > _this4.size) { abort = true; reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size')); return; } accumBytes += chunk.length; accum.push(chunk); }); body.on('end', function () { if (abort) { return; } clearTimeout(resTimeout); try { resolve(Buffer.concat(accum, accumBytes)); } catch (err) { // handle streams that have accumulated too much data (issue #414) reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err)); } }); }); } /** * Detect buffer encoding and convert to target encoding * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding * * @param Buffer buffer Incoming buffer * @param String encoding Target encoding * @return String */ function convertBody(buffer, headers) { if (typeof convert !== 'function') { throw new Error('The package `encoding` must be installed to use the textConverted() function'); } const ct = headers.get('content-type'); let charset = 'utf-8'; let res, str; // header if (ct) { res = /charset=([^;]*)/i.exec(ct); } // no charset in content type, peek at response body for at most 1024 bytes str = buffer.slice(0, 1024).toString(); // html5 if (!res && str) { res = / 0 && arguments[0] !== undefined ? arguments[0] : undefined; this[MAP] = Object.create(null); if (init instanceof Headers) { const rawHeaders = init.raw(); const headerNames = Object.keys(rawHeaders); for (const headerName of headerNames) { for (const value of rawHeaders[headerName]) { this.append(headerName, value); } } return; } // We don't worry about converting prop to ByteString here as append() // will handle it. if (init == null) ; else if (typeof init === 'object') { const method = init[Symbol.iterator]; if (method != null) { if (typeof method !== 'function') { throw new TypeError('Header pairs must be iterable'); } // sequence> // Note: per spec we have to first exhaust the lists then process them const pairs = []; for (const pair of init) { if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') { throw new TypeError('Each header pair must be iterable'); } pairs.push(Array.from(pair)); } for (const pair of pairs) { if (pair.length !== 2) { throw new TypeError('Each header pair must be a name/value tuple'); } this.append(pair[0], pair[1]); } } else { // record for (const key of Object.keys(init)) { const value = init[key]; this.append(key, value); } } } else { throw new TypeError('Provided initializer must be an object'); } } /** * Return combined header value given name * * @param String name Header name * @return Mixed */ get(name) { name = `${name}`; validateName(name); const key = find(this[MAP], name); if (key === undefined) { return null; } return this[MAP][key].join(', '); } /** * Iterate over all headers * * @param Function callback Executed for each item with parameters (value, name, thisArg) * @param Boolean thisArg `this` context for callback function * @return Void */ forEach(callback) { let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; let pairs = getHeaders(this); let i = 0; while (i < pairs.length) { var _pairs$i = pairs[i]; const name = _pairs$i[0], value = _pairs$i[1]; callback.call(thisArg, value, name, this); pairs = getHeaders(this); i++; } } /** * Overwrite header values given name * * @param String name Header name * @param String value Header value * @return Void */ set(name, value) { name = `${name}`; value = `${value}`; validateName(name); validateValue(value); const key = find(this[MAP], name); this[MAP][key !== undefined ? key : name] = [value]; } /** * Append a value onto existing header * * @param String name Header name * @param String value Header value * @return Void */ append(name, value) { name = `${name}`; value = `${value}`; validateName(name); validateValue(value); const key = find(this[MAP], name); if (key !== undefined) { this[MAP][key].push(value); } else { this[MAP][name] = [value]; } } /** * Check for header name existence * * @param String name Header name * @return Boolean */ has(name) { name = `${name}`; validateName(name); return find(this[MAP], name) !== undefined; } /** * Delete all header values given name * * @param String name Header name * @return Void */ delete(name) { name = `${name}`; validateName(name); const key = find(this[MAP], name); if (key !== undefined) { delete this[MAP][key]; } } /** * Return raw headers (non-spec api) * * @return Object */ raw() { return this[MAP]; } /** * Get an iterator on keys. * * @return Iterator */ keys() { return createHeadersIterator(this, 'key'); } /** * Get an iterator on values. * * @return Iterator */ values() { return createHeadersIterator(this, 'value'); } /** * Get an iterator on entries. * * This is the default iterator of the Headers object. * * @return Iterator */ [Symbol.iterator]() { return createHeadersIterator(this, 'key+value'); } } Headers.prototype.entries = Headers.prototype[Symbol.iterator]; Object.defineProperty(Headers.prototype, Symbol.toStringTag, { value: 'Headers', writable: false, enumerable: false, configurable: true }); Object.defineProperties(Headers.prototype, { get: { enumerable: true }, forEach: { enumerable: true }, set: { enumerable: true }, append: { enumerable: true }, has: { enumerable: true }, delete: { enumerable: true }, keys: { enumerable: true }, values: { enumerable: true }, entries: { enumerable: true } }); function getHeaders(headers) { let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value'; const keys = Object.keys(headers[MAP]).sort(); return keys.map(kind === 'key' ? function (k) { return k.toLowerCase(); } : kind === 'value' ? function (k) { return headers[MAP][k].join(', '); } : function (k) { return [k.toLowerCase(), headers[MAP][k].join(', ')]; }); } const INTERNAL = Symbol('internal'); function createHeadersIterator(target, kind) { const iterator = Object.create(HeadersIteratorPrototype); iterator[INTERNAL] = { target, kind, index: 0 }; return iterator; } const HeadersIteratorPrototype = Object.setPrototypeOf({ next() { // istanbul ignore if if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) { throw new TypeError('Value of `this` is not a HeadersIterator'); } var _INTERNAL = this[INTERNAL]; const target = _INTERNAL.target, kind = _INTERNAL.kind, index = _INTERNAL.index; const values = getHeaders(target, kind); const len = values.length; if (index >= len) { return { value: undefined, done: true }; } this[INTERNAL].index = index + 1; return { value: values[index], done: false }; } }, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))); Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, { value: 'HeadersIterator', writable: false, enumerable: false, configurable: true }); /** * Export the Headers object in a form that Node.js can consume. * * @param Headers headers * @return Object */ function exportNodeCompatibleHeaders(headers) { const obj = Object.assign({ __proto__: null }, headers[MAP]); // http.request() only supports string as Host header. This hack makes // specifying custom Host header possible. const hostHeaderKey = find(headers[MAP], 'Host'); if (hostHeaderKey !== undefined) { obj[hostHeaderKey] = obj[hostHeaderKey][0]; } return obj; } /** * Create a Headers object from an object of headers, ignoring those that do * not conform to HTTP grammar productions. * * @param Object obj Object of headers * @return Headers */ function createHeadersLenient(obj) { const headers = new Headers(); for (const name of Object.keys(obj)) { if (invalidTokenRegex.test(name)) { continue; } if (Array.isArray(obj[name])) { for (const val of obj[name]) { if (invalidHeaderCharRegex.test(val)) { continue; } if (headers[MAP][name] === undefined) { headers[MAP][name] = [val]; } else { headers[MAP][name].push(val); } } } else if (!invalidHeaderCharRegex.test(obj[name])) { headers[MAP][name] = [obj[name]]; } } return headers; } const INTERNALS$1 = Symbol('Response internals'); // fix an issue where "STATUS_CODES" aren't a named export for node <10 const STATUS_CODES = http.STATUS_CODES; /** * Response class * * @param Stream body Readable stream * @param Object opts Response options * @return Void */ class Response { constructor() { let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; Body.call(this, body, opts); const status = opts.status || 200; const headers = new Headers(opts.headers); if (body != null && !headers.has('Content-Type')) { const contentType = extractContentType(body); if (contentType) { headers.append('Content-Type', contentType); } } this[INTERNALS$1] = { url: opts.url, status, statusText: opts.statusText || STATUS_CODES[status], headers, counter: opts.counter }; } get url() { return this[INTERNALS$1].url || ''; } get status() { return this[INTERNALS$1].status; } /** * Convenience property representing if the request ended normally */ get ok() { return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; } get redirected() { return this[INTERNALS$1].counter > 0; } get statusText() { return this[INTERNALS$1].statusText; } get headers() { return this[INTERNALS$1].headers; } /** * Clone this response * * @return Response */ clone() { return new Response(clone(this), { url: this.url, status: this.status, statusText: this.statusText, headers: this.headers, ok: this.ok, redirected: this.redirected }); } } Body.mixIn(Response.prototype); Object.defineProperties(Response.prototype, { url: { enumerable: true }, status: { enumerable: true }, ok: { enumerable: true }, redirected: { enumerable: true }, statusText: { enumerable: true }, headers: { enumerable: true }, clone: { enumerable: true } }); Object.defineProperty(Response.prototype, Symbol.toStringTag, { value: 'Response', writable: false, enumerable: false, configurable: true }); const INTERNALS$2 = Symbol('Request internals'); const URL = Url.URL || whatwgUrl.URL; // fix an issue where "format", "parse" aren't a named export for node <10 const parse_url = Url.parse; const format_url = Url.format; /** * Wrapper around `new URL` to handle arbitrary URLs * * @param {string} urlStr * @return {void} */ function parseURL(urlStr) { /* Check whether the URL is absolute or not Scheme: https://tools.ietf.org/html/rfc3986#section-3.1 Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3 */ if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.exec(urlStr)) { urlStr = new URL(urlStr).toString(); } // Fallback to old implementation for arbitrary URLs return parse_url(urlStr); } const streamDestructionSupported = 'destroy' in Stream.Readable.prototype; /** * Check if a value is an instance of Request. * * @param Mixed input * @return Boolean */ function isRequest(input) { return typeof input === 'object' && typeof input[INTERNALS$2] === 'object'; } function isAbortSignal(signal) { const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal); return !!(proto && proto.constructor.name === 'AbortSignal'); } /** * Request class * * @param Mixed input Url or Request instance * @param Object init Custom options * @return Void */ class Request { constructor(input) { let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; let parsedURL; // normalize input if (!isRequest(input)) { if (input && input.href) { // in order to support Node.js' Url objects; though WHATWG's URL objects // will fall into this branch also (since their `toString()` will return // `href` property anyway) parsedURL = parseURL(input.href); } else { // coerce input to a string before attempting to parse parsedURL = parseURL(`${input}`); } input = {}; } else { parsedURL = parseURL(input.url); } let method = init.method || input.method || 'GET'; method = method.toUpperCase(); if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { throw new TypeError('Request with GET/HEAD method cannot have body'); } let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; Body.call(this, inputBody, { timeout: init.timeout || input.timeout || 0, size: init.size || input.size || 0 }); const headers = new Headers(init.headers || input.headers || {}); if (inputBody != null && !headers.has('Content-Type')) { const contentType = extractContentType(inputBody); if (contentType) { headers.append('Content-Type', contentType); } } let signal = isRequest(input) ? input.signal : null; if ('signal' in init) signal = init.signal; if (signal != null && !isAbortSignal(signal)) { throw new TypeError('Expected signal to be an instanceof AbortSignal'); } this[INTERNALS$2] = { method, redirect: init.redirect || input.redirect || 'follow', headers, parsedURL, signal }; // node-fetch-only options this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20; this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true; this.counter = init.counter || input.counter || 0; this.agent = init.agent || input.agent; } get method() { return this[INTERNALS$2].method; } get url() { return format_url(this[INTERNALS$2].parsedURL); } get headers() { return this[INTERNALS$2].headers; } get redirect() { return this[INTERNALS$2].redirect; } get signal() { return this[INTERNALS$2].signal; } /** * Clone this request * * @return Request */ clone() { return new Request(this); } } Body.mixIn(Request.prototype); Object.defineProperty(Request.prototype, Symbol.toStringTag, { value: 'Request', writable: false, enumerable: false, configurable: true }); Object.defineProperties(Request.prototype, { method: { enumerable: true }, url: { enumerable: true }, headers: { enumerable: true }, redirect: { enumerable: true }, clone: { enumerable: true }, signal: { enumerable: true } }); /** * Convert a Request to Node.js http request options. * * @param Request A Request instance * @return Object The options object to be passed to http.request */ function getNodeRequestOptions(request) { const parsedURL = request[INTERNALS$2].parsedURL; const headers = new Headers(request[INTERNALS$2].headers); // fetch step 1.3 if (!headers.has('Accept')) { headers.set('Accept', '*/*'); } // Basic fetch if (!parsedURL.protocol || !parsedURL.hostname) { throw new TypeError('Only absolute URLs are supported'); } if (!/^https?:$/.test(parsedURL.protocol)) { throw new TypeError('Only HTTP(S) protocols are supported'); } if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) { throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8'); } // HTTP-network-or-cache fetch steps 2.4-2.7 let contentLengthValue = null; if (request.body == null && /^(POST|PUT)$/i.test(request.method)) { contentLengthValue = '0'; } if (request.body != null) { const totalBytes = getTotalBytes(request); if (typeof totalBytes === 'number') { contentLengthValue = String(totalBytes); } } if (contentLengthValue) { headers.set('Content-Length', contentLengthValue); } // HTTP-network-or-cache fetch step 2.11 if (!headers.has('User-Agent')) { headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)'); } // HTTP-network-or-cache fetch step 2.15 if (request.compress && !headers.has('Accept-Encoding')) { headers.set('Accept-Encoding', 'gzip,deflate'); } let agent = request.agent; if (typeof agent === 'function') { agent = agent(parsedURL); } if (!headers.has('Connection') && !agent) { headers.set('Connection', 'close'); } // HTTP-network fetch step 4.2 // chunked encoding is handled by Node.js return Object.assign({}, parsedURL, { method: request.method, headers: exportNodeCompatibleHeaders(headers), agent }); } /** * abort-error.js * * AbortError interface for cancelled requests */ /** * Create AbortError instance * * @param String message Error message for human * @return AbortError */ function AbortError(message) { Error.call(this, message); this.type = 'aborted'; this.message = message; // hide custom error implementation details from end-users Error.captureStackTrace(this, this.constructor); } AbortError.prototype = Object.create(Error.prototype); AbortError.prototype.constructor = AbortError; AbortError.prototype.name = 'AbortError'; const URL$1 = Url.URL || whatwgUrl.URL; // fix an issue where "PassThrough", "resolve" aren't a named export for node <10 const PassThrough$1 = Stream.PassThrough; const isDomainOrSubdomain = function isDomainOrSubdomain(destination, original) { const orig = new URL$1(original).hostname; const dest = new URL$1(destination).hostname; return orig === dest || orig[orig.length - dest.length - 1] === '.' && orig.endsWith(dest); }; /** * isSameProtocol reports whether the two provided URLs use the same protocol. * * Both domains must already be in canonical form. * @param {string|URL} original * @param {string|URL} destination */ const isSameProtocol = function isSameProtocol(destination, original) { const orig = new URL$1(original).protocol; const dest = new URL$1(destination).protocol; return orig === dest; }; /** * Fetch function * * @param Mixed url Absolute url or Request instance * @param Object opts Fetch options * @return Promise */ function fetch(url, opts) { // allow custom promise if (!fetch.Promise) { throw new Error('native promise missing, set fetch.Promise to your favorite alternative'); } Body.Promise = fetch.Promise; // wrap http.request into fetch return new fetch.Promise(function (resolve, reject) { // build request object const request = new Request(url, opts); const options = getNodeRequestOptions(request); const send = (options.protocol === 'https:' ? https : http).request; const signal = request.signal; let response = null; const abort = function abort() { let error = new AbortError('The user aborted a request.'); reject(error); if (request.body && request.body instanceof Stream.Readable) { destroyStream(request.body, error); } if (!response || !response.body) return; response.body.emit('error', error); }; if (signal && signal.aborted) { abort(); return; } const abortAndFinalize = function abortAndFinalize() { abort(); finalize(); }; // send request const req = send(options); let reqTimeout; if (signal) { signal.addEventListener('abort', abortAndFinalize); } function finalize() { req.abort(); if (signal) signal.removeEventListener('abort', abortAndFinalize); clearTimeout(reqTimeout); } if (request.timeout) { req.once('socket', function (socket) { reqTimeout = setTimeout(function () { reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout')); finalize(); }, request.timeout); }); } req.on('error', function (err) { reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)); if (response && response.body) { destroyStream(response.body, err); } finalize(); }); fixResponseChunkedTransferBadEnding(req, function (err) { if (signal && signal.aborted) { return; } if (response && response.body) { destroyStream(response.body, err); } }); /* c8 ignore next 18 */ if (parseInt(process.version.substring(1)) < 14) { // Before Node.js 14, pipeline() does not fully support async iterators and does not always // properly handle when the socket close/end events are out of order. req.on('socket', function (s) { s.addListener('close', function (hadError) { // if a data listener is still present we didn't end cleanly const hasDataListener = s.listenerCount('data') > 0; // if end happened before close but the socket didn't emit an error, do it now if (response && hasDataListener && !hadError && !(signal && signal.aborted)) { const err = new Error('Premature close'); err.code = 'ERR_STREAM_PREMATURE_CLOSE'; response.body.emit('error', err); } }); }); } req.on('response', function (res) { clearTimeout(reqTimeout); const headers = createHeadersLenient(res.headers); // HTTP fetch step 5 if (fetch.isRedirect(res.statusCode)) { // HTTP fetch step 5.2 const location = headers.get('Location'); // HTTP fetch step 5.3 let locationURL = null; try { locationURL = location === null ? null : new URL$1(location, request.url).toString(); } catch (err) { // error here can only be invalid URL in Location: header // do not throw when options.redirect == manual // let the user extract the errorneous redirect URL if (request.redirect !== 'manual') { reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect')); finalize(); return; } } // HTTP fetch step 5.5 switch (request.redirect) { case 'error': reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect')); finalize(); return; case 'manual': // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL. if (locationURL !== null) { // handle corrupted header try { headers.set('Location', locationURL); } catch (err) { // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request reject(err); } } break; case 'follow': // HTTP-redirect fetch step 2 if (locationURL === null) { break; } // HTTP-redirect fetch step 5 if (request.counter >= request.follow) { reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect')); finalize(); return; } // HTTP-redirect fetch step 6 (counter increment) // Create a new Request object. const requestOpts = { headers: new Headers(request.headers), follow: request.follow, counter: request.counter + 1, agent: request.agent, compress: request.compress, method: request.method, body: request.body, signal: request.signal, timeout: request.timeout, size: request.size }; if (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) { for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) { requestOpts.headers.delete(name); } } // HTTP-redirect fetch step 9 if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) { reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect')); finalize(); return; } // HTTP-redirect fetch step 11 if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') { requestOpts.method = 'GET'; requestOpts.body = undefined; requestOpts.headers.delete('content-length'); } // HTTP-redirect fetch step 15 resolve(fetch(new Request(locationURL, requestOpts))); finalize(); return; } } // prepare response res.once('end', function () { if (signal) signal.removeEventListener('abort', abortAndFinalize); }); let body = res.pipe(new PassThrough$1()); const response_options = { url: request.url, status: res.statusCode, statusText: res.statusMessage, headers: headers, size: request.size, timeout: request.timeout, counter: request.counter }; // HTTP-network fetch step 12.1.1.3 const codings = headers.get('Content-Encoding'); // HTTP-network fetch step 12.1.1.4: handle content codings // in following scenarios we ignore compression support // 1. compression support is disabled // 2. HEAD request // 3. no Content-Encoding header // 4. no content response (204) // 5. content not modified response (304) if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) { response = new Response(body, response_options); resolve(response); return; } // For Node v6+ // Be less strict when decoding compressed responses, since sometimes // servers send slightly invalid responses that are still accepted // by common browsers. // Always using Z_SYNC_FLUSH is what cURL does. const zlibOptions = { flush: zlib.Z_SYNC_FLUSH, finishFlush: zlib.Z_SYNC_FLUSH }; // for gzip if (codings == 'gzip' || codings == 'x-gzip') { body = body.pipe(zlib.createGunzip(zlibOptions)); response = new Response(body, response_options); resolve(response); return; } // for deflate if (codings == 'deflate' || codings == 'x-deflate') { // handle the infamous raw deflate response from old servers // a hack for old IIS and Apache servers const raw = res.pipe(new PassThrough$1()); raw.once('data', function (chunk) { // see http://stackoverflow.com/questions/37519828 if ((chunk[0] & 0x0F) === 0x08) { body = body.pipe(zlib.createInflate()); } else { body = body.pipe(zlib.createInflateRaw()); } response = new Response(body, response_options); resolve(response); }); raw.on('end', function () { // some old IIS servers return zero-length OK deflate responses, so 'data' is never emitted. if (!response) { response = new Response(body, response_options); resolve(response); } }); return; } // for br if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') { body = body.pipe(zlib.createBrotliDecompress()); response = new Response(body, response_options); resolve(response); return; } // otherwise, use response as-is response = new Response(body, response_options); resolve(response); }); writeToStream(req, request); }); } function fixResponseChunkedTransferBadEnding(request, errorCallback) { let socket; request.on('socket', function (s) { socket = s; }); request.on('response', function (response) { const headers = response.headers; if (headers['transfer-encoding'] === 'chunked' && !headers['content-length']) { response.once('close', function (hadError) { // tests for socket presence, as in some situations the // the 'socket' event is not triggered for the request // (happens in deno), avoids `TypeError` // if a data listener is still present we didn't end cleanly const hasDataListener = socket && socket.listenerCount('data') > 0; if (hasDataListener && !hadError) { const err = new Error('Premature close'); err.code = 'ERR_STREAM_PREMATURE_CLOSE'; errorCallback(err); } }); } }); } function destroyStream(stream, err) { if (stream.destroy) { stream.destroy(err); } else { // node < 8 stream.emit('error', err); stream.end(); } } /** * Redirect code matching * * @param Number code Status code * @return Boolean */ fetch.isRedirect = function (code) { return code === 301 || code === 302 || code === 303 || code === 307 || code === 308; }; // expose Promise fetch.Promise = global.Promise; module.exports = exports = fetch; Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = exports; exports.Headers = Headers; exports.Request = Request; exports.Response = Response; exports.FetchError = FetchError; /***/ }), /***/ 42299: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var punycode = __nccwpck_require__(85477); var mappingTable = __nccwpck_require__(1907); var PROCESSING_OPTIONS = { TRANSITIONAL: 0, NONTRANSITIONAL: 1 }; function normalize(str) { // fix bug in v8 return str.split('\u0000').map(function (s) { return s.normalize('NFC'); }).join('\u0000'); } function findStatus(val) { var start = 0; var end = mappingTable.length - 1; while (start <= end) { var mid = Math.floor((start + end) / 2); var target = mappingTable[mid]; if (target[0][0] <= val && target[0][1] >= val) { return target; } else if (target[0][0] > val) { end = mid - 1; } else { start = mid + 1; } } return null; } var regexAstralSymbols = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g; function countSymbols(string) { return string // replace every surrogate pair with a BMP symbol .replace(regexAstralSymbols, '_') // then get the length .length; } function mapChars(domain_name, useSTD3, processing_option) { var hasError = false; var processed = ""; var len = countSymbols(domain_name); for (var i = 0; i < len; ++i) { var codePoint = domain_name.codePointAt(i); var status = findStatus(codePoint); switch (status[1]) { case "disallowed": hasError = true; processed += String.fromCodePoint(codePoint); break; case "ignored": break; case "mapped": processed += String.fromCodePoint.apply(String, status[2]); break; case "deviation": if (processing_option === PROCESSING_OPTIONS.TRANSITIONAL) { processed += String.fromCodePoint.apply(String, status[2]); } else { processed += String.fromCodePoint(codePoint); } break; case "valid": processed += String.fromCodePoint(codePoint); break; case "disallowed_STD3_mapped": if (useSTD3) { hasError = true; processed += String.fromCodePoint(codePoint); } else { processed += String.fromCodePoint.apply(String, status[2]); } break; case "disallowed_STD3_valid": if (useSTD3) { hasError = true; } processed += String.fromCodePoint(codePoint); break; } } return { string: processed, error: hasError }; } var combiningMarksRegex = /[\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08E4-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C03\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D01-\u0D03\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u18A9\u1920-\u192B\u1930-\u193B\u19B0-\u19C0\u19C8\u19C9\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF5\u1DFC-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C4\uA8E0-\uA8F1\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2D]|\uD800[\uDDFD\uDEE0\uDF76-\uDF7A]|\uD802[\uDE01-\uDE03\uDE05\uDE06\uDE0C-\uDE0F\uDE38-\uDE3A\uDE3F\uDEE5\uDEE6]|\uD804[\uDC00-\uDC02\uDC38-\uDC46\uDC7F-\uDC82\uDCB0-\uDCBA\uDD00-\uDD02\uDD27-\uDD34\uDD73\uDD80-\uDD82\uDDB3-\uDDC0\uDE2C-\uDE37\uDEDF-\uDEEA\uDF01-\uDF03\uDF3C\uDF3E-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF57\uDF62\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDCB0-\uDCC3\uDDAF-\uDDB5\uDDB8-\uDDC0\uDE30-\uDE40\uDEAB-\uDEB7]|\uD81A[\uDEF0-\uDEF4\uDF30-\uDF36]|\uD81B[\uDF51-\uDF7E\uDF8F-\uDF92]|\uD82F[\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD83A[\uDCD0-\uDCD6]|\uDB40[\uDD00-\uDDEF]/; function validateLabel(label, processing_option) { if (label.substr(0, 4) === "xn--") { label = punycode.toUnicode(label); processing_option = PROCESSING_OPTIONS.NONTRANSITIONAL; } var error = false; if (normalize(label) !== label || (label[3] === "-" && label[4] === "-") || label[0] === "-" || label[label.length - 1] === "-" || label.indexOf(".") !== -1 || label.search(combiningMarksRegex) === 0) { error = true; } var len = countSymbols(label); for (var i = 0; i < len; ++i) { var status = findStatus(label.codePointAt(i)); if ((processing === PROCESSING_OPTIONS.TRANSITIONAL && status[1] !== "valid") || (processing === PROCESSING_OPTIONS.NONTRANSITIONAL && status[1] !== "valid" && status[1] !== "deviation")) { error = true; break; } } return { label: label, error: error }; } function processing(domain_name, useSTD3, processing_option) { var result = mapChars(domain_name, useSTD3, processing_option); result.string = normalize(result.string); var labels = result.string.split("."); for (var i = 0; i < labels.length; ++i) { try { var validation = validateLabel(labels[i]); labels[i] = validation.label; result.error = result.error || validation.error; } catch(e) { result.error = true; } } return { string: labels.join("."), error: result.error }; } module.exports.toASCII = function(domain_name, useSTD3, processing_option, verifyDnsLength) { var result = processing(domain_name, useSTD3, processing_option); var labels = result.string.split("."); labels = labels.map(function(l) { try { return punycode.toASCII(l); } catch(e) { result.error = true; return l; } }); if (verifyDnsLength) { var total = labels.slice(0, labels.length - 1).join(".").length; if (total.length > 253 || total.length === 0) { result.error = true; } for (var i=0; i < labels.length; ++i) { if (labels.length > 63 || labels.length === 0) { result.error = true; break; } } } if (result.error) return null; return labels.join("."); }; module.exports.toUnicode = function(domain_name, useSTD3) { var result = processing(domain_name, useSTD3, PROCESSING_OPTIONS.NONTRANSITIONAL); return { domain: result.string, error: result.error }; }; module.exports.PROCESSING_OPTIONS = PROCESSING_OPTIONS; /***/ }), /***/ 15871: /***/ ((module) => { "use strict"; var conversions = {}; module.exports = conversions; function sign(x) { return x < 0 ? -1 : 1; } function evenRound(x) { // Round x to the nearest integer, choosing the even integer if it lies halfway between two. if ((x % 1) === 0.5 && (x & 1) === 0) { // [even number].5; round down (i.e. floor) return Math.floor(x); } else { return Math.round(x); } } function createNumberConversion(bitLength, typeOpts) { if (!typeOpts.unsigned) { --bitLength; } const lowerBound = typeOpts.unsigned ? 0 : -Math.pow(2, bitLength); const upperBound = Math.pow(2, bitLength) - 1; const moduloVal = typeOpts.moduloBitLength ? Math.pow(2, typeOpts.moduloBitLength) : Math.pow(2, bitLength); const moduloBound = typeOpts.moduloBitLength ? Math.pow(2, typeOpts.moduloBitLength - 1) : Math.pow(2, bitLength - 1); return function(V, opts) { if (!opts) opts = {}; let x = +V; if (opts.enforceRange) { if (!Number.isFinite(x)) { throw new TypeError("Argument is not a finite number"); } x = sign(x) * Math.floor(Math.abs(x)); if (x < lowerBound || x > upperBound) { throw new TypeError("Argument is not in byte range"); } return x; } if (!isNaN(x) && opts.clamp) { x = evenRound(x); if (x < lowerBound) x = lowerBound; if (x > upperBound) x = upperBound; return x; } if (!Number.isFinite(x) || x === 0) { return 0; } x = sign(x) * Math.floor(Math.abs(x)); x = x % moduloVal; if (!typeOpts.unsigned && x >= moduloBound) { return x - moduloVal; } else if (typeOpts.unsigned) { if (x < 0) { x += moduloVal; } else if (x === -0) { // don't return negative zero return 0; } } return x; } } conversions["void"] = function () { return undefined; }; conversions["boolean"] = function (val) { return !!val; }; conversions["byte"] = createNumberConversion(8, { unsigned: false }); conversions["octet"] = createNumberConversion(8, { unsigned: true }); conversions["short"] = createNumberConversion(16, { unsigned: false }); conversions["unsigned short"] = createNumberConversion(16, { unsigned: true }); conversions["long"] = createNumberConversion(32, { unsigned: false }); conversions["unsigned long"] = createNumberConversion(32, { unsigned: true }); conversions["long long"] = createNumberConversion(32, { unsigned: false, moduloBitLength: 64 }); conversions["unsigned long long"] = createNumberConversion(32, { unsigned: true, moduloBitLength: 64 }); conversions["double"] = function (V) { const x = +V; if (!Number.isFinite(x)) { throw new TypeError("Argument is not a finite floating-point value"); } return x; }; conversions["unrestricted double"] = function (V) { const x = +V; if (isNaN(x)) { throw new TypeError("Argument is NaN"); } return x; }; // not quite valid, but good enough for JS conversions["float"] = conversions["double"]; conversions["unrestricted float"] = conversions["unrestricted double"]; conversions["DOMString"] = function (V, opts) { if (!opts) opts = {}; if (opts.treatNullAsEmptyString && V === null) { return ""; } return String(V); }; conversions["ByteString"] = function (V, opts) { const x = String(V); let c = undefined; for (let i = 0; (c = x.codePointAt(i)) !== undefined; ++i) { if (c > 255) { throw new TypeError("Argument is not a valid bytestring"); } } return x; }; conversions["USVString"] = function (V) { const S = String(V); const n = S.length; const U = []; for (let i = 0; i < n; ++i) { const c = S.charCodeAt(i); if (c < 0xD800 || c > 0xDFFF) { U.push(String.fromCodePoint(c)); } else if (0xDC00 <= c && c <= 0xDFFF) { U.push(String.fromCodePoint(0xFFFD)); } else { if (i === n - 1) { U.push(String.fromCodePoint(0xFFFD)); } else { const d = S.charCodeAt(i + 1); if (0xDC00 <= d && d <= 0xDFFF) { const a = c & 0x3FF; const b = d & 0x3FF; U.push(String.fromCodePoint((2 << 15) + (2 << 9) * a + b)); ++i; } else { U.push(String.fromCodePoint(0xFFFD)); } } } } return U.join(''); }; conversions["Date"] = function (V, opts) { if (!(V instanceof Date)) { throw new TypeError("Argument is not a Date object"); } if (isNaN(V)) { return undefined; } return V; }; conversions["RegExp"] = function (V, opts) { if (!(V instanceof RegExp)) { V = new RegExp(V); } return V; }; /***/ }), /***/ 58262: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; const usm = __nccwpck_require__(40033); exports.implementation = class URLImpl { constructor(constructorArgs) { const url = constructorArgs[0]; const base = constructorArgs[1]; let parsedBase = null; if (base !== undefined) { parsedBase = usm.basicURLParse(base); if (parsedBase === "failure") { throw new TypeError("Invalid base URL"); } } const parsedURL = usm.basicURLParse(url, { baseURL: parsedBase }); if (parsedURL === "failure") { throw new TypeError("Invalid URL"); } this._url = parsedURL; // TODO: query stuff } get href() { return usm.serializeURL(this._url); } set href(v) { const parsedURL = usm.basicURLParse(v); if (parsedURL === "failure") { throw new TypeError("Invalid URL"); } this._url = parsedURL; } get origin() { return usm.serializeURLOrigin(this._url); } get protocol() { return this._url.scheme + ":"; } set protocol(v) { usm.basicURLParse(v + ":", { url: this._url, stateOverride: "scheme start" }); } get username() { return this._url.username; } set username(v) { if (usm.cannotHaveAUsernamePasswordPort(this._url)) { return; } usm.setTheUsername(this._url, v); } get password() { return this._url.password; } set password(v) { if (usm.cannotHaveAUsernamePasswordPort(this._url)) { return; } usm.setThePassword(this._url, v); } get host() { const url = this._url; if (url.host === null) { return ""; } if (url.port === null) { return usm.serializeHost(url.host); } return usm.serializeHost(url.host) + ":" + usm.serializeInteger(url.port); } set host(v) { if (this._url.cannotBeABaseURL) { return; } usm.basicURLParse(v, { url: this._url, stateOverride: "host" }); } get hostname() { if (this._url.host === null) { return ""; } return usm.serializeHost(this._url.host); } set hostname(v) { if (this._url.cannotBeABaseURL) { return; } usm.basicURLParse(v, { url: this._url, stateOverride: "hostname" }); } get port() { if (this._url.port === null) { return ""; } return usm.serializeInteger(this._url.port); } set port(v) { if (usm.cannotHaveAUsernamePasswordPort(this._url)) { return; } if (v === "") { this._url.port = null; } else { usm.basicURLParse(v, { url: this._url, stateOverride: "port" }); } } get pathname() { if (this._url.cannotBeABaseURL) { return this._url.path[0]; } if (this._url.path.length === 0) { return ""; } return "/" + this._url.path.join("/"); } set pathname(v) { if (this._url.cannotBeABaseURL) { return; } this._url.path = []; usm.basicURLParse(v, { url: this._url, stateOverride: "path start" }); } get search() { if (this._url.query === null || this._url.query === "") { return ""; } return "?" + this._url.query; } set search(v) { // TODO: query stuff const url = this._url; if (v === "") { url.query = null; return; } const input = v[0] === "?" ? v.substring(1) : v; url.query = ""; usm.basicURLParse(input, { url, stateOverride: "query" }); } get hash() { if (this._url.fragment === null || this._url.fragment === "") { return ""; } return "#" + this._url.fragment; } set hash(v) { if (v === "") { this._url.fragment = null; return; } const input = v[0] === "#" ? v.substring(1) : v; this._url.fragment = ""; usm.basicURLParse(input, { url: this._url, stateOverride: "fragment" }); } toJSON() { return this.href; } }; /***/ }), /***/ 80653: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const conversions = __nccwpck_require__(15871); const utils = __nccwpck_require__(60276); const Impl = __nccwpck_require__(58262); const impl = utils.implSymbol; function URL(url) { if (!this || this[impl] || !(this instanceof URL)) { throw new TypeError("Failed to construct 'URL': Please use the 'new' operator, this DOM object constructor cannot be called as a function."); } if (arguments.length < 1) { throw new TypeError("Failed to construct 'URL': 1 argument required, but only " + arguments.length + " present."); } const args = []; for (let i = 0; i < arguments.length && i < 2; ++i) { args[i] = arguments[i]; } args[0] = conversions["USVString"](args[0]); if (args[1] !== undefined) { args[1] = conversions["USVString"](args[1]); } module.exports.setup(this, args); } URL.prototype.toJSON = function toJSON() { if (!this || !module.exports.is(this)) { throw new TypeError("Illegal invocation"); } const args = []; for (let i = 0; i < arguments.length && i < 0; ++i) { args[i] = arguments[i]; } return this[impl].toJSON.apply(this[impl], args); }; Object.defineProperty(URL.prototype, "href", { get() { return this[impl].href; }, set(V) { V = conversions["USVString"](V); this[impl].href = V; }, enumerable: true, configurable: true }); URL.prototype.toString = function () { if (!this || !module.exports.is(this)) { throw new TypeError("Illegal invocation"); } return this.href; }; Object.defineProperty(URL.prototype, "origin", { get() { return this[impl].origin; }, enumerable: true, configurable: true }); Object.defineProperty(URL.prototype, "protocol", { get() { return this[impl].protocol; }, set(V) { V = conversions["USVString"](V); this[impl].protocol = V; }, enumerable: true, configurable: true }); Object.defineProperty(URL.prototype, "username", { get() { return this[impl].username; }, set(V) { V = conversions["USVString"](V); this[impl].username = V; }, enumerable: true, configurable: true }); Object.defineProperty(URL.prototype, "password", { get() { return this[impl].password; }, set(V) { V = conversions["USVString"](V); this[impl].password = V; }, enumerable: true, configurable: true }); Object.defineProperty(URL.prototype, "host", { get() { return this[impl].host; }, set(V) { V = conversions["USVString"](V); this[impl].host = V; }, enumerable: true, configurable: true }); Object.defineProperty(URL.prototype, "hostname", { get() { return this[impl].hostname; }, set(V) { V = conversions["USVString"](V); this[impl].hostname = V; }, enumerable: true, configurable: true }); Object.defineProperty(URL.prototype, "port", { get() { return this[impl].port; }, set(V) { V = conversions["USVString"](V); this[impl].port = V; }, enumerable: true, configurable: true }); Object.defineProperty(URL.prototype, "pathname", { get() { return this[impl].pathname; }, set(V) { V = conversions["USVString"](V); this[impl].pathname = V; }, enumerable: true, configurable: true }); Object.defineProperty(URL.prototype, "search", { get() { return this[impl].search; }, set(V) { V = conversions["USVString"](V); this[impl].search = V; }, enumerable: true, configurable: true }); Object.defineProperty(URL.prototype, "hash", { get() { return this[impl].hash; }, set(V) { V = conversions["USVString"](V); this[impl].hash = V; }, enumerable: true, configurable: true }); module.exports = { is(obj) { return !!obj && obj[impl] instanceof Impl.implementation; }, create(constructorArgs, privateData) { let obj = Object.create(URL.prototype); this.setup(obj, constructorArgs, privateData); return obj; }, setup(obj, constructorArgs, privateData) { if (!privateData) privateData = {}; privateData.wrapper = obj; obj[impl] = new Impl.implementation(constructorArgs, privateData); obj[impl][utils.wrapperSymbol] = obj; }, interface: URL, expose: { Window: { URL: URL }, Worker: { URL: URL } } }; /***/ }), /***/ 73323: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; exports.URL = __nccwpck_require__(80653)["interface"]; exports.serializeURL = __nccwpck_require__(40033).serializeURL; exports.serializeURLOrigin = __nccwpck_require__(40033).serializeURLOrigin; exports.basicURLParse = __nccwpck_require__(40033).basicURLParse; exports.setTheUsername = __nccwpck_require__(40033).setTheUsername; exports.setThePassword = __nccwpck_require__(40033).setThePassword; exports.serializeHost = __nccwpck_require__(40033).serializeHost; exports.serializeInteger = __nccwpck_require__(40033).serializeInteger; exports.parseURL = __nccwpck_require__(40033).parseURL; /***/ }), /***/ 40033: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const punycode = __nccwpck_require__(85477); const tr46 = __nccwpck_require__(42299); const specialSchemes = { ftp: 21, file: null, gopher: 70, http: 80, https: 443, ws: 80, wss: 443 }; const failure = Symbol("failure"); function countSymbols(str) { return punycode.ucs2.decode(str).length; } function at(input, idx) { const c = input[idx]; return isNaN(c) ? undefined : String.fromCodePoint(c); } function isASCIIDigit(c) { return c >= 0x30 && c <= 0x39; } function isASCIIAlpha(c) { return (c >= 0x41 && c <= 0x5A) || (c >= 0x61 && c <= 0x7A); } function isASCIIAlphanumeric(c) { return isASCIIAlpha(c) || isASCIIDigit(c); } function isASCIIHex(c) { return isASCIIDigit(c) || (c >= 0x41 && c <= 0x46) || (c >= 0x61 && c <= 0x66); } function isSingleDot(buffer) { return buffer === "." || buffer.toLowerCase() === "%2e"; } function isDoubleDot(buffer) { buffer = buffer.toLowerCase(); return buffer === ".." || buffer === "%2e." || buffer === ".%2e" || buffer === "%2e%2e"; } function isWindowsDriveLetterCodePoints(cp1, cp2) { return isASCIIAlpha(cp1) && (cp2 === 58 || cp2 === 124); } function isWindowsDriveLetterString(string) { return string.length === 2 && isASCIIAlpha(string.codePointAt(0)) && (string[1] === ":" || string[1] === "|"); } function isNormalizedWindowsDriveLetterString(string) { return string.length === 2 && isASCIIAlpha(string.codePointAt(0)) && string[1] === ":"; } function containsForbiddenHostCodePoint(string) { return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|%|\/|:|\?|@|\[|\\|\]/) !== -1; } function containsForbiddenHostCodePointExcludingPercent(string) { return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|\?|@|\[|\\|\]/) !== -1; } function isSpecialScheme(scheme) { return specialSchemes[scheme] !== undefined; } function isSpecial(url) { return isSpecialScheme(url.scheme); } function defaultPort(scheme) { return specialSchemes[scheme]; } function percentEncode(c) { let hex = c.toString(16).toUpperCase(); if (hex.length === 1) { hex = "0" + hex; } return "%" + hex; } function utf8PercentEncode(c) { const buf = new Buffer(c); let str = ""; for (let i = 0; i < buf.length; ++i) { str += percentEncode(buf[i]); } return str; } function utf8PercentDecode(str) { const input = new Buffer(str); const output = []; for (let i = 0; i < input.length; ++i) { if (input[i] !== 37) { output.push(input[i]); } else if (input[i] === 37 && isASCIIHex(input[i + 1]) && isASCIIHex(input[i + 2])) { output.push(parseInt(input.slice(i + 1, i + 3).toString(), 16)); i += 2; } else { output.push(input[i]); } } return new Buffer(output).toString(); } function isC0ControlPercentEncode(c) { return c <= 0x1F || c > 0x7E; } const extraPathPercentEncodeSet = new Set([32, 34, 35, 60, 62, 63, 96, 123, 125]); function isPathPercentEncode(c) { return isC0ControlPercentEncode(c) || extraPathPercentEncodeSet.has(c); } const extraUserinfoPercentEncodeSet = new Set([47, 58, 59, 61, 64, 91, 92, 93, 94, 124]); function isUserinfoPercentEncode(c) { return isPathPercentEncode(c) || extraUserinfoPercentEncodeSet.has(c); } function percentEncodeChar(c, encodeSetPredicate) { const cStr = String.fromCodePoint(c); if (encodeSetPredicate(c)) { return utf8PercentEncode(cStr); } return cStr; } function parseIPv4Number(input) { let R = 10; if (input.length >= 2 && input.charAt(0) === "0" && input.charAt(1).toLowerCase() === "x") { input = input.substring(2); R = 16; } else if (input.length >= 2 && input.charAt(0) === "0") { input = input.substring(1); R = 8; } if (input === "") { return 0; } const regex = R === 10 ? /[^0-9]/ : (R === 16 ? /[^0-9A-Fa-f]/ : /[^0-7]/); if (regex.test(input)) { return failure; } return parseInt(input, R); } function parseIPv4(input) { const parts = input.split("."); if (parts[parts.length - 1] === "") { if (parts.length > 1) { parts.pop(); } } if (parts.length > 4) { return input; } const numbers = []; for (const part of parts) { if (part === "") { return input; } const n = parseIPv4Number(part); if (n === failure) { return input; } numbers.push(n); } for (let i = 0; i < numbers.length - 1; ++i) { if (numbers[i] > 255) { return failure; } } if (numbers[numbers.length - 1] >= Math.pow(256, 5 - numbers.length)) { return failure; } let ipv4 = numbers.pop(); let counter = 0; for (const n of numbers) { ipv4 += n * Math.pow(256, 3 - counter); ++counter; } return ipv4; } function serializeIPv4(address) { let output = ""; let n = address; for (let i = 1; i <= 4; ++i) { output = String(n % 256) + output; if (i !== 4) { output = "." + output; } n = Math.floor(n / 256); } return output; } function parseIPv6(input) { const address = [0, 0, 0, 0, 0, 0, 0, 0]; let pieceIndex = 0; let compress = null; let pointer = 0; input = punycode.ucs2.decode(input); if (input[pointer] === 58) { if (input[pointer + 1] !== 58) { return failure; } pointer += 2; ++pieceIndex; compress = pieceIndex; } while (pointer < input.length) { if (pieceIndex === 8) { return failure; } if (input[pointer] === 58) { if (compress !== null) { return failure; } ++pointer; ++pieceIndex; compress = pieceIndex; continue; } let value = 0; let length = 0; while (length < 4 && isASCIIHex(input[pointer])) { value = value * 0x10 + parseInt(at(input, pointer), 16); ++pointer; ++length; } if (input[pointer] === 46) { if (length === 0) { return failure; } pointer -= length; if (pieceIndex > 6) { return failure; } let numbersSeen = 0; while (input[pointer] !== undefined) { let ipv4Piece = null; if (numbersSeen > 0) { if (input[pointer] === 46 && numbersSeen < 4) { ++pointer; } else { return failure; } } if (!isASCIIDigit(input[pointer])) { return failure; } while (isASCIIDigit(input[pointer])) { const number = parseInt(at(input, pointer)); if (ipv4Piece === null) { ipv4Piece = number; } else if (ipv4Piece === 0) { return failure; } else { ipv4Piece = ipv4Piece * 10 + number; } if (ipv4Piece > 255) { return failure; } ++pointer; } address[pieceIndex] = address[pieceIndex] * 0x100 + ipv4Piece; ++numbersSeen; if (numbersSeen === 2 || numbersSeen === 4) { ++pieceIndex; } } if (numbersSeen !== 4) { return failure; } break; } else if (input[pointer] === 58) { ++pointer; if (input[pointer] === undefined) { return failure; } } else if (input[pointer] !== undefined) { return failure; } address[pieceIndex] = value; ++pieceIndex; } if (compress !== null) { let swaps = pieceIndex - compress; pieceIndex = 7; while (pieceIndex !== 0 && swaps > 0) { const temp = address[compress + swaps - 1]; address[compress + swaps - 1] = address[pieceIndex]; address[pieceIndex] = temp; --pieceIndex; --swaps; } } else if (compress === null && pieceIndex !== 8) { return failure; } return address; } function serializeIPv6(address) { let output = ""; const seqResult = findLongestZeroSequence(address); const compress = seqResult.idx; let ignore0 = false; for (let pieceIndex = 0; pieceIndex <= 7; ++pieceIndex) { if (ignore0 && address[pieceIndex] === 0) { continue; } else if (ignore0) { ignore0 = false; } if (compress === pieceIndex) { const separator = pieceIndex === 0 ? "::" : ":"; output += separator; ignore0 = true; continue; } output += address[pieceIndex].toString(16); if (pieceIndex !== 7) { output += ":"; } } return output; } function parseHost(input, isSpecialArg) { if (input[0] === "[") { if (input[input.length - 1] !== "]") { return failure; } return parseIPv6(input.substring(1, input.length - 1)); } if (!isSpecialArg) { return parseOpaqueHost(input); } const domain = utf8PercentDecode(input); const asciiDomain = tr46.toASCII(domain, false, tr46.PROCESSING_OPTIONS.NONTRANSITIONAL, false); if (asciiDomain === null) { return failure; } if (containsForbiddenHostCodePoint(asciiDomain)) { return failure; } const ipv4Host = parseIPv4(asciiDomain); if (typeof ipv4Host === "number" || ipv4Host === failure) { return ipv4Host; } return asciiDomain; } function parseOpaqueHost(input) { if (containsForbiddenHostCodePointExcludingPercent(input)) { return failure; } let output = ""; const decoded = punycode.ucs2.decode(input); for (let i = 0; i < decoded.length; ++i) { output += percentEncodeChar(decoded[i], isC0ControlPercentEncode); } return output; } function findLongestZeroSequence(arr) { let maxIdx = null; let maxLen = 1; // only find elements > 1 let currStart = null; let currLen = 0; for (let i = 0; i < arr.length; ++i) { if (arr[i] !== 0) { if (currLen > maxLen) { maxIdx = currStart; maxLen = currLen; } currStart = null; currLen = 0; } else { if (currStart === null) { currStart = i; } ++currLen; } } // if trailing zeros if (currLen > maxLen) { maxIdx = currStart; maxLen = currLen; } return { idx: maxIdx, len: maxLen }; } function serializeHost(host) { if (typeof host === "number") { return serializeIPv4(host); } // IPv6 serializer if (host instanceof Array) { return "[" + serializeIPv6(host) + "]"; } return host; } function trimControlChars(url) { return url.replace(/^[\u0000-\u001F\u0020]+|[\u0000-\u001F\u0020]+$/g, ""); } function trimTabAndNewline(url) { return url.replace(/\u0009|\u000A|\u000D/g, ""); } function shortenPath(url) { const path = url.path; if (path.length === 0) { return; } if (url.scheme === "file" && path.length === 1 && isNormalizedWindowsDriveLetter(path[0])) { return; } path.pop(); } function includesCredentials(url) { return url.username !== "" || url.password !== ""; } function cannotHaveAUsernamePasswordPort(url) { return url.host === null || url.host === "" || url.cannotBeABaseURL || url.scheme === "file"; } function isNormalizedWindowsDriveLetter(string) { return /^[A-Za-z]:$/.test(string); } function URLStateMachine(input, base, encodingOverride, url, stateOverride) { this.pointer = 0; this.input = input; this.base = base || null; this.encodingOverride = encodingOverride || "utf-8"; this.stateOverride = stateOverride; this.url = url; this.failure = false; this.parseError = false; if (!this.url) { this.url = { scheme: "", username: "", password: "", host: null, port: null, path: [], query: null, fragment: null, cannotBeABaseURL: false }; const res = trimControlChars(this.input); if (res !== this.input) { this.parseError = true; } this.input = res; } const res = trimTabAndNewline(this.input); if (res !== this.input) { this.parseError = true; } this.input = res; this.state = stateOverride || "scheme start"; this.buffer = ""; this.atFlag = false; this.arrFlag = false; this.passwordTokenSeenFlag = false; this.input = punycode.ucs2.decode(this.input); for (; this.pointer <= this.input.length; ++this.pointer) { const c = this.input[this.pointer]; const cStr = isNaN(c) ? undefined : String.fromCodePoint(c); // exec state machine const ret = this["parse " + this.state](c, cStr); if (!ret) { break; // terminate algorithm } else if (ret === failure) { this.failure = true; break; } } } URLStateMachine.prototype["parse scheme start"] = function parseSchemeStart(c, cStr) { if (isASCIIAlpha(c)) { this.buffer += cStr.toLowerCase(); this.state = "scheme"; } else if (!this.stateOverride) { this.state = "no scheme"; --this.pointer; } else { this.parseError = true; return failure; } return true; }; URLStateMachine.prototype["parse scheme"] = function parseScheme(c, cStr) { if (isASCIIAlphanumeric(c) || c === 43 || c === 45 || c === 46) { this.buffer += cStr.toLowerCase(); } else if (c === 58) { if (this.stateOverride) { if (isSpecial(this.url) && !isSpecialScheme(this.buffer)) { return false; } if (!isSpecial(this.url) && isSpecialScheme(this.buffer)) { return false; } if ((includesCredentials(this.url) || this.url.port !== null) && this.buffer === "file") { return false; } if (this.url.scheme === "file" && (this.url.host === "" || this.url.host === null)) { return false; } } this.url.scheme = this.buffer; this.buffer = ""; if (this.stateOverride) { return false; } if (this.url.scheme === "file") { if (this.input[this.pointer + 1] !== 47 || this.input[this.pointer + 2] !== 47) { this.parseError = true; } this.state = "file"; } else if (isSpecial(this.url) && this.base !== null && this.base.scheme === this.url.scheme) { this.state = "special relative or authority"; } else if (isSpecial(this.url)) { this.state = "special authority slashes"; } else if (this.input[this.pointer + 1] === 47) { this.state = "path or authority"; ++this.pointer; } else { this.url.cannotBeABaseURL = true; this.url.path.push(""); this.state = "cannot-be-a-base-URL path"; } } else if (!this.stateOverride) { this.buffer = ""; this.state = "no scheme"; this.pointer = -1; } else { this.parseError = true; return failure; } return true; }; URLStateMachine.prototype["parse no scheme"] = function parseNoScheme(c) { if (this.base === null || (this.base.cannotBeABaseURL && c !== 35)) { return failure; } else if (this.base.cannotBeABaseURL && c === 35) { this.url.scheme = this.base.scheme; this.url.path = this.base.path.slice(); this.url.query = this.base.query; this.url.fragment = ""; this.url.cannotBeABaseURL = true; this.state = "fragment"; } else if (this.base.scheme === "file") { this.state = "file"; --this.pointer; } else { this.state = "relative"; --this.pointer; } return true; }; URLStateMachine.prototype["parse special relative or authority"] = function parseSpecialRelativeOrAuthority(c) { if (c === 47 && this.input[this.pointer + 1] === 47) { this.state = "special authority ignore slashes"; ++this.pointer; } else { this.parseError = true; this.state = "relative"; --this.pointer; } return true; }; URLStateMachine.prototype["parse path or authority"] = function parsePathOrAuthority(c) { if (c === 47) { this.state = "authority"; } else { this.state = "path"; --this.pointer; } return true; }; URLStateMachine.prototype["parse relative"] = function parseRelative(c) { this.url.scheme = this.base.scheme; if (isNaN(c)) { this.url.username = this.base.username; this.url.password = this.base.password; this.url.host = this.base.host; this.url.port = this.base.port; this.url.path = this.base.path.slice(); this.url.query = this.base.query; } else if (c === 47) { this.state = "relative slash"; } else if (c === 63) { this.url.username = this.base.username; this.url.password = this.base.password; this.url.host = this.base.host; this.url.port = this.base.port; this.url.path = this.base.path.slice(); this.url.query = ""; this.state = "query"; } else if (c === 35) { this.url.username = this.base.username; this.url.password = this.base.password; this.url.host = this.base.host; this.url.port = this.base.port; this.url.path = this.base.path.slice(); this.url.query = this.base.query; this.url.fragment = ""; this.state = "fragment"; } else if (isSpecial(this.url) && c === 92) { this.parseError = true; this.state = "relative slash"; } else { this.url.username = this.base.username; this.url.password = this.base.password; this.url.host = this.base.host; this.url.port = this.base.port; this.url.path = this.base.path.slice(0, this.base.path.length - 1); this.state = "path"; --this.pointer; } return true; }; URLStateMachine.prototype["parse relative slash"] = function parseRelativeSlash(c) { if (isSpecial(this.url) && (c === 47 || c === 92)) { if (c === 92) { this.parseError = true; } this.state = "special authority ignore slashes"; } else if (c === 47) { this.state = "authority"; } else { this.url.username = this.base.username; this.url.password = this.base.password; this.url.host = this.base.host; this.url.port = this.base.port; this.state = "path"; --this.pointer; } return true; }; URLStateMachine.prototype["parse special authority slashes"] = function parseSpecialAuthoritySlashes(c) { if (c === 47 && this.input[this.pointer + 1] === 47) { this.state = "special authority ignore slashes"; ++this.pointer; } else { this.parseError = true; this.state = "special authority ignore slashes"; --this.pointer; } return true; }; URLStateMachine.prototype["parse special authority ignore slashes"] = function parseSpecialAuthorityIgnoreSlashes(c) { if (c !== 47 && c !== 92) { this.state = "authority"; --this.pointer; } else { this.parseError = true; } return true; }; URLStateMachine.prototype["parse authority"] = function parseAuthority(c, cStr) { if (c === 64) { this.parseError = true; if (this.atFlag) { this.buffer = "%40" + this.buffer; } this.atFlag = true; // careful, this is based on buffer and has its own pointer (this.pointer != pointer) and inner chars const len = countSymbols(this.buffer); for (let pointer = 0; pointer < len; ++pointer) { const codePoint = this.buffer.codePointAt(pointer); if (codePoint === 58 && !this.passwordTokenSeenFlag) { this.passwordTokenSeenFlag = true; continue; } const encodedCodePoints = percentEncodeChar(codePoint, isUserinfoPercentEncode); if (this.passwordTokenSeenFlag) { this.url.password += encodedCodePoints; } else { this.url.username += encodedCodePoints; } } this.buffer = ""; } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || (isSpecial(this.url) && c === 92)) { if (this.atFlag && this.buffer === "") { this.parseError = true; return failure; } this.pointer -= countSymbols(this.buffer) + 1; this.buffer = ""; this.state = "host"; } else { this.buffer += cStr; } return true; }; URLStateMachine.prototype["parse hostname"] = URLStateMachine.prototype["parse host"] = function parseHostName(c, cStr) { if (this.stateOverride && this.url.scheme === "file") { --this.pointer; this.state = "file host"; } else if (c === 58 && !this.arrFlag) { if (this.buffer === "") { this.parseError = true; return failure; } const host = parseHost(this.buffer, isSpecial(this.url)); if (host === failure) { return failure; } this.url.host = host; this.buffer = ""; this.state = "port"; if (this.stateOverride === "hostname") { return false; } } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || (isSpecial(this.url) && c === 92)) { --this.pointer; if (isSpecial(this.url) && this.buffer === "") { this.parseError = true; return failure; } else if (this.stateOverride && this.buffer === "" && (includesCredentials(this.url) || this.url.port !== null)) { this.parseError = true; return false; } const host = parseHost(this.buffer, isSpecial(this.url)); if (host === failure) { return failure; } this.url.host = host; this.buffer = ""; this.state = "path start"; if (this.stateOverride) { return false; } } else { if (c === 91) { this.arrFlag = true; } else if (c === 93) { this.arrFlag = false; } this.buffer += cStr; } return true; }; URLStateMachine.prototype["parse port"] = function parsePort(c, cStr) { if (isASCIIDigit(c)) { this.buffer += cStr; } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || (isSpecial(this.url) && c === 92) || this.stateOverride) { if (this.buffer !== "") { const port = parseInt(this.buffer); if (port > Math.pow(2, 16) - 1) { this.parseError = true; return failure; } this.url.port = port === defaultPort(this.url.scheme) ? null : port; this.buffer = ""; } if (this.stateOverride) { return false; } this.state = "path start"; --this.pointer; } else { this.parseError = true; return failure; } return true; }; const fileOtherwiseCodePoints = new Set([47, 92, 63, 35]); URLStateMachine.prototype["parse file"] = function parseFile(c) { this.url.scheme = "file"; if (c === 47 || c === 92) { if (c === 92) { this.parseError = true; } this.state = "file slash"; } else if (this.base !== null && this.base.scheme === "file") { if (isNaN(c)) { this.url.host = this.base.host; this.url.path = this.base.path.slice(); this.url.query = this.base.query; } else if (c === 63) { this.url.host = this.base.host; this.url.path = this.base.path.slice(); this.url.query = ""; this.state = "query"; } else if (c === 35) { this.url.host = this.base.host; this.url.path = this.base.path.slice(); this.url.query = this.base.query; this.url.fragment = ""; this.state = "fragment"; } else { if (this.input.length - this.pointer - 1 === 0 || // remaining consists of 0 code points !isWindowsDriveLetterCodePoints(c, this.input[this.pointer + 1]) || (this.input.length - this.pointer - 1 >= 2 && // remaining has at least 2 code points !fileOtherwiseCodePoints.has(this.input[this.pointer + 2]))) { this.url.host = this.base.host; this.url.path = this.base.path.slice(); shortenPath(this.url); } else { this.parseError = true; } this.state = "path"; --this.pointer; } } else { this.state = "path"; --this.pointer; } return true; }; URLStateMachine.prototype["parse file slash"] = function parseFileSlash(c) { if (c === 47 || c === 92) { if (c === 92) { this.parseError = true; } this.state = "file host"; } else { if (this.base !== null && this.base.scheme === "file") { if (isNormalizedWindowsDriveLetterString(this.base.path[0])) { this.url.path.push(this.base.path[0]); } else { this.url.host = this.base.host; } } this.state = "path"; --this.pointer; } return true; }; URLStateMachine.prototype["parse file host"] = function parseFileHost(c, cStr) { if (isNaN(c) || c === 47 || c === 92 || c === 63 || c === 35) { --this.pointer; if (!this.stateOverride && isWindowsDriveLetterString(this.buffer)) { this.parseError = true; this.state = "path"; } else if (this.buffer === "") { this.url.host = ""; if (this.stateOverride) { return false; } this.state = "path start"; } else { let host = parseHost(this.buffer, isSpecial(this.url)); if (host === failure) { return failure; } if (host === "localhost") { host = ""; } this.url.host = host; if (this.stateOverride) { return false; } this.buffer = ""; this.state = "path start"; } } else { this.buffer += cStr; } return true; }; URLStateMachine.prototype["parse path start"] = function parsePathStart(c) { if (isSpecial(this.url)) { if (c === 92) { this.parseError = true; } this.state = "path"; if (c !== 47 && c !== 92) { --this.pointer; } } else if (!this.stateOverride && c === 63) { this.url.query = ""; this.state = "query"; } else if (!this.stateOverride && c === 35) { this.url.fragment = ""; this.state = "fragment"; } else if (c !== undefined) { this.state = "path"; if (c !== 47) { --this.pointer; } } return true; }; URLStateMachine.prototype["parse path"] = function parsePath(c) { if (isNaN(c) || c === 47 || (isSpecial(this.url) && c === 92) || (!this.stateOverride && (c === 63 || c === 35))) { if (isSpecial(this.url) && c === 92) { this.parseError = true; } if (isDoubleDot(this.buffer)) { shortenPath(this.url); if (c !== 47 && !(isSpecial(this.url) && c === 92)) { this.url.path.push(""); } } else if (isSingleDot(this.buffer) && c !== 47 && !(isSpecial(this.url) && c === 92)) { this.url.path.push(""); } else if (!isSingleDot(this.buffer)) { if (this.url.scheme === "file" && this.url.path.length === 0 && isWindowsDriveLetterString(this.buffer)) { if (this.url.host !== "" && this.url.host !== null) { this.parseError = true; this.url.host = ""; } this.buffer = this.buffer[0] + ":"; } this.url.path.push(this.buffer); } this.buffer = ""; if (this.url.scheme === "file" && (c === undefined || c === 63 || c === 35)) { while (this.url.path.length > 1 && this.url.path[0] === "") { this.parseError = true; this.url.path.shift(); } } if (c === 63) { this.url.query = ""; this.state = "query"; } if (c === 35) { this.url.fragment = ""; this.state = "fragment"; } } else { // TODO: If c is not a URL code point and not "%", parse error. if (c === 37 && (!isASCIIHex(this.input[this.pointer + 1]) || !isASCIIHex(this.input[this.pointer + 2]))) { this.parseError = true; } this.buffer += percentEncodeChar(c, isPathPercentEncode); } return true; }; URLStateMachine.prototype["parse cannot-be-a-base-URL path"] = function parseCannotBeABaseURLPath(c) { if (c === 63) { this.url.query = ""; this.state = "query"; } else if (c === 35) { this.url.fragment = ""; this.state = "fragment"; } else { // TODO: Add: not a URL code point if (!isNaN(c) && c !== 37) { this.parseError = true; } if (c === 37 && (!isASCIIHex(this.input[this.pointer + 1]) || !isASCIIHex(this.input[this.pointer + 2]))) { this.parseError = true; } if (!isNaN(c)) { this.url.path[0] = this.url.path[0] + percentEncodeChar(c, isC0ControlPercentEncode); } } return true; }; URLStateMachine.prototype["parse query"] = function parseQuery(c, cStr) { if (isNaN(c) || (!this.stateOverride && c === 35)) { if (!isSpecial(this.url) || this.url.scheme === "ws" || this.url.scheme === "wss") { this.encodingOverride = "utf-8"; } const buffer = new Buffer(this.buffer); // TODO: Use encoding override instead for (let i = 0; i < buffer.length; ++i) { if (buffer[i] < 0x21 || buffer[i] > 0x7E || buffer[i] === 0x22 || buffer[i] === 0x23 || buffer[i] === 0x3C || buffer[i] === 0x3E) { this.url.query += percentEncode(buffer[i]); } else { this.url.query += String.fromCodePoint(buffer[i]); } } this.buffer = ""; if (c === 35) { this.url.fragment = ""; this.state = "fragment"; } } else { // TODO: If c is not a URL code point and not "%", parse error. if (c === 37 && (!isASCIIHex(this.input[this.pointer + 1]) || !isASCIIHex(this.input[this.pointer + 2]))) { this.parseError = true; } this.buffer += cStr; } return true; }; URLStateMachine.prototype["parse fragment"] = function parseFragment(c) { if (isNaN(c)) { // do nothing } else if (c === 0x0) { this.parseError = true; } else { // TODO: If c is not a URL code point and not "%", parse error. if (c === 37 && (!isASCIIHex(this.input[this.pointer + 1]) || !isASCIIHex(this.input[this.pointer + 2]))) { this.parseError = true; } this.url.fragment += percentEncodeChar(c, isC0ControlPercentEncode); } return true; }; function serializeURL(url, excludeFragment) { let output = url.scheme + ":"; if (url.host !== null) { output += "//"; if (url.username !== "" || url.password !== "") { output += url.username; if (url.password !== "") { output += ":" + url.password; } output += "@"; } output += serializeHost(url.host); if (url.port !== null) { output += ":" + url.port; } } else if (url.host === null && url.scheme === "file") { output += "//"; } if (url.cannotBeABaseURL) { output += url.path[0]; } else { for (const string of url.path) { output += "/" + string; } } if (url.query !== null) { output += "?" + url.query; } if (!excludeFragment && url.fragment !== null) { output += "#" + url.fragment; } return output; } function serializeOrigin(tuple) { let result = tuple.scheme + "://"; result += serializeHost(tuple.host); if (tuple.port !== null) { result += ":" + tuple.port; } return result; } module.exports.serializeURL = serializeURL; module.exports.serializeURLOrigin = function (url) { // https://url.spec.whatwg.org/#concept-url-origin switch (url.scheme) { case "blob": try { return module.exports.serializeURLOrigin(module.exports.parseURL(url.path[0])); } catch (e) { // serializing an opaque origin returns "null" return "null"; } case "ftp": case "gopher": case "http": case "https": case "ws": case "wss": return serializeOrigin({ scheme: url.scheme, host: url.host, port: url.port }); case "file": // spec says "exercise to the reader", chrome says "file://" return "file://"; default: // serializing an opaque origin returns "null" return "null"; } }; module.exports.basicURLParse = function (input, options) { if (options === undefined) { options = {}; } const usm = new URLStateMachine(input, options.baseURL, options.encodingOverride, options.url, options.stateOverride); if (usm.failure) { return "failure"; } return usm.url; }; module.exports.setTheUsername = function (url, username) { url.username = ""; const decoded = punycode.ucs2.decode(username); for (let i = 0; i < decoded.length; ++i) { url.username += percentEncodeChar(decoded[i], isUserinfoPercentEncode); } }; module.exports.setThePassword = function (url, password) { url.password = ""; const decoded = punycode.ucs2.decode(password); for (let i = 0; i < decoded.length; ++i) { url.password += percentEncodeChar(decoded[i], isUserinfoPercentEncode); } }; module.exports.serializeHost = serializeHost; module.exports.cannotHaveAUsernamePasswordPort = cannotHaveAUsernamePasswordPort; module.exports.serializeInteger = function (integer) { return String(integer); }; module.exports.parseURL = function (input, options) { if (options === undefined) { options = {}; } // We don't handle blobs, so this just delegates: return module.exports.basicURLParse(input, { baseURL: options.baseURL, encodingOverride: options.encodingOverride }); }; /***/ }), /***/ 60276: /***/ ((module) => { "use strict"; module.exports.mixin = function mixin(target, source) { const keys = Object.getOwnPropertyNames(source); for (let i = 0; i < keys.length; ++i) { Object.defineProperty(target, keys[i], Object.getOwnPropertyDescriptor(source, keys[i])); } }; module.exports.wrapperSymbol = Symbol("wrapper"); module.exports.implSymbol = Symbol("impl"); module.exports.wrapperForImpl = function (impl) { return impl[module.exports.wrapperSymbol]; }; module.exports.implForWrapper = function (wrapper) { return wrapper[module.exports.implSymbol]; }; /***/ }), /***/ 20502: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const path = __nccwpck_require__(71017); const pathKey = __nccwpck_require__(20539); const npmRunPath = options => { options = { cwd: process.cwd(), path: process.env[pathKey()], execPath: process.execPath, ...options }; let previous; let cwdPath = path.resolve(options.cwd); const result = []; while (previous !== cwdPath) { result.push(path.join(cwdPath, 'node_modules/.bin')); previous = cwdPath; cwdPath = path.resolve(cwdPath, '..'); } // Ensure the running `node` binary is used const execPathDir = path.resolve(options.cwd, options.execPath, '..'); result.push(execPathDir); return result.concat(options.path).join(path.delimiter); }; module.exports = npmRunPath; // TODO: Remove this for the next major release module.exports["default"] = npmRunPath; module.exports.env = options => { options = { env: process.env, ...options }; const env = {...options.env}; const path = pathKey({env}); options.path = env[path]; env[path] = module.exports(options); return env; }; /***/ }), /***/ 43248: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { var crypto = __nccwpck_require__(6113) function sha (key, body, algorithm) { return crypto.createHmac(algorithm, key).update(body).digest('base64') } function rsa (key, body) { return crypto.createSign('RSA-SHA1').update(body).sign(key, 'base64') } function rfc3986 (str) { return encodeURIComponent(str) .replace(/!/g,'%21') .replace(/\*/g,'%2A') .replace(/\(/g,'%28') .replace(/\)/g,'%29') .replace(/'/g,'%27') } // Maps object to bi-dimensional array // Converts { foo: 'A', bar: [ 'b', 'B' ]} to // [ ['foo', 'A'], ['bar', 'b'], ['bar', 'B'] ] function map (obj) { var key, val, arr = [] for (key in obj) { val = obj[key] if (Array.isArray(val)) for (var i = 0; i < val.length; i++) arr.push([key, val[i]]) else if (typeof val === 'object') for (var prop in val) arr.push([key + '[' + prop + ']', val[prop]]) else arr.push([key, val]) } return arr } // Compare function for sort function compare (a, b) { return a > b ? 1 : a < b ? -1 : 0 } function generateBase (httpMethod, base_uri, params) { // adapted from https://dev.twitter.com/docs/auth/oauth and // https://dev.twitter.com/docs/auth/creating-signature // Parameter normalization // http://tools.ietf.org/html/rfc5849#section-3.4.1.3.2 var normalized = map(params) // 1. First, the name and value of each parameter are encoded .map(function (p) { return [ rfc3986(p[0]), rfc3986(p[1] || '') ] }) // 2. The parameters are sorted by name, using ascending byte value // ordering. If two or more parameters share the same name, they // are sorted by their value. .sort(function (a, b) { return compare(a[0], b[0]) || compare(a[1], b[1]) }) // 3. The name of each parameter is concatenated to its corresponding // value using an "=" character (ASCII code 61) as a separator, even // if the value is empty. .map(function (p) { return p.join('=') }) // 4. The sorted name/value pairs are concatenated together into a // single string by using an "&" character (ASCII code 38) as // separator. .join('&') var base = [ rfc3986(httpMethod ? httpMethod.toUpperCase() : 'GET'), rfc3986(base_uri), rfc3986(normalized) ].join('&') return base } function hmacsign (httpMethod, base_uri, params, consumer_secret, token_secret) { var base = generateBase(httpMethod, base_uri, params) var key = [ consumer_secret || '', token_secret || '' ].map(rfc3986).join('&') return sha(key, base, 'sha1') } function hmacsign256 (httpMethod, base_uri, params, consumer_secret, token_secret) { var base = generateBase(httpMethod, base_uri, params) var key = [ consumer_secret || '', token_secret || '' ].map(rfc3986).join('&') return sha(key, base, 'sha256') } function rsasign (httpMethod, base_uri, params, private_key, token_secret) { var base = generateBase(httpMethod, base_uri, params) var key = private_key || '' return rsa(key, base) } function plaintext (consumer_secret, token_secret) { var key = [ consumer_secret || '', token_secret || '' ].map(rfc3986).join('&') return key } function sign (signMethod, httpMethod, base_uri, params, consumer_secret, token_secret) { var method var skipArgs = 1 switch (signMethod) { case 'RSA-SHA1': method = rsasign break case 'HMAC-SHA1': method = hmacsign break case 'HMAC-SHA256': method = hmacsign256 break case 'PLAINTEXT': method = plaintext skipArgs = 4 break default: throw new Error('Signature method not supported: ' + signMethod) } return method.apply(null, [].slice.call(arguments, skipArgs)) } exports.hmacsign = hmacsign exports.hmacsign256 = hmacsign256 exports.rsasign = rsasign exports.plaintext = plaintext exports.sign = sign exports.rfc3986 = rfc3986 exports.generateBase = generateBase /***/ }), /***/ 24856: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; var crypto = __nccwpck_require__(6113); /** * Exported function * * Options: * * - `algorithm` hash algo to be used by this instance: *'sha1', 'md5' * - `excludeValues` {true|*false} hash object keys, values ignored * - `encoding` hash encoding, supports 'buffer', '*hex', 'binary', 'base64' * - `ignoreUnknown` {true|*false} ignore unknown object types * - `replacer` optional function that replaces values before hashing * - `respectFunctionProperties` {*true|false} consider function properties when hashing * - `respectFunctionNames` {*true|false} consider 'name' property of functions for hashing * - `respectType` {*true|false} Respect special properties (prototype, constructor) * when hashing to distinguish between types * - `unorderedArrays` {true|*false} Sort all arrays before hashing * - `unorderedSets` {*true|false} Sort `Set` and `Map` instances before hashing * * = default * * @param {object} object value to hash * @param {object} options hashing options * @return {string} hash value * @api public */ exports = module.exports = objectHash; function objectHash(object, options){ options = applyDefaults(object, options); return hash(object, options); } /** * Exported sugar methods * * @param {object} object value to hash * @return {string} hash value * @api public */ exports.sha1 = function(object){ return objectHash(object); }; exports.keys = function(object){ return objectHash(object, {excludeValues: true, algorithm: 'sha1', encoding: 'hex'}); }; exports.MD5 = function(object){ return objectHash(object, {algorithm: 'md5', encoding: 'hex'}); }; exports.keysMD5 = function(object){ return objectHash(object, {algorithm: 'md5', encoding: 'hex', excludeValues: true}); }; // Internals var hashes = crypto.getHashes ? crypto.getHashes().slice() : ['sha1', 'md5']; hashes.push('passthrough'); var encodings = ['buffer', 'hex', 'binary', 'base64']; function applyDefaults(object, sourceOptions){ sourceOptions = sourceOptions || {}; // create a copy rather than mutating var options = {}; options.algorithm = sourceOptions.algorithm || 'sha1'; options.encoding = sourceOptions.encoding || 'hex'; options.excludeValues = sourceOptions.excludeValues ? true : false; options.algorithm = options.algorithm.toLowerCase(); options.encoding = options.encoding.toLowerCase(); options.ignoreUnknown = sourceOptions.ignoreUnknown !== true ? false : true; // default to false options.respectType = sourceOptions.respectType === false ? false : true; // default to true options.respectFunctionNames = sourceOptions.respectFunctionNames === false ? false : true; options.respectFunctionProperties = sourceOptions.respectFunctionProperties === false ? false : true; options.unorderedArrays = sourceOptions.unorderedArrays !== true ? false : true; // default to false options.unorderedSets = sourceOptions.unorderedSets === false ? false : true; // default to false options.unorderedObjects = sourceOptions.unorderedObjects === false ? false : true; // default to true options.replacer = sourceOptions.replacer || undefined; options.excludeKeys = sourceOptions.excludeKeys || undefined; if(typeof object === 'undefined') { throw new Error('Object argument required.'); } // if there is a case-insensitive match in the hashes list, accept it // (i.e. SHA256 for sha256) for (var i = 0; i < hashes.length; ++i) { if (hashes[i].toLowerCase() === options.algorithm.toLowerCase()) { options.algorithm = hashes[i]; } } if(hashes.indexOf(options.algorithm) === -1){ throw new Error('Algorithm "' + options.algorithm + '" not supported. ' + 'supported values: ' + hashes.join(', ')); } if(encodings.indexOf(options.encoding) === -1 && options.algorithm !== 'passthrough'){ throw new Error('Encoding "' + options.encoding + '" not supported. ' + 'supported values: ' + encodings.join(', ')); } return options; } /** Check if the given function is a native function */ function isNativeFunction(f) { if ((typeof f) !== 'function') { return false; } var exp = /^function\s+\w*\s*\(\s*\)\s*{\s+\[native code\]\s+}$/i; return exp.exec(Function.prototype.toString.call(f)) != null; } function hash(object, options) { var hashingStream; if (options.algorithm !== 'passthrough') { hashingStream = crypto.createHash(options.algorithm); } else { hashingStream = new PassThrough(); } if (typeof hashingStream.write === 'undefined') { hashingStream.write = hashingStream.update; hashingStream.end = hashingStream.update; } var hasher = typeHasher(options, hashingStream); hasher.dispatch(object); if (!hashingStream.update) { hashingStream.end(''); } if (hashingStream.digest) { return hashingStream.digest(options.encoding === 'buffer' ? undefined : options.encoding); } var buf = hashingStream.read(); if (options.encoding === 'buffer') { return buf; } return buf.toString(options.encoding); } /** * Expose streaming API * * @param {object} object Value to serialize * @param {object} options Options, as for hash() * @param {object} stream A stream to write the serializiation to * @api public */ exports.writeToStream = function(object, options, stream) { if (typeof stream === 'undefined') { stream = options; options = {}; } options = applyDefaults(object, options); return typeHasher(options, stream).dispatch(object); }; function typeHasher(options, writeTo, context){ context = context || []; var write = function(str) { if (writeTo.update) { return writeTo.update(str, 'utf8'); } else { return writeTo.write(str, 'utf8'); } }; return { dispatch: function(value){ if (options.replacer) { value = options.replacer(value); } var type = typeof value; if (value === null) { type = 'null'; } //console.log("[DEBUG] Dispatch: ", value, "->", type, " -> ", "_" + type); return this['_' + type](value); }, _object: function(object) { var pattern = (/\[object (.*)\]/i); var objString = Object.prototype.toString.call(object); var objType = pattern.exec(objString); if (!objType) { // object type did not match [object ...] objType = 'unknown:[' + objString + ']'; } else { objType = objType[1]; // take only the class name } objType = objType.toLowerCase(); var objectNumber = null; if ((objectNumber = context.indexOf(object)) >= 0) { return this.dispatch('[CIRCULAR:' + objectNumber + ']'); } else { context.push(object); } if (typeof Buffer !== 'undefined' && Buffer.isBuffer && Buffer.isBuffer(object)) { write('buffer:'); return write(object); } if(objType !== 'object' && objType !== 'function' && objType !== 'asyncfunction') { if(this['_' + objType]) { this['_' + objType](object); } else if (options.ignoreUnknown) { return write('[' + objType + ']'); } else { throw new Error('Unknown object type "' + objType + '"'); } }else{ var keys = Object.keys(object); if (options.unorderedObjects) { keys = keys.sort(); } // Make sure to incorporate special properties, so // Types with different prototypes will produce // a different hash and objects derived from // different functions (`new Foo`, `new Bar`) will // produce different hashes. // We never do this for native functions since some // seem to break because of that. if (options.respectType !== false && !isNativeFunction(object)) { keys.splice(0, 0, 'prototype', '__proto__', 'constructor'); } if (options.excludeKeys) { keys = keys.filter(function(key) { return !options.excludeKeys(key); }); } write('object:' + keys.length + ':'); var self = this; return keys.forEach(function(key){ self.dispatch(key); write(':'); if(!options.excludeValues) { self.dispatch(object[key]); } write(','); }); } }, _array: function(arr, unordered){ unordered = typeof unordered !== 'undefined' ? unordered : options.unorderedArrays !== false; // default to options.unorderedArrays var self = this; write('array:' + arr.length + ':'); if (!unordered || arr.length <= 1) { return arr.forEach(function(entry) { return self.dispatch(entry); }); } // the unordered case is a little more complicated: // since there is no canonical ordering on objects, // i.e. {a:1} < {a:2} and {a:1} > {a:2} are both false, // we first serialize each entry using a PassThrough stream // before sorting. // also: we can’t use the same context array for all entries // since the order of hashing should *not* matter. instead, // we keep track of the additions to a copy of the context array // and add all of them to the global context array when we’re done var contextAdditions = []; var entries = arr.map(function(entry) { var strm = new PassThrough(); var localContext = context.slice(); // make copy var hasher = typeHasher(options, strm, localContext); hasher.dispatch(entry); // take only what was added to localContext and append it to contextAdditions contextAdditions = contextAdditions.concat(localContext.slice(context.length)); return strm.read().toString(); }); context = context.concat(contextAdditions); entries.sort(); return this._array(entries, false); }, _date: function(date){ return write('date:' + date.toJSON()); }, _symbol: function(sym){ return write('symbol:' + sym.toString()); }, _error: function(err){ return write('error:' + err.toString()); }, _boolean: function(bool){ return write('bool:' + bool.toString()); }, _string: function(string){ write('string:' + string.length + ':'); write(string.toString()); }, _function: function(fn){ write('fn:'); if (isNativeFunction(fn)) { this.dispatch('[native]'); } else { this.dispatch(fn.toString()); } if (options.respectFunctionNames !== false) { // Make sure we can still distinguish native functions // by their name, otherwise String and Function will // have the same hash this.dispatch("function-name:" + String(fn.name)); } if (options.respectFunctionProperties) { this._object(fn); } }, _number: function(number){ return write('number:' + number.toString()); }, _xml: function(xml){ return write('xml:' + xml.toString()); }, _null: function() { return write('Null'); }, _undefined: function() { return write('Undefined'); }, _regexp: function(regex){ return write('regex:' + regex.toString()); }, _uint8array: function(arr){ write('uint8array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _uint8clampedarray: function(arr){ write('uint8clampedarray:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _int8array: function(arr){ write('uint8array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _uint16array: function(arr){ write('uint16array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _int16array: function(arr){ write('uint16array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _uint32array: function(arr){ write('uint32array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _int32array: function(arr){ write('uint32array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _float32array: function(arr){ write('float32array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _float64array: function(arr){ write('float64array:'); return this.dispatch(Array.prototype.slice.call(arr)); }, _arraybuffer: function(arr){ write('arraybuffer:'); return this.dispatch(new Uint8Array(arr)); }, _url: function(url) { return write('url:' + url.toString(), 'utf8'); }, _map: function(map) { write('map:'); var arr = Array.from(map); return this._array(arr, options.unorderedSets !== false); }, _set: function(set) { write('set:'); var arr = Array.from(set); return this._array(arr, options.unorderedSets !== false); }, _file: function(file) { write('file:'); return this.dispatch([file.name, file.size, file.type, file.lastModfied]); }, _blob: function() { if (options.ignoreUnknown) { return write('[blob]'); } throw Error('Hashing Blob objects is currently not supported\n' + '(see https://github.com/puleos/object-hash/issues/26)\n' + 'Use "options.replacer" or "options.ignoreUnknown"\n'); }, _domwindow: function() { return write('domwindow'); }, _bigint: function(number){ return write('bigint:' + number.toString()); }, /* Node.js standard native objects */ _process: function() { return write('process'); }, _timer: function() { return write('timer'); }, _pipe: function() { return write('pipe'); }, _tcp: function() { return write('tcp'); }, _udp: function() { return write('udp'); }, _tty: function() { return write('tty'); }, _statwatcher: function() { return write('statwatcher'); }, _securecontext: function() { return write('securecontext'); }, _connection: function() { return write('connection'); }, _zlib: function() { return write('zlib'); }, _context: function() { return write('context'); }, _nodescript: function() { return write('nodescript'); }, _httpparser: function() { return write('httpparser'); }, _dataview: function() { return write('dataview'); }, _signal: function() { return write('signal'); }, _fsevent: function() { return write('fsevent'); }, _tlswrap: function() { return write('tlswrap'); }, }; } // Mini-implementation of stream.PassThrough // We are far from having need for the full implementation, and we can // make assumptions like "many writes, then only one final read" // and we can ignore encoding specifics function PassThrough() { return { buf: '', write: function(b) { this.buf += b; }, end: function(b) { this.buf += b; }, read: function() { return this.buf; } }; } /***/ }), /***/ 1270: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { strict: assert } = __nccwpck_require__(39491); const { createHash } = __nccwpck_require__(6113); const { format } = __nccwpck_require__(73837); const shake256 = __nccwpck_require__(19811); let encode; if (Buffer.isEncoding('base64url')) { encode = (input) => input.toString('base64url'); } else { const fromBase64 = (base64) => base64.replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_'); encode = (input) => fromBase64(input.toString('base64')); } /** SPECIFICATION * Its (_hash) value is the base64url encoding of the left-most half of the hash of the octets of * the ASCII representation of the token value, where the hash algorithm used is the hash algorithm * used in the alg Header Parameter of the ID Token's JOSE Header. For instance, if the alg is * RS256, hash the token value with SHA-256, then take the left-most 128 bits and base64url encode * them. The _hash value is a case sensitive string. */ /** * @name getHash * @api private * * returns the sha length based off the JOSE alg heade value, defaults to sha256 * * @param token {String} token value to generate the hash from * @param alg {String} ID Token JOSE header alg value (i.e. RS256, HS384, ES512, PS256) * @param [crv] {String} For EdDSA the curve decides what hash algorithm is used. Required for EdDSA */ function getHash(alg, crv) { switch (alg) { case 'HS256': case 'RS256': case 'PS256': case 'ES256': case 'ES256K': return createHash('sha256'); case 'HS384': case 'RS384': case 'PS384': case 'ES384': return createHash('sha384'); case 'HS512': case 'RS512': case 'PS512': case 'ES512': return createHash('sha512'); case 'EdDSA': switch (crv) { case 'Ed25519': return createHash('sha512'); case 'Ed448': if (!shake256) { throw new TypeError('Ed448 *_hash calculation is not supported in your Node.js runtime version'); } return createHash('shake256', { outputLength: 114 }); default: throw new TypeError('unrecognized or invalid EdDSA curve provided'); } default: throw new TypeError('unrecognized or invalid JWS algorithm provided'); } } function generate(token, alg, crv) { const digest = getHash(alg, crv).update(token).digest(); return encode(digest.slice(0, digest.length / 2)); } function validate(names, actual, source, alg, crv) { if (typeof names.claim !== 'string' || !names.claim) { throw new TypeError('names.claim must be a non-empty string'); } if (typeof names.source !== 'string' || !names.source) { throw new TypeError('names.source must be a non-empty string'); } assert(typeof actual === 'string' && actual, `${names.claim} must be a non-empty string`); assert(typeof source === 'string' && source, `${names.source} must be a non-empty string`); let expected; let msg; try { expected = generate(source, alg, crv); } catch (err) { msg = format('%s could not be validated (%s)', names.claim, err.message); } msg = msg || format('%s mismatch, expected %s, got: %s', names.claim, expected, actual); assert.equal(expected, actual, msg); } module.exports = { validate, generate, }; /***/ }), /***/ 19811: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const crypto = __nccwpck_require__(6113); const [major, minor] = process.version.substring(1).split('.').map((x) => parseInt(x, 10)); const xofOutputLength = major > 12 || (major === 12 && minor >= 8); const shake256 = xofOutputLength && crypto.getHashes().includes('shake256'); module.exports = shake256; /***/ }), /***/ 1223: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var wrappy = __nccwpck_require__(62940) module.exports = wrappy(once) module.exports.strict = wrappy(onceStrict) once.proto = once(function () { Object.defineProperty(Function.prototype, 'once', { value: function () { return once(this) }, configurable: true }) Object.defineProperty(Function.prototype, 'onceStrict', { value: function () { return onceStrict(this) }, configurable: true }) }) function once (fn) { var f = function () { if (f.called) return f.value f.called = true return f.value = fn.apply(this, arguments) } f.called = false return f } function onceStrict (fn) { var f = function () { if (f.called) throw new Error(f.onceError) f.called = true return f.value = fn.apply(this, arguments) } var name = fn.name || 'Function wrapped with `once`' f.onceError = name + " shouldn't be called more than once" f.called = false return f } /***/ }), /***/ 89082: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const mimicFn = __nccwpck_require__(76047); const calledFunctions = new WeakMap(); const onetime = (function_, options = {}) => { if (typeof function_ !== 'function') { throw new TypeError('Expected a function'); } let returnValue; let callCount = 0; const functionName = function_.displayName || function_.name || ''; const onetime = function (...arguments_) { calledFunctions.set(onetime, ++callCount); if (callCount === 1) { returnValue = function_.apply(this, arguments_); function_ = null; } else if (options.throw === true) { throw new Error(`Function \`${functionName}\` can only be called once`); } return returnValue; }; mimicFn(onetime, function_); calledFunctions.set(onetime, callCount); return onetime; }; module.exports = onetime; // TODO: Remove this for the next major release module.exports["default"] = onetime; module.exports.callCount = function_ => { if (!calledFunctions.has(function_)) { throw new Error(`The given function \`${function_.name}\` is not wrapped by the \`onetime\` package`); } return calledFunctions.get(function_); }; /***/ }), /***/ 19072: /***/ ((module) => { "use strict"; class CancelError extends Error { constructor(reason) { super(reason || 'Promise was canceled'); this.name = 'CancelError'; } get isCanceled() { return true; } } class PCancelable { static fn(userFn) { return (...arguments_) => { return new PCancelable((resolve, reject, onCancel) => { arguments_.push(onCancel); // eslint-disable-next-line promise/prefer-await-to-then userFn(...arguments_).then(resolve, reject); }); }; } constructor(executor) { this._cancelHandlers = []; this._isPending = true; this._isCanceled = false; this._rejectOnCancel = true; this._promise = new Promise((resolve, reject) => { this._reject = reject; const onResolve = value => { if (!this._isCanceled || !onCancel.shouldReject) { this._isPending = false; resolve(value); } }; const onReject = error => { this._isPending = false; reject(error); }; const onCancel = handler => { if (!this._isPending) { throw new Error('The `onCancel` handler was attached after the promise settled.'); } this._cancelHandlers.push(handler); }; Object.defineProperties(onCancel, { shouldReject: { get: () => this._rejectOnCancel, set: boolean => { this._rejectOnCancel = boolean; } } }); return executor(onResolve, onReject, onCancel); }); } then(onFulfilled, onRejected) { // eslint-disable-next-line promise/prefer-await-to-then return this._promise.then(onFulfilled, onRejected); } catch(onRejected) { return this._promise.catch(onRejected); } finally(onFinally) { return this._promise.finally(onFinally); } cancel(reason) { if (!this._isPending || this._isCanceled) { return; } this._isCanceled = true; if (this._cancelHandlers.length > 0) { try { for (const handler of this._cancelHandlers) { handler(); } } catch (error) { this._reject(error); return; } } if (this._rejectOnCancel) { this._reject(new CancelError(reason)); } } get isCanceled() { return this._isCanceled; } } Object.setPrototypeOf(PCancelable.prototype, Promise.prototype); module.exports = PCancelable; module.exports.CancelError = CancelError; /***/ }), /***/ 38714: /***/ ((module) => { "use strict"; function posix(path) { return path.charAt(0) === '/'; } function win32(path) { // https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56 var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/; var result = splitDeviceRe.exec(path); var device = result[1] || ''; var isUnc = Boolean(device && device.charAt(1) !== ':'); // UNC paths are always absolute return Boolean(result[2] || isUnc); } module.exports = process.platform === 'win32' ? win32 : posix; module.exports.posix = posix; module.exports.win32 = win32; /***/ }), /***/ 20539: /***/ ((module) => { "use strict"; const pathKey = (options = {}) => { const environment = options.env || process.env; const platform = options.platform || process.platform; if (platform !== 'win32') { return 'PATH'; } return Object.keys(environment).reverse().find(key => key.toUpperCase() === 'PATH') || 'Path'; }; module.exports = pathKey; // TODO: Remove this for the next major release module.exports["default"] = pathKey; /***/ }), /***/ 85644: /***/ (function(module) { // Generated by CoffeeScript 1.12.2 (function() { var getNanoSeconds, hrtime, loadTime, moduleLoadTime, nodeLoadTime, upTime; if ((typeof performance !== "undefined" && performance !== null) && performance.now) { module.exports = function() { return performance.now(); }; } else if ((typeof process !== "undefined" && process !== null) && process.hrtime) { module.exports = function() { return (getNanoSeconds() - nodeLoadTime) / 1e6; }; hrtime = process.hrtime; getNanoSeconds = function() { var hr; hr = hrtime(); return hr[0] * 1e9 + hr[1]; }; moduleLoadTime = getNanoSeconds(); upTime = process.uptime() * 1e9; nodeLoadTime = moduleLoadTime - upTime; } else if (Date.now) { module.exports = function() { return Date.now() - loadTime; }; loadTime = Date.now(); } else { module.exports = function() { return new Date().getTime() - loadTime; }; loadTime = new Date().getTime(); } }).call(this); //# sourceMappingURL=performance-now.js.map /***/ }), /***/ 29975: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /*eslint no-var:0, prefer-arrow-callback: 0, object-shorthand: 0 */ var Punycode = __nccwpck_require__(85477); var internals = {}; // // Read rules from file. // internals.rules = (__nccwpck_require__(3704).map)(function (rule) { return { rule: rule, suffix: rule.replace(/^(\*\.|\!)/, ''), punySuffix: -1, wildcard: rule.charAt(0) === '*', exception: rule.charAt(0) === '!' }; }); // // Check is given string ends with `suffix`. // internals.endsWith = function (str, suffix) { return str.indexOf(suffix, str.length - suffix.length) !== -1; }; // // Find rule for a given domain. // internals.findRule = function (domain) { var punyDomain = Punycode.toASCII(domain); return internals.rules.reduce(function (memo, rule) { if (rule.punySuffix === -1){ rule.punySuffix = Punycode.toASCII(rule.suffix); } if (!internals.endsWith(punyDomain, '.' + rule.punySuffix) && punyDomain !== rule.punySuffix) { return memo; } // This has been commented out as it never seems to run. This is because // sub tlds always appear after their parents and we never find a shorter // match. //if (memo) { // var memoSuffix = Punycode.toASCII(memo.suffix); // if (memoSuffix.length >= punySuffix.length) { // return memo; // } //} return rule; }, null); }; // // Error codes and messages. // exports.errorCodes = { DOMAIN_TOO_SHORT: 'Domain name too short.', DOMAIN_TOO_LONG: 'Domain name too long. It should be no more than 255 chars.', LABEL_STARTS_WITH_DASH: 'Domain name label can not start with a dash.', LABEL_ENDS_WITH_DASH: 'Domain name label can not end with a dash.', LABEL_TOO_LONG: 'Domain name label should be at most 63 chars long.', LABEL_TOO_SHORT: 'Domain name label should be at least 1 character long.', LABEL_INVALID_CHARS: 'Domain name label can only contain alphanumeric characters or dashes.' }; // // Validate domain name and throw if not valid. // // From wikipedia: // // Hostnames are composed of series of labels concatenated with dots, as are all // domain names. Each label must be between 1 and 63 characters long, and the // entire hostname (including the delimiting dots) has a maximum of 255 chars. // // Allowed chars: // // * `a-z` // * `0-9` // * `-` but not as a starting or ending character // * `.` as a separator for the textual portions of a domain name // // * http://en.wikipedia.org/wiki/Domain_name // * http://en.wikipedia.org/wiki/Hostname // internals.validate = function (input) { // Before we can validate we need to take care of IDNs with unicode chars. var ascii = Punycode.toASCII(input); if (ascii.length < 1) { return 'DOMAIN_TOO_SHORT'; } if (ascii.length > 255) { return 'DOMAIN_TOO_LONG'; } // Check each part's length and allowed chars. var labels = ascii.split('.'); var label; for (var i = 0; i < labels.length; ++i) { label = labels[i]; if (!label.length) { return 'LABEL_TOO_SHORT'; } if (label.length > 63) { return 'LABEL_TOO_LONG'; } if (label.charAt(0) === '-') { return 'LABEL_STARTS_WITH_DASH'; } if (label.charAt(label.length - 1) === '-') { return 'LABEL_ENDS_WITH_DASH'; } if (!/^[a-z0-9\-]+$/.test(label)) { return 'LABEL_INVALID_CHARS'; } } }; // // Public API // // // Parse domain. // exports.parse = function (input) { if (typeof input !== 'string') { throw new TypeError('Domain name must be a string.'); } // Force domain to lowercase. var domain = input.slice(0).toLowerCase(); // Handle FQDN. // TODO: Simply remove trailing dot? if (domain.charAt(domain.length - 1) === '.') { domain = domain.slice(0, domain.length - 1); } // Validate and sanitise input. var error = internals.validate(domain); if (error) { return { input: input, error: { message: exports.errorCodes[error], code: error } }; } var parsed = { input: input, tld: null, sld: null, domain: null, subdomain: null, listed: false }; var domainParts = domain.split('.'); // Non-Internet TLD if (domainParts[domainParts.length - 1] === 'local') { return parsed; } var handlePunycode = function () { if (!/xn--/.test(domain)) { return parsed; } if (parsed.domain) { parsed.domain = Punycode.toASCII(parsed.domain); } if (parsed.subdomain) { parsed.subdomain = Punycode.toASCII(parsed.subdomain); } return parsed; }; var rule = internals.findRule(domain); // Unlisted tld. if (!rule) { if (domainParts.length < 2) { return parsed; } parsed.tld = domainParts.pop(); parsed.sld = domainParts.pop(); parsed.domain = [parsed.sld, parsed.tld].join('.'); if (domainParts.length) { parsed.subdomain = domainParts.pop(); } return handlePunycode(); } // At this point we know the public suffix is listed. parsed.listed = true; var tldParts = rule.suffix.split('.'); var privateParts = domainParts.slice(0, domainParts.length - tldParts.length); if (rule.exception) { privateParts.push(tldParts.shift()); } parsed.tld = tldParts.join('.'); if (!privateParts.length) { return handlePunycode(); } if (rule.wildcard) { tldParts.unshift(privateParts.pop()); parsed.tld = tldParts.join('.'); } if (!privateParts.length) { return handlePunycode(); } parsed.sld = privateParts.pop(); parsed.domain = [parsed.sld, parsed.tld].join('.'); if (privateParts.length) { parsed.subdomain = privateParts.join('.'); } return handlePunycode(); }; // // Get domain. // exports.get = function (domain) { if (!domain) { return null; } return exports.parse(domain).domain || null; }; // // Check whether domain belongs to a known public suffix. // exports.isValid = function (domain) { var parsed = exports.parse(domain); return Boolean(parsed.domain && parsed.listed); }; /***/ }), /***/ 18341: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var once = __nccwpck_require__(1223) var eos = __nccwpck_require__(81205) var fs = __nccwpck_require__(57147) // we only need fs to get the ReadStream and WriteStream prototypes var noop = function () {} var ancient = /^v?\.0/.test(process.version) var isFn = function (fn) { return typeof fn === 'function' } var isFS = function (stream) { if (!ancient) return false // newer node version do not need to care about fs is a special way if (!fs) return false // browser return (stream instanceof (fs.ReadStream || noop) || stream instanceof (fs.WriteStream || noop)) && isFn(stream.close) } var isRequest = function (stream) { return stream.setHeader && isFn(stream.abort) } var destroyer = function (stream, reading, writing, callback) { callback = once(callback) var closed = false stream.on('close', function () { closed = true }) eos(stream, {readable: reading, writable: writing}, function (err) { if (err) return callback(err) closed = true callback() }) var destroyed = false return function (err) { if (closed) return if (destroyed) return destroyed = true if (isFS(stream)) return stream.close(noop) // use close for fs streams to avoid fd leaks if (isRequest(stream)) return stream.abort() // request.destroy just do .end - .abort is what we want if (isFn(stream.destroy)) return stream.destroy() callback(err || new Error('stream was destroyed')) } } var call = function (fn) { fn() } var pipe = function (from, to) { return from.pipe(to) } var pump = function () { var streams = Array.prototype.slice.call(arguments) var callback = isFn(streams[streams.length - 1] || noop) && streams.pop() || noop if (Array.isArray(streams[0])) streams = streams[0] if (streams.length < 2) throw new Error('pump requires two streams per minimum') var error var destroys = streams.map(function (stream, i) { var reading = i < streams.length - 1 var writing = i > 0 return destroyer(stream, reading, writing, function (err) { if (!error) error = err if (err) destroys.forEach(call) if (reading) return destroys.forEach(call) callback(error) }) }) return streams.reduce(pipe) } module.exports = pump /***/ }), /***/ 49273: /***/ ((module) => { "use strict"; class QuickLRU { constructor(options = {}) { if (!(options.maxSize && options.maxSize > 0)) { throw new TypeError('`maxSize` must be a number greater than 0'); } this.maxSize = options.maxSize; this.onEviction = options.onEviction; this.cache = new Map(); this.oldCache = new Map(); this._size = 0; } _set(key, value) { this.cache.set(key, value); this._size++; if (this._size >= this.maxSize) { this._size = 0; if (typeof this.onEviction === 'function') { for (const [key, value] of this.oldCache.entries()) { this.onEviction(key, value); } } this.oldCache = this.cache; this.cache = new Map(); } } get(key) { if (this.cache.has(key)) { return this.cache.get(key); } if (this.oldCache.has(key)) { const value = this.oldCache.get(key); this.oldCache.delete(key); this._set(key, value); return value; } } set(key, value) { if (this.cache.has(key)) { this.cache.set(key, value); } else { this._set(key, value); } return this; } has(key) { return this.cache.has(key) || this.oldCache.has(key); } peek(key) { if (this.cache.has(key)) { return this.cache.get(key); } if (this.oldCache.has(key)) { return this.oldCache.get(key); } } delete(key) { const deleted = this.cache.delete(key); if (deleted) { this._size--; } return this.oldCache.delete(key) || deleted; } clear() { this.cache.clear(); this.oldCache.clear(); this._size = 0; } * keys() { for (const [key] of this) { yield key; } } * values() { for (const [, value] of this) { yield value; } } * [Symbol.iterator]() { for (const item of this.cache) { yield item; } for (const item of this.oldCache) { const [key] = item; if (!this.cache.has(key)) { yield item; } } } get size() { let oldCacheSize = 0; for (const key of this.oldCache.keys()) { if (!this.cache.has(key)) { oldCacheSize++; } } return Math.min(this._size + oldCacheSize, this.maxSize); } } module.exports = QuickLRU; /***/ }), /***/ 29977: /***/ (() => { /*! ***************************************************************************** Copyright (C) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ var Reflect; (function (Reflect) { // Metadata Proposal // https://rbuckton.github.io/reflect-metadata/ (function (factory) { var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : Function("return this;")(); var exporter = makeExporter(Reflect); if (typeof root.Reflect === "undefined") { root.Reflect = Reflect; } else { exporter = makeExporter(root.Reflect, exporter); } factory(exporter); function makeExporter(target, previous) { return function (key, value) { if (typeof target[key] !== "function") { Object.defineProperty(target, key, { configurable: true, writable: true, value: value }); } if (previous) previous(key, value); }; } })(function (exporter) { var hasOwn = Object.prototype.hasOwnProperty; // feature test for Symbol support var supportsSymbol = typeof Symbol === "function"; var toPrimitiveSymbol = supportsSymbol && typeof Symbol.toPrimitive !== "undefined" ? Symbol.toPrimitive : "@@toPrimitive"; var iteratorSymbol = supportsSymbol && typeof Symbol.iterator !== "undefined" ? Symbol.iterator : "@@iterator"; var supportsCreate = typeof Object.create === "function"; // feature test for Object.create support var supportsProto = { __proto__: [] } instanceof Array; // feature test for __proto__ support var downLevel = !supportsCreate && !supportsProto; var HashMap = { // create an object in dictionary mode (a.k.a. "slow" mode in v8) create: supportsCreate ? function () { return MakeDictionary(Object.create(null)); } : supportsProto ? function () { return MakeDictionary({ __proto__: null }); } : function () { return MakeDictionary({}); }, has: downLevel ? function (map, key) { return hasOwn.call(map, key); } : function (map, key) { return key in map; }, get: downLevel ? function (map, key) { return hasOwn.call(map, key) ? map[key] : undefined; } : function (map, key) { return map[key]; }, }; // Load global or shim versions of Map, Set, and WeakMap var functionPrototype = Object.getPrototypeOf(Function); var usePolyfill = typeof process === "object" && process.env && process.env["REFLECT_METADATA_USE_MAP_POLYFILL"] === "true"; var _Map = !usePolyfill && typeof Map === "function" && typeof Map.prototype.entries === "function" ? Map : CreateMapPolyfill(); var _Set = !usePolyfill && typeof Set === "function" && typeof Set.prototype.entries === "function" ? Set : CreateSetPolyfill(); var _WeakMap = !usePolyfill && typeof WeakMap === "function" ? WeakMap : CreateWeakMapPolyfill(); // [[Metadata]] internal slot // https://rbuckton.github.io/reflect-metadata/#ordinary-object-internal-methods-and-internal-slots var Metadata = new _WeakMap(); /** * Applies a set of decorators to a property of a target object. * @param decorators An array of decorators. * @param target The target object. * @param propertyKey (Optional) The property key to decorate. * @param attributes (Optional) The property descriptor for the target key. * @remarks Decorators are applied in reverse order. * @example * * class Example { * // property declarations are not part of ES6, though they are valid in TypeScript: * // static staticProperty; * // property; * * constructor(p) { } * static staticMethod(p) { } * method(p) { } * } * * // constructor * Example = Reflect.decorate(decoratorsArray, Example); * * // property (on constructor) * Reflect.decorate(decoratorsArray, Example, "staticProperty"); * * // property (on prototype) * Reflect.decorate(decoratorsArray, Example.prototype, "property"); * * // method (on constructor) * Object.defineProperty(Example, "staticMethod", * Reflect.decorate(decoratorsArray, Example, "staticMethod", * Object.getOwnPropertyDescriptor(Example, "staticMethod"))); * * // method (on prototype) * Object.defineProperty(Example.prototype, "method", * Reflect.decorate(decoratorsArray, Example.prototype, "method", * Object.getOwnPropertyDescriptor(Example.prototype, "method"))); * */ function decorate(decorators, target, propertyKey, attributes) { if (!IsUndefined(propertyKey)) { if (!IsArray(decorators)) throw new TypeError(); if (!IsObject(target)) throw new TypeError(); if (!IsObject(attributes) && !IsUndefined(attributes) && !IsNull(attributes)) throw new TypeError(); if (IsNull(attributes)) attributes = undefined; propertyKey = ToPropertyKey(propertyKey); return DecorateProperty(decorators, target, propertyKey, attributes); } else { if (!IsArray(decorators)) throw new TypeError(); if (!IsConstructor(target)) throw new TypeError(); return DecorateConstructor(decorators, target); } } exporter("decorate", decorate); // 4.1.2 Reflect.metadata(metadataKey, metadataValue) // https://rbuckton.github.io/reflect-metadata/#reflect.metadata /** * A default metadata decorator factory that can be used on a class, class member, or parameter. * @param metadataKey The key for the metadata entry. * @param metadataValue The value for the metadata entry. * @returns A decorator function. * @remarks * If `metadataKey` is already defined for the target and target key, the * metadataValue for that key will be overwritten. * @example * * // constructor * @Reflect.metadata(key, value) * class Example { * } * * // property (on constructor, TypeScript only) * class Example { * @Reflect.metadata(key, value) * static staticProperty; * } * * // property (on prototype, TypeScript only) * class Example { * @Reflect.metadata(key, value) * property; * } * * // method (on constructor) * class Example { * @Reflect.metadata(key, value) * static staticMethod() { } * } * * // method (on prototype) * class Example { * @Reflect.metadata(key, value) * method() { } * } * */ function metadata(metadataKey, metadataValue) { function decorator(target, propertyKey) { if (!IsObject(target)) throw new TypeError(); if (!IsUndefined(propertyKey) && !IsPropertyKey(propertyKey)) throw new TypeError(); OrdinaryDefineOwnMetadata(metadataKey, metadataValue, target, propertyKey); } return decorator; } exporter("metadata", metadata); /** * Define a unique metadata entry on the target. * @param metadataKey A key used to store and retrieve metadata. * @param metadataValue A value that contains attached metadata. * @param target The target object on which to define metadata. * @param propertyKey (Optional) The property key for the target. * @example * * class Example { * // property declarations are not part of ES6, though they are valid in TypeScript: * // static staticProperty; * // property; * * constructor(p) { } * static staticMethod(p) { } * method(p) { } * } * * // constructor * Reflect.defineMetadata("custom:annotation", options, Example); * * // property (on constructor) * Reflect.defineMetadata("custom:annotation", options, Example, "staticProperty"); * * // property (on prototype) * Reflect.defineMetadata("custom:annotation", options, Example.prototype, "property"); * * // method (on constructor) * Reflect.defineMetadata("custom:annotation", options, Example, "staticMethod"); * * // method (on prototype) * Reflect.defineMetadata("custom:annotation", options, Example.prototype, "method"); * * // decorator factory as metadata-producing annotation. * function MyAnnotation(options): Decorator { * return (target, key?) => Reflect.defineMetadata("custom:annotation", options, target, key); * } * */ function defineMetadata(metadataKey, metadataValue, target, propertyKey) { if (!IsObject(target)) throw new TypeError(); if (!IsUndefined(propertyKey)) propertyKey = ToPropertyKey(propertyKey); return OrdinaryDefineOwnMetadata(metadataKey, metadataValue, target, propertyKey); } exporter("defineMetadata", defineMetadata); /** * Gets a value indicating whether the target object or its prototype chain has the provided metadata key defined. * @param metadataKey A key used to store and retrieve metadata. * @param target The target object on which the metadata is defined. * @param propertyKey (Optional) The property key for the target. * @returns `true` if the metadata key was defined on the target object or its prototype chain; otherwise, `false`. * @example * * class Example { * // property declarations are not part of ES6, though they are valid in TypeScript: * // static staticProperty; * // property; * * constructor(p) { } * static staticMethod(p) { } * method(p) { } * } * * // constructor * result = Reflect.hasMetadata("custom:annotation", Example); * * // property (on constructor) * result = Reflect.hasMetadata("custom:annotation", Example, "staticProperty"); * * // property (on prototype) * result = Reflect.hasMetadata("custom:annotation", Example.prototype, "property"); * * // method (on constructor) * result = Reflect.hasMetadata("custom:annotation", Example, "staticMethod"); * * // method (on prototype) * result = Reflect.hasMetadata("custom:annotation", Example.prototype, "method"); * */ function hasMetadata(metadataKey, target, propertyKey) { if (!IsObject(target)) throw new TypeError(); if (!IsUndefined(propertyKey)) propertyKey = ToPropertyKey(propertyKey); return OrdinaryHasMetadata(metadataKey, target, propertyKey); } exporter("hasMetadata", hasMetadata); /** * Gets a value indicating whether the target object has the provided metadata key defined. * @param metadataKey A key used to store and retrieve metadata. * @param target The target object on which the metadata is defined. * @param propertyKey (Optional) The property key for the target. * @returns `true` if the metadata key was defined on the target object; otherwise, `false`. * @example * * class Example { * // property declarations are not part of ES6, though they are valid in TypeScript: * // static staticProperty; * // property; * * constructor(p) { } * static staticMethod(p) { } * method(p) { } * } * * // constructor * result = Reflect.hasOwnMetadata("custom:annotation", Example); * * // property (on constructor) * result = Reflect.hasOwnMetadata("custom:annotation", Example, "staticProperty"); * * // property (on prototype) * result = Reflect.hasOwnMetadata("custom:annotation", Example.prototype, "property"); * * // method (on constructor) * result = Reflect.hasOwnMetadata("custom:annotation", Example, "staticMethod"); * * // method (on prototype) * result = Reflect.hasOwnMetadata("custom:annotation", Example.prototype, "method"); * */ function hasOwnMetadata(metadataKey, target, propertyKey) { if (!IsObject(target)) throw new TypeError(); if (!IsUndefined(propertyKey)) propertyKey = ToPropertyKey(propertyKey); return OrdinaryHasOwnMetadata(metadataKey, target, propertyKey); } exporter("hasOwnMetadata", hasOwnMetadata); /** * Gets the metadata value for the provided metadata key on the target object or its prototype chain. * @param metadataKey A key used to store and retrieve metadata. * @param target The target object on which the metadata is defined. * @param propertyKey (Optional) The property key for the target. * @returns The metadata value for the metadata key if found; otherwise, `undefined`. * @example * * class Example { * // property declarations are not part of ES6, though they are valid in TypeScript: * // static staticProperty; * // property; * * constructor(p) { } * static staticMethod(p) { } * method(p) { } * } * * // constructor * result = Reflect.getMetadata("custom:annotation", Example); * * // property (on constructor) * result = Reflect.getMetadata("custom:annotation", Example, "staticProperty"); * * // property (on prototype) * result = Reflect.getMetadata("custom:annotation", Example.prototype, "property"); * * // method (on constructor) * result = Reflect.getMetadata("custom:annotation", Example, "staticMethod"); * * // method (on prototype) * result = Reflect.getMetadata("custom:annotation", Example.prototype, "method"); * */ function getMetadata(metadataKey, target, propertyKey) { if (!IsObject(target)) throw new TypeError(); if (!IsUndefined(propertyKey)) propertyKey = ToPropertyKey(propertyKey); return OrdinaryGetMetadata(metadataKey, target, propertyKey); } exporter("getMetadata", getMetadata); /** * Gets the metadata value for the provided metadata key on the target object. * @param metadataKey A key used to store and retrieve metadata. * @param target The target object on which the metadata is defined. * @param propertyKey (Optional) The property key for the target. * @returns The metadata value for the metadata key if found; otherwise, `undefined`. * @example * * class Example { * // property declarations are not part of ES6, though they are valid in TypeScript: * // static staticProperty; * // property; * * constructor(p) { } * static staticMethod(p) { } * method(p) { } * } * * // constructor * result = Reflect.getOwnMetadata("custom:annotation", Example); * * // property (on constructor) * result = Reflect.getOwnMetadata("custom:annotation", Example, "staticProperty"); * * // property (on prototype) * result = Reflect.getOwnMetadata("custom:annotation", Example.prototype, "property"); * * // method (on constructor) * result = Reflect.getOwnMetadata("custom:annotation", Example, "staticMethod"); * * // method (on prototype) * result = Reflect.getOwnMetadata("custom:annotation", Example.prototype, "method"); * */ function getOwnMetadata(metadataKey, target, propertyKey) { if (!IsObject(target)) throw new TypeError(); if (!IsUndefined(propertyKey)) propertyKey = ToPropertyKey(propertyKey); return OrdinaryGetOwnMetadata(metadataKey, target, propertyKey); } exporter("getOwnMetadata", getOwnMetadata); /** * Gets the metadata keys defined on the target object or its prototype chain. * @param target The target object on which the metadata is defined. * @param propertyKey (Optional) The property key for the target. * @returns An array of unique metadata keys. * @example * * class Example { * // property declarations are not part of ES6, though they are valid in TypeScript: * // static staticProperty; * // property; * * constructor(p) { } * static staticMethod(p) { } * method(p) { } * } * * // constructor * result = Reflect.getMetadataKeys(Example); * * // property (on constructor) * result = Reflect.getMetadataKeys(Example, "staticProperty"); * * // property (on prototype) * result = Reflect.getMetadataKeys(Example.prototype, "property"); * * // method (on constructor) * result = Reflect.getMetadataKeys(Example, "staticMethod"); * * // method (on prototype) * result = Reflect.getMetadataKeys(Example.prototype, "method"); * */ function getMetadataKeys(target, propertyKey) { if (!IsObject(target)) throw new TypeError(); if (!IsUndefined(propertyKey)) propertyKey = ToPropertyKey(propertyKey); return OrdinaryMetadataKeys(target, propertyKey); } exporter("getMetadataKeys", getMetadataKeys); /** * Gets the unique metadata keys defined on the target object. * @param target The target object on which the metadata is defined. * @param propertyKey (Optional) The property key for the target. * @returns An array of unique metadata keys. * @example * * class Example { * // property declarations are not part of ES6, though they are valid in TypeScript: * // static staticProperty; * // property; * * constructor(p) { } * static staticMethod(p) { } * method(p) { } * } * * // constructor * result = Reflect.getOwnMetadataKeys(Example); * * // property (on constructor) * result = Reflect.getOwnMetadataKeys(Example, "staticProperty"); * * // property (on prototype) * result = Reflect.getOwnMetadataKeys(Example.prototype, "property"); * * // method (on constructor) * result = Reflect.getOwnMetadataKeys(Example, "staticMethod"); * * // method (on prototype) * result = Reflect.getOwnMetadataKeys(Example.prototype, "method"); * */ function getOwnMetadataKeys(target, propertyKey) { if (!IsObject(target)) throw new TypeError(); if (!IsUndefined(propertyKey)) propertyKey = ToPropertyKey(propertyKey); return OrdinaryOwnMetadataKeys(target, propertyKey); } exporter("getOwnMetadataKeys", getOwnMetadataKeys); /** * Deletes the metadata entry from the target object with the provided key. * @param metadataKey A key used to store and retrieve metadata. * @param target The target object on which the metadata is defined. * @param propertyKey (Optional) The property key for the target. * @returns `true` if the metadata entry was found and deleted; otherwise, false. * @example * * class Example { * // property declarations are not part of ES6, though they are valid in TypeScript: * // static staticProperty; * // property; * * constructor(p) { } * static staticMethod(p) { } * method(p) { } * } * * // constructor * result = Reflect.deleteMetadata("custom:annotation", Example); * * // property (on constructor) * result = Reflect.deleteMetadata("custom:annotation", Example, "staticProperty"); * * // property (on prototype) * result = Reflect.deleteMetadata("custom:annotation", Example.prototype, "property"); * * // method (on constructor) * result = Reflect.deleteMetadata("custom:annotation", Example, "staticMethod"); * * // method (on prototype) * result = Reflect.deleteMetadata("custom:annotation", Example.prototype, "method"); * */ function deleteMetadata(metadataKey, target, propertyKey) { if (!IsObject(target)) throw new TypeError(); if (!IsUndefined(propertyKey)) propertyKey = ToPropertyKey(propertyKey); var metadataMap = GetOrCreateMetadataMap(target, propertyKey, /*Create*/ false); if (IsUndefined(metadataMap)) return false; if (!metadataMap.delete(metadataKey)) return false; if (metadataMap.size > 0) return true; var targetMetadata = Metadata.get(target); targetMetadata.delete(propertyKey); if (targetMetadata.size > 0) return true; Metadata.delete(target); return true; } exporter("deleteMetadata", deleteMetadata); function DecorateConstructor(decorators, target) { for (var i = decorators.length - 1; i >= 0; --i) { var decorator = decorators[i]; var decorated = decorator(target); if (!IsUndefined(decorated) && !IsNull(decorated)) { if (!IsConstructor(decorated)) throw new TypeError(); target = decorated; } } return target; } function DecorateProperty(decorators, target, propertyKey, descriptor) { for (var i = decorators.length - 1; i >= 0; --i) { var decorator = decorators[i]; var decorated = decorator(target, propertyKey, descriptor); if (!IsUndefined(decorated) && !IsNull(decorated)) { if (!IsObject(decorated)) throw new TypeError(); descriptor = decorated; } } return descriptor; } function GetOrCreateMetadataMap(O, P, Create) { var targetMetadata = Metadata.get(O); if (IsUndefined(targetMetadata)) { if (!Create) return undefined; targetMetadata = new _Map(); Metadata.set(O, targetMetadata); } var metadataMap = targetMetadata.get(P); if (IsUndefined(metadataMap)) { if (!Create) return undefined; metadataMap = new _Map(); targetMetadata.set(P, metadataMap); } return metadataMap; } // 3.1.1.1 OrdinaryHasMetadata(MetadataKey, O, P) // https://rbuckton.github.io/reflect-metadata/#ordinaryhasmetadata function OrdinaryHasMetadata(MetadataKey, O, P) { var hasOwn = OrdinaryHasOwnMetadata(MetadataKey, O, P); if (hasOwn) return true; var parent = OrdinaryGetPrototypeOf(O); if (!IsNull(parent)) return OrdinaryHasMetadata(MetadataKey, parent, P); return false; } // 3.1.2.1 OrdinaryHasOwnMetadata(MetadataKey, O, P) // https://rbuckton.github.io/reflect-metadata/#ordinaryhasownmetadata function OrdinaryHasOwnMetadata(MetadataKey, O, P) { var metadataMap = GetOrCreateMetadataMap(O, P, /*Create*/ false); if (IsUndefined(metadataMap)) return false; return ToBoolean(metadataMap.has(MetadataKey)); } // 3.1.3.1 OrdinaryGetMetadata(MetadataKey, O, P) // https://rbuckton.github.io/reflect-metadata/#ordinarygetmetadata function OrdinaryGetMetadata(MetadataKey, O, P) { var hasOwn = OrdinaryHasOwnMetadata(MetadataKey, O, P); if (hasOwn) return OrdinaryGetOwnMetadata(MetadataKey, O, P); var parent = OrdinaryGetPrototypeOf(O); if (!IsNull(parent)) return OrdinaryGetMetadata(MetadataKey, parent, P); return undefined; } // 3.1.4.1 OrdinaryGetOwnMetadata(MetadataKey, O, P) // https://rbuckton.github.io/reflect-metadata/#ordinarygetownmetadata function OrdinaryGetOwnMetadata(MetadataKey, O, P) { var metadataMap = GetOrCreateMetadataMap(O, P, /*Create*/ false); if (IsUndefined(metadataMap)) return undefined; return metadataMap.get(MetadataKey); } // 3.1.5.1 OrdinaryDefineOwnMetadata(MetadataKey, MetadataValue, O, P) // https://rbuckton.github.io/reflect-metadata/#ordinarydefineownmetadata function OrdinaryDefineOwnMetadata(MetadataKey, MetadataValue, O, P) { var metadataMap = GetOrCreateMetadataMap(O, P, /*Create*/ true); metadataMap.set(MetadataKey, MetadataValue); } // 3.1.6.1 OrdinaryMetadataKeys(O, P) // https://rbuckton.github.io/reflect-metadata/#ordinarymetadatakeys function OrdinaryMetadataKeys(O, P) { var ownKeys = OrdinaryOwnMetadataKeys(O, P); var parent = OrdinaryGetPrototypeOf(O); if (parent === null) return ownKeys; var parentKeys = OrdinaryMetadataKeys(parent, P); if (parentKeys.length <= 0) return ownKeys; if (ownKeys.length <= 0) return parentKeys; var set = new _Set(); var keys = []; for (var _i = 0, ownKeys_1 = ownKeys; _i < ownKeys_1.length; _i++) { var key = ownKeys_1[_i]; var hasKey = set.has(key); if (!hasKey) { set.add(key); keys.push(key); } } for (var _a = 0, parentKeys_1 = parentKeys; _a < parentKeys_1.length; _a++) { var key = parentKeys_1[_a]; var hasKey = set.has(key); if (!hasKey) { set.add(key); keys.push(key); } } return keys; } // 3.1.7.1 OrdinaryOwnMetadataKeys(O, P) // https://rbuckton.github.io/reflect-metadata/#ordinaryownmetadatakeys function OrdinaryOwnMetadataKeys(O, P) { var keys = []; var metadataMap = GetOrCreateMetadataMap(O, P, /*Create*/ false); if (IsUndefined(metadataMap)) return keys; var keysObj = metadataMap.keys(); var iterator = GetIterator(keysObj); var k = 0; while (true) { var next = IteratorStep(iterator); if (!next) { keys.length = k; return keys; } var nextValue = IteratorValue(next); try { keys[k] = nextValue; } catch (e) { try { IteratorClose(iterator); } finally { throw e; } } k++; } } // 6 ECMAScript Data Typ0es and Values // https://tc39.github.io/ecma262/#sec-ecmascript-data-types-and-values function Type(x) { if (x === null) return 1 /* Null */; switch (typeof x) { case "undefined": return 0 /* Undefined */; case "boolean": return 2 /* Boolean */; case "string": return 3 /* String */; case "symbol": return 4 /* Symbol */; case "number": return 5 /* Number */; case "object": return x === null ? 1 /* Null */ : 6 /* Object */; default: return 6 /* Object */; } } // 6.1.1 The Undefined Type // https://tc39.github.io/ecma262/#sec-ecmascript-language-types-undefined-type function IsUndefined(x) { return x === undefined; } // 6.1.2 The Null Type // https://tc39.github.io/ecma262/#sec-ecmascript-language-types-null-type function IsNull(x) { return x === null; } // 6.1.5 The Symbol Type // https://tc39.github.io/ecma262/#sec-ecmascript-language-types-symbol-type function IsSymbol(x) { return typeof x === "symbol"; } // 6.1.7 The Object Type // https://tc39.github.io/ecma262/#sec-object-type function IsObject(x) { return typeof x === "object" ? x !== null : typeof x === "function"; } // 7.1 Type Conversion // https://tc39.github.io/ecma262/#sec-type-conversion // 7.1.1 ToPrimitive(input [, PreferredType]) // https://tc39.github.io/ecma262/#sec-toprimitive function ToPrimitive(input, PreferredType) { switch (Type(input)) { case 0 /* Undefined */: return input; case 1 /* Null */: return input; case 2 /* Boolean */: return input; case 3 /* String */: return input; case 4 /* Symbol */: return input; case 5 /* Number */: return input; } var hint = PreferredType === 3 /* String */ ? "string" : PreferredType === 5 /* Number */ ? "number" : "default"; var exoticToPrim = GetMethod(input, toPrimitiveSymbol); if (exoticToPrim !== undefined) { var result = exoticToPrim.call(input, hint); if (IsObject(result)) throw new TypeError(); return result; } return OrdinaryToPrimitive(input, hint === "default" ? "number" : hint); } // 7.1.1.1 OrdinaryToPrimitive(O, hint) // https://tc39.github.io/ecma262/#sec-ordinarytoprimitive function OrdinaryToPrimitive(O, hint) { if (hint === "string") { var toString_1 = O.toString; if (IsCallable(toString_1)) { var result = toString_1.call(O); if (!IsObject(result)) return result; } var valueOf = O.valueOf; if (IsCallable(valueOf)) { var result = valueOf.call(O); if (!IsObject(result)) return result; } } else { var valueOf = O.valueOf; if (IsCallable(valueOf)) { var result = valueOf.call(O); if (!IsObject(result)) return result; } var toString_2 = O.toString; if (IsCallable(toString_2)) { var result = toString_2.call(O); if (!IsObject(result)) return result; } } throw new TypeError(); } // 7.1.2 ToBoolean(argument) // https://tc39.github.io/ecma262/2016/#sec-toboolean function ToBoolean(argument) { return !!argument; } // 7.1.12 ToString(argument) // https://tc39.github.io/ecma262/#sec-tostring function ToString(argument) { return "" + argument; } // 7.1.14 ToPropertyKey(argument) // https://tc39.github.io/ecma262/#sec-topropertykey function ToPropertyKey(argument) { var key = ToPrimitive(argument, 3 /* String */); if (IsSymbol(key)) return key; return ToString(key); } // 7.2 Testing and Comparison Operations // https://tc39.github.io/ecma262/#sec-testing-and-comparison-operations // 7.2.2 IsArray(argument) // https://tc39.github.io/ecma262/#sec-isarray function IsArray(argument) { return Array.isArray ? Array.isArray(argument) : argument instanceof Object ? argument instanceof Array : Object.prototype.toString.call(argument) === "[object Array]"; } // 7.2.3 IsCallable(argument) // https://tc39.github.io/ecma262/#sec-iscallable function IsCallable(argument) { // NOTE: This is an approximation as we cannot check for [[Call]] internal method. return typeof argument === "function"; } // 7.2.4 IsConstructor(argument) // https://tc39.github.io/ecma262/#sec-isconstructor function IsConstructor(argument) { // NOTE: This is an approximation as we cannot check for [[Construct]] internal method. return typeof argument === "function"; } // 7.2.7 IsPropertyKey(argument) // https://tc39.github.io/ecma262/#sec-ispropertykey function IsPropertyKey(argument) { switch (Type(argument)) { case 3 /* String */: return true; case 4 /* Symbol */: return true; default: return false; } } // 7.3 Operations on Objects // https://tc39.github.io/ecma262/#sec-operations-on-objects // 7.3.9 GetMethod(V, P) // https://tc39.github.io/ecma262/#sec-getmethod function GetMethod(V, P) { var func = V[P]; if (func === undefined || func === null) return undefined; if (!IsCallable(func)) throw new TypeError(); return func; } // 7.4 Operations on Iterator Objects // https://tc39.github.io/ecma262/#sec-operations-on-iterator-objects function GetIterator(obj) { var method = GetMethod(obj, iteratorSymbol); if (!IsCallable(method)) throw new TypeError(); // from Call var iterator = method.call(obj); if (!IsObject(iterator)) throw new TypeError(); return iterator; } // 7.4.4 IteratorValue(iterResult) // https://tc39.github.io/ecma262/2016/#sec-iteratorvalue function IteratorValue(iterResult) { return iterResult.value; } // 7.4.5 IteratorStep(iterator) // https://tc39.github.io/ecma262/#sec-iteratorstep function IteratorStep(iterator) { var result = iterator.next(); return result.done ? false : result; } // 7.4.6 IteratorClose(iterator, completion) // https://tc39.github.io/ecma262/#sec-iteratorclose function IteratorClose(iterator) { var f = iterator["return"]; if (f) f.call(iterator); } // 9.1 Ordinary Object Internal Methods and Internal Slots // https://tc39.github.io/ecma262/#sec-ordinary-object-internal-methods-and-internal-slots // 9.1.1.1 OrdinaryGetPrototypeOf(O) // https://tc39.github.io/ecma262/#sec-ordinarygetprototypeof function OrdinaryGetPrototypeOf(O) { var proto = Object.getPrototypeOf(O); if (typeof O !== "function" || O === functionPrototype) return proto; // TypeScript doesn't set __proto__ in ES5, as it's non-standard. // Try to determine the superclass constructor. Compatible implementations // must either set __proto__ on a subclass constructor to the superclass constructor, // or ensure each class has a valid `constructor` property on its prototype that // points back to the constructor. // If this is not the same as Function.[[Prototype]], then this is definately inherited. // This is the case when in ES6 or when using __proto__ in a compatible browser. if (proto !== functionPrototype) return proto; // If the super prototype is Object.prototype, null, or undefined, then we cannot determine the heritage. var prototype = O.prototype; var prototypeProto = prototype && Object.getPrototypeOf(prototype); if (prototypeProto == null || prototypeProto === Object.prototype) return proto; // If the constructor was not a function, then we cannot determine the heritage. var constructor = prototypeProto.constructor; if (typeof constructor !== "function") return proto; // If we have some kind of self-reference, then we cannot determine the heritage. if (constructor === O) return proto; // we have a pretty good guess at the heritage. return constructor; } // naive Map shim function CreateMapPolyfill() { var cacheSentinel = {}; var arraySentinel = []; var MapIterator = /** @class */ (function () { function MapIterator(keys, values, selector) { this._index = 0; this._keys = keys; this._values = values; this._selector = selector; } MapIterator.prototype["@@iterator"] = function () { return this; }; MapIterator.prototype[iteratorSymbol] = function () { return this; }; MapIterator.prototype.next = function () { var index = this._index; if (index >= 0 && index < this._keys.length) { var result = this._selector(this._keys[index], this._values[index]); if (index + 1 >= this._keys.length) { this._index = -1; this._keys = arraySentinel; this._values = arraySentinel; } else { this._index++; } return { value: result, done: false }; } return { value: undefined, done: true }; }; MapIterator.prototype.throw = function (error) { if (this._index >= 0) { this._index = -1; this._keys = arraySentinel; this._values = arraySentinel; } throw error; }; MapIterator.prototype.return = function (value) { if (this._index >= 0) { this._index = -1; this._keys = arraySentinel; this._values = arraySentinel; } return { value: value, done: true }; }; return MapIterator; }()); return /** @class */ (function () { function Map() { this._keys = []; this._values = []; this._cacheKey = cacheSentinel; this._cacheIndex = -2; } Object.defineProperty(Map.prototype, "size", { get: function () { return this._keys.length; }, enumerable: true, configurable: true }); Map.prototype.has = function (key) { return this._find(key, /*insert*/ false) >= 0; }; Map.prototype.get = function (key) { var index = this._find(key, /*insert*/ false); return index >= 0 ? this._values[index] : undefined; }; Map.prototype.set = function (key, value) { var index = this._find(key, /*insert*/ true); this._values[index] = value; return this; }; Map.prototype.delete = function (key) { var index = this._find(key, /*insert*/ false); if (index >= 0) { var size = this._keys.length; for (var i = index + 1; i < size; i++) { this._keys[i - 1] = this._keys[i]; this._values[i - 1] = this._values[i]; } this._keys.length--; this._values.length--; if (key === this._cacheKey) { this._cacheKey = cacheSentinel; this._cacheIndex = -2; } return true; } return false; }; Map.prototype.clear = function () { this._keys.length = 0; this._values.length = 0; this._cacheKey = cacheSentinel; this._cacheIndex = -2; }; Map.prototype.keys = function () { return new MapIterator(this._keys, this._values, getKey); }; Map.prototype.values = function () { return new MapIterator(this._keys, this._values, getValue); }; Map.prototype.entries = function () { return new MapIterator(this._keys, this._values, getEntry); }; Map.prototype["@@iterator"] = function () { return this.entries(); }; Map.prototype[iteratorSymbol] = function () { return this.entries(); }; Map.prototype._find = function (key, insert) { if (this._cacheKey !== key) { this._cacheIndex = this._keys.indexOf(this._cacheKey = key); } if (this._cacheIndex < 0 && insert) { this._cacheIndex = this._keys.length; this._keys.push(key); this._values.push(undefined); } return this._cacheIndex; }; return Map; }()); function getKey(key, _) { return key; } function getValue(_, value) { return value; } function getEntry(key, value) { return [key, value]; } } // naive Set shim function CreateSetPolyfill() { return /** @class */ (function () { function Set() { this._map = new _Map(); } Object.defineProperty(Set.prototype, "size", { get: function () { return this._map.size; }, enumerable: true, configurable: true }); Set.prototype.has = function (value) { return this._map.has(value); }; Set.prototype.add = function (value) { return this._map.set(value, value), this; }; Set.prototype.delete = function (value) { return this._map.delete(value); }; Set.prototype.clear = function () { this._map.clear(); }; Set.prototype.keys = function () { return this._map.keys(); }; Set.prototype.values = function () { return this._map.values(); }; Set.prototype.entries = function () { return this._map.entries(); }; Set.prototype["@@iterator"] = function () { return this.keys(); }; Set.prototype[iteratorSymbol] = function () { return this.keys(); }; return Set; }()); } // naive WeakMap shim function CreateWeakMapPolyfill() { var UUID_SIZE = 16; var keys = HashMap.create(); var rootKey = CreateUniqueKey(); return /** @class */ (function () { function WeakMap() { this._key = CreateUniqueKey(); } WeakMap.prototype.has = function (target) { var table = GetOrCreateWeakMapTable(target, /*create*/ false); return table !== undefined ? HashMap.has(table, this._key) : false; }; WeakMap.prototype.get = function (target) { var table = GetOrCreateWeakMapTable(target, /*create*/ false); return table !== undefined ? HashMap.get(table, this._key) : undefined; }; WeakMap.prototype.set = function (target, value) { var table = GetOrCreateWeakMapTable(target, /*create*/ true); table[this._key] = value; return this; }; WeakMap.prototype.delete = function (target) { var table = GetOrCreateWeakMapTable(target, /*create*/ false); return table !== undefined ? delete table[this._key] : false; }; WeakMap.prototype.clear = function () { // NOTE: not a real clear, just makes the previous data unreachable this._key = CreateUniqueKey(); }; return WeakMap; }()); function CreateUniqueKey() { var key; do key = "@@WeakMap@@" + CreateUUID(); while (HashMap.has(keys, key)); keys[key] = true; return key; } function GetOrCreateWeakMapTable(target, create) { if (!hasOwn.call(target, rootKey)) { if (!create) return undefined; Object.defineProperty(target, rootKey, { value: HashMap.create() }); } return target[rootKey]; } function FillRandomBytes(buffer, size) { for (var i = 0; i < size; ++i) buffer[i] = Math.random() * 0xff | 0; return buffer; } function GenRandomBytes(size) { if (typeof Uint8Array === "function") { if (typeof crypto !== "undefined") return crypto.getRandomValues(new Uint8Array(size)); if (typeof msCrypto !== "undefined") return msCrypto.getRandomValues(new Uint8Array(size)); return FillRandomBytes(new Uint8Array(size), size); } return FillRandomBytes(new Array(size), size); } function CreateUUID() { var data = GenRandomBytes(UUID_SIZE); // mark as random - RFC 4122 § 4.4 data[6] = data[6] & 0x4f | 0x40; data[8] = data[8] & 0xbf | 0x80; var result = ""; for (var offset = 0; offset < UUID_SIZE; ++offset) { var byte = data[offset]; if (offset === 4 || offset === 6 || offset === 8) result += "-"; if (byte < 16) result += "0"; result += byte.toString(16).toLowerCase(); } return result; } } // uses a heuristic used by v8 and chakra to force an object into dictionary mode. function MakeDictionary(obj) { obj.__ = undefined; delete obj.__; return obj; } }); })(Reflect || (Reflect = {})); /***/ }), /***/ 48699: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // Copyright 2010-2012 Mikeal Rogers // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. var extend = __nccwpck_require__(38171) var cookies = __nccwpck_require__(50976) var helpers = __nccwpck_require__(74845) var paramsHaveRequestBody = helpers.paramsHaveRequestBody // organize params for patch, post, put, head, del function initParams (uri, options, callback) { if (typeof options === 'function') { callback = options } var params = {} if (options !== null && typeof options === 'object') { extend(params, options, {uri: uri}) } else if (typeof uri === 'string') { extend(params, {uri: uri}) } else { extend(params, uri) } params.callback = callback || params.callback return params } function request (uri, options, callback) { if (typeof uri === 'undefined') { throw new Error('undefined is not a valid uri or options object.') } var params = initParams(uri, options, callback) if (params.method === 'HEAD' && paramsHaveRequestBody(params)) { throw new Error('HTTP HEAD requests MUST NOT include a request body.') } return new request.Request(params) } function verbFunc (verb) { var method = verb.toUpperCase() return function (uri, options, callback) { var params = initParams(uri, options, callback) params.method = method return request(params, params.callback) } } // define like this to please codeintel/intellisense IDEs request.get = verbFunc('get') request.head = verbFunc('head') request.options = verbFunc('options') request.post = verbFunc('post') request.put = verbFunc('put') request.patch = verbFunc('patch') request.del = verbFunc('delete') request['delete'] = verbFunc('delete') request.jar = function (store) { return cookies.jar(store) } request.cookie = function (str) { return cookies.parse(str) } function wrapRequestMethod (method, options, requester, verb) { return function (uri, opts, callback) { var params = initParams(uri, opts, callback) var target = {} extend(true, target, options, params) target.pool = params.pool || options.pool if (verb) { target.method = verb.toUpperCase() } if (typeof requester === 'function') { method = requester } return method(target, target.callback) } } request.defaults = function (options, requester) { var self = this options = options || {} if (typeof options === 'function') { requester = options options = {} } var defaults = wrapRequestMethod(self, options, requester) var verbs = ['get', 'head', 'post', 'put', 'patch', 'del', 'delete'] verbs.forEach(function (verb) { defaults[verb] = wrapRequestMethod(self[verb], options, requester, verb) }) defaults.cookie = wrapRequestMethod(self.cookie, options, requester) defaults.jar = self.jar defaults.defaults = self.defaults return defaults } request.forever = function (agentOptions, optionsArg) { var options = {} if (optionsArg) { extend(options, optionsArg) } if (agentOptions) { options.agentOptions = agentOptions } options.forever = true return request.defaults(options) } // Exports module.exports = request request.Request = __nccwpck_require__(70304) request.initParams = initParams // Backwards compatibility for request.debug Object.defineProperty(request, 'debug', { enumerable: true, get: function () { return request.Request.debug }, set: function (debug) { request.Request.debug = debug } }) /***/ }), /***/ 76996: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; var caseless = __nccwpck_require__(35684) var uuid = __nccwpck_require__(71435) var helpers = __nccwpck_require__(74845) var md5 = helpers.md5 var toBase64 = helpers.toBase64 function Auth (request) { // define all public properties here this.request = request this.hasAuth = false this.sentAuth = false this.bearerToken = null this.user = null this.pass = null } Auth.prototype.basic = function (user, pass, sendImmediately) { var self = this if (typeof user !== 'string' || (pass !== undefined && typeof pass !== 'string')) { self.request.emit('error', new Error('auth() received invalid user or password')) } self.user = user self.pass = pass self.hasAuth = true var header = user + ':' + (pass || '') if (sendImmediately || typeof sendImmediately === 'undefined') { var authHeader = 'Basic ' + toBase64(header) self.sentAuth = true return authHeader } } Auth.prototype.bearer = function (bearer, sendImmediately) { var self = this self.bearerToken = bearer self.hasAuth = true if (sendImmediately || typeof sendImmediately === 'undefined') { if (typeof bearer === 'function') { bearer = bearer() } var authHeader = 'Bearer ' + (bearer || '') self.sentAuth = true return authHeader } } Auth.prototype.digest = function (method, path, authHeader) { // TODO: More complete implementation of RFC 2617. // - handle challenge.domain // - support qop="auth-int" only // - handle Authentication-Info (not necessarily?) // - check challenge.stale (not necessarily?) // - increase nc (not necessarily?) // For reference: // http://tools.ietf.org/html/rfc2617#section-3 // https://github.com/bagder/curl/blob/master/lib/http_digest.c var self = this var challenge = {} var re = /([a-z0-9_-]+)=(?:"([^"]+)"|([a-z0-9_-]+))/gi while (true) { var match = re.exec(authHeader) if (!match) { break } challenge[match[1]] = match[2] || match[3] } /** * RFC 2617: handle both MD5 and MD5-sess algorithms. * * If the algorithm directive's value is "MD5" or unspecified, then HA1 is * HA1=MD5(username:realm:password) * If the algorithm directive's value is "MD5-sess", then HA1 is * HA1=MD5(MD5(username:realm:password):nonce:cnonce) */ var ha1Compute = function (algorithm, user, realm, pass, nonce, cnonce) { var ha1 = md5(user + ':' + realm + ':' + pass) if (algorithm && algorithm.toLowerCase() === 'md5-sess') { return md5(ha1 + ':' + nonce + ':' + cnonce) } else { return ha1 } } var qop = /(^|,)\s*auth\s*($|,)/.test(challenge.qop) && 'auth' var nc = qop && '00000001' var cnonce = qop && uuid().replace(/-/g, '') var ha1 = ha1Compute(challenge.algorithm, self.user, challenge.realm, self.pass, challenge.nonce, cnonce) var ha2 = md5(method + ':' + path) var digestResponse = qop ? md5(ha1 + ':' + challenge.nonce + ':' + nc + ':' + cnonce + ':' + qop + ':' + ha2) : md5(ha1 + ':' + challenge.nonce + ':' + ha2) var authValues = { username: self.user, realm: challenge.realm, nonce: challenge.nonce, uri: path, qop: qop, response: digestResponse, nc: nc, cnonce: cnonce, algorithm: challenge.algorithm, opaque: challenge.opaque } authHeader = [] for (var k in authValues) { if (authValues[k]) { if (k === 'qop' || k === 'nc' || k === 'algorithm') { authHeader.push(k + '=' + authValues[k]) } else { authHeader.push(k + '="' + authValues[k] + '"') } } } authHeader = 'Digest ' + authHeader.join(', ') self.sentAuth = true return authHeader } Auth.prototype.onRequest = function (user, pass, sendImmediately, bearer) { var self = this var request = self.request var authHeader if (bearer === undefined && user === undefined) { self.request.emit('error', new Error('no auth mechanism defined')) } else if (bearer !== undefined) { authHeader = self.bearer(bearer, sendImmediately) } else { authHeader = self.basic(user, pass, sendImmediately) } if (authHeader) { request.setHeader('authorization', authHeader) } } Auth.prototype.onResponse = function (response) { var self = this var request = self.request if (!self.hasAuth || self.sentAuth) { return null } var c = caseless(response.headers) var authHeader = c.get('www-authenticate') var authVerb = authHeader && authHeader.split(' ')[0].toLowerCase() request.debug('reauth', authVerb) switch (authVerb) { case 'basic': return self.basic(self.user, self.pass, true) case 'bearer': return self.bearer(self.bearerToken, true) case 'digest': return self.digest(request.method, request.path, authHeader) } } exports.g = Auth /***/ }), /***/ 50976: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; var tough = __nccwpck_require__(47372) var Cookie = tough.Cookie var CookieJar = tough.CookieJar exports.parse = function (str) { if (str && str.uri) { str = str.uri } if (typeof str !== 'string') { throw new Error('The cookie function only accepts STRING as param') } return Cookie.parse(str, {loose: true}) } // Adapt the sometimes-Async api of tough.CookieJar to our requirements function RequestJar (store) { var self = this self._jar = new CookieJar(store, {looseMode: true}) } RequestJar.prototype.setCookie = function (cookieOrStr, uri, options) { var self = this return self._jar.setCookieSync(cookieOrStr, uri, options || {}) } RequestJar.prototype.getCookieString = function (uri) { var self = this return self._jar.getCookieStringSync(uri) } RequestJar.prototype.getCookies = function (uri) { var self = this return self._jar.getCookiesSync(uri) } exports.jar = function (store) { return new RequestJar(store) } /***/ }), /***/ 75654: /***/ ((module) => { "use strict"; function formatHostname (hostname) { // canonicalize the hostname, so that 'oogle.com' won't match 'google.com' return hostname.replace(/^\.*/, '.').toLowerCase() } function parseNoProxyZone (zone) { zone = zone.trim().toLowerCase() var zoneParts = zone.split(':', 2) var zoneHost = formatHostname(zoneParts[0]) var zonePort = zoneParts[1] var hasPort = zone.indexOf(':') > -1 return {hostname: zoneHost, port: zonePort, hasPort: hasPort} } function uriInNoProxy (uri, noProxy) { var port = uri.port || (uri.protocol === 'https:' ? '443' : '80') var hostname = formatHostname(uri.hostname) var noProxyList = noProxy.split(',') // iterate through the noProxyList until it finds a match. return noProxyList.map(parseNoProxyZone).some(function (noProxyZone) { var isMatchedAt = hostname.indexOf(noProxyZone.hostname) var hostnameMatched = ( isMatchedAt > -1 && (isMatchedAt === hostname.length - noProxyZone.hostname.length) ) if (noProxyZone.hasPort) { return (port === noProxyZone.port) && hostnameMatched } return hostnameMatched }) } function getProxyFromURI (uri) { // Decide the proper request proxy to use based on the request URI object and the // environmental variables (NO_PROXY, HTTP_PROXY, etc.) // respect NO_PROXY environment variables (see: https://lynx.invisible-island.net/lynx2.8.7/breakout/lynx_help/keystrokes/environments.html) var noProxy = process.env.NO_PROXY || process.env.no_proxy || '' // if the noProxy is a wildcard then return null if (noProxy === '*') { return null } // if the noProxy is not empty and the uri is found return null if (noProxy !== '' && uriInNoProxy(uri, noProxy)) { return null } // Check for HTTP or HTTPS Proxy in environment Else default to null if (uri.protocol === 'http:') { return process.env.HTTP_PROXY || process.env.http_proxy || null } if (uri.protocol === 'https:') { return process.env.HTTPS_PROXY || process.env.https_proxy || process.env.HTTP_PROXY || process.env.http_proxy || null } // if none of that works, return null // (What uri protocol are you using then?) return null } module.exports = getProxyFromURI /***/ }), /***/ 3248: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; var fs = __nccwpck_require__(57147) var qs = __nccwpck_require__(63477) var validate = __nccwpck_require__(75697) var extend = __nccwpck_require__(38171) function Har (request) { this.request = request } Har.prototype.reducer = function (obj, pair) { // new property ? if (obj[pair.name] === undefined) { obj[pair.name] = pair.value return obj } // existing? convert to array var arr = [ obj[pair.name], pair.value ] obj[pair.name] = arr return obj } Har.prototype.prep = function (data) { // construct utility properties data.queryObj = {} data.headersObj = {} data.postData.jsonObj = false data.postData.paramsObj = false // construct query objects if (data.queryString && data.queryString.length) { data.queryObj = data.queryString.reduce(this.reducer, {}) } // construct headers objects if (data.headers && data.headers.length) { // loweCase header keys data.headersObj = data.headers.reduceRight(function (headers, header) { headers[header.name] = header.value return headers }, {}) } // construct Cookie header if (data.cookies && data.cookies.length) { var cookies = data.cookies.map(function (cookie) { return cookie.name + '=' + cookie.value }) if (cookies.length) { data.headersObj.cookie = cookies.join('; ') } } // prep body function some (arr) { return arr.some(function (type) { return data.postData.mimeType.indexOf(type) === 0 }) } if (some([ 'multipart/mixed', 'multipart/related', 'multipart/form-data', 'multipart/alternative'])) { // reset values data.postData.mimeType = 'multipart/form-data' } else if (some([ 'application/x-www-form-urlencoded'])) { if (!data.postData.params) { data.postData.text = '' } else { data.postData.paramsObj = data.postData.params.reduce(this.reducer, {}) // always overwrite data.postData.text = qs.stringify(data.postData.paramsObj) } } else if (some([ 'text/json', 'text/x-json', 'application/json', 'application/x-json'])) { data.postData.mimeType = 'application/json' if (data.postData.text) { try { data.postData.jsonObj = JSON.parse(data.postData.text) } catch (e) { this.request.debug(e) // force back to text/plain data.postData.mimeType = 'text/plain' } } } return data } Har.prototype.options = function (options) { // skip if no har property defined if (!options.har) { return options } var har = {} extend(har, options.har) // only process the first entry if (har.log && har.log.entries) { har = har.log.entries[0] } // add optional properties to make validation successful har.url = har.url || options.url || options.uri || options.baseUrl || '/' har.httpVersion = har.httpVersion || 'HTTP/1.1' har.queryString = har.queryString || [] har.headers = har.headers || [] har.cookies = har.cookies || [] har.postData = har.postData || {} har.postData.mimeType = har.postData.mimeType || 'application/octet-stream' har.bodySize = 0 har.headersSize = 0 har.postData.size = 0 if (!validate.request(har)) { return options } // clean up and get some utility properties var req = this.prep(har) // construct new options if (req.url) { options.url = req.url } if (req.method) { options.method = req.method } if (Object.keys(req.queryObj).length) { options.qs = req.queryObj } if (Object.keys(req.headersObj).length) { options.headers = req.headersObj } function test (type) { return req.postData.mimeType.indexOf(type) === 0 } if (test('application/x-www-form-urlencoded')) { options.form = req.postData.paramsObj } else if (test('application/json')) { if (req.postData.jsonObj) { options.body = req.postData.jsonObj options.json = true } } else if (test('multipart/form-data')) { options.formData = {} req.postData.params.forEach(function (param) { var attachment = {} if (!param.fileName && !param.contentType) { options.formData[param.name] = param.value return } // attempt to read from disk! if (param.fileName && !param.value) { attachment.value = fs.createReadStream(param.fileName) } else if (param.value) { attachment.value = param.value } if (param.fileName) { attachment.options = { filename: param.fileName, contentType: param.contentType ? param.contentType : null } } options.formData[param.name] = attachment }) } else { if (req.postData.text) { options.body = req.postData.text } } return options } exports.t = Har /***/ }), /***/ 34473: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; var crypto = __nccwpck_require__(6113) function randomString (size) { var bits = (size + 1) * 6 var buffer = crypto.randomBytes(Math.ceil(bits / 8)) var string = buffer.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '') return string.slice(0, size) } function calculatePayloadHash (payload, algorithm, contentType) { var hash = crypto.createHash(algorithm) hash.update('hawk.1.payload\n') hash.update((contentType ? contentType.split(';')[0].trim().toLowerCase() : '') + '\n') hash.update(payload || '') hash.update('\n') return hash.digest('base64') } exports.calculateMac = function (credentials, opts) { var normalized = 'hawk.1.header\n' + opts.ts + '\n' + opts.nonce + '\n' + (opts.method || '').toUpperCase() + '\n' + opts.resource + '\n' + opts.host.toLowerCase() + '\n' + opts.port + '\n' + (opts.hash || '') + '\n' if (opts.ext) { normalized = normalized + opts.ext.replace('\\', '\\\\').replace('\n', '\\n') } normalized = normalized + '\n' if (opts.app) { normalized = normalized + opts.app + '\n' + (opts.dlg || '') + '\n' } var hmac = crypto.createHmac(credentials.algorithm, credentials.key).update(normalized) var digest = hmac.digest('base64') return digest } exports.header = function (uri, method, opts) { var timestamp = opts.timestamp || Math.floor((Date.now() + (opts.localtimeOffsetMsec || 0)) / 1000) var credentials = opts.credentials if (!credentials || !credentials.id || !credentials.key || !credentials.algorithm) { return '' } if (['sha1', 'sha256'].indexOf(credentials.algorithm) === -1) { return '' } var artifacts = { ts: timestamp, nonce: opts.nonce || randomString(6), method: method, resource: uri.pathname + (uri.search || ''), host: uri.hostname, port: uri.port || (uri.protocol === 'http:' ? 80 : 443), hash: opts.hash, ext: opts.ext, app: opts.app, dlg: opts.dlg } if (!artifacts.hash && (opts.payload || opts.payload === '')) { artifacts.hash = calculatePayloadHash(opts.payload, credentials.algorithm, opts.contentType) } var mac = exports.calculateMac(credentials, artifacts) var hasExt = artifacts.ext !== null && artifacts.ext !== undefined && artifacts.ext !== '' var header = 'Hawk id="' + credentials.id + '", ts="' + artifacts.ts + '", nonce="' + artifacts.nonce + (artifacts.hash ? '", hash="' + artifacts.hash : '') + (hasExt ? '", ext="' + artifacts.ext.replace(/\\/g, '\\\\').replace(/"/g, '\\"') : '') + '", mac="' + mac + '"' if (artifacts.app) { header = header + ', app="' + artifacts.app + (artifacts.dlg ? '", dlg="' + artifacts.dlg : '') + '"' } return header } /***/ }), /***/ 74845: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; var jsonSafeStringify = __nccwpck_require__(57073) var crypto = __nccwpck_require__(6113) var Buffer = (__nccwpck_require__(21867).Buffer) var defer = typeof setImmediate === 'undefined' ? process.nextTick : setImmediate function paramsHaveRequestBody (params) { return ( params.body || params.requestBodyStream || (params.json && typeof params.json !== 'boolean') || params.multipart ) } function safeStringify (obj, replacer) { var ret try { ret = JSON.stringify(obj, replacer) } catch (e) { ret = jsonSafeStringify(obj, replacer) } return ret } function md5 (str) { return crypto.createHash('md5').update(str).digest('hex') } function isReadStream (rs) { return rs.readable && rs.path && rs.mode } function toBase64 (str) { return Buffer.from(str || '', 'utf8').toString('base64') } function copy (obj) { var o = {} Object.keys(obj).forEach(function (i) { o[i] = obj[i] }) return o } function version () { var numbers = process.version.replace('v', '').split('.') return { major: parseInt(numbers[0], 10), minor: parseInt(numbers[1], 10), patch: parseInt(numbers[2], 10) } } exports.paramsHaveRequestBody = paramsHaveRequestBody exports.safeStringify = safeStringify exports.md5 = md5 exports.isReadStream = isReadStream exports.toBase64 = toBase64 exports.copy = copy exports.version = version exports.defer = defer /***/ }), /***/ 87810: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; var uuid = __nccwpck_require__(71435) var CombinedStream = __nccwpck_require__(85443) var isstream = __nccwpck_require__(83362) var Buffer = (__nccwpck_require__(21867).Buffer) function Multipart (request) { this.request = request this.boundary = uuid() this.chunked = false this.body = null } Multipart.prototype.isChunked = function (options) { var self = this var chunked = false var parts = options.data || options if (!parts.forEach) { self.request.emit('error', new Error('Argument error, options.multipart.')) } if (options.chunked !== undefined) { chunked = options.chunked } if (self.request.getHeader('transfer-encoding') === 'chunked') { chunked = true } if (!chunked) { parts.forEach(function (part) { if (typeof part.body === 'undefined') { self.request.emit('error', new Error('Body attribute missing in multipart.')) } if (isstream(part.body)) { chunked = true } }) } return chunked } Multipart.prototype.setHeaders = function (chunked) { var self = this if (chunked && !self.request.hasHeader('transfer-encoding')) { self.request.setHeader('transfer-encoding', 'chunked') } var header = self.request.getHeader('content-type') if (!header || header.indexOf('multipart') === -1) { self.request.setHeader('content-type', 'multipart/related; boundary=' + self.boundary) } else { if (header.indexOf('boundary') !== -1) { self.boundary = header.replace(/.*boundary=([^\s;]+).*/, '$1') } else { self.request.setHeader('content-type', header + '; boundary=' + self.boundary) } } } Multipart.prototype.build = function (parts, chunked) { var self = this var body = chunked ? new CombinedStream() : [] function add (part) { if (typeof part === 'number') { part = part.toString() } return chunked ? body.append(part) : body.push(Buffer.from(part)) } if (self.request.preambleCRLF) { add('\r\n') } parts.forEach(function (part) { var preamble = '--' + self.boundary + '\r\n' Object.keys(part).forEach(function (key) { if (key === 'body') { return } preamble += key + ': ' + part[key] + '\r\n' }) preamble += '\r\n' add(preamble) add(part.body) add('\r\n') }) add('--' + self.boundary + '--') if (self.request.postambleCRLF) { add('\r\n') } return body } Multipart.prototype.onRequest = function (options) { var self = this var chunked = self.isChunked(options) var parts = options.data || options self.setHeaders(chunked) self.chunked = chunked self.body = self.build(parts, chunked) } exports.$ = Multipart /***/ }), /***/ 41174: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; var url = __nccwpck_require__(57310) var qs = __nccwpck_require__(47457) var caseless = __nccwpck_require__(35684) var uuid = __nccwpck_require__(71435) var oauth = __nccwpck_require__(43248) var crypto = __nccwpck_require__(6113) var Buffer = (__nccwpck_require__(21867).Buffer) function OAuth (request) { this.request = request this.params = null } OAuth.prototype.buildParams = function (_oauth, uri, method, query, form, qsLib) { var oa = {} for (var i in _oauth) { oa['oauth_' + i] = _oauth[i] } if (!oa.oauth_version) { oa.oauth_version = '1.0' } if (!oa.oauth_timestamp) { oa.oauth_timestamp = Math.floor(Date.now() / 1000).toString() } if (!oa.oauth_nonce) { oa.oauth_nonce = uuid().replace(/-/g, '') } if (!oa.oauth_signature_method) { oa.oauth_signature_method = 'HMAC-SHA1' } var consumer_secret_or_private_key = oa.oauth_consumer_secret || oa.oauth_private_key // eslint-disable-line camelcase delete oa.oauth_consumer_secret delete oa.oauth_private_key var token_secret = oa.oauth_token_secret // eslint-disable-line camelcase delete oa.oauth_token_secret var realm = oa.oauth_realm delete oa.oauth_realm delete oa.oauth_transport_method var baseurl = uri.protocol + '//' + uri.host + uri.pathname var params = qsLib.parse([].concat(query, form, qsLib.stringify(oa)).join('&')) oa.oauth_signature = oauth.sign( oa.oauth_signature_method, method, baseurl, params, consumer_secret_or_private_key, // eslint-disable-line camelcase token_secret // eslint-disable-line camelcase ) if (realm) { oa.realm = realm } return oa } OAuth.prototype.buildBodyHash = function (_oauth, body) { if (['HMAC-SHA1', 'RSA-SHA1'].indexOf(_oauth.signature_method || 'HMAC-SHA1') < 0) { this.request.emit('error', new Error('oauth: ' + _oauth.signature_method + ' signature_method not supported with body_hash signing.')) } var shasum = crypto.createHash('sha1') shasum.update(body || '') var sha1 = shasum.digest('hex') return Buffer.from(sha1, 'hex').toString('base64') } OAuth.prototype.concatParams = function (oa, sep, wrap) { wrap = wrap || '' var params = Object.keys(oa).filter(function (i) { return i !== 'realm' && i !== 'oauth_signature' }).sort() if (oa.realm) { params.splice(0, 0, 'realm') } params.push('oauth_signature') return params.map(function (i) { return i + '=' + wrap + oauth.rfc3986(oa[i]) + wrap }).join(sep) } OAuth.prototype.onRequest = function (_oauth) { var self = this self.params = _oauth var uri = self.request.uri || {} var method = self.request.method || '' var headers = caseless(self.request.headers) var body = self.request.body || '' var qsLib = self.request.qsLib || qs var form var query var contentType = headers.get('content-type') || '' var formContentType = 'application/x-www-form-urlencoded' var transport = _oauth.transport_method || 'header' if (contentType.slice(0, formContentType.length) === formContentType) { contentType = formContentType form = body } if (uri.query) { query = uri.query } if (transport === 'body' && (method !== 'POST' || contentType !== formContentType)) { self.request.emit('error', new Error('oauth: transport_method of body requires POST ' + 'and content-type ' + formContentType)) } if (!form && typeof _oauth.body_hash === 'boolean') { _oauth.body_hash = self.buildBodyHash(_oauth, self.request.body.toString()) } var oa = self.buildParams(_oauth, uri, method, query, form, qsLib) switch (transport) { case 'header': self.request.setHeader('Authorization', 'OAuth ' + self.concatParams(oa, ',', '"')) break case 'query': var href = self.request.uri.href += (query ? '&' : '?') + self.concatParams(oa, '&') self.request.uri = url.parse(href) self.request.path = self.request.uri.path break case 'body': self.request.body = (form ? form + '&' : '') + self.concatParams(oa, '&') break default: self.request.emit('error', new Error('oauth: transport_method invalid')) } } exports.f = OAuth /***/ }), /***/ 66476: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; var qs = __nccwpck_require__(47457) var querystring = __nccwpck_require__(63477) function Querystring (request) { this.request = request this.lib = null this.useQuerystring = null this.parseOptions = null this.stringifyOptions = null } Querystring.prototype.init = function (options) { if (this.lib) { return } this.useQuerystring = options.useQuerystring this.lib = (this.useQuerystring ? querystring : qs) this.parseOptions = options.qsParseOptions || {} this.stringifyOptions = options.qsStringifyOptions || {} } Querystring.prototype.stringify = function (obj) { return (this.useQuerystring) ? this.rfc3986(this.lib.stringify(obj, this.stringifyOptions.sep || null, this.stringifyOptions.eq || null, this.stringifyOptions)) : this.lib.stringify(obj, this.stringifyOptions) } Querystring.prototype.parse = function (str) { return (this.useQuerystring) ? this.lib.parse(str, this.parseOptions.sep || null, this.parseOptions.eq || null, this.parseOptions) : this.lib.parse(str, this.parseOptions) } Querystring.prototype.rfc3986 = function (str) { return str.replace(/[!'()*]/g, function (c) { return '%' + c.charCodeAt(0).toString(16).toUpperCase() }) } Querystring.prototype.unescape = querystring.unescape exports.h = Querystring /***/ }), /***/ 3048: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; var url = __nccwpck_require__(57310) var isUrl = /^https?:/ function Redirect (request) { this.request = request this.followRedirect = true this.followRedirects = true this.followAllRedirects = false this.followOriginalHttpMethod = false this.allowRedirect = function () { return true } this.maxRedirects = 10 this.redirects = [] this.redirectsFollowed = 0 this.removeRefererHeader = false } Redirect.prototype.onRequest = function (options) { var self = this if (options.maxRedirects !== undefined) { self.maxRedirects = options.maxRedirects } if (typeof options.followRedirect === 'function') { self.allowRedirect = options.followRedirect } if (options.followRedirect !== undefined) { self.followRedirects = !!options.followRedirect } if (options.followAllRedirects !== undefined) { self.followAllRedirects = options.followAllRedirects } if (self.followRedirects || self.followAllRedirects) { self.redirects = self.redirects || [] } if (options.removeRefererHeader !== undefined) { self.removeRefererHeader = options.removeRefererHeader } if (options.followOriginalHttpMethod !== undefined) { self.followOriginalHttpMethod = options.followOriginalHttpMethod } } Redirect.prototype.redirectTo = function (response) { var self = this var request = self.request var redirectTo = null if (response.statusCode >= 300 && response.statusCode < 400 && response.caseless.has('location')) { var location = response.caseless.get('location') request.debug('redirect', location) if (self.followAllRedirects) { redirectTo = location } else if (self.followRedirects) { switch (request.method) { case 'PATCH': case 'PUT': case 'POST': case 'DELETE': // Do not follow redirects break default: redirectTo = location break } } } else if (response.statusCode === 401) { var authHeader = request._auth.onResponse(response) if (authHeader) { request.setHeader('authorization', authHeader) redirectTo = request.uri } } return redirectTo } Redirect.prototype.onResponse = function (response) { var self = this var request = self.request var redirectTo = self.redirectTo(response) if (!redirectTo || !self.allowRedirect.call(request, response)) { return false } request.debug('redirect to', redirectTo) // ignore any potential response body. it cannot possibly be useful // to us at this point. // response.resume should be defined, but check anyway before calling. Workaround for browserify. if (response.resume) { response.resume() } if (self.redirectsFollowed >= self.maxRedirects) { request.emit('error', new Error('Exceeded maxRedirects. Probably stuck in a redirect loop ' + request.uri.href)) return false } self.redirectsFollowed += 1 if (!isUrl.test(redirectTo)) { redirectTo = url.resolve(request.uri.href, redirectTo) } var uriPrev = request.uri request.uri = url.parse(redirectTo) // handle the case where we change protocol from https to http or vice versa if (request.uri.protocol !== uriPrev.protocol) { delete request.agent } self.redirects.push({ statusCode: response.statusCode, redirectUri: redirectTo }) if (self.followAllRedirects && request.method !== 'HEAD' && response.statusCode !== 401 && response.statusCode !== 307) { request.method = self.followOriginalHttpMethod ? request.method : 'GET' } // request.method = 'GET' // Force all redirects to use GET || commented out fixes #215 delete request.src delete request.req delete request._started if (response.statusCode !== 401 && response.statusCode !== 307) { // Remove parameters from the previous response, unless this is the second request // for a server that requires digest authentication. delete request.body delete request._form if (request.headers) { request.removeHeader('host') request.removeHeader('content-type') request.removeHeader('content-length') if (request.uri.hostname !== request.originalHost.split(':')[0]) { // Remove authorization if changing hostnames (but not if just // changing ports or protocols). This matches the behavior of curl: // https://github.com/bagder/curl/blob/6beb0eee/lib/http.c#L710 request.removeHeader('authorization') } } } if (!self.removeRefererHeader) { request.setHeader('referer', uriPrev.href) } request.emit('redirect') request.init() return true } exports.l = Redirect /***/ }), /***/ 17619: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; var url = __nccwpck_require__(57310) var tunnel = __nccwpck_require__(11137) var defaultProxyHeaderWhiteList = [ 'accept', 'accept-charset', 'accept-encoding', 'accept-language', 'accept-ranges', 'cache-control', 'content-encoding', 'content-language', 'content-location', 'content-md5', 'content-range', 'content-type', 'connection', 'date', 'expect', 'max-forwards', 'pragma', 'referer', 'te', 'user-agent', 'via' ] var defaultProxyHeaderExclusiveList = [ 'proxy-authorization' ] function constructProxyHost (uriObject) { var port = uriObject.port var protocol = uriObject.protocol var proxyHost = uriObject.hostname + ':' if (port) { proxyHost += port } else if (protocol === 'https:') { proxyHost += '443' } else { proxyHost += '80' } return proxyHost } function constructProxyHeaderWhiteList (headers, proxyHeaderWhiteList) { var whiteList = proxyHeaderWhiteList .reduce(function (set, header) { set[header.toLowerCase()] = true return set }, {}) return Object.keys(headers) .filter(function (header) { return whiteList[header.toLowerCase()] }) .reduce(function (set, header) { set[header] = headers[header] return set }, {}) } function constructTunnelOptions (request, proxyHeaders) { var proxy = request.proxy var tunnelOptions = { proxy: { host: proxy.hostname, port: +proxy.port, proxyAuth: proxy.auth, headers: proxyHeaders }, headers: request.headers, ca: request.ca, cert: request.cert, key: request.key, passphrase: request.passphrase, pfx: request.pfx, ciphers: request.ciphers, rejectUnauthorized: request.rejectUnauthorized, secureOptions: request.secureOptions, secureProtocol: request.secureProtocol } return tunnelOptions } function constructTunnelFnName (uri, proxy) { var uriProtocol = (uri.protocol === 'https:' ? 'https' : 'http') var proxyProtocol = (proxy.protocol === 'https:' ? 'Https' : 'Http') return [uriProtocol, proxyProtocol].join('Over') } function getTunnelFn (request) { var uri = request.uri var proxy = request.proxy var tunnelFnName = constructTunnelFnName(uri, proxy) return tunnel[tunnelFnName] } function Tunnel (request) { this.request = request this.proxyHeaderWhiteList = defaultProxyHeaderWhiteList this.proxyHeaderExclusiveList = [] if (typeof request.tunnel !== 'undefined') { this.tunnelOverride = request.tunnel } } Tunnel.prototype.isEnabled = function () { var self = this var request = self.request // Tunnel HTTPS by default. Allow the user to override this setting. // If self.tunnelOverride is set (the user specified a value), use it. if (typeof self.tunnelOverride !== 'undefined') { return self.tunnelOverride } // If the destination is HTTPS, tunnel. if (request.uri.protocol === 'https:') { return true } // Otherwise, do not use tunnel. return false } Tunnel.prototype.setup = function (options) { var self = this var request = self.request options = options || {} if (typeof request.proxy === 'string') { request.proxy = url.parse(request.proxy) } if (!request.proxy || !request.tunnel) { return false } // Setup Proxy Header Exclusive List and White List if (options.proxyHeaderWhiteList) { self.proxyHeaderWhiteList = options.proxyHeaderWhiteList } if (options.proxyHeaderExclusiveList) { self.proxyHeaderExclusiveList = options.proxyHeaderExclusiveList } var proxyHeaderExclusiveList = self.proxyHeaderExclusiveList.concat(defaultProxyHeaderExclusiveList) var proxyHeaderWhiteList = self.proxyHeaderWhiteList.concat(proxyHeaderExclusiveList) // Setup Proxy Headers and Proxy Headers Host // Only send the Proxy White Listed Header names var proxyHeaders = constructProxyHeaderWhiteList(request.headers, proxyHeaderWhiteList) proxyHeaders.host = constructProxyHost(request.uri) proxyHeaderExclusiveList.forEach(request.removeHeader, request) // Set Agent from Tunnel Data var tunnelFn = getTunnelFn(request) var tunnelOptions = constructTunnelOptions(request, proxyHeaders) request.agent = tunnelFn(tunnelOptions) return true } Tunnel.defaultProxyHeaderWhiteList = defaultProxyHeaderWhiteList Tunnel.defaultProxyHeaderExclusiveList = defaultProxyHeaderExclusiveList exports.n = Tunnel /***/ }), /***/ 11377: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var CombinedStream = __nccwpck_require__(85443); var util = __nccwpck_require__(73837); var path = __nccwpck_require__(71017); var http = __nccwpck_require__(13685); var https = __nccwpck_require__(95687); var parseUrl = (__nccwpck_require__(57310).parse); var fs = __nccwpck_require__(57147); var mime = __nccwpck_require__(43583); var asynckit = __nccwpck_require__(14812); var populate = __nccwpck_require__(94932); // Public API module.exports = FormData; // make it a Stream util.inherits(FormData, CombinedStream); /** * Create readable "multipart/form-data" streams. * Can be used to submit forms * and file uploads to other web applications. * * @constructor * @param {Object} options - Properties to be added/overriden for FormData and CombinedStream */ function FormData(options) { if (!(this instanceof FormData)) { return new FormData(); } this._overheadLength = 0; this._valueLength = 0; this._valuesToMeasure = []; CombinedStream.call(this); options = options || {}; for (var option in options) { this[option] = options[option]; } } FormData.LINE_BREAK = '\r\n'; FormData.DEFAULT_CONTENT_TYPE = 'application/octet-stream'; FormData.prototype.append = function(field, value, options) { options = options || {}; // allow filename as single option if (typeof options == 'string') { options = {filename: options}; } var append = CombinedStream.prototype.append.bind(this); // all that streamy business can't handle numbers if (typeof value == 'number') { value = '' + value; } // https://github.com/felixge/node-form-data/issues/38 if (util.isArray(value)) { // Please convert your array into string // the way web server expects it this._error(new Error('Arrays are not supported.')); return; } var header = this._multiPartHeader(field, value, options); var footer = this._multiPartFooter(); append(header); append(value); append(footer); // pass along options.knownLength this._trackLength(header, value, options); }; FormData.prototype._trackLength = function(header, value, options) { var valueLength = 0; // used w/ getLengthSync(), when length is known. // e.g. for streaming directly from a remote server, // w/ a known file a size, and not wanting to wait for // incoming file to finish to get its size. if (options.knownLength != null) { valueLength += +options.knownLength; } else if (Buffer.isBuffer(value)) { valueLength = value.length; } else if (typeof value === 'string') { valueLength = Buffer.byteLength(value); } this._valueLength += valueLength; // @check why add CRLF? does this account for custom/multiple CRLFs? this._overheadLength += Buffer.byteLength(header) + FormData.LINE_BREAK.length; // empty or either doesn't have path or not an http response if (!value || ( !value.path && !(value.readable && value.hasOwnProperty('httpVersion')) )) { return; } // no need to bother with the length if (!options.knownLength) { this._valuesToMeasure.push(value); } }; FormData.prototype._lengthRetriever = function(value, callback) { if (value.hasOwnProperty('fd')) { // take read range into a account // `end` = Infinity –> read file till the end // // TODO: Looks like there is bug in Node fs.createReadStream // it doesn't respect `end` options without `start` options // Fix it when node fixes it. // https://github.com/joyent/node/issues/7819 if (value.end != undefined && value.end != Infinity && value.start != undefined) { // when end specified // no need to calculate range // inclusive, starts with 0 callback(null, value.end + 1 - (value.start ? value.start : 0)); // not that fast snoopy } else { // still need to fetch file size from fs fs.stat(value.path, function(err, stat) { var fileSize; if (err) { callback(err); return; } // update final size based on the range options fileSize = stat.size - (value.start ? value.start : 0); callback(null, fileSize); }); } // or http response } else if (value.hasOwnProperty('httpVersion')) { callback(null, +value.headers['content-length']); // or request stream http://github.com/mikeal/request } else if (value.hasOwnProperty('httpModule')) { // wait till response come back value.on('response', function(response) { value.pause(); callback(null, +response.headers['content-length']); }); value.resume(); // something else } else { callback('Unknown stream'); } }; FormData.prototype._multiPartHeader = function(field, value, options) { // custom header specified (as string)? // it becomes responsible for boundary // (e.g. to handle extra CRLFs on .NET servers) if (typeof options.header == 'string') { return options.header; } var contentDisposition = this._getContentDisposition(value, options); var contentType = this._getContentType(value, options); var contents = ''; var headers = { // add custom disposition as third element or keep it two elements if not 'Content-Disposition': ['form-data', 'name="' + field + '"'].concat(contentDisposition || []), // if no content type. allow it to be empty array 'Content-Type': [].concat(contentType || []) }; // allow custom headers. if (typeof options.header == 'object') { populate(headers, options.header); } var header; for (var prop in headers) { if (!headers.hasOwnProperty(prop)) continue; header = headers[prop]; // skip nullish headers. if (header == null) { continue; } // convert all headers to arrays. if (!Array.isArray(header)) { header = [header]; } // add non-empty headers. if (header.length) { contents += prop + ': ' + header.join('; ') + FormData.LINE_BREAK; } } return '--' + this.getBoundary() + FormData.LINE_BREAK + contents + FormData.LINE_BREAK; }; FormData.prototype._getContentDisposition = function(value, options) { var filename , contentDisposition ; if (typeof options.filepath === 'string') { // custom filepath for relative paths filename = path.normalize(options.filepath).replace(/\\/g, '/'); } else if (options.filename || value.name || value.path) { // custom filename take precedence // formidable and the browser add a name property // fs- and request- streams have path property filename = path.basename(options.filename || value.name || value.path); } else if (value.readable && value.hasOwnProperty('httpVersion')) { // or try http response filename = path.basename(value.client._httpMessage.path); } if (filename) { contentDisposition = 'filename="' + filename + '"'; } return contentDisposition; }; FormData.prototype._getContentType = function(value, options) { // use custom content-type above all var contentType = options.contentType; // or try `name` from formidable, browser if (!contentType && value.name) { contentType = mime.lookup(value.name); } // or try `path` from fs-, request- streams if (!contentType && value.path) { contentType = mime.lookup(value.path); } // or if it's http-reponse if (!contentType && value.readable && value.hasOwnProperty('httpVersion')) { contentType = value.headers['content-type']; } // or guess it from the filepath or filename if (!contentType && (options.filepath || options.filename)) { contentType = mime.lookup(options.filepath || options.filename); } // fallback to the default content type if `value` is not simple value if (!contentType && typeof value == 'object') { contentType = FormData.DEFAULT_CONTENT_TYPE; } return contentType; }; FormData.prototype._multiPartFooter = function() { return function(next) { var footer = FormData.LINE_BREAK; var lastPart = (this._streams.length === 0); if (lastPart) { footer += this._lastBoundary(); } next(footer); }.bind(this); }; FormData.prototype._lastBoundary = function() { return '--' + this.getBoundary() + '--' + FormData.LINE_BREAK; }; FormData.prototype.getHeaders = function(userHeaders) { var header; var formHeaders = { 'content-type': 'multipart/form-data; boundary=' + this.getBoundary() }; for (header in userHeaders) { if (userHeaders.hasOwnProperty(header)) { formHeaders[header.toLowerCase()] = userHeaders[header]; } } return formHeaders; }; FormData.prototype.getBoundary = function() { if (!this._boundary) { this._generateBoundary(); } return this._boundary; }; FormData.prototype._generateBoundary = function() { // This generates a 50 character boundary similar to those used by Firefox. // They are optimized for boyer-moore parsing. var boundary = '--------------------------'; for (var i = 0; i < 24; i++) { boundary += Math.floor(Math.random() * 10).toString(16); } this._boundary = boundary; }; // Note: getLengthSync DOESN'T calculate streams length // As workaround one can calculate file size manually // and add it as knownLength option FormData.prototype.getLengthSync = function() { var knownLength = this._overheadLength + this._valueLength; // Don't get confused, there are 3 "internal" streams for each keyval pair // so it basically checks if there is any value added to the form if (this._streams.length) { knownLength += this._lastBoundary().length; } // https://github.com/form-data/form-data/issues/40 if (!this.hasKnownLength()) { // Some async length retrievers are present // therefore synchronous length calculation is false. // Please use getLength(callback) to get proper length this._error(new Error('Cannot calculate proper length in synchronous way.')); } return knownLength; }; // Public API to check if length of added values is known // https://github.com/form-data/form-data/issues/196 // https://github.com/form-data/form-data/issues/262 FormData.prototype.hasKnownLength = function() { var hasKnownLength = true; if (this._valuesToMeasure.length) { hasKnownLength = false; } return hasKnownLength; }; FormData.prototype.getLength = function(cb) { var knownLength = this._overheadLength + this._valueLength; if (this._streams.length) { knownLength += this._lastBoundary().length; } if (!this._valuesToMeasure.length) { process.nextTick(cb.bind(this, null, knownLength)); return; } asynckit.parallel(this._valuesToMeasure, this._lengthRetriever, function(err, values) { if (err) { cb(err); return; } values.forEach(function(length) { knownLength += length; }); cb(null, knownLength); }); }; FormData.prototype.submit = function(params, cb) { var request , options , defaults = {method: 'post'} ; // parse provided url if it's string // or treat it as options object if (typeof params == 'string') { params = parseUrl(params); options = populate({ port: params.port, path: params.pathname, host: params.hostname, protocol: params.protocol }, defaults); // use custom params } else { options = populate(params, defaults); // if no port provided use default one if (!options.port) { options.port = options.protocol == 'https:' ? 443 : 80; } } // put that good code in getHeaders to some use options.headers = this.getHeaders(params.headers); // https if specified, fallback to http in any other case if (options.protocol == 'https:') { request = https.request(options); } else { request = http.request(options); } // get content length and fire away this.getLength(function(err, length) { if (err) { this._error(err); return; } // add content length request.setHeader('Content-Length', length); this.pipe(request); if (cb) { request.on('error', cb); request.on('response', cb.bind(this, null)); } }.bind(this)); return request; }; FormData.prototype._error = function(err) { if (!this.error) { this.error = err; this.pause(); this.emit('error', err); } }; FormData.prototype.toString = function () { return '[object FormData]'; }; /***/ }), /***/ 94932: /***/ ((module) => { // populates missing values module.exports = function(dst, src) { Object.keys(src).forEach(function(prop) { dst[prop] = dst[prop] || src[prop]; }); return dst; }; /***/ }), /***/ 28321: /***/ ((module) => { "use strict"; var replace = String.prototype.replace; var percentTwenties = /%20/g; module.exports = { 'default': 'RFC3986', formatters: { RFC1738: function (value) { return replace.call(value, percentTwenties, '+'); }, RFC3986: function (value) { return String(value); } }, RFC1738: 'RFC1738', RFC3986: 'RFC3986' }; /***/ }), /***/ 47457: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var stringify = __nccwpck_require__(64021); var parse = __nccwpck_require__(90693); var formats = __nccwpck_require__(28321); module.exports = { formats: formats, parse: parse, stringify: stringify }; /***/ }), /***/ 90693: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var utils = __nccwpck_require__(17409); var has = Object.prototype.hasOwnProperty; var defaults = { allowDots: false, allowPrototypes: false, arrayLimit: 20, decoder: utils.decode, delimiter: '&', depth: 5, parameterLimit: 1000, plainObjects: false, strictNullHandling: false }; var parseValues = function parseQueryStringValues(str, options) { var obj = {}; var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, '') : str; var limit = options.parameterLimit === Infinity ? undefined : options.parameterLimit; var parts = cleanStr.split(options.delimiter, limit); for (var i = 0; i < parts.length; ++i) { var part = parts[i]; var bracketEqualsPos = part.indexOf(']='); var pos = bracketEqualsPos === -1 ? part.indexOf('=') : bracketEqualsPos + 1; var key, val; if (pos === -1) { key = options.decoder(part, defaults.decoder); val = options.strictNullHandling ? null : ''; } else { key = options.decoder(part.slice(0, pos), defaults.decoder); val = options.decoder(part.slice(pos + 1), defaults.decoder); } if (has.call(obj, key)) { obj[key] = [].concat(obj[key]).concat(val); } else { obj[key] = val; } } return obj; }; var parseObject = function (chain, val, options) { var leaf = val; for (var i = chain.length - 1; i >= 0; --i) { var obj; var root = chain[i]; if (root === '[]' && options.parseArrays) { obj = [].concat(leaf); } else { obj = options.plainObjects ? Object.create(null) : {}; var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root; var index = parseInt(cleanRoot, 10); if (!options.parseArrays && cleanRoot === '') { obj = { 0: leaf }; } else if ( !isNaN(index) && root !== cleanRoot && String(index) === cleanRoot && index >= 0 && (options.parseArrays && index <= options.arrayLimit) ) { obj = []; obj[index] = leaf; } else if (cleanRoot !== '__proto__') { obj[cleanRoot] = leaf; } } leaf = obj; } return leaf; }; var parseKeys = function parseQueryStringKeys(givenKey, val, options) { if (!givenKey) { return; } // Transform dot notation to bracket notation var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, '[$1]') : givenKey; // The regex chunks var brackets = /(\[[^[\]]*])/; var child = /(\[[^[\]]*])/g; // Get the parent var segment = brackets.exec(key); var parent = segment ? key.slice(0, segment.index) : key; // Stash the parent if it exists var keys = []; if (parent) { // If we aren't using plain objects, optionally prefix keys // that would overwrite object prototype properties if (!options.plainObjects && has.call(Object.prototype, parent)) { if (!options.allowPrototypes) { return; } } keys.push(parent); } // Loop through children appending to the array until we hit depth var i = 0; while ((segment = child.exec(key)) !== null && i < options.depth) { i += 1; if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) { if (!options.allowPrototypes) { return; } } keys.push(segment[1]); } // If there's a remainder, just add whatever is left if (segment) { keys.push('[' + key.slice(segment.index) + ']'); } return parseObject(keys, val, options); }; module.exports = function (str, opts) { var options = opts ? utils.assign({}, opts) : {}; if (options.decoder !== null && options.decoder !== undefined && typeof options.decoder !== 'function') { throw new TypeError('Decoder has to be a function.'); } options.ignoreQueryPrefix = options.ignoreQueryPrefix === true; options.delimiter = typeof options.delimiter === 'string' || utils.isRegExp(options.delimiter) ? options.delimiter : defaults.delimiter; options.depth = typeof options.depth === 'number' ? options.depth : defaults.depth; options.arrayLimit = typeof options.arrayLimit === 'number' ? options.arrayLimit : defaults.arrayLimit; options.parseArrays = options.parseArrays !== false; options.decoder = typeof options.decoder === 'function' ? options.decoder : defaults.decoder; options.allowDots = typeof options.allowDots === 'boolean' ? options.allowDots : defaults.allowDots; options.plainObjects = typeof options.plainObjects === 'boolean' ? options.plainObjects : defaults.plainObjects; options.allowPrototypes = typeof options.allowPrototypes === 'boolean' ? options.allowPrototypes : defaults.allowPrototypes; options.parameterLimit = typeof options.parameterLimit === 'number' ? options.parameterLimit : defaults.parameterLimit; options.strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults.strictNullHandling; if (str === '' || str === null || typeof str === 'undefined') { return options.plainObjects ? Object.create(null) : {}; } var tempObj = typeof str === 'string' ? parseValues(str, options) : str; var obj = options.plainObjects ? Object.create(null) : {}; // Iterate over the keys and setup the new object var keys = Object.keys(tempObj); for (var i = 0; i < keys.length; ++i) { var key = keys[i]; var newObj = parseKeys(key, tempObj[key], options); obj = utils.merge(obj, newObj, options); } return utils.compact(obj); }; /***/ }), /***/ 64021: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var utils = __nccwpck_require__(17409); var formats = __nccwpck_require__(28321); var arrayPrefixGenerators = { brackets: function brackets(prefix) { return prefix + '[]'; }, indices: function indices(prefix, key) { return prefix + '[' + key + ']'; }, repeat: function repeat(prefix) { return prefix; } }; var isArray = Array.isArray; var push = Array.prototype.push; var pushToArray = function (arr, valueOrArray) { push.apply(arr, isArray(valueOrArray) ? valueOrArray : [valueOrArray]); }; var toISO = Date.prototype.toISOString; var defaults = { delimiter: '&', encode: true, encoder: utils.encode, encodeValuesOnly: false, serializeDate: function serializeDate(date) { return toISO.call(date); }, skipNulls: false, strictNullHandling: false }; var stringify = function stringify( object, prefix, generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter, encodeValuesOnly ) { var obj = object; if (typeof filter === 'function') { obj = filter(prefix, obj); } else if (obj instanceof Date) { obj = serializeDate(obj); } if (obj === null) { if (strictNullHandling) { return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder) : prefix; } obj = ''; } if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean' || utils.isBuffer(obj)) { if (encoder) { var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder); return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults.encoder))]; } return [formatter(prefix) + '=' + formatter(String(obj))]; } var values = []; if (typeof obj === 'undefined') { return values; } var objKeys; if (isArray(filter)) { objKeys = filter; } else { var keys = Object.keys(obj); objKeys = sort ? keys.sort(sort) : keys; } for (var i = 0; i < objKeys.length; ++i) { var key = objKeys[i]; if (skipNulls && obj[key] === null) { continue; } if (isArray(obj)) { pushToArray(values, stringify( obj[key], generateArrayPrefix(prefix, key), generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter, encodeValuesOnly )); } else { pushToArray(values, stringify( obj[key], prefix + (allowDots ? '.' + key : '[' + key + ']'), generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter, encodeValuesOnly )); } } return values; }; module.exports = function (object, opts) { var obj = object; var options = opts ? utils.assign({}, opts) : {}; if (options.encoder !== null && typeof options.encoder !== 'undefined' && typeof options.encoder !== 'function') { throw new TypeError('Encoder has to be a function.'); } var delimiter = typeof options.delimiter === 'undefined' ? defaults.delimiter : options.delimiter; var strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults.strictNullHandling; var skipNulls = typeof options.skipNulls === 'boolean' ? options.skipNulls : defaults.skipNulls; var encode = typeof options.encode === 'boolean' ? options.encode : defaults.encode; var encoder = typeof options.encoder === 'function' ? options.encoder : defaults.encoder; var sort = typeof options.sort === 'function' ? options.sort : null; var allowDots = typeof options.allowDots === 'undefined' ? false : options.allowDots; var serializeDate = typeof options.serializeDate === 'function' ? options.serializeDate : defaults.serializeDate; var encodeValuesOnly = typeof options.encodeValuesOnly === 'boolean' ? options.encodeValuesOnly : defaults.encodeValuesOnly; if (typeof options.format === 'undefined') { options.format = formats['default']; } else if (!Object.prototype.hasOwnProperty.call(formats.formatters, options.format)) { throw new TypeError('Unknown format option provided.'); } var formatter = formats.formatters[options.format]; var objKeys; var filter; if (typeof options.filter === 'function') { filter = options.filter; obj = filter('', obj); } else if (isArray(options.filter)) { filter = options.filter; objKeys = filter; } var keys = []; if (typeof obj !== 'object' || obj === null) { return ''; } var arrayFormat; if (options.arrayFormat in arrayPrefixGenerators) { arrayFormat = options.arrayFormat; } else if ('indices' in options) { arrayFormat = options.indices ? 'indices' : 'repeat'; } else { arrayFormat = 'indices'; } var generateArrayPrefix = arrayPrefixGenerators[arrayFormat]; if (!objKeys) { objKeys = Object.keys(obj); } if (sort) { objKeys.sort(sort); } for (var i = 0; i < objKeys.length; ++i) { var key = objKeys[i]; if (skipNulls && obj[key] === null) { continue; } pushToArray(keys, stringify( obj[key], key, generateArrayPrefix, strictNullHandling, skipNulls, encode ? encoder : null, filter, sort, allowDots, serializeDate, formatter, encodeValuesOnly )); } var joined = keys.join(delimiter); var prefix = options.addQueryPrefix === true ? '?' : ''; return joined.length > 0 ? prefix + joined : ''; }; /***/ }), /***/ 17409: /***/ ((module) => { "use strict"; var has = Object.prototype.hasOwnProperty; var hexTable = (function () { var array = []; for (var i = 0; i < 256; ++i) { array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase()); } return array; }()); var compactQueue = function compactQueue(queue) { var obj; while (queue.length) { var item = queue.pop(); obj = item.obj[item.prop]; if (Array.isArray(obj)) { var compacted = []; for (var j = 0; j < obj.length; ++j) { if (typeof obj[j] !== 'undefined') { compacted.push(obj[j]); } } item.obj[item.prop] = compacted; } } return obj; }; var arrayToObject = function arrayToObject(source, options) { var obj = options && options.plainObjects ? Object.create(null) : {}; for (var i = 0; i < source.length; ++i) { if (typeof source[i] !== 'undefined') { obj[i] = source[i]; } } return obj; }; var merge = function merge(target, source, options) { if (!source) { return target; } if (typeof source !== 'object') { if (Array.isArray(target)) { target.push(source); } else if (target && typeof target === 'object') { if ((options && (options.plainObjects || options.allowPrototypes)) || !has.call(Object.prototype, source)) { target[source] = true; } } else { return [target, source]; } return target; } if (!target || typeof target !== 'object') { return [target].concat(source); } var mergeTarget = target; if (Array.isArray(target) && !Array.isArray(source)) { mergeTarget = arrayToObject(target, options); } if (Array.isArray(target) && Array.isArray(source)) { source.forEach(function (item, i) { if (has.call(target, i)) { var targetItem = target[i]; if (targetItem && typeof targetItem === 'object' && item && typeof item === 'object') { target[i] = merge(targetItem, item, options); } else { target.push(item); } } else { target[i] = item; } }); return target; } return Object.keys(source).reduce(function (acc, key) { var value = source[key]; if (has.call(acc, key)) { acc[key] = merge(acc[key], value, options); } else { acc[key] = value; } return acc; }, mergeTarget); }; var assign = function assignSingleSource(target, source) { return Object.keys(source).reduce(function (acc, key) { acc[key] = source[key]; return acc; }, target); }; var decode = function (str) { try { return decodeURIComponent(str.replace(/\+/g, ' ')); } catch (e) { return str; } }; var encode = function encode(str) { // This code was originally written by Brian White (mscdex) for the io.js core querystring library. // It has been adapted here for stricter adherence to RFC 3986 if (str.length === 0) { return str; } var string = typeof str === 'string' ? str : String(str); var out = ''; for (var i = 0; i < string.length; ++i) { var c = string.charCodeAt(i); if ( c === 0x2D // - || c === 0x2E // . || c === 0x5F // _ || c === 0x7E // ~ || (c >= 0x30 && c <= 0x39) // 0-9 || (c >= 0x41 && c <= 0x5A) // a-z || (c >= 0x61 && c <= 0x7A) // A-Z ) { out += string.charAt(i); continue; } if (c < 0x80) { out = out + hexTable[c]; continue; } if (c < 0x800) { out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]); continue; } if (c < 0xD800 || c >= 0xE000) { out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]); continue; } i += 1; c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF)); /* eslint operator-linebreak: [2, "before"] */ out += hexTable[0xF0 | (c >> 18)] + hexTable[0x80 | ((c >> 12) & 0x3F)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]; } return out; }; var compact = function compact(value) { var queue = [{ obj: { o: value }, prop: 'o' }]; var refs = []; for (var i = 0; i < queue.length; ++i) { var item = queue[i]; var obj = item.obj[item.prop]; var keys = Object.keys(obj); for (var j = 0; j < keys.length; ++j) { var key = keys[j]; var val = obj[key]; if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) { queue.push({ obj: obj, prop: key }); refs.push(val); } } } return compactQueue(queue); }; var isRegExp = function isRegExp(obj) { return Object.prototype.toString.call(obj) === '[object RegExp]'; }; var isBuffer = function isBuffer(obj) { if (obj === null || typeof obj === 'undefined') { return false; } return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); }; module.exports = { arrayToObject: arrayToObject, assign: assign, compact: compact, decode: decode, encode: encode, isBuffer: isBuffer, isRegExp: isRegExp, merge: merge }; /***/ }), /***/ 67087: /***/ ((module) => { /** * Convert array of 16 byte values to UUID string format of the form: * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX */ var byteToHex = []; for (var i = 0; i < 256; ++i) { byteToHex[i] = (i + 0x100).toString(16).substr(1); } function bytesToUuid(buf, offset) { var i = offset || 0; var bth = byteToHex; // join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4 return ([ bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]] ]).join(''); } module.exports = bytesToUuid; /***/ }), /***/ 9117: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // Unique ID creation requires a high quality random # generator. In node.js // this is pretty straight-forward - we use the crypto API. var crypto = __nccwpck_require__(6113); module.exports = function nodeRNG() { return crypto.randomBytes(16); }; /***/ }), /***/ 71435: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var rng = __nccwpck_require__(9117); var bytesToUuid = __nccwpck_require__(67087); function v4(options, buf, offset) { var i = buf && offset || 0; if (typeof(options) == 'string') { buf = options === 'binary' ? new Array(16) : null; options = null; } options = options || {}; var rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` rnds[6] = (rnds[6] & 0x0f) | 0x40; rnds[8] = (rnds[8] & 0x3f) | 0x80; // Copy bytes to buffer, if provided if (buf) { for (var ii = 0; ii < 16; ++ii) { buf[i + ii] = rnds[ii]; } } return buf || bytesToUuid(rnds); } module.exports = v4; /***/ }), /***/ 70304: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var http = __nccwpck_require__(13685) var https = __nccwpck_require__(95687) var url = __nccwpck_require__(57310) var util = __nccwpck_require__(73837) var stream = __nccwpck_require__(12781) var zlib = __nccwpck_require__(59796) var aws2 = __nccwpck_require__(96342) var aws4 = __nccwpck_require__(16071) var httpSignature = __nccwpck_require__(42479) var mime = __nccwpck_require__(43583) var caseless = __nccwpck_require__(35684) var ForeverAgent = __nccwpck_require__(47568) var FormData = __nccwpck_require__(11377) var extend = __nccwpck_require__(38171) var isstream = __nccwpck_require__(83362) var isTypedArray = (__nccwpck_require__(10657).strict) var helpers = __nccwpck_require__(74845) var cookies = __nccwpck_require__(50976) var getProxyFromURI = __nccwpck_require__(75654) var Querystring = (__nccwpck_require__(66476)/* .Querystring */ .h) var Har = (__nccwpck_require__(3248)/* .Har */ .t) var Auth = (__nccwpck_require__(76996)/* .Auth */ .g) var OAuth = (__nccwpck_require__(41174)/* .OAuth */ .f) var hawk = __nccwpck_require__(34473) var Multipart = (__nccwpck_require__(87810)/* .Multipart */ .$) var Redirect = (__nccwpck_require__(3048)/* .Redirect */ .l) var Tunnel = (__nccwpck_require__(17619)/* .Tunnel */ .n) var now = __nccwpck_require__(85644) var Buffer = (__nccwpck_require__(21867).Buffer) var safeStringify = helpers.safeStringify var isReadStream = helpers.isReadStream var toBase64 = helpers.toBase64 var defer = helpers.defer var copy = helpers.copy var version = helpers.version var globalCookieJar = cookies.jar() var globalPool = {} function filterForNonReserved (reserved, options) { // Filter out properties that are not reserved. // Reserved values are passed in at call site. var object = {} for (var i in options) { var notReserved = (reserved.indexOf(i) === -1) if (notReserved) { object[i] = options[i] } } return object } function filterOutReservedFunctions (reserved, options) { // Filter out properties that are functions and are reserved. // Reserved values are passed in at call site. var object = {} for (var i in options) { var isReserved = !(reserved.indexOf(i) === -1) var isFunction = (typeof options[i] === 'function') if (!(isReserved && isFunction)) { object[i] = options[i] } } return object } // Return a simpler request object to allow serialization function requestToJSON () { var self = this return { uri: self.uri, method: self.method, headers: self.headers } } // Return a simpler response object to allow serialization function responseToJSON () { var self = this return { statusCode: self.statusCode, body: self.body, headers: self.headers, request: requestToJSON.call(self.request) } } function Request (options) { // if given the method property in options, set property explicitMethod to true // extend the Request instance with any non-reserved properties // remove any reserved functions from the options object // set Request instance to be readable and writable // call init var self = this // start with HAR, then override with additional options if (options.har) { self._har = new Har(self) options = self._har.options(options) } stream.Stream.call(self) var reserved = Object.keys(Request.prototype) var nonReserved = filterForNonReserved(reserved, options) extend(self, nonReserved) options = filterOutReservedFunctions(reserved, options) self.readable = true self.writable = true if (options.method) { self.explicitMethod = true } self._qs = new Querystring(self) self._auth = new Auth(self) self._oauth = new OAuth(self) self._multipart = new Multipart(self) self._redirect = new Redirect(self) self._tunnel = new Tunnel(self) self.init(options) } util.inherits(Request, stream.Stream) // Debugging Request.debug = process.env.NODE_DEBUG && /\brequest\b/.test(process.env.NODE_DEBUG) function debug () { if (Request.debug) { console.error('REQUEST %s', util.format.apply(util, arguments)) } } Request.prototype.debug = debug Request.prototype.init = function (options) { // init() contains all the code to setup the request object. // the actual outgoing request is not started until start() is called // this function is called from both the constructor and on redirect. var self = this if (!options) { options = {} } self.headers = self.headers ? copy(self.headers) : {} // Delete headers with value undefined since they break // ClientRequest.OutgoingMessage.setHeader in node 0.12 for (var headerName in self.headers) { if (typeof self.headers[headerName] === 'undefined') { delete self.headers[headerName] } } caseless.httpify(self, self.headers) if (!self.method) { self.method = options.method || 'GET' } if (!self.localAddress) { self.localAddress = options.localAddress } self._qs.init(options) debug(options) if (!self.pool && self.pool !== false) { self.pool = globalPool } self.dests = self.dests || [] self.__isRequestRequest = true // Protect against double callback if (!self._callback && self.callback) { self._callback = self.callback self.callback = function () { if (self._callbackCalled) { return // Print a warning maybe? } self._callbackCalled = true self._callback.apply(self, arguments) } self.on('error', self.callback.bind()) self.on('complete', self.callback.bind(self, null)) } // People use this property instead all the time, so support it if (!self.uri && self.url) { self.uri = self.url delete self.url } // If there's a baseUrl, then use it as the base URL (i.e. uri must be // specified as a relative path and is appended to baseUrl). if (self.baseUrl) { if (typeof self.baseUrl !== 'string') { return self.emit('error', new Error('options.baseUrl must be a string')) } if (typeof self.uri !== 'string') { return self.emit('error', new Error('options.uri must be a string when using options.baseUrl')) } if (self.uri.indexOf('//') === 0 || self.uri.indexOf('://') !== -1) { return self.emit('error', new Error('options.uri must be a path when using options.baseUrl')) } // Handle all cases to make sure that there's only one slash between // baseUrl and uri. var baseUrlEndsWithSlash = self.baseUrl.lastIndexOf('/') === self.baseUrl.length - 1 var uriStartsWithSlash = self.uri.indexOf('/') === 0 if (baseUrlEndsWithSlash && uriStartsWithSlash) { self.uri = self.baseUrl + self.uri.slice(1) } else if (baseUrlEndsWithSlash || uriStartsWithSlash) { self.uri = self.baseUrl + self.uri } else if (self.uri === '') { self.uri = self.baseUrl } else { self.uri = self.baseUrl + '/' + self.uri } delete self.baseUrl } // A URI is needed by this point, emit error if we haven't been able to get one if (!self.uri) { return self.emit('error', new Error('options.uri is a required argument')) } // If a string URI/URL was given, parse it into a URL object if (typeof self.uri === 'string') { self.uri = url.parse(self.uri) } // Some URL objects are not from a URL parsed string and need href added if (!self.uri.href) { self.uri.href = url.format(self.uri) } // DEPRECATED: Warning for users of the old Unix Sockets URL Scheme if (self.uri.protocol === 'unix:') { return self.emit('error', new Error('`unix://` URL scheme is no longer supported. Please use the format `http://unix:SOCKET:PATH`')) } // Support Unix Sockets if (self.uri.host === 'unix') { self.enableUnixSocket() } if (self.strictSSL === false) { self.rejectUnauthorized = false } if (!self.uri.pathname) { self.uri.pathname = '/' } if (!(self.uri.host || (self.uri.hostname && self.uri.port)) && !self.uri.isUnix) { // Invalid URI: it may generate lot of bad errors, like 'TypeError: Cannot call method `indexOf` of undefined' in CookieJar // Detect and reject it as soon as possible var faultyUri = url.format(self.uri) var message = 'Invalid URI "' + faultyUri + '"' if (Object.keys(options).length === 0) { // No option ? This can be the sign of a redirect // As this is a case where the user cannot do anything (they didn't call request directly with this URL) // they should be warned that it can be caused by a redirection (can save some hair) message += '. This can be caused by a crappy redirection.' } // This error was fatal self.abort() return self.emit('error', new Error(message)) } if (!self.hasOwnProperty('proxy')) { self.proxy = getProxyFromURI(self.uri) } self.tunnel = self._tunnel.isEnabled() if (self.proxy) { self._tunnel.setup(options) } self._redirect.onRequest(options) self.setHost = false if (!self.hasHeader('host')) { var hostHeaderName = self.originalHostHeaderName || 'host' self.setHeader(hostHeaderName, self.uri.host) // Drop :port suffix from Host header if known protocol. if (self.uri.port) { if ((self.uri.port === '80' && self.uri.protocol === 'http:') || (self.uri.port === '443' && self.uri.protocol === 'https:')) { self.setHeader(hostHeaderName, self.uri.hostname) } } self.setHost = true } self.jar(self._jar || options.jar) if (!self.uri.port) { if (self.uri.protocol === 'http:') { self.uri.port = 80 } else if (self.uri.protocol === 'https:') { self.uri.port = 443 } } if (self.proxy && !self.tunnel) { self.port = self.proxy.port self.host = self.proxy.hostname } else { self.port = self.uri.port self.host = self.uri.hostname } if (options.form) { self.form(options.form) } if (options.formData) { var formData = options.formData var requestForm = self.form() var appendFormValue = function (key, value) { if (value && value.hasOwnProperty('value') && value.hasOwnProperty('options')) { requestForm.append(key, value.value, value.options) } else { requestForm.append(key, value) } } for (var formKey in formData) { if (formData.hasOwnProperty(formKey)) { var formValue = formData[formKey] if (formValue instanceof Array) { for (var j = 0; j < formValue.length; j++) { appendFormValue(formKey, formValue[j]) } } else { appendFormValue(formKey, formValue) } } } } if (options.qs) { self.qs(options.qs) } if (self.uri.path) { self.path = self.uri.path } else { self.path = self.uri.pathname + (self.uri.search || '') } if (self.path.length === 0) { self.path = '/' } // Auth must happen last in case signing is dependent on other headers if (options.aws) { self.aws(options.aws) } if (options.hawk) { self.hawk(options.hawk) } if (options.httpSignature) { self.httpSignature(options.httpSignature) } if (options.auth) { if (Object.prototype.hasOwnProperty.call(options.auth, 'username')) { options.auth.user = options.auth.username } if (Object.prototype.hasOwnProperty.call(options.auth, 'password')) { options.auth.pass = options.auth.password } self.auth( options.auth.user, options.auth.pass, options.auth.sendImmediately, options.auth.bearer ) } if (self.gzip && !self.hasHeader('accept-encoding')) { self.setHeader('accept-encoding', 'gzip, deflate') } if (self.uri.auth && !self.hasHeader('authorization')) { var uriAuthPieces = self.uri.auth.split(':').map(function (item) { return self._qs.unescape(item) }) self.auth(uriAuthPieces[0], uriAuthPieces.slice(1).join(':'), true) } if (!self.tunnel && self.proxy && self.proxy.auth && !self.hasHeader('proxy-authorization')) { var proxyAuthPieces = self.proxy.auth.split(':').map(function (item) { return self._qs.unescape(item) }) var authHeader = 'Basic ' + toBase64(proxyAuthPieces.join(':')) self.setHeader('proxy-authorization', authHeader) } if (self.proxy && !self.tunnel) { self.path = (self.uri.protocol + '//' + self.uri.host + self.path) } if (options.json) { self.json(options.json) } if (options.multipart) { self.multipart(options.multipart) } if (options.time) { self.timing = true // NOTE: elapsedTime is deprecated in favor of .timings self.elapsedTime = self.elapsedTime || 0 } function setContentLength () { if (isTypedArray(self.body)) { self.body = Buffer.from(self.body) } if (!self.hasHeader('content-length')) { var length if (typeof self.body === 'string') { length = Buffer.byteLength(self.body) } else if (Array.isArray(self.body)) { length = self.body.reduce(function (a, b) { return a + b.length }, 0) } else { length = self.body.length } if (length) { self.setHeader('content-length', length) } else { self.emit('error', new Error('Argument error, options.body.')) } } } if (self.body && !isstream(self.body)) { setContentLength() } if (options.oauth) { self.oauth(options.oauth) } else if (self._oauth.params && self.hasHeader('authorization')) { self.oauth(self._oauth.params) } var protocol = self.proxy && !self.tunnel ? self.proxy.protocol : self.uri.protocol var defaultModules = {'http:': http, 'https:': https} var httpModules = self.httpModules || {} self.httpModule = httpModules[protocol] || defaultModules[protocol] if (!self.httpModule) { return self.emit('error', new Error('Invalid protocol: ' + protocol)) } if (options.ca) { self.ca = options.ca } if (!self.agent) { if (options.agentOptions) { self.agentOptions = options.agentOptions } if (options.agentClass) { self.agentClass = options.agentClass } else if (options.forever) { var v = version() // use ForeverAgent in node 0.10- only if (v.major === 0 && v.minor <= 10) { self.agentClass = protocol === 'http:' ? ForeverAgent : ForeverAgent.SSL } else { self.agentClass = self.httpModule.Agent self.agentOptions = self.agentOptions || {} self.agentOptions.keepAlive = true } } else { self.agentClass = self.httpModule.Agent } } if (self.pool === false) { self.agent = false } else { self.agent = self.agent || self.getNewAgent() } self.on('pipe', function (src) { if (self.ntick && self._started) { self.emit('error', new Error('You cannot pipe to this stream after the outbound request has started.')) } self.src = src if (isReadStream(src)) { if (!self.hasHeader('content-type')) { self.setHeader('content-type', mime.lookup(src.path)) } } else { if (src.headers) { for (var i in src.headers) { if (!self.hasHeader(i)) { self.setHeader(i, src.headers[i]) } } } if (self._json && !self.hasHeader('content-type')) { self.setHeader('content-type', 'application/json') } if (src.method && !self.explicitMethod) { self.method = src.method } } // self.on('pipe', function () { // console.error('You have already piped to this stream. Pipeing twice is likely to break the request.') // }) }) defer(function () { if (self._aborted) { return } var end = function () { if (self._form) { if (!self._auth.hasAuth) { self._form.pipe(self) } else if (self._auth.hasAuth && self._auth.sentAuth) { self._form.pipe(self) } } if (self._multipart && self._multipart.chunked) { self._multipart.body.pipe(self) } if (self.body) { if (isstream(self.body)) { self.body.pipe(self) } else { setContentLength() if (Array.isArray(self.body)) { self.body.forEach(function (part) { self.write(part) }) } else { self.write(self.body) } self.end() } } else if (self.requestBodyStream) { console.warn('options.requestBodyStream is deprecated, please pass the request object to stream.pipe.') self.requestBodyStream.pipe(self) } else if (!self.src) { if (self._auth.hasAuth && !self._auth.sentAuth) { self.end() return } if (self.method !== 'GET' && typeof self.method !== 'undefined') { self.setHeader('content-length', 0) } self.end() } } if (self._form && !self.hasHeader('content-length')) { // Before ending the request, we had to compute the length of the whole form, asyncly self.setHeader(self._form.getHeaders(), true) self._form.getLength(function (err, length) { if (!err && !isNaN(length)) { self.setHeader('content-length', length) } end() }) } else { end() } self.ntick = true }) } Request.prototype.getNewAgent = function () { var self = this var Agent = self.agentClass var options = {} if (self.agentOptions) { for (var i in self.agentOptions) { options[i] = self.agentOptions[i] } } if (self.ca) { options.ca = self.ca } if (self.ciphers) { options.ciphers = self.ciphers } if (self.secureProtocol) { options.secureProtocol = self.secureProtocol } if (self.secureOptions) { options.secureOptions = self.secureOptions } if (typeof self.rejectUnauthorized !== 'undefined') { options.rejectUnauthorized = self.rejectUnauthorized } if (self.cert && self.key) { options.key = self.key options.cert = self.cert } if (self.pfx) { options.pfx = self.pfx } if (self.passphrase) { options.passphrase = self.passphrase } var poolKey = '' // different types of agents are in different pools if (Agent !== self.httpModule.Agent) { poolKey += Agent.name } // ca option is only relevant if proxy or destination are https var proxy = self.proxy if (typeof proxy === 'string') { proxy = url.parse(proxy) } var isHttps = (proxy && proxy.protocol === 'https:') || this.uri.protocol === 'https:' if (isHttps) { if (options.ca) { if (poolKey) { poolKey += ':' } poolKey += options.ca } if (typeof options.rejectUnauthorized !== 'undefined') { if (poolKey) { poolKey += ':' } poolKey += options.rejectUnauthorized } if (options.cert) { if (poolKey) { poolKey += ':' } poolKey += options.cert.toString('ascii') + options.key.toString('ascii') } if (options.pfx) { if (poolKey) { poolKey += ':' } poolKey += options.pfx.toString('ascii') } if (options.ciphers) { if (poolKey) { poolKey += ':' } poolKey += options.ciphers } if (options.secureProtocol) { if (poolKey) { poolKey += ':' } poolKey += options.secureProtocol } if (options.secureOptions) { if (poolKey) { poolKey += ':' } poolKey += options.secureOptions } } if (self.pool === globalPool && !poolKey && Object.keys(options).length === 0 && self.httpModule.globalAgent) { // not doing anything special. Use the globalAgent return self.httpModule.globalAgent } // we're using a stored agent. Make sure it's protocol-specific poolKey = self.uri.protocol + poolKey // generate a new agent for this setting if none yet exists if (!self.pool[poolKey]) { self.pool[poolKey] = new Agent(options) // properly set maxSockets on new agents if (self.pool.maxSockets) { self.pool[poolKey].maxSockets = self.pool.maxSockets } } return self.pool[poolKey] } Request.prototype.start = function () { // start() is called once we are ready to send the outgoing HTTP request. // this is usually called on the first write(), end() or on nextTick() var self = this if (self.timing) { // All timings will be relative to this request's startTime. In order to do this, // we need to capture the wall-clock start time (via Date), immediately followed // by the high-resolution timer (via now()). While these two won't be set // at the _exact_ same time, they should be close enough to be able to calculate // high-resolution, monotonically non-decreasing timestamps relative to startTime. var startTime = new Date().getTime() var startTimeNow = now() } if (self._aborted) { return } self._started = true self.method = self.method || 'GET' self.href = self.uri.href if (self.src && self.src.stat && self.src.stat.size && !self.hasHeader('content-length')) { self.setHeader('content-length', self.src.stat.size) } if (self._aws) { self.aws(self._aws, true) } // We have a method named auth, which is completely different from the http.request // auth option. If we don't remove it, we're gonna have a bad time. var reqOptions = copy(self) delete reqOptions.auth debug('make request', self.uri.href) // node v6.8.0 now supports a `timeout` value in `http.request()`, but we // should delete it for now since we handle timeouts manually for better // consistency with node versions before v6.8.0 delete reqOptions.timeout try { self.req = self.httpModule.request(reqOptions) } catch (err) { self.emit('error', err) return } if (self.timing) { self.startTime = startTime self.startTimeNow = startTimeNow // Timing values will all be relative to startTime (by comparing to startTimeNow // so we have an accurate clock) self.timings = {} } var timeout if (self.timeout && !self.timeoutTimer) { if (self.timeout < 0) { timeout = 0 } else if (typeof self.timeout === 'number' && isFinite(self.timeout)) { timeout = self.timeout } } self.req.on('response', self.onRequestResponse.bind(self)) self.req.on('error', self.onRequestError.bind(self)) self.req.on('drain', function () { self.emit('drain') }) self.req.on('socket', function (socket) { // `._connecting` was the old property which was made public in node v6.1.0 var isConnecting = socket._connecting || socket.connecting if (self.timing) { self.timings.socket = now() - self.startTimeNow if (isConnecting) { var onLookupTiming = function () { self.timings.lookup = now() - self.startTimeNow } var onConnectTiming = function () { self.timings.connect = now() - self.startTimeNow } socket.once('lookup', onLookupTiming) socket.once('connect', onConnectTiming) // clean up timing event listeners if needed on error self.req.once('error', function () { socket.removeListener('lookup', onLookupTiming) socket.removeListener('connect', onConnectTiming) }) } } var setReqTimeout = function () { // This timeout sets the amount of time to wait *between* bytes sent // from the server once connected. // // In particular, it's useful for erroring if the server fails to send // data halfway through streaming a response. self.req.setTimeout(timeout, function () { if (self.req) { self.abort() var e = new Error('ESOCKETTIMEDOUT') e.code = 'ESOCKETTIMEDOUT' e.connect = false self.emit('error', e) } }) } if (timeout !== undefined) { // Only start the connection timer if we're actually connecting a new // socket, otherwise if we're already connected (because this is a // keep-alive connection) do not bother. This is important since we won't // get a 'connect' event for an already connected socket. if (isConnecting) { var onReqSockConnect = function () { socket.removeListener('connect', onReqSockConnect) self.clearTimeout() setReqTimeout() } socket.on('connect', onReqSockConnect) self.req.on('error', function (err) { // eslint-disable-line handle-callback-err socket.removeListener('connect', onReqSockConnect) }) // Set a timeout in memory - this block will throw if the server takes more // than `timeout` to write the HTTP status and headers (corresponding to // the on('response') event on the client). NB: this measures wall-clock // time, not the time between bytes sent by the server. self.timeoutTimer = setTimeout(function () { socket.removeListener('connect', onReqSockConnect) self.abort() var e = new Error('ETIMEDOUT') e.code = 'ETIMEDOUT' e.connect = true self.emit('error', e) }, timeout) } else { // We're already connected setReqTimeout() } } self.emit('socket', socket) }) self.emit('request', self.req) } Request.prototype.onRequestError = function (error) { var self = this if (self._aborted) { return } if (self.req && self.req._reusedSocket && error.code === 'ECONNRESET' && self.agent.addRequestNoreuse) { self.agent = { addRequest: self.agent.addRequestNoreuse.bind(self.agent) } self.start() self.req.end() return } self.clearTimeout() self.emit('error', error) } Request.prototype.onRequestResponse = function (response) { var self = this if (self.timing) { self.timings.response = now() - self.startTimeNow } debug('onRequestResponse', self.uri.href, response.statusCode, response.headers) response.on('end', function () { if (self.timing) { self.timings.end = now() - self.startTimeNow response.timingStart = self.startTime // fill in the blanks for any periods that didn't trigger, such as // no lookup or connect due to keep alive if (!self.timings.socket) { self.timings.socket = 0 } if (!self.timings.lookup) { self.timings.lookup = self.timings.socket } if (!self.timings.connect) { self.timings.connect = self.timings.lookup } if (!self.timings.response) { self.timings.response = self.timings.connect } debug('elapsed time', self.timings.end) // elapsedTime includes all redirects self.elapsedTime += Math.round(self.timings.end) // NOTE: elapsedTime is deprecated in favor of .timings response.elapsedTime = self.elapsedTime // timings is just for the final fetch response.timings = self.timings // pre-calculate phase timings as well response.timingPhases = { wait: self.timings.socket, dns: self.timings.lookup - self.timings.socket, tcp: self.timings.connect - self.timings.lookup, firstByte: self.timings.response - self.timings.connect, download: self.timings.end - self.timings.response, total: self.timings.end } } debug('response end', self.uri.href, response.statusCode, response.headers) }) if (self._aborted) { debug('aborted', self.uri.href) response.resume() return } self.response = response response.request = self response.toJSON = responseToJSON // XXX This is different on 0.10, because SSL is strict by default if (self.httpModule === https && self.strictSSL && (!response.hasOwnProperty('socket') || !response.socket.authorized)) { debug('strict ssl error', self.uri.href) var sslErr = response.hasOwnProperty('socket') ? response.socket.authorizationError : self.uri.href + ' does not support SSL' self.emit('error', new Error('SSL Error: ' + sslErr)) return } // Save the original host before any redirect (if it changes, we need to // remove any authorization headers). Also remember the case of the header // name because lots of broken servers expect Host instead of host and we // want the caller to be able to specify this. self.originalHost = self.getHeader('host') if (!self.originalHostHeaderName) { self.originalHostHeaderName = self.hasHeader('host') } if (self.setHost) { self.removeHeader('host') } self.clearTimeout() var targetCookieJar = (self._jar && self._jar.setCookie) ? self._jar : globalCookieJar var addCookie = function (cookie) { // set the cookie if it's domain in the href's domain. try { targetCookieJar.setCookie(cookie, self.uri.href, {ignoreError: true}) } catch (e) { self.emit('error', e) } } response.caseless = caseless(response.headers) if (response.caseless.has('set-cookie') && (!self._disableCookies)) { var headerName = response.caseless.has('set-cookie') if (Array.isArray(response.headers[headerName])) { response.headers[headerName].forEach(addCookie) } else { addCookie(response.headers[headerName]) } } if (self._redirect.onResponse(response)) { return // Ignore the rest of the response } else { // Be a good stream and emit end when the response is finished. // Hack to emit end on close because of a core bug that never fires end response.on('close', function () { if (!self._ended) { self.response.emit('end') } }) response.once('end', function () { self._ended = true }) var noBody = function (code) { return ( self.method === 'HEAD' || // Informational (code >= 100 && code < 200) || // No Content code === 204 || // Not Modified code === 304 ) } var responseContent if (self.gzip && !noBody(response.statusCode)) { var contentEncoding = response.headers['content-encoding'] || 'identity' contentEncoding = contentEncoding.trim().toLowerCase() // Be more lenient with decoding compressed responses, since (very rarely) // servers send slightly invalid gzip responses that are still accepted // by common browsers. // Always using Z_SYNC_FLUSH is what cURL does. var zlibOptions = { flush: zlib.Z_SYNC_FLUSH, finishFlush: zlib.Z_SYNC_FLUSH } if (contentEncoding === 'gzip') { responseContent = zlib.createGunzip(zlibOptions) response.pipe(responseContent) } else if (contentEncoding === 'deflate') { responseContent = zlib.createInflate(zlibOptions) response.pipe(responseContent) } else { // Since previous versions didn't check for Content-Encoding header, // ignore any invalid values to preserve backwards-compatibility if (contentEncoding !== 'identity') { debug('ignoring unrecognized Content-Encoding ' + contentEncoding) } responseContent = response } } else { responseContent = response } if (self.encoding) { if (self.dests.length !== 0) { console.error('Ignoring encoding parameter as this stream is being piped to another stream which makes the encoding option invalid.') } else { responseContent.setEncoding(self.encoding) } } if (self._paused) { responseContent.pause() } self.responseContent = responseContent self.emit('response', response) self.dests.forEach(function (dest) { self.pipeDest(dest) }) responseContent.on('data', function (chunk) { if (self.timing && !self.responseStarted) { self.responseStartTime = (new Date()).getTime() // NOTE: responseStartTime is deprecated in favor of .timings response.responseStartTime = self.responseStartTime } self._destdata = true self.emit('data', chunk) }) responseContent.once('end', function (chunk) { self.emit('end', chunk) }) responseContent.on('error', function (error) { self.emit('error', error) }) responseContent.on('close', function () { self.emit('close') }) if (self.callback) { self.readResponseBody(response) } else { // if no callback self.on('end', function () { if (self._aborted) { debug('aborted', self.uri.href) return } self.emit('complete', response) }) } } debug('finish init function', self.uri.href) } Request.prototype.readResponseBody = function (response) { var self = this debug("reading response's body") var buffers = [] var bufferLength = 0 var strings = [] self.on('data', function (chunk) { if (!Buffer.isBuffer(chunk)) { strings.push(chunk) } else if (chunk.length) { bufferLength += chunk.length buffers.push(chunk) } }) self.on('end', function () { debug('end event', self.uri.href) if (self._aborted) { debug('aborted', self.uri.href) // `buffer` is defined in the parent scope and used in a closure it exists for the life of the request. // This can lead to leaky behavior if the user retains a reference to the request object. buffers = [] bufferLength = 0 return } if (bufferLength) { debug('has body', self.uri.href, bufferLength) response.body = Buffer.concat(buffers, bufferLength) if (self.encoding !== null) { response.body = response.body.toString(self.encoding) } // `buffer` is defined in the parent scope and used in a closure it exists for the life of the Request. // This can lead to leaky behavior if the user retains a reference to the request object. buffers = [] bufferLength = 0 } else if (strings.length) { // The UTF8 BOM [0xEF,0xBB,0xBF] is converted to [0xFE,0xFF] in the JS UTC16/UCS2 representation. // Strip this value out when the encoding is set to 'utf8', as upstream consumers won't expect it and it breaks JSON.parse(). if (self.encoding === 'utf8' && strings[0].length > 0 && strings[0][0] === '\uFEFF') { strings[0] = strings[0].substring(1) } response.body = strings.join('') } if (self._json) { try { response.body = JSON.parse(response.body, self._jsonReviver) } catch (e) { debug('invalid JSON received', self.uri.href) } } debug('emitting complete', self.uri.href) if (typeof response.body === 'undefined' && !self._json) { response.body = self.encoding === null ? Buffer.alloc(0) : '' } self.emit('complete', response, response.body) }) } Request.prototype.abort = function () { var self = this self._aborted = true if (self.req) { self.req.abort() } else if (self.response) { self.response.destroy() } self.clearTimeout() self.emit('abort') } Request.prototype.pipeDest = function (dest) { var self = this var response = self.response // Called after the response is received if (dest.headers && !dest.headersSent) { if (response.caseless.has('content-type')) { var ctname = response.caseless.has('content-type') if (dest.setHeader) { dest.setHeader(ctname, response.headers[ctname]) } else { dest.headers[ctname] = response.headers[ctname] } } if (response.caseless.has('content-length')) { var clname = response.caseless.has('content-length') if (dest.setHeader) { dest.setHeader(clname, response.headers[clname]) } else { dest.headers[clname] = response.headers[clname] } } } if (dest.setHeader && !dest.headersSent) { for (var i in response.headers) { // If the response content is being decoded, the Content-Encoding header // of the response doesn't represent the piped content, so don't pass it. if (!self.gzip || i !== 'content-encoding') { dest.setHeader(i, response.headers[i]) } } dest.statusCode = response.statusCode } if (self.pipefilter) { self.pipefilter(response, dest) } } Request.prototype.qs = function (q, clobber) { var self = this var base if (!clobber && self.uri.query) { base = self._qs.parse(self.uri.query) } else { base = {} } for (var i in q) { base[i] = q[i] } var qs = self._qs.stringify(base) if (qs === '') { return self } self.uri = url.parse(self.uri.href.split('?')[0] + '?' + qs) self.url = self.uri self.path = self.uri.path if (self.uri.host === 'unix') { self.enableUnixSocket() } return self } Request.prototype.form = function (form) { var self = this if (form) { if (!/^application\/x-www-form-urlencoded\b/.test(self.getHeader('content-type'))) { self.setHeader('content-type', 'application/x-www-form-urlencoded') } self.body = (typeof form === 'string') ? self._qs.rfc3986(form.toString('utf8')) : self._qs.stringify(form).toString('utf8') return self } // create form-data object self._form = new FormData() self._form.on('error', function (err) { err.message = 'form-data: ' + err.message self.emit('error', err) self.abort() }) return self._form } Request.prototype.multipart = function (multipart) { var self = this self._multipart.onRequest(multipart) if (!self._multipart.chunked) { self.body = self._multipart.body } return self } Request.prototype.json = function (val) { var self = this if (!self.hasHeader('accept')) { self.setHeader('accept', 'application/json') } if (typeof self.jsonReplacer === 'function') { self._jsonReplacer = self.jsonReplacer } self._json = true if (typeof val === 'boolean') { if (self.body !== undefined) { if (!/^application\/x-www-form-urlencoded\b/.test(self.getHeader('content-type'))) { self.body = safeStringify(self.body, self._jsonReplacer) } else { self.body = self._qs.rfc3986(self.body) } if (!self.hasHeader('content-type')) { self.setHeader('content-type', 'application/json') } } } else { self.body = safeStringify(val, self._jsonReplacer) if (!self.hasHeader('content-type')) { self.setHeader('content-type', 'application/json') } } if (typeof self.jsonReviver === 'function') { self._jsonReviver = self.jsonReviver } return self } Request.prototype.getHeader = function (name, headers) { var self = this var result, re, match if (!headers) { headers = self.headers } Object.keys(headers).forEach(function (key) { if (key.length !== name.length) { return } re = new RegExp(name, 'i') match = key.match(re) if (match) { result = headers[key] } }) return result } Request.prototype.enableUnixSocket = function () { // Get the socket & request paths from the URL var unixParts = this.uri.path.split(':') var host = unixParts[0] var path = unixParts[1] // Apply unix properties to request this.socketPath = host this.uri.pathname = path this.uri.path = path this.uri.host = host this.uri.hostname = host this.uri.isUnix = true } Request.prototype.auth = function (user, pass, sendImmediately, bearer) { var self = this self._auth.onRequest(user, pass, sendImmediately, bearer) return self } Request.prototype.aws = function (opts, now) { var self = this if (!now) { self._aws = opts return self } if (opts.sign_version === 4 || opts.sign_version === '4') { // use aws4 var options = { host: self.uri.host, path: self.uri.path, method: self.method, headers: self.headers, body: self.body } if (opts.service) { options.service = opts.service } var signRes = aws4.sign(options, { accessKeyId: opts.key, secretAccessKey: opts.secret, sessionToken: opts.session }) self.setHeader('authorization', signRes.headers.Authorization) self.setHeader('x-amz-date', signRes.headers['X-Amz-Date']) if (signRes.headers['X-Amz-Security-Token']) { self.setHeader('x-amz-security-token', signRes.headers['X-Amz-Security-Token']) } } else { // default: use aws-sign2 var date = new Date() self.setHeader('date', date.toUTCString()) var auth = { key: opts.key, secret: opts.secret, verb: self.method.toUpperCase(), date: date, contentType: self.getHeader('content-type') || '', md5: self.getHeader('content-md5') || '', amazonHeaders: aws2.canonicalizeHeaders(self.headers) } var path = self.uri.path if (opts.bucket && path) { auth.resource = '/' + opts.bucket + path } else if (opts.bucket && !path) { auth.resource = '/' + opts.bucket } else if (!opts.bucket && path) { auth.resource = path } else if (!opts.bucket && !path) { auth.resource = '/' } auth.resource = aws2.canonicalizeResource(auth.resource) self.setHeader('authorization', aws2.authorization(auth)) } return self } Request.prototype.httpSignature = function (opts) { var self = this httpSignature.signRequest({ getHeader: function (header) { return self.getHeader(header, self.headers) }, setHeader: function (header, value) { self.setHeader(header, value) }, method: self.method, path: self.path }, opts) debug('httpSignature authorization', self.getHeader('authorization')) return self } Request.prototype.hawk = function (opts) { var self = this self.setHeader('Authorization', hawk.header(self.uri, self.method, opts)) } Request.prototype.oauth = function (_oauth) { var self = this self._oauth.onRequest(_oauth) return self } Request.prototype.jar = function (jar) { var self = this var cookies if (self._redirect.redirectsFollowed === 0) { self.originalCookieHeader = self.getHeader('cookie') } if (!jar) { // disable cookies cookies = false self._disableCookies = true } else { var targetCookieJar = jar.getCookieString ? jar : globalCookieJar var urihref = self.uri.href // fetch cookie in the Specified host if (targetCookieJar) { cookies = targetCookieJar.getCookieString(urihref) } } // if need cookie and cookie is not empty if (cookies && cookies.length) { if (self.originalCookieHeader) { // Don't overwrite existing Cookie header self.setHeader('cookie', self.originalCookieHeader + '; ' + cookies) } else { self.setHeader('cookie', cookies) } } self._jar = jar return self } // Stream API Request.prototype.pipe = function (dest, opts) { var self = this if (self.response) { if (self._destdata) { self.emit('error', new Error('You cannot pipe after data has been emitted from the response.')) } else if (self._ended) { self.emit('error', new Error('You cannot pipe after the response has been ended.')) } else { stream.Stream.prototype.pipe.call(self, dest, opts) self.pipeDest(dest) return dest } } else { self.dests.push(dest) stream.Stream.prototype.pipe.call(self, dest, opts) return dest } } Request.prototype.write = function () { var self = this if (self._aborted) { return } if (!self._started) { self.start() } if (self.req) { return self.req.write.apply(self.req, arguments) } } Request.prototype.end = function (chunk) { var self = this if (self._aborted) { return } if (chunk) { self.write(chunk) } if (!self._started) { self.start() } if (self.req) { self.req.end() } } Request.prototype.pause = function () { var self = this if (!self.responseContent) { self._paused = true } else { self.responseContent.pause.apply(self.responseContent, arguments) } } Request.prototype.resume = function () { var self = this if (!self.responseContent) { self._paused = false } else { self.responseContent.resume.apply(self.responseContent, arguments) } } Request.prototype.destroy = function () { var self = this this.clearTimeout() if (!self._ended) { self.end() } else if (self.response) { self.response.destroy() } } Request.prototype.clearTimeout = function () { if (this.timeoutTimer) { clearTimeout(this.timeoutTimer) this.timeoutTimer = null } } Request.defaultProxyHeaderWhiteList = Tunnel.defaultProxyHeaderWhiteList.slice() Request.defaultProxyHeaderExclusiveList = Tunnel.defaultProxyHeaderExclusiveList.slice() // Exports Request.prototype.toJSON = requestToJSON module.exports = Request /***/ }), /***/ 46624: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const tls = __nccwpck_require__(24404); module.exports = (options = {}, connect = tls.connect) => new Promise((resolve, reject) => { let timeout = false; let socket; const callback = async () => { await socketPromise; socket.off('timeout', onTimeout); socket.off('error', reject); if (options.resolveSocket) { resolve({alpnProtocol: socket.alpnProtocol, socket, timeout}); if (timeout) { await Promise.resolve(); socket.emit('timeout'); } } else { socket.destroy(); resolve({alpnProtocol: socket.alpnProtocol, timeout}); } }; const onTimeout = async () => { timeout = true; callback(); }; const socketPromise = (async () => { try { socket = await connect(options, callback); socket.on('error', reject); socket.once('timeout', onTimeout); } catch (error) { reject(error); } })(); }); /***/ }), /***/ 9004: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const Readable = (__nccwpck_require__(12781).Readable); const lowercaseKeys = __nccwpck_require__(9662); class Response extends Readable { constructor(statusCode, headers, body, url) { if (typeof statusCode !== 'number') { throw new TypeError('Argument `statusCode` should be a number'); } if (typeof headers !== 'object') { throw new TypeError('Argument `headers` should be an object'); } if (!(body instanceof Buffer)) { throw new TypeError('Argument `body` should be a buffer'); } if (typeof url !== 'string') { throw new TypeError('Argument `url` should be a string'); } super(); this.statusCode = statusCode; this.headers = lowercaseKeys(headers); this.body = body; this.url = url; } _read() { this.push(this.body); this.push(null); } } module.exports = Response; /***/ }), /***/ 97417: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /* eslint-disable @typescript-eslint/strict-boolean-expressions */ function parse(string, encoding, opts) { var _opts$out; if (opts === void 0) { opts = {}; } // Build the character lookup table: if (!encoding.codes) { encoding.codes = {}; for (var i = 0; i < encoding.chars.length; ++i) { encoding.codes[encoding.chars[i]] = i; } } // The string must have a whole number of bytes: if (!opts.loose && string.length * encoding.bits & 7) { throw new SyntaxError('Invalid padding'); } // Count the padding bytes: var end = string.length; while (string[end - 1] === '=') { --end; // If we get a whole number of bytes, there is too much padding: if (!opts.loose && !((string.length - end) * encoding.bits & 7)) { throw new SyntaxError('Invalid padding'); } } // Allocate the output: var out = new ((_opts$out = opts.out) != null ? _opts$out : Uint8Array)(end * encoding.bits / 8 | 0); // Parse the data: var bits = 0; // Number of bits currently in the buffer var buffer = 0; // Bits waiting to be written out, MSB first var written = 0; // Next byte to write for (var _i = 0; _i < end; ++_i) { // Read one character from the string: var value = encoding.codes[string[_i]]; if (value === undefined) { throw new SyntaxError('Invalid character ' + string[_i]); } // Append the bits to the buffer: buffer = buffer << encoding.bits | value; bits += encoding.bits; // Write out some bits if the buffer has a byte's worth: if (bits >= 8) { bits -= 8; out[written++] = 0xff & buffer >> bits; } } // Verify that we have received just enough bits: if (bits >= encoding.bits || 0xff & buffer << 8 - bits) { throw new SyntaxError('Unexpected end of data'); } return out; } function stringify(data, encoding, opts) { if (opts === void 0) { opts = {}; } var _opts = opts, _opts$pad = _opts.pad, pad = _opts$pad === void 0 ? true : _opts$pad; var mask = (1 << encoding.bits) - 1; var out = ''; var bits = 0; // Number of bits currently in the buffer var buffer = 0; // Bits waiting to be written out, MSB first for (var i = 0; i < data.length; ++i) { // Slurp data into the buffer: buffer = buffer << 8 | 0xff & data[i]; bits += 8; // Write out as much as we can: while (bits > encoding.bits) { bits -= encoding.bits; out += encoding.chars[mask & buffer >> bits]; } } // Partial character: if (bits) { out += encoding.chars[mask & buffer << encoding.bits - bits]; } // Add padding characters until we hit a byte boundary: if (pad) { while (out.length * encoding.bits & 7) { out += '='; } } return out; } /* eslint-disable @typescript-eslint/strict-boolean-expressions */ var base16Encoding = { chars: '0123456789ABCDEF', bits: 4 }; var base32Encoding = { chars: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567', bits: 5 }; var base32HexEncoding = { chars: '0123456789ABCDEFGHIJKLMNOPQRSTUV', bits: 5 }; var base64Encoding = { chars: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/', bits: 6 }; var base64UrlEncoding = { chars: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_', bits: 6 }; var base16 = { parse: function parse$1(string, opts) { return parse(string.toUpperCase(), base16Encoding, opts); }, stringify: function stringify$1(data, opts) { return stringify(data, base16Encoding, opts); } }; var base32 = { parse: function parse$1(string, opts) { if (opts === void 0) { opts = {}; } return parse(opts.loose ? string.toUpperCase().replace(/0/g, 'O').replace(/1/g, 'L').replace(/8/g, 'B') : string, base32Encoding, opts); }, stringify: function stringify$1(data, opts) { return stringify(data, base32Encoding, opts); } }; var base32hex = { parse: function parse$1(string, opts) { return parse(string, base32HexEncoding, opts); }, stringify: function stringify$1(data, opts) { return stringify(data, base32HexEncoding, opts); } }; var base64 = { parse: function parse$1(string, opts) { return parse(string, base64Encoding, opts); }, stringify: function stringify$1(data, opts) { return stringify(data, base64Encoding, opts); } }; var base64url = { parse: function parse$1(string, opts) { return parse(string, base64UrlEncoding, opts); }, stringify: function stringify$1(data, opts) { return stringify(data, base64UrlEncoding, opts); } }; var codec = { parse: parse, stringify: stringify }; exports.base16 = base16; exports.base32 = base32; exports.base32hex = base32hex; exports.base64 = base64; exports.base64url = base64url; exports.codec = codec; /***/ }), /***/ 14959: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const assert = __nccwpck_require__(39491) const path = __nccwpck_require__(71017) const fs = __nccwpck_require__(57147) let glob = undefined try { glob = __nccwpck_require__(91957) } catch (_err) { // treat glob as optional. } const defaultGlobOpts = { nosort: true, silent: true } // for EMFILE handling let timeout = 0 const isWindows = (process.platform === "win32") const defaults = options => { const methods = [ 'unlink', 'chmod', 'stat', 'lstat', 'rmdir', 'readdir' ] methods.forEach(m => { options[m] = options[m] || fs[m] m = m + 'Sync' options[m] = options[m] || fs[m] }) options.maxBusyTries = options.maxBusyTries || 3 options.emfileWait = options.emfileWait || 1000 if (options.glob === false) { options.disableGlob = true } if (options.disableGlob !== true && glob === undefined) { throw Error('glob dependency not found, set `options.disableGlob = true` if intentional') } options.disableGlob = options.disableGlob || false options.glob = options.glob || defaultGlobOpts } const rimraf = (p, options, cb) => { if (typeof options === 'function') { cb = options options = {} } assert(p, 'rimraf: missing path') assert.equal(typeof p, 'string', 'rimraf: path should be a string') assert.equal(typeof cb, 'function', 'rimraf: callback function required') assert(options, 'rimraf: invalid options argument provided') assert.equal(typeof options, 'object', 'rimraf: options should be object') defaults(options) let busyTries = 0 let errState = null let n = 0 const next = (er) => { errState = errState || er if (--n === 0) cb(errState) } const afterGlob = (er, results) => { if (er) return cb(er) n = results.length if (n === 0) return cb() results.forEach(p => { const CB = (er) => { if (er) { if ((er.code === "EBUSY" || er.code === "ENOTEMPTY" || er.code === "EPERM") && busyTries < options.maxBusyTries) { busyTries ++ // try again, with the same exact callback as this one. return setTimeout(() => rimraf_(p, options, CB), busyTries * 100) } // this one won't happen if graceful-fs is used. if (er.code === "EMFILE" && timeout < options.emfileWait) { return setTimeout(() => rimraf_(p, options, CB), timeout ++) } // already gone if (er.code === "ENOENT") er = null } timeout = 0 next(er) } rimraf_(p, options, CB) }) } if (options.disableGlob || !glob.hasMagic(p)) return afterGlob(null, [p]) options.lstat(p, (er, stat) => { if (!er) return afterGlob(null, [p]) glob(p, options.glob, afterGlob) }) } // Two possible strategies. // 1. Assume it's a file. unlink it, then do the dir stuff on EPERM or EISDIR // 2. Assume it's a directory. readdir, then do the file stuff on ENOTDIR // // Both result in an extra syscall when you guess wrong. However, there // are likely far more normal files in the world than directories. This // is based on the assumption that a the average number of files per // directory is >= 1. // // If anyone ever complains about this, then I guess the strategy could // be made configurable somehow. But until then, YAGNI. const rimraf_ = (p, options, cb) => { assert(p) assert(options) assert(typeof cb === 'function') // sunos lets the root user unlink directories, which is... weird. // so we have to lstat here and make sure it's not a dir. options.lstat(p, (er, st) => { if (er && er.code === "ENOENT") return cb(null) // Windows can EPERM on stat. Life is suffering. if (er && er.code === "EPERM" && isWindows) fixWinEPERM(p, options, er, cb) if (st && st.isDirectory()) return rmdir(p, options, er, cb) options.unlink(p, er => { if (er) { if (er.code === "ENOENT") return cb(null) if (er.code === "EPERM") return (isWindows) ? fixWinEPERM(p, options, er, cb) : rmdir(p, options, er, cb) if (er.code === "EISDIR") return rmdir(p, options, er, cb) } return cb(er) }) }) } const fixWinEPERM = (p, options, er, cb) => { assert(p) assert(options) assert(typeof cb === 'function') options.chmod(p, 0o666, er2 => { if (er2) cb(er2.code === "ENOENT" ? null : er) else options.stat(p, (er3, stats) => { if (er3) cb(er3.code === "ENOENT" ? null : er) else if (stats.isDirectory()) rmdir(p, options, er, cb) else options.unlink(p, cb) }) }) } const fixWinEPERMSync = (p, options, er) => { assert(p) assert(options) try { options.chmodSync(p, 0o666) } catch (er2) { if (er2.code === "ENOENT") return else throw er } let stats try { stats = options.statSync(p) } catch (er3) { if (er3.code === "ENOENT") return else throw er } if (stats.isDirectory()) rmdirSync(p, options, er) else options.unlinkSync(p) } const rmdir = (p, options, originalEr, cb) => { assert(p) assert(options) assert(typeof cb === 'function') // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS) // if we guessed wrong, and it's not a directory, then // raise the original error. options.rmdir(p, er => { if (er && (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM")) rmkids(p, options, cb) else if (er && er.code === "ENOTDIR") cb(originalEr) else cb(er) }) } const rmkids = (p, options, cb) => { assert(p) assert(options) assert(typeof cb === 'function') options.readdir(p, (er, files) => { if (er) return cb(er) let n = files.length if (n === 0) return options.rmdir(p, cb) let errState files.forEach(f => { rimraf(path.join(p, f), options, er => { if (errState) return if (er) return cb(errState = er) if (--n === 0) options.rmdir(p, cb) }) }) }) } // this looks simpler, and is strictly *faster*, but will // tie up the JavaScript thread and fail on excessively // deep directory trees. const rimrafSync = (p, options) => { options = options || {} defaults(options) assert(p, 'rimraf: missing path') assert.equal(typeof p, 'string', 'rimraf: path should be a string') assert(options, 'rimraf: missing options') assert.equal(typeof options, 'object', 'rimraf: options should be object') let results if (options.disableGlob || !glob.hasMagic(p)) { results = [p] } else { try { options.lstatSync(p) results = [p] } catch (er) { results = glob.sync(p, options.glob) } } if (!results.length) return for (let i = 0; i < results.length; i++) { const p = results[i] let st try { st = options.lstatSync(p) } catch (er) { if (er.code === "ENOENT") return // Windows can EPERM on stat. Life is suffering. if (er.code === "EPERM" && isWindows) fixWinEPERMSync(p, options, er) } try { // sunos lets the root user unlink directories, which is... weird. if (st && st.isDirectory()) rmdirSync(p, options, null) else options.unlinkSync(p) } catch (er) { if (er.code === "ENOENT") return if (er.code === "EPERM") return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er) if (er.code !== "EISDIR") throw er rmdirSync(p, options, er) } } } const rmdirSync = (p, options, originalEr) => { assert(p) assert(options) try { options.rmdirSync(p) } catch (er) { if (er.code === "ENOENT") return if (er.code === "ENOTDIR") throw originalEr if (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM") rmkidsSync(p, options) } } const rmkidsSync = (p, options) => { assert(p) assert(options) options.readdirSync(p).forEach(f => rimrafSync(path.join(p, f), options)) // We only end up here once we got ENOTEMPTY at least once, and // at this point, we are guaranteed to have removed all the kids. // So, we know that it won't be ENOENT or ENOTDIR or anything else. // try really hard to delete stuff on windows, because it has a // PROFOUNDLY annoying habit of not closing handles promptly when // files are deleted, resulting in spurious ENOTEMPTY errors. const retries = isWindows ? 100 : 1 let i = 0 do { let threw = true try { const ret = options.rmdirSync(p, options) threw = false return ret } finally { if (++i < retries && threw) continue } } while (true) } module.exports = rimraf rimraf.sync = rimrafSync /***/ }), /***/ 21867: /***/ ((module, exports, __nccwpck_require__) => { /*! safe-buffer. MIT License. Feross Aboukhadijeh */ /* eslint-disable node/no-deprecated-api */ var buffer = __nccwpck_require__(14300) var Buffer = buffer.Buffer // alternative to using Object.keys for old browsers function copyProps (src, dst) { for (var key in src) { dst[key] = src[key] } } if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { module.exports = buffer } else { // Copy properties from require('buffer') copyProps(buffer, exports) exports.Buffer = SafeBuffer } function SafeBuffer (arg, encodingOrOffset, length) { return Buffer(arg, encodingOrOffset, length) } SafeBuffer.prototype = Object.create(Buffer.prototype) // Copy static methods from Buffer copyProps(Buffer, SafeBuffer) SafeBuffer.from = function (arg, encodingOrOffset, length) { if (typeof arg === 'number') { throw new TypeError('Argument must not be a number') } return Buffer(arg, encodingOrOffset, length) } SafeBuffer.alloc = function (size, fill, encoding) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number') } var buf = Buffer(size) if (fill !== undefined) { if (typeof encoding === 'string') { buf.fill(fill, encoding) } else { buf.fill(fill) } } else { buf.fill(0) } return buf } SafeBuffer.allocUnsafe = function (size) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number') } return Buffer(size) } SafeBuffer.allocUnsafeSlow = function (size) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number') } return buffer.SlowBuffer(size) } /***/ }), /***/ 15118: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /* eslint-disable node/no-deprecated-api */ var buffer = __nccwpck_require__(14300) var Buffer = buffer.Buffer var safer = {} var key for (key in buffer) { if (!buffer.hasOwnProperty(key)) continue if (key === 'SlowBuffer' || key === 'Buffer') continue safer[key] = buffer[key] } var Safer = safer.Buffer = {} for (key in Buffer) { if (!Buffer.hasOwnProperty(key)) continue if (key === 'allocUnsafe' || key === 'allocUnsafeSlow') continue Safer[key] = Buffer[key] } safer.Buffer.prototype = Buffer.prototype if (!Safer.from || Safer.from === Uint8Array.from) { Safer.from = function (value, encodingOrOffset, length) { if (typeof value === 'number') { throw new TypeError('The "value" argument must not be of type number. Received type ' + typeof value) } if (value && typeof value.length === 'undefined') { throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type ' + typeof value) } return Buffer(value, encodingOrOffset, length) } } if (!Safer.alloc) { Safer.alloc = function (size, fill, encoding) { if (typeof size !== 'number') { throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size) } if (size < 0 || size >= 2 * (1 << 30)) { throw new RangeError('The value "' + size + '" is invalid for option "size"') } var buf = Buffer(size) if (!fill || fill.length === 0) { buf.fill(0) } else if (typeof encoding === 'string') { buf.fill(fill, encoding) } else { buf.fill(fill) } return buf } } if (!safer.kStringMaxLength) { try { safer.kStringMaxLength = process.binding('buffer').kStringMaxLength } catch (e) { // we can't determine kStringMaxLength in environments where process.binding // is unsupported, so let's not set it } } if (!safer.constants) { safer.constants = { MAX_LENGTH: safer.kMaxLength } if (safer.kStringMaxLength) { safer.constants.MAX_STRING_LENGTH = safer.kStringMaxLength } } module.exports = safer /***/ }), /***/ 91532: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const ANY = Symbol('SemVer ANY') // hoisted class for cyclic dependency class Comparator { static get ANY () { return ANY } constructor (comp, options) { options = parseOptions(options) if (comp instanceof Comparator) { if (comp.loose === !!options.loose) { return comp } else { comp = comp.value } } comp = comp.trim().split(/\s+/).join(' ') debug('comparator', comp, options) this.options = options this.loose = !!options.loose this.parse(comp) if (this.semver === ANY) { this.value = '' } else { this.value = this.operator + this.semver.version } debug('comp', this) } parse (comp) { const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] const m = comp.match(r) if (!m) { throw new TypeError(`Invalid comparator: ${comp}`) } this.operator = m[1] !== undefined ? m[1] : '' if (this.operator === '=') { this.operator = '' } // if it literally is just '>' or '' then allow anything. if (!m[2]) { this.semver = ANY } else { this.semver = new SemVer(m[2], this.options.loose) } } toString () { return this.value } test (version) { debug('Comparator.test', version, this.options.loose) if (this.semver === ANY || version === ANY) { return true } if (typeof version === 'string') { try { version = new SemVer(version, this.options) } catch (er) { return false } } return cmp(version, this.operator, this.semver, this.options) } intersects (comp, options) { if (!(comp instanceof Comparator)) { throw new TypeError('a Comparator is required') } if (this.operator === '') { if (this.value === '') { return true } return new Range(comp.value, options).test(this.value) } else if (comp.operator === '') { if (comp.value === '') { return true } return new Range(this.value, options).test(comp.semver) } options = parseOptions(options) // Special cases where nothing can possibly be lower if (options.includePrerelease && (this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) { return false } if (!options.includePrerelease && (this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) { return false } // Same direction increasing (> or >=) if (this.operator.startsWith('>') && comp.operator.startsWith('>')) { return true } // Same direction decreasing (< or <=) if (this.operator.startsWith('<') && comp.operator.startsWith('<')) { return true } // same SemVer and both sides are inclusive (<= or >=) if ( (this.semver.version === comp.semver.version) && this.operator.includes('=') && comp.operator.includes('=')) { return true } // opposite directions less than if (cmp(this.semver, '<', comp.semver, options) && this.operator.startsWith('>') && comp.operator.startsWith('<')) { return true } // opposite directions greater than if (cmp(this.semver, '>', comp.semver, options) && this.operator.startsWith('<') && comp.operator.startsWith('>')) { return true } return false } } module.exports = Comparator const parseOptions = __nccwpck_require__(40785) const { safeRe: re, t } = __nccwpck_require__(9523) const cmp = __nccwpck_require__(75098) const debug = __nccwpck_require__(50427) const SemVer = __nccwpck_require__(48088) const Range = __nccwpck_require__(9828) /***/ }), /***/ 9828: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // hoisted class for cyclic dependency class Range { constructor (range, options) { options = parseOptions(options) if (range instanceof Range) { if ( range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease ) { return range } else { return new Range(range.raw, options) } } if (range instanceof Comparator) { // just put it in the set and return this.raw = range.value this.set = [[range]] this.format() return this } this.options = options this.loose = !!options.loose this.includePrerelease = !!options.includePrerelease // First reduce all whitespace as much as possible so we do not have to rely // on potentially slow regexes like \s*. This is then stored and used for // future error messages as well. this.raw = range .trim() .split(/\s+/) .join(' ') // First, split on || this.set = this.raw .split('||') // map the range to a 2d array of comparators .map(r => this.parseRange(r.trim())) // throw out any comparator lists that are empty // this generally means that it was not a valid range, which is allowed // in loose mode, but will still throw if the WHOLE range is invalid. .filter(c => c.length) if (!this.set.length) { throw new TypeError(`Invalid SemVer Range: ${this.raw}`) } // if we have any that are not the null set, throw out null sets. if (this.set.length > 1) { // keep the first one, in case they're all null sets const first = this.set[0] this.set = this.set.filter(c => !isNullSet(c[0])) if (this.set.length === 0) { this.set = [first] } else if (this.set.length > 1) { // if we have any that are *, then the range is just * for (const c of this.set) { if (c.length === 1 && isAny(c[0])) { this.set = [c] break } } } } this.format() } format () { this.range = this.set .map((comps) => comps.join(' ').trim()) .join('||') .trim() return this.range } toString () { return this.range } parseRange (range) { // memoize range parsing for performance. // this is a very hot path, and fully deterministic. const memoOpts = (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | (this.options.loose && FLAG_LOOSE) const memoKey = memoOpts + ':' + range const cached = cache.get(memoKey) if (cached) { return cached } const loose = this.options.loose // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE] range = range.replace(hr, hyphenReplace(this.options.includePrerelease)) debug('hyphen replace', range) // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace) debug('comparator trim', range) // `~ 1.2.3` => `~1.2.3` range = range.replace(re[t.TILDETRIM], tildeTrimReplace) debug('tilde trim', range) // `^ 1.2.3` => `^1.2.3` range = range.replace(re[t.CARETTRIM], caretTrimReplace) debug('caret trim', range) // At this point, the range is completely trimmed and // ready to be split into comparators. let rangeList = range .split(' ') .map(comp => parseComparator(comp, this.options)) .join(' ') .split(/\s+/) // >=0.0.0 is equivalent to * .map(comp => replaceGTE0(comp, this.options)) if (loose) { // in loose mode, throw out any that are not valid comparators rangeList = rangeList.filter(comp => { debug('loose invalid filter', comp, this.options) return !!comp.match(re[t.COMPARATORLOOSE]) }) } debug('range list', rangeList) // if any comparators are the null set, then replace with JUST null set // if more than one comparator, remove any * comparators // also, don't include the same comparator more than once const rangeMap = new Map() const comparators = rangeList.map(comp => new Comparator(comp, this.options)) for (const comp of comparators) { if (isNullSet(comp)) { return [comp] } rangeMap.set(comp.value, comp) } if (rangeMap.size > 1 && rangeMap.has('')) { rangeMap.delete('') } const result = [...rangeMap.values()] cache.set(memoKey, result) return result } intersects (range, options) { if (!(range instanceof Range)) { throw new TypeError('a Range is required') } return this.set.some((thisComparators) => { return ( isSatisfiable(thisComparators, options) && range.set.some((rangeComparators) => { return ( isSatisfiable(rangeComparators, options) && thisComparators.every((thisComparator) => { return rangeComparators.every((rangeComparator) => { return thisComparator.intersects(rangeComparator, options) }) }) ) }) ) }) } // if ANY of the sets match ALL of its comparators, then pass test (version) { if (!version) { return false } if (typeof version === 'string') { try { version = new SemVer(version, this.options) } catch (er) { return false } } for (let i = 0; i < this.set.length; i++) { if (testSet(this.set[i], version, this.options)) { return true } } return false } } module.exports = Range const LRU = __nccwpck_require__(7129) const cache = new LRU({ max: 1000 }) const parseOptions = __nccwpck_require__(40785) const Comparator = __nccwpck_require__(91532) const debug = __nccwpck_require__(50427) const SemVer = __nccwpck_require__(48088) const { safeRe: re, t, comparatorTrimReplace, tildeTrimReplace, caretTrimReplace, } = __nccwpck_require__(9523) const { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = __nccwpck_require__(42293) const isNullSet = c => c.value === '<0.0.0-0' const isAny = c => c.value === '' // take a set of comparators and determine whether there // exists a version which can satisfy it const isSatisfiable = (comparators, options) => { let result = true const remainingComparators = comparators.slice() let testComparator = remainingComparators.pop() while (result && remainingComparators.length) { result = remainingComparators.every((otherComparator) => { return testComparator.intersects(otherComparator, options) }) testComparator = remainingComparators.pop() } return result } // comprised of xranges, tildes, stars, and gtlt's at this point. // already replaced the hyphen ranges // turn into a set of JUST comparators. const parseComparator = (comp, options) => { debug('comp', comp, options) comp = replaceCarets(comp, options) debug('caret', comp) comp = replaceTildes(comp, options) debug('tildes', comp) comp = replaceXRanges(comp, options) debug('xrange', comp) comp = replaceStars(comp, options) debug('stars', comp) return comp } const isX = id => !id || id.toLowerCase() === 'x' || id === '*' // ~, ~> --> * (any, kinda silly) // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 // ~0.0.1 --> >=0.0.1 <0.1.0-0 const replaceTildes = (comp, options) => { return comp .trim() .split(/\s+/) .map((c) => replaceTilde(c, options)) .join(' ') } const replaceTilde = (comp, options) => { const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE] return comp.replace(r, (_, M, m, p, pr) => { debug('tilde', comp, _, M, m, p, pr) let ret if (isX(M)) { ret = '' } else if (isX(m)) { ret = `>=${M}.0.0 <${+M + 1}.0.0-0` } else if (isX(p)) { // ~1.2 == >=1.2.0 <1.3.0-0 ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0` } else if (pr) { debug('replaceTilde pr', pr) ret = `>=${M}.${m}.${p}-${pr } <${M}.${+m + 1}.0-0` } else { // ~1.2.3 == >=1.2.3 <1.3.0-0 ret = `>=${M}.${m}.${p } <${M}.${+m + 1}.0-0` } debug('tilde return', ret) return ret }) } // ^ --> * (any, kinda silly) // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 // ^1.2.3 --> >=1.2.3 <2.0.0-0 // ^1.2.0 --> >=1.2.0 <2.0.0-0 // ^0.0.1 --> >=0.0.1 <0.0.2-0 // ^0.1.0 --> >=0.1.0 <0.2.0-0 const replaceCarets = (comp, options) => { return comp .trim() .split(/\s+/) .map((c) => replaceCaret(c, options)) .join(' ') } const replaceCaret = (comp, options) => { debug('caret', comp, options) const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET] const z = options.includePrerelease ? '-0' : '' return comp.replace(r, (_, M, m, p, pr) => { debug('caret', comp, _, M, m, p, pr) let ret if (isX(M)) { ret = '' } else if (isX(m)) { ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0` } else if (isX(p)) { if (M === '0') { ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0` } else { ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0` } } else if (pr) { debug('replaceCaret pr', pr) if (M === '0') { if (m === '0') { ret = `>=${M}.${m}.${p}-${pr } <${M}.${m}.${+p + 1}-0` } else { ret = `>=${M}.${m}.${p}-${pr } <${M}.${+m + 1}.0-0` } } else { ret = `>=${M}.${m}.${p}-${pr } <${+M + 1}.0.0-0` } } else { debug('no pr') if (M === '0') { if (m === '0') { ret = `>=${M}.${m}.${p }${z} <${M}.${m}.${+p + 1}-0` } else { ret = `>=${M}.${m}.${p }${z} <${M}.${+m + 1}.0-0` } } else { ret = `>=${M}.${m}.${p } <${+M + 1}.0.0-0` } } debug('caret return', ret) return ret }) } const replaceXRanges = (comp, options) => { debug('replaceXRanges', comp, options) return comp .split(/\s+/) .map((c) => replaceXRange(c, options)) .join(' ') } const replaceXRange = (comp, options) => { comp = comp.trim() const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE] return comp.replace(r, (ret, gtlt, M, m, p, pr) => { debug('xRange', comp, ret, gtlt, M, m, p, pr) const xM = isX(M) const xm = xM || isX(m) const xp = xm || isX(p) const anyX = xp if (gtlt === '=' && anyX) { gtlt = '' } // if we're including prereleases in the match, then we need // to fix this to -0, the lowest possible prerelease value pr = options.includePrerelease ? '-0' : '' if (xM) { if (gtlt === '>' || gtlt === '<') { // nothing is allowed ret = '<0.0.0-0' } else { // nothing is forbidden ret = '*' } } else if (gtlt && anyX) { // we know patch is an x, because we have any x at all. // replace X with 0 if (xm) { m = 0 } p = 0 if (gtlt === '>') { // >1 => >=2.0.0 // >1.2 => >=1.3.0 gtlt = '>=' if (xm) { M = +M + 1 m = 0 p = 0 } else { m = +m + 1 p = 0 } } else if (gtlt === '<=') { // <=0.7.x is actually <0.8.0, since any 0.7.x should // pass. Similarly, <=7.x is actually <8.0.0, etc. gtlt = '<' if (xm) { M = +M + 1 } else { m = +m + 1 } } if (gtlt === '<') { pr = '-0' } ret = `${gtlt + M}.${m}.${p}${pr}` } else if (xm) { ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0` } else if (xp) { ret = `>=${M}.${m}.0${pr } <${M}.${+m + 1}.0-0` } debug('xRange return', ret) return ret }) } // Because * is AND-ed with everything else in the comparator, // and '' means "any version", just remove the *s entirely. const replaceStars = (comp, options) => { debug('replaceStars', comp, options) // Looseness is ignored here. star is always as loose as it gets! return comp .trim() .replace(re[t.STAR], '') } const replaceGTE0 = (comp, options) => { debug('replaceGTE0', comp, options) return comp .trim() .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '') } // This function is passed to string.replace(re[t.HYPHENRANGE]) // M, m, patch, prerelease, build // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 // 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do // 1.2 - 3.4 => >=1.2.0 <3.5.0-0 const hyphenReplace = incPr => ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) => { if (isX(fM)) { from = '' } else if (isX(fm)) { from = `>=${fM}.0.0${incPr ? '-0' : ''}` } else if (isX(fp)) { from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}` } else if (fpr) { from = `>=${from}` } else { from = `>=${from}${incPr ? '-0' : ''}` } if (isX(tM)) { to = '' } else if (isX(tm)) { to = `<${+tM + 1}.0.0-0` } else if (isX(tp)) { to = `<${tM}.${+tm + 1}.0-0` } else if (tpr) { to = `<=${tM}.${tm}.${tp}-${tpr}` } else if (incPr) { to = `<${tM}.${tm}.${+tp + 1}-0` } else { to = `<=${to}` } return `${from} ${to}`.trim() } const testSet = (set, version, options) => { for (let i = 0; i < set.length; i++) { if (!set[i].test(version)) { return false } } if (version.prerelease.length && !options.includePrerelease) { // Find the set of versions that are allowed to have prereleases // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 // That should allow `1.2.3-pr.2` to pass. // However, `1.2.4-alpha.notready` should NOT be allowed, // even though it's within the range set by the comparators. for (let i = 0; i < set.length; i++) { debug(set[i].semver) if (set[i].semver === Comparator.ANY) { continue } if (set[i].semver.prerelease.length > 0) { const allowed = set[i].semver if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) { return true } } } // Version has a -pre, but it's not one of the ones we like. return false } return true } /***/ }), /***/ 48088: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const debug = __nccwpck_require__(50427) const { MAX_LENGTH, MAX_SAFE_INTEGER } = __nccwpck_require__(42293) const { safeRe: re, t } = __nccwpck_require__(9523) const parseOptions = __nccwpck_require__(40785) const { compareIdentifiers } = __nccwpck_require__(92463) class SemVer { constructor (version, options) { options = parseOptions(options) if (version instanceof SemVer) { if (version.loose === !!options.loose && version.includePrerelease === !!options.includePrerelease) { return version } else { version = version.version } } else if (typeof version !== 'string') { throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`) } if (version.length > MAX_LENGTH) { throw new TypeError( `version is longer than ${MAX_LENGTH} characters` ) } debug('SemVer', version, options) this.options = options this.loose = !!options.loose // this isn't actually relevant for versions, but keep it so that we // don't run into trouble passing this.options around. this.includePrerelease = !!options.includePrerelease const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]) if (!m) { throw new TypeError(`Invalid Version: ${version}`) } this.raw = version // these are actually numbers this.major = +m[1] this.minor = +m[2] this.patch = +m[3] if (this.major > MAX_SAFE_INTEGER || this.major < 0) { throw new TypeError('Invalid major version') } if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { throw new TypeError('Invalid minor version') } if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { throw new TypeError('Invalid patch version') } // numberify any prerelease numeric ids if (!m[4]) { this.prerelease = [] } else { this.prerelease = m[4].split('.').map((id) => { if (/^[0-9]+$/.test(id)) { const num = +id if (num >= 0 && num < MAX_SAFE_INTEGER) { return num } } return id }) } this.build = m[5] ? m[5].split('.') : [] this.format() } format () { this.version = `${this.major}.${this.minor}.${this.patch}` if (this.prerelease.length) { this.version += `-${this.prerelease.join('.')}` } return this.version } toString () { return this.version } compare (other) { debug('SemVer.compare', this.version, this.options, other) if (!(other instanceof SemVer)) { if (typeof other === 'string' && other === this.version) { return 0 } other = new SemVer(other, this.options) } if (other.version === this.version) { return 0 } return this.compareMain(other) || this.comparePre(other) } compareMain (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } return ( compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch) ) } comparePre (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } // NOT having a prerelease is > having one if (this.prerelease.length && !other.prerelease.length) { return -1 } else if (!this.prerelease.length && other.prerelease.length) { return 1 } else if (!this.prerelease.length && !other.prerelease.length) { return 0 } let i = 0 do { const a = this.prerelease[i] const b = other.prerelease[i] debug('prerelease compare', i, a, b) if (a === undefined && b === undefined) { return 0 } else if (b === undefined) { return 1 } else if (a === undefined) { return -1 } else if (a === b) { continue } else { return compareIdentifiers(a, b) } } while (++i) } compareBuild (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } let i = 0 do { const a = this.build[i] const b = other.build[i] debug('prerelease compare', i, a, b) if (a === undefined && b === undefined) { return 0 } else if (b === undefined) { return 1 } else if (a === undefined) { return -1 } else if (a === b) { continue } else { return compareIdentifiers(a, b) } } while (++i) } // preminor will bump the version up to the next minor release, and immediately // down to pre-release. premajor and prepatch work the same way. inc (release, identifier, identifierBase) { switch (release) { case 'premajor': this.prerelease.length = 0 this.patch = 0 this.minor = 0 this.major++ this.inc('pre', identifier, identifierBase) break case 'preminor': this.prerelease.length = 0 this.patch = 0 this.minor++ this.inc('pre', identifier, identifierBase) break case 'prepatch': // If this is already a prerelease, it will bump to the next version // drop any prereleases that might already exist, since they are not // relevant at this point. this.prerelease.length = 0 this.inc('patch', identifier, identifierBase) this.inc('pre', identifier, identifierBase) break // If the input is a non-prerelease version, this acts the same as // prepatch. case 'prerelease': if (this.prerelease.length === 0) { this.inc('patch', identifier, identifierBase) } this.inc('pre', identifier, identifierBase) break case 'major': // If this is a pre-major version, bump up to the same major version. // Otherwise increment major. // 1.0.0-5 bumps to 1.0.0 // 1.1.0 bumps to 2.0.0 if ( this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0 ) { this.major++ } this.minor = 0 this.patch = 0 this.prerelease = [] break case 'minor': // If this is a pre-minor version, bump up to the same minor version. // Otherwise increment minor. // 1.2.0-5 bumps to 1.2.0 // 1.2.1 bumps to 1.3.0 if (this.patch !== 0 || this.prerelease.length === 0) { this.minor++ } this.patch = 0 this.prerelease = [] break case 'patch': // If this is not a pre-release version, it will increment the patch. // If it is a pre-release it will bump up to the same patch version. // 1.2.0-5 patches to 1.2.0 // 1.2.0 patches to 1.2.1 if (this.prerelease.length === 0) { this.patch++ } this.prerelease = [] break // This probably shouldn't be used publicly. // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. case 'pre': { const base = Number(identifierBase) ? 1 : 0 if (!identifier && identifierBase === false) { throw new Error('invalid increment argument: identifier is empty') } if (this.prerelease.length === 0) { this.prerelease = [base] } else { let i = this.prerelease.length while (--i >= 0) { if (typeof this.prerelease[i] === 'number') { this.prerelease[i]++ i = -2 } } if (i === -1) { // didn't increment anything if (identifier === this.prerelease.join('.') && identifierBase === false) { throw new Error('invalid increment argument: identifier already exists') } this.prerelease.push(base) } } if (identifier) { // 1.2.0-beta.1 bumps to 1.2.0-beta.2, // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 let prerelease = [identifier, base] if (identifierBase === false) { prerelease = [identifier] } if (compareIdentifiers(this.prerelease[0], identifier) === 0) { if (isNaN(this.prerelease[1])) { this.prerelease = prerelease } } else { this.prerelease = prerelease } } break } default: throw new Error(`invalid increment argument: ${release}`) } this.raw = this.format() if (this.build.length) { this.raw += `+${this.build.join('.')}` } return this } } module.exports = SemVer /***/ }), /***/ 48848: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const parse = __nccwpck_require__(75925) const clean = (version, options) => { const s = parse(version.trim().replace(/^[=v]+/, ''), options) return s ? s.version : null } module.exports = clean /***/ }), /***/ 75098: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const eq = __nccwpck_require__(91898) const neq = __nccwpck_require__(6017) const gt = __nccwpck_require__(84123) const gte = __nccwpck_require__(15522) const lt = __nccwpck_require__(80194) const lte = __nccwpck_require__(77520) const cmp = (a, op, b, loose) => { switch (op) { case '===': if (typeof a === 'object') { a = a.version } if (typeof b === 'object') { b = b.version } return a === b case '!==': if (typeof a === 'object') { a = a.version } if (typeof b === 'object') { b = b.version } return a !== b case '': case '=': case '==': return eq(a, b, loose) case '!=': return neq(a, b, loose) case '>': return gt(a, b, loose) case '>=': return gte(a, b, loose) case '<': return lt(a, b, loose) case '<=': return lte(a, b, loose) default: throw new TypeError(`Invalid operator: ${op}`) } } module.exports = cmp /***/ }), /***/ 13466: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const SemVer = __nccwpck_require__(48088) const parse = __nccwpck_require__(75925) const { safeRe: re, t } = __nccwpck_require__(9523) const coerce = (version, options) => { if (version instanceof SemVer) { return version } if (typeof version === 'number') { version = String(version) } if (typeof version !== 'string') { return null } options = options || {} let match = null if (!options.rtl) { match = version.match(re[t.COERCE]) } else { // Find the right-most coercible string that does not share // a terminus with a more left-ward coercible string. // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' // // Walk through the string checking with a /g regexp // Manually set the index so as to pick up overlapping matches. // Stop when we get a match that ends at the string end, since no // coercible string can be more right-ward without the same terminus. let next while ((next = re[t.COERCERTL].exec(version)) && (!match || match.index + match[0].length !== version.length) ) { if (!match || next.index + next[0].length !== match.index + match[0].length) { match = next } re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length } // leave it in a clean state re[t.COERCERTL].lastIndex = -1 } if (match === null) { return null } return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options) } module.exports = coerce /***/ }), /***/ 92156: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const SemVer = __nccwpck_require__(48088) const compareBuild = (a, b, loose) => { const versionA = new SemVer(a, loose) const versionB = new SemVer(b, loose) return versionA.compare(versionB) || versionA.compareBuild(versionB) } module.exports = compareBuild /***/ }), /***/ 62804: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const compare = __nccwpck_require__(44309) const compareLoose = (a, b) => compare(a, b, true) module.exports = compareLoose /***/ }), /***/ 44309: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const SemVer = __nccwpck_require__(48088) const compare = (a, b, loose) => new SemVer(a, loose).compare(new SemVer(b, loose)) module.exports = compare /***/ }), /***/ 64297: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const parse = __nccwpck_require__(75925) const diff = (version1, version2) => { const v1 = parse(version1, null, true) const v2 = parse(version2, null, true) const comparison = v1.compare(v2) if (comparison === 0) { return null } const v1Higher = comparison > 0 const highVersion = v1Higher ? v1 : v2 const lowVersion = v1Higher ? v2 : v1 const highHasPre = !!highVersion.prerelease.length const lowHasPre = !!lowVersion.prerelease.length if (lowHasPre && !highHasPre) { // Going from prerelease -> no prerelease requires some special casing // If the low version has only a major, then it will always be a major // Some examples: // 1.0.0-1 -> 1.0.0 // 1.0.0-1 -> 1.1.1 // 1.0.0-1 -> 2.0.0 if (!lowVersion.patch && !lowVersion.minor) { return 'major' } // Otherwise it can be determined by checking the high version if (highVersion.patch) { // anything higher than a patch bump would result in the wrong version return 'patch' } if (highVersion.minor) { // anything higher than a minor bump would result in the wrong version return 'minor' } // bumping major/minor/patch all have same result return 'major' } // add the `pre` prefix if we are going to a prerelease version const prefix = highHasPre ? 'pre' : '' if (v1.major !== v2.major) { return prefix + 'major' } if (v1.minor !== v2.minor) { return prefix + 'minor' } if (v1.patch !== v2.patch) { return prefix + 'patch' } // high and low are preleases return 'prerelease' } module.exports = diff /***/ }), /***/ 91898: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const compare = __nccwpck_require__(44309) const eq = (a, b, loose) => compare(a, b, loose) === 0 module.exports = eq /***/ }), /***/ 84123: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const compare = __nccwpck_require__(44309) const gt = (a, b, loose) => compare(a, b, loose) > 0 module.exports = gt /***/ }), /***/ 15522: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const compare = __nccwpck_require__(44309) const gte = (a, b, loose) => compare(a, b, loose) >= 0 module.exports = gte /***/ }), /***/ 30900: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const SemVer = __nccwpck_require__(48088) const inc = (version, release, options, identifier, identifierBase) => { if (typeof (options) === 'string') { identifierBase = identifier identifier = options options = undefined } try { return new SemVer( version instanceof SemVer ? version.version : version, options ).inc(release, identifier, identifierBase).version } catch (er) { return null } } module.exports = inc /***/ }), /***/ 80194: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const compare = __nccwpck_require__(44309) const lt = (a, b, loose) => compare(a, b, loose) < 0 module.exports = lt /***/ }), /***/ 77520: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const compare = __nccwpck_require__(44309) const lte = (a, b, loose) => compare(a, b, loose) <= 0 module.exports = lte /***/ }), /***/ 76688: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const SemVer = __nccwpck_require__(48088) const major = (a, loose) => new SemVer(a, loose).major module.exports = major /***/ }), /***/ 38447: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const SemVer = __nccwpck_require__(48088) const minor = (a, loose) => new SemVer(a, loose).minor module.exports = minor /***/ }), /***/ 6017: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const compare = __nccwpck_require__(44309) const neq = (a, b, loose) => compare(a, b, loose) !== 0 module.exports = neq /***/ }), /***/ 75925: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const SemVer = __nccwpck_require__(48088) const parse = (version, options, throwErrors = false) => { if (version instanceof SemVer) { return version } try { return new SemVer(version, options) } catch (er) { if (!throwErrors) { return null } throw er } } module.exports = parse /***/ }), /***/ 42866: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const SemVer = __nccwpck_require__(48088) const patch = (a, loose) => new SemVer(a, loose).patch module.exports = patch /***/ }), /***/ 24016: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const parse = __nccwpck_require__(75925) const prerelease = (version, options) => { const parsed = parse(version, options) return (parsed && parsed.prerelease.length) ? parsed.prerelease : null } module.exports = prerelease /***/ }), /***/ 76417: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const compare = __nccwpck_require__(44309) const rcompare = (a, b, loose) => compare(b, a, loose) module.exports = rcompare /***/ }), /***/ 8701: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const compareBuild = __nccwpck_require__(92156) const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)) module.exports = rsort /***/ }), /***/ 6055: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const Range = __nccwpck_require__(9828) const satisfies = (version, range, options) => { try { range = new Range(range, options) } catch (er) { return false } return range.test(version) } module.exports = satisfies /***/ }), /***/ 61426: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const compareBuild = __nccwpck_require__(92156) const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose)) module.exports = sort /***/ }), /***/ 19601: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const parse = __nccwpck_require__(75925) const valid = (version, options) => { const v = parse(version, options) return v ? v.version : null } module.exports = valid /***/ }), /***/ 11383: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // just pre-load all the stuff that index.js lazily exports const internalRe = __nccwpck_require__(9523) const constants = __nccwpck_require__(42293) const SemVer = __nccwpck_require__(48088) const identifiers = __nccwpck_require__(92463) const parse = __nccwpck_require__(75925) const valid = __nccwpck_require__(19601) const clean = __nccwpck_require__(48848) const inc = __nccwpck_require__(30900) const diff = __nccwpck_require__(64297) const major = __nccwpck_require__(76688) const minor = __nccwpck_require__(38447) const patch = __nccwpck_require__(42866) const prerelease = __nccwpck_require__(24016) const compare = __nccwpck_require__(44309) const rcompare = __nccwpck_require__(76417) const compareLoose = __nccwpck_require__(62804) const compareBuild = __nccwpck_require__(92156) const sort = __nccwpck_require__(61426) const rsort = __nccwpck_require__(8701) const gt = __nccwpck_require__(84123) const lt = __nccwpck_require__(80194) const eq = __nccwpck_require__(91898) const neq = __nccwpck_require__(6017) const gte = __nccwpck_require__(15522) const lte = __nccwpck_require__(77520) const cmp = __nccwpck_require__(75098) const coerce = __nccwpck_require__(13466) const Comparator = __nccwpck_require__(91532) const Range = __nccwpck_require__(9828) const satisfies = __nccwpck_require__(6055) const toComparators = __nccwpck_require__(52706) const maxSatisfying = __nccwpck_require__(20579) const minSatisfying = __nccwpck_require__(10832) const minVersion = __nccwpck_require__(34179) const validRange = __nccwpck_require__(2098) const outside = __nccwpck_require__(60420) const gtr = __nccwpck_require__(9380) const ltr = __nccwpck_require__(33323) const intersects = __nccwpck_require__(27008) const simplifyRange = __nccwpck_require__(75297) const subset = __nccwpck_require__(7863) module.exports = { parse, valid, clean, inc, diff, major, minor, patch, prerelease, compare, rcompare, compareLoose, compareBuild, sort, rsort, gt, lt, eq, neq, gte, lte, cmp, coerce, Comparator, Range, satisfies, toComparators, maxSatisfying, minSatisfying, minVersion, validRange, outside, gtr, ltr, intersects, simplifyRange, subset, SemVer, re: internalRe.re, src: internalRe.src, tokens: internalRe.t, SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, RELEASE_TYPES: constants.RELEASE_TYPES, compareIdentifiers: identifiers.compareIdentifiers, rcompareIdentifiers: identifiers.rcompareIdentifiers, } /***/ }), /***/ 42293: /***/ ((module) => { // Note: this is the semver.org version of the spec that it implements // Not necessarily the package version of this code. const SEMVER_SPEC_VERSION = '2.0.0' const MAX_LENGTH = 256 const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */ 9007199254740991 // Max safe segment length for coercion. const MAX_SAFE_COMPONENT_LENGTH = 16 // Max safe length for a build identifier. The max length minus 6 characters for // the shortest version with a build 0.0.0+BUILD. const MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6 const RELEASE_TYPES = [ 'major', 'premajor', 'minor', 'preminor', 'patch', 'prepatch', 'prerelease', ] module.exports = { MAX_LENGTH, MAX_SAFE_COMPONENT_LENGTH, MAX_SAFE_BUILD_LENGTH, MAX_SAFE_INTEGER, RELEASE_TYPES, SEMVER_SPEC_VERSION, FLAG_INCLUDE_PRERELEASE: 0b001, FLAG_LOOSE: 0b010, } /***/ }), /***/ 50427: /***/ ((module) => { const debug = ( typeof process === 'object' && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ) ? (...args) => console.error('SEMVER', ...args) : () => {} module.exports = debug /***/ }), /***/ 92463: /***/ ((module) => { const numeric = /^[0-9]+$/ const compareIdentifiers = (a, b) => { const anum = numeric.test(a) const bnum = numeric.test(b) if (anum && bnum) { a = +a b = +b } return a === b ? 0 : (anum && !bnum) ? -1 : (bnum && !anum) ? 1 : a < b ? -1 : 1 } const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a) module.exports = { compareIdentifiers, rcompareIdentifiers, } /***/ }), /***/ 40785: /***/ ((module) => { // parse out just the options we care about const looseOption = Object.freeze({ loose: true }) const emptyOpts = Object.freeze({ }) const parseOptions = options => { if (!options) { return emptyOpts } if (typeof options !== 'object') { return looseOption } return options } module.exports = parseOptions /***/ }), /***/ 9523: /***/ ((module, exports, __nccwpck_require__) => { const { MAX_SAFE_COMPONENT_LENGTH, MAX_SAFE_BUILD_LENGTH, MAX_LENGTH, } = __nccwpck_require__(42293) const debug = __nccwpck_require__(50427) exports = module.exports = {} // The actual regexps go on exports.re const re = exports.re = [] const safeRe = exports.safeRe = [] const src = exports.src = [] const t = exports.t = {} let R = 0 const LETTERDASHNUMBER = '[a-zA-Z0-9-]' // Replace some greedy regex tokens to prevent regex dos issues. These regex are // used internally via the safeRe object since all inputs in this library get // normalized first to trim and collapse all extra whitespace. The original // regexes are exported for userland consumption and lower level usage. A // future breaking change could export the safer regex only with a note that // all input should have extra whitespace removed. const safeRegexReplacements = [ ['\\s', 1], ['\\d', MAX_LENGTH], [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH], ] const makeSafeRegex = (value) => { for (const [token, max] of safeRegexReplacements) { value = value .split(`${token}*`).join(`${token}{0,${max}}`) .split(`${token}+`).join(`${token}{1,${max}}`) } return value } const createToken = (name, value, isGlobal) => { const safe = makeSafeRegex(value) const index = R++ debug(name, index, value) t[name] = index src[index] = value re[index] = new RegExp(value, isGlobal ? 'g' : undefined) safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined) } // The following Regular Expressions can be used for tokenizing, // validating, and parsing SemVer version strings. // ## Numeric Identifier // A single `0`, or a non-zero digit followed by zero or more digits. createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*') createToken('NUMERICIDENTIFIERLOOSE', '\\d+') // ## Non-numeric Identifier // Zero or more digits, followed by a letter or hyphen, and then zero or // more letters, digits, or hyphens. createToken('NONNUMERICIDENTIFIER', `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`) // ## Main Version // Three dot-separated numeric identifiers. createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + `(${src[t.NUMERICIDENTIFIER]})\\.` + `(${src[t.NUMERICIDENTIFIER]})`) createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t.NUMERICIDENTIFIERLOOSE]})`) // ## Pre-release Version Identifier // A numeric identifier, or a non-numeric identifier. createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER] }|${src[t.NONNUMERICIDENTIFIER]})`) createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE] }|${src[t.NONNUMERICIDENTIFIER]})`) // ## Pre-release Version // Hyphen, followed by one or more dot-separated pre-release version // identifiers. createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] }(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`) createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] }(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`) // ## Build Metadata Identifier // Any combination of digits, letters, or hyphens. createToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`) // ## Build Metadata // Plus sign, followed by one or more period-separated build metadata // identifiers. createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] }(?:\\.${src[t.BUILDIDENTIFIER]})*))`) // ## Full Version String // A main version, followed optionally by a pre-release version and // build metadata. // Note that the only major, minor, patch, and pre-release sections of // the version string are capturing groups. The build metadata is not a // capturing group, because it should not ever be used in version // comparison. createToken('FULLPLAIN', `v?${src[t.MAINVERSION] }${src[t.PRERELEASE]}?${ src[t.BUILD]}?`) createToken('FULL', `^${src[t.FULLPLAIN]}$`) // like full, but allows v1.2.3 and =1.2.3, which people do sometimes. // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty // common in the npm registry. createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] }${src[t.PRERELEASELOOSE]}?${ src[t.BUILD]}?`) createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`) createToken('GTLT', '((?:<|>)?=?)') // Something like "2.*" or "1.2.x". // Note that "x.x" is a valid xRange identifer, meaning "any version" // Only the first item is strictly required. createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`) createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`) createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + `(?:${src[t.PRERELEASE]})?${ src[t.BUILD]}?` + `)?)?`) createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:${src[t.PRERELEASELOOSE]})?${ src[t.BUILD]}?` + `)?)?`) createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`) createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`) // Coercion. // Extract anything that could conceivably be a part of a valid semver createToken('COERCE', `${'(^|[^\\d])' + '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + `(?:$|[^\\d])`) createToken('COERCERTL', src[t.COERCE], true) // Tilde ranges. // Meaning is "reasonably at or greater than" createToken('LONETILDE', '(?:~>?)') createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true) exports.tildeTrimReplace = '$1~' createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`) createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`) // Caret ranges. // Meaning is "at least and backwards compatible with" createToken('LONECARET', '(?:\\^)') createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true) exports.caretTrimReplace = '$1^' createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`) createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`) // A simple gt/lt/eq thing, or just "" to indicate "any version" createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`) createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`) // An expression to strip any whitespace between the gtlt and the thing // it modifies, so that `> 1.2.3` ==> `>1.2.3` createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] }\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true) exports.comparatorTrimReplace = '$1$2$3' // Something like `1.2.3 - 1.2.4` // Note that these all use the loose form, because they'll be // checked against either the strict or loose comparator form // later. createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + `\\s+-\\s+` + `(${src[t.XRANGEPLAIN]})` + `\\s*$`) createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + `\\s+-\\s+` + `(${src[t.XRANGEPLAINLOOSE]})` + `\\s*$`) // Star ranges basically just allow anything at all. createToken('STAR', '(<|>)?=?\\s*\\*') // >=0.0.0 is like a star createToken('GTE0', '^\\s*>=\\s*0\\.0\\.0\\s*$') createToken('GTE0PRE', '^\\s*>=\\s*0\\.0\\.0-0\\s*$') /***/ }), /***/ 9380: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // Determine if version is greater than all the versions possible in the range. const outside = __nccwpck_require__(60420) const gtr = (version, range, options) => outside(version, range, '>', options) module.exports = gtr /***/ }), /***/ 27008: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const Range = __nccwpck_require__(9828) const intersects = (r1, r2, options) => { r1 = new Range(r1, options) r2 = new Range(r2, options) return r1.intersects(r2, options) } module.exports = intersects /***/ }), /***/ 33323: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const outside = __nccwpck_require__(60420) // Determine if version is less than all the versions possible in the range const ltr = (version, range, options) => outside(version, range, '<', options) module.exports = ltr /***/ }), /***/ 20579: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const SemVer = __nccwpck_require__(48088) const Range = __nccwpck_require__(9828) const maxSatisfying = (versions, range, options) => { let max = null let maxSV = null let rangeObj = null try { rangeObj = new Range(range, options) } catch (er) { return null } versions.forEach((v) => { if (rangeObj.test(v)) { // satisfies(v, range, options) if (!max || maxSV.compare(v) === -1) { // compare(max, v, true) max = v maxSV = new SemVer(max, options) } } }) return max } module.exports = maxSatisfying /***/ }), /***/ 10832: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const SemVer = __nccwpck_require__(48088) const Range = __nccwpck_require__(9828) const minSatisfying = (versions, range, options) => { let min = null let minSV = null let rangeObj = null try { rangeObj = new Range(range, options) } catch (er) { return null } versions.forEach((v) => { if (rangeObj.test(v)) { // satisfies(v, range, options) if (!min || minSV.compare(v) === 1) { // compare(min, v, true) min = v minSV = new SemVer(min, options) } } }) return min } module.exports = minSatisfying /***/ }), /***/ 34179: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const SemVer = __nccwpck_require__(48088) const Range = __nccwpck_require__(9828) const gt = __nccwpck_require__(84123) const minVersion = (range, loose) => { range = new Range(range, loose) let minver = new SemVer('0.0.0') if (range.test(minver)) { return minver } minver = new SemVer('0.0.0-0') if (range.test(minver)) { return minver } minver = null for (let i = 0; i < range.set.length; ++i) { const comparators = range.set[i] let setMin = null comparators.forEach((comparator) => { // Clone to avoid manipulating the comparator's semver object. const compver = new SemVer(comparator.semver.version) switch (comparator.operator) { case '>': if (compver.prerelease.length === 0) { compver.patch++ } else { compver.prerelease.push(0) } compver.raw = compver.format() /* fallthrough */ case '': case '>=': if (!setMin || gt(compver, setMin)) { setMin = compver } break case '<': case '<=': /* Ignore maximum versions */ break /* istanbul ignore next */ default: throw new Error(`Unexpected operation: ${comparator.operator}`) } }) if (setMin && (!minver || gt(minver, setMin))) { minver = setMin } } if (minver && range.test(minver)) { return minver } return null } module.exports = minVersion /***/ }), /***/ 60420: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const SemVer = __nccwpck_require__(48088) const Comparator = __nccwpck_require__(91532) const { ANY } = Comparator const Range = __nccwpck_require__(9828) const satisfies = __nccwpck_require__(6055) const gt = __nccwpck_require__(84123) const lt = __nccwpck_require__(80194) const lte = __nccwpck_require__(77520) const gte = __nccwpck_require__(15522) const outside = (version, range, hilo, options) => { version = new SemVer(version, options) range = new Range(range, options) let gtfn, ltefn, ltfn, comp, ecomp switch (hilo) { case '>': gtfn = gt ltefn = lte ltfn = lt comp = '>' ecomp = '>=' break case '<': gtfn = lt ltefn = gte ltfn = gt comp = '<' ecomp = '<=' break default: throw new TypeError('Must provide a hilo val of "<" or ">"') } // If it satisfies the range it is not outside if (satisfies(version, range, options)) { return false } // From now on, variable terms are as if we're in "gtr" mode. // but note that everything is flipped for the "ltr" function. for (let i = 0; i < range.set.length; ++i) { const comparators = range.set[i] let high = null let low = null comparators.forEach((comparator) => { if (comparator.semver === ANY) { comparator = new Comparator('>=0.0.0') } high = high || comparator low = low || comparator if (gtfn(comparator.semver, high.semver, options)) { high = comparator } else if (ltfn(comparator.semver, low.semver, options)) { low = comparator } }) // If the edge version comparator has a operator then our version // isn't outside it if (high.operator === comp || high.operator === ecomp) { return false } // If the lowest version comparator has an operator and our version // is less than it then it isn't higher than the range if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) { return false } else if (low.operator === ecomp && ltfn(version, low.semver)) { return false } } return true } module.exports = outside /***/ }), /***/ 75297: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // given a set of versions and a range, create a "simplified" range // that includes the same versions that the original range does // If the original range is shorter than the simplified one, return that. const satisfies = __nccwpck_require__(6055) const compare = __nccwpck_require__(44309) module.exports = (versions, range, options) => { const set = [] let first = null let prev = null const v = versions.sort((a, b) => compare(a, b, options)) for (const version of v) { const included = satisfies(version, range, options) if (included) { prev = version if (!first) { first = version } } else { if (prev) { set.push([first, prev]) } prev = null first = null } } if (first) { set.push([first, null]) } const ranges = [] for (const [min, max] of set) { if (min === max) { ranges.push(min) } else if (!max && min === v[0]) { ranges.push('*') } else if (!max) { ranges.push(`>=${min}`) } else if (min === v[0]) { ranges.push(`<=${max}`) } else { ranges.push(`${min} - ${max}`) } } const simplified = ranges.join(' || ') const original = typeof range.raw === 'string' ? range.raw : String(range) return simplified.length < original.length ? simplified : range } /***/ }), /***/ 7863: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const Range = __nccwpck_require__(9828) const Comparator = __nccwpck_require__(91532) const { ANY } = Comparator const satisfies = __nccwpck_require__(6055) const compare = __nccwpck_require__(44309) // Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: // - Every simple range `r1, r2, ...` is a null set, OR // - Every simple range `r1, r2, ...` which is not a null set is a subset of // some `R1, R2, ...` // // Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: // - If c is only the ANY comparator // - If C is only the ANY comparator, return true // - Else if in prerelease mode, return false // - else replace c with `[>=0.0.0]` // - If C is only the ANY comparator // - if in prerelease mode, return true // - else replace C with `[>=0.0.0]` // - Let EQ be the set of = comparators in c // - If EQ is more than one, return true (null set) // - Let GT be the highest > or >= comparator in c // - Let LT be the lowest < or <= comparator in c // - If GT and LT, and GT.semver > LT.semver, return true (null set) // - If any C is a = range, and GT or LT are set, return false // - If EQ // - If GT, and EQ does not satisfy GT, return true (null set) // - If LT, and EQ does not satisfy LT, return true (null set) // - If EQ satisfies every C, return true // - Else return false // - If GT // - If GT.semver is lower than any > or >= comp in C, return false // - If GT is >=, and GT.semver does not satisfy every C, return false // - If GT.semver has a prerelease, and not in prerelease mode // - If no C has a prerelease and the GT.semver tuple, return false // - If LT // - If LT.semver is greater than any < or <= comp in C, return false // - If LT is <=, and LT.semver does not satisfy every C, return false // - If GT.semver has a prerelease, and not in prerelease mode // - If no C has a prerelease and the LT.semver tuple, return false // - Else return true const subset = (sub, dom, options = {}) => { if (sub === dom) { return true } sub = new Range(sub, options) dom = new Range(dom, options) let sawNonNull = false OUTER: for (const simpleSub of sub.set) { for (const simpleDom of dom.set) { const isSub = simpleSubset(simpleSub, simpleDom, options) sawNonNull = sawNonNull || isSub !== null if (isSub) { continue OUTER } } // the null set is a subset of everything, but null simple ranges in // a complex range should be ignored. so if we saw a non-null range, // then we know this isn't a subset, but if EVERY simple range was null, // then it is a subset. if (sawNonNull) { return false } } return true } const minimumVersionWithPreRelease = [new Comparator('>=0.0.0-0')] const minimumVersion = [new Comparator('>=0.0.0')] const simpleSubset = (sub, dom, options) => { if (sub === dom) { return true } if (sub.length === 1 && sub[0].semver === ANY) { if (dom.length === 1 && dom[0].semver === ANY) { return true } else if (options.includePrerelease) { sub = minimumVersionWithPreRelease } else { sub = minimumVersion } } if (dom.length === 1 && dom[0].semver === ANY) { if (options.includePrerelease) { return true } else { dom = minimumVersion } } const eqSet = new Set() let gt, lt for (const c of sub) { if (c.operator === '>' || c.operator === '>=') { gt = higherGT(gt, c, options) } else if (c.operator === '<' || c.operator === '<=') { lt = lowerLT(lt, c, options) } else { eqSet.add(c.semver) } } if (eqSet.size > 1) { return null } let gtltComp if (gt && lt) { gtltComp = compare(gt.semver, lt.semver, options) if (gtltComp > 0) { return null } else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) { return null } } // will iterate one or zero times for (const eq of eqSet) { if (gt && !satisfies(eq, String(gt), options)) { return null } if (lt && !satisfies(eq, String(lt), options)) { return null } for (const c of dom) { if (!satisfies(eq, String(c), options)) { return false } } return true } let higher, lower let hasDomLT, hasDomGT // if the subset has a prerelease, we need a comparator in the superset // with the same tuple and a prerelease, or it's not a subset let needDomLTPre = lt && !options.includePrerelease && lt.semver.prerelease.length ? lt.semver : false let needDomGTPre = gt && !options.includePrerelease && gt.semver.prerelease.length ? gt.semver : false // exception: <1.2.3-0 is the same as <1.2.3 if (needDomLTPre && needDomLTPre.prerelease.length === 1 && lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { needDomLTPre = false } for (const c of dom) { hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>=' hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<=' if (gt) { if (needDomGTPre) { if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomGTPre.major && c.semver.minor === needDomGTPre.minor && c.semver.patch === needDomGTPre.patch) { needDomGTPre = false } } if (c.operator === '>' || c.operator === '>=') { higher = higherGT(gt, c, options) if (higher === c && higher !== gt) { return false } } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) { return false } } if (lt) { if (needDomLTPre) { if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomLTPre.major && c.semver.minor === needDomLTPre.minor && c.semver.patch === needDomLTPre.patch) { needDomLTPre = false } } if (c.operator === '<' || c.operator === '<=') { lower = lowerLT(lt, c, options) if (lower === c && lower !== lt) { return false } } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) { return false } } if (!c.operator && (lt || gt) && gtltComp !== 0) { return false } } // if there was a < or >, and nothing in the dom, then must be false // UNLESS it was limited by another range in the other direction. // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 if (gt && hasDomLT && !lt && gtltComp !== 0) { return false } if (lt && hasDomGT && !gt && gtltComp !== 0) { return false } // we needed a prerelease range in a specific tuple, but didn't get one // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, // because it includes prereleases in the 1.2.3 tuple if (needDomGTPre || needDomLTPre) { return false } return true } // >=1.2.3 is lower than >1.2.3 const higherGT = (a, b, options) => { if (!a) { return b } const comp = compare(a.semver, b.semver, options) return comp > 0 ? a : comp < 0 ? b : b.operator === '>' && a.operator === '>=' ? b : a } // <=1.2.3 is higher than <1.2.3 const lowerLT = (a, b, options) => { if (!a) { return b } const comp = compare(a.semver, b.semver, options) return comp < 0 ? a : comp > 0 ? b : b.operator === '<' && a.operator === '<=' ? b : a } module.exports = subset /***/ }), /***/ 52706: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const Range = __nccwpck_require__(9828) // Mostly just for testing and legacy API reasons const toComparators = (range, options) => new Range(range, options).set .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')) module.exports = toComparators /***/ }), /***/ 2098: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const Range = __nccwpck_require__(9828) const validRange = (range, options) => { try { // Return '*' instead of '' so that truthiness works. // This will throw if it's invalid anyway return new Range(range, options).range || '*' } catch (er) { return null } } module.exports = validRange /***/ }), /***/ 67032: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const shebangRegex = __nccwpck_require__(72638); module.exports = (string = '') => { const match = string.match(shebangRegex); if (!match) { return null; } const [path, argument] = match[0].replace(/#! ?/, '').split(' '); const binary = path.split('/').pop(); if (binary === 'env') { return argument; } return argument ? `${binary} ${argument}` : binary; }; /***/ }), /***/ 72638: /***/ ((module) => { "use strict"; module.exports = /^#!(.*)/; /***/ }), /***/ 45123: /***/ ((module) => { module.exports = [ 'cat', 'cd', 'chmod', 'cp', 'dirs', 'echo', 'exec', 'find', 'grep', 'head', 'ln', 'ls', 'mkdir', 'mv', 'pwd', 'rm', 'sed', 'set', 'sort', 'tail', 'tempdir', 'test', 'to', 'toEnd', 'touch', 'uniq', 'which', ]; /***/ }), /***/ 33516: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { // // ShellJS // Unix shell commands on top of Node's API // // Copyright (c) 2012 Artur Adib // http://github.com/shelljs/shelljs // function __ncc_wildcard$0 (arg) { if (arg === "cat.js" || arg === "cat") return __nccwpck_require__(30271); else if (arg === "cd.js" || arg === "cd") return __nccwpck_require__(42051); else if (arg === "chmod.js" || arg === "chmod") return __nccwpck_require__(24975); else if (arg === "common.js" || arg === "common") return __nccwpck_require__(53687); else if (arg === "cp.js" || arg === "cp") return __nccwpck_require__(34932); else if (arg === "dirs.js" || arg === "dirs") return __nccwpck_require__(41178); else if (arg === "echo.js" || arg === "echo") return __nccwpck_require__(10243); else if (arg === "error.js" || arg === "error") return __nccwpck_require__(10232); else if (arg === "exec-child.js" || arg === "exec-child") return __nccwpck_require__(69607); else if (arg === "exec.js" || arg === "exec") return __nccwpck_require__(10896); else if (arg === "find.js" || arg === "find") return __nccwpck_require__(47838); else if (arg === "grep.js" || arg === "grep") return __nccwpck_require__(17417); else if (arg === "head.js" || arg === "head") return __nccwpck_require__(6613); else if (arg === "ln.js" || arg === "ln") return __nccwpck_require__(15787); else if (arg === "ls.js" || arg === "ls") return __nccwpck_require__(35561); else if (arg === "mkdir.js" || arg === "mkdir") return __nccwpck_require__(72695); else if (arg === "mv.js" || arg === "mv") return __nccwpck_require__(39849); else if (arg === "popd.js" || arg === "popd") return __nccwpck_require__(50227); else if (arg === "pushd.js" || arg === "pushd") return __nccwpck_require__(44177); else if (arg === "pwd.js" || arg === "pwd") return __nccwpck_require__(58553); else if (arg === "rm.js" || arg === "rm") return __nccwpck_require__(22830); else if (arg === "sed.js" || arg === "sed") return __nccwpck_require__(25899); else if (arg === "set.js" || arg === "set") return __nccwpck_require__(11411); else if (arg === "sort.js" || arg === "sort") return __nccwpck_require__(72116); else if (arg === "tail.js" || arg === "tail") return __nccwpck_require__(42284); else if (arg === "tempdir.js" || arg === "tempdir") return __nccwpck_require__(76150); else if (arg === "test.js" || arg === "test") return __nccwpck_require__(79723); else if (arg === "to.js" || arg === "to") return __nccwpck_require__(71961); else if (arg === "toEnd.js" || arg === "toEnd") return __nccwpck_require__(33736); else if (arg === "touch.js" || arg === "touch") return __nccwpck_require__(28358); else if (arg === "uniq.js" || arg === "uniq") return __nccwpck_require__(77286); else if (arg === "which.js" || arg === "which") return __nccwpck_require__(64766); } var common = __nccwpck_require__(53687); //@ //@ All commands run synchronously, unless otherwise stated. //@ All commands accept standard bash globbing characters (`*`, `?`, etc.), //@ compatible with the [node `glob` module](https://github.com/isaacs/node-glob). //@ //@ For less-commonly used commands and features, please check out our [wiki //@ page](https://github.com/shelljs/shelljs/wiki). //@ // Include the docs for all the default commands //@commands // Load all default commands (__nccwpck_require__(45123).forEach)(function (command) { __ncc_wildcard$0(command); }); //@ //@ ### exit(code) //@ //@ Exits the current process with the given exit `code`. exports.exit = process.exit; //@include ./src/error exports.error = __nccwpck_require__(10232); //@include ./src/common exports.ShellString = common.ShellString; //@ //@ ### env['VAR_NAME'] //@ //@ Object containing environment variables (both getter and setter). Shortcut //@ to `process.env`. exports.env = process.env; //@ //@ ### Pipes //@ //@ Examples: //@ //@ ```javascript //@ grep('foo', 'file1.txt', 'file2.txt').sed(/o/g, 'a').to('output.txt'); //@ echo('files with o\'s in the name:\n' + ls().grep('o')); //@ cat('test.js').exec('node'); // pipe to exec() call //@ ``` //@ //@ Commands can send their output to another command in a pipe-like fashion. //@ `sed`, `grep`, `cat`, `exec`, `to`, and `toEnd` can appear on the right-hand //@ side of a pipe. Pipes can be chained. //@ //@ ## Configuration //@ exports.config = common.config; //@ //@ ### config.silent //@ //@ Example: //@ //@ ```javascript //@ var sh = require('shelljs'); //@ var silentState = sh.config.silent; // save old silent state //@ sh.config.silent = true; //@ /* ... */ //@ sh.config.silent = silentState; // restore old silent state //@ ``` //@ //@ Suppresses all command output if `true`, except for `echo()` calls. //@ Default is `false`. //@ //@ ### config.fatal //@ //@ Example: //@ //@ ```javascript //@ require('shelljs/global'); //@ config.fatal = true; // or set('-e'); //@ cp('this_file_does_not_exist', '/dev/null'); // throws Error here //@ /* more commands... */ //@ ``` //@ //@ If `true`, the script will throw a Javascript error when any shell.js //@ command encounters an error. Default is `false`. This is analogous to //@ Bash's `set -e`. //@ //@ ### config.verbose //@ //@ Example: //@ //@ ```javascript //@ config.verbose = true; // or set('-v'); //@ cd('dir/'); //@ rm('-rf', 'foo.txt', 'bar.txt'); //@ exec('echo hello'); //@ ``` //@ //@ Will print each command as follows: //@ //@ ``` //@ cd dir/ //@ rm -rf foo.txt bar.txt //@ exec echo hello //@ ``` //@ //@ ### config.globOptions //@ //@ Example: //@ //@ ```javascript //@ config.globOptions = {nodir: true}; //@ ``` //@ //@ Use this value for calls to `glob.sync()` instead of the default options. //@ //@ ### config.reset() //@ //@ Example: //@ //@ ```javascript //@ var shell = require('shelljs'); //@ // Make changes to shell.config, and do stuff... //@ /* ... */ //@ shell.config.reset(); // reset to original state //@ // Do more stuff, but with original settings //@ /* ... */ //@ ``` //@ //@ Reset `shell.config` to the defaults: //@ //@ ```javascript //@ { //@ fatal: false, //@ globOptions: {}, //@ maxdepth: 255, //@ noglob: false, //@ silent: false, //@ verbose: false, //@ } //@ ``` /***/ }), /***/ 30271: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var common = __nccwpck_require__(53687); var fs = __nccwpck_require__(57147); common.register('cat', _cat, { canReceivePipe: true, cmdOptions: { 'n': 'number', }, }); //@ //@ ### cat([options,] file [, file ...]) //@ ### cat([options,] file_array) //@ //@ Available options: //@ //@ + `-n`: number all output lines //@ //@ Examples: //@ //@ ```javascript //@ var str = cat('file*.txt'); //@ var str = cat('file1', 'file2'); //@ var str = cat(['file1', 'file2']); // same as above //@ ``` //@ //@ Returns a string containing the given file, or a concatenated string //@ containing the files if more than one file is given (a new line character is //@ introduced between each file). function _cat(options, files) { var cat = common.readFromPipe(); if (!files && !cat) common.error('no paths given'); files = [].slice.call(arguments, 1); files.forEach(function (file) { if (!fs.existsSync(file)) { common.error('no such file or directory: ' + file); } else if (common.statFollowLinks(file).isDirectory()) { common.error(file + ': Is a directory'); } cat += fs.readFileSync(file, 'utf8'); }); if (options.number) { cat = addNumbers(cat); } return cat; } module.exports = _cat; function addNumbers(cat) { var lines = cat.split('\n'); var lastLine = lines.pop(); lines = lines.map(function (line, i) { return numberedLine(i + 1, line); }); if (lastLine.length) { lastLine = numberedLine(lines.length + 1, lastLine); } lines.push(lastLine); return lines.join('\n'); } function numberedLine(n, line) { // GNU cat use six pad start number + tab. See http://lingrok.org/xref/coreutils/src/cat.c#57 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart var number = (' ' + n).slice(-6) + '\t'; return number + line; } /***/ }), /***/ 42051: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var os = __nccwpck_require__(22037); var common = __nccwpck_require__(53687); common.register('cd', _cd, {}); //@ //@ ### cd([dir]) //@ //@ Changes to directory `dir` for the duration of the script. Changes to home //@ directory if no argument is supplied. function _cd(options, dir) { if (!dir) dir = os.homedir(); if (dir === '-') { if (!process.env.OLDPWD) { common.error('could not find previous directory'); } else { dir = process.env.OLDPWD; } } try { var curDir = process.cwd(); process.chdir(dir); process.env.OLDPWD = curDir; } catch (e) { // something went wrong, let's figure out the error var err; try { common.statFollowLinks(dir); // if this succeeds, it must be some sort of file err = 'not a directory: ' + dir; } catch (e2) { err = 'no such file or directory: ' + dir; } if (err) common.error(err); } return ''; } module.exports = _cd; /***/ }), /***/ 24975: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var common = __nccwpck_require__(53687); var fs = __nccwpck_require__(57147); var path = __nccwpck_require__(71017); var PERMS = (function (base) { return { OTHER_EXEC: base.EXEC, OTHER_WRITE: base.WRITE, OTHER_READ: base.READ, GROUP_EXEC: base.EXEC << 3, GROUP_WRITE: base.WRITE << 3, GROUP_READ: base.READ << 3, OWNER_EXEC: base.EXEC << 6, OWNER_WRITE: base.WRITE << 6, OWNER_READ: base.READ << 6, // Literal octal numbers are apparently not allowed in "strict" javascript. STICKY: parseInt('01000', 8), SETGID: parseInt('02000', 8), SETUID: parseInt('04000', 8), TYPE_MASK: parseInt('0770000', 8), }; }({ EXEC: 1, WRITE: 2, READ: 4, })); common.register('chmod', _chmod, { }); //@ //@ ### chmod([options,] octal_mode || octal_string, file) //@ ### chmod([options,] symbolic_mode, file) //@ //@ Available options: //@ //@ + `-v`: output a diagnostic for every file processed//@ //@ + `-c`: like verbose, but report only when a change is made//@ //@ + `-R`: change files and directories recursively//@ //@ //@ Examples: //@ //@ ```javascript //@ chmod(755, '/Users/brandon'); //@ chmod('755', '/Users/brandon'); // same as above //@ chmod('u+x', '/Users/brandon'); //@ chmod('-R', 'a-w', '/Users/brandon'); //@ ``` //@ //@ Alters the permissions of a file or directory by either specifying the //@ absolute permissions in octal form or expressing the changes in symbols. //@ This command tries to mimic the POSIX behavior as much as possible. //@ Notable exceptions: //@ //@ + In symbolic modes, `a-r` and `-r` are identical. No consideration is //@ given to the `umask`. //@ + There is no "quiet" option, since default behavior is to run silent. function _chmod(options, mode, filePattern) { if (!filePattern) { if (options.length > 0 && options.charAt(0) === '-') { // Special case where the specified file permissions started with - to subtract perms, which // get picked up by the option parser as command flags. // If we are down by one argument and options starts with -, shift everything over. [].unshift.call(arguments, ''); } else { common.error('You must specify a file.'); } } options = common.parseOptions(options, { 'R': 'recursive', 'c': 'changes', 'v': 'verbose', }); filePattern = [].slice.call(arguments, 2); var files; // TODO: replace this with a call to common.expand() if (options.recursive) { files = []; filePattern.forEach(function addFile(expandedFile) { var stat = common.statNoFollowLinks(expandedFile); if (!stat.isSymbolicLink()) { files.push(expandedFile); if (stat.isDirectory()) { // intentionally does not follow symlinks. fs.readdirSync(expandedFile).forEach(function (child) { addFile(expandedFile + '/' + child); }); } } }); } else { files = filePattern; } files.forEach(function innerChmod(file) { file = path.resolve(file); if (!fs.existsSync(file)) { common.error('File not found: ' + file); } // When recursing, don't follow symlinks. if (options.recursive && common.statNoFollowLinks(file).isSymbolicLink()) { return; } var stat = common.statFollowLinks(file); var isDir = stat.isDirectory(); var perms = stat.mode; var type = perms & PERMS.TYPE_MASK; var newPerms = perms; if (isNaN(parseInt(mode, 8))) { // parse options mode.split(',').forEach(function (symbolicMode) { var pattern = /([ugoa]*)([=\+-])([rwxXst]*)/i; var matches = pattern.exec(symbolicMode); if (matches) { var applyTo = matches[1]; var operator = matches[2]; var change = matches[3]; var changeOwner = applyTo.indexOf('u') !== -1 || applyTo === 'a' || applyTo === ''; var changeGroup = applyTo.indexOf('g') !== -1 || applyTo === 'a' || applyTo === ''; var changeOther = applyTo.indexOf('o') !== -1 || applyTo === 'a' || applyTo === ''; var changeRead = change.indexOf('r') !== -1; var changeWrite = change.indexOf('w') !== -1; var changeExec = change.indexOf('x') !== -1; var changeExecDir = change.indexOf('X') !== -1; var changeSticky = change.indexOf('t') !== -1; var changeSetuid = change.indexOf('s') !== -1; if (changeExecDir && isDir) { changeExec = true; } var mask = 0; if (changeOwner) { mask |= (changeRead ? PERMS.OWNER_READ : 0) + (changeWrite ? PERMS.OWNER_WRITE : 0) + (changeExec ? PERMS.OWNER_EXEC : 0) + (changeSetuid ? PERMS.SETUID : 0); } if (changeGroup) { mask |= (changeRead ? PERMS.GROUP_READ : 0) + (changeWrite ? PERMS.GROUP_WRITE : 0) + (changeExec ? PERMS.GROUP_EXEC : 0) + (changeSetuid ? PERMS.SETGID : 0); } if (changeOther) { mask |= (changeRead ? PERMS.OTHER_READ : 0) + (changeWrite ? PERMS.OTHER_WRITE : 0) + (changeExec ? PERMS.OTHER_EXEC : 0); } // Sticky bit is special - it's not tied to user, group or other. if (changeSticky) { mask |= PERMS.STICKY; } switch (operator) { case '+': newPerms |= mask; break; case '-': newPerms &= ~mask; break; case '=': newPerms = type + mask; // According to POSIX, when using = to explicitly set the // permissions, setuid and setgid can never be cleared. if (common.statFollowLinks(file).isDirectory()) { newPerms |= (PERMS.SETUID + PERMS.SETGID) & perms; } break; default: common.error('Could not recognize operator: `' + operator + '`'); } if (options.verbose) { console.log(file + ' -> ' + newPerms.toString(8)); } if (perms !== newPerms) { if (!options.verbose && options.changes) { console.log(file + ' -> ' + newPerms.toString(8)); } fs.chmodSync(file, newPerms); perms = newPerms; // for the next round of changes! } } else { common.error('Invalid symbolic mode change: ' + symbolicMode); } }); } else { // they gave us a full number newPerms = type + parseInt(mode, 8); // POSIX rules are that setuid and setgid can only be added using numeric // form, but not cleared. if (common.statFollowLinks(file).isDirectory()) { newPerms |= (PERMS.SETUID + PERMS.SETGID) & perms; } fs.chmodSync(file, newPerms); } }); return ''; } module.exports = _chmod; /***/ }), /***/ 53687: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Ignore warning about 'new String()' /* eslint no-new-wrappers: 0 */ var os = __nccwpck_require__(22037); var fs = __nccwpck_require__(57147); var glob = __nccwpck_require__(91957); var shell = __nccwpck_require__(33516); var shellMethods = Object.create(shell); exports.extend = Object.assign; // Check if we're running under electron var isElectron = Boolean(process.versions.electron); // Module globals (assume no execPath by default) var DEFAULT_CONFIG = { fatal: false, globOptions: {}, maxdepth: 255, noglob: false, silent: false, verbose: false, execPath: null, bufLength: 64 * 1024, // 64KB }; var config = { reset: function () { Object.assign(this, DEFAULT_CONFIG); if (!isElectron) { this.execPath = process.execPath; } }, resetForTesting: function () { this.reset(); this.silent = true; }, }; config.reset(); exports.config = config; // Note: commands should generally consider these as read-only values. var state = { error: null, errorCode: 0, currentCmd: 'shell.js', }; exports.state = state; delete process.env.OLDPWD; // initially, there's no previous directory // Reliably test if something is any sort of javascript object function isObject(a) { return typeof a === 'object' && a !== null; } exports.isObject = isObject; function log() { /* istanbul ignore next */ if (!config.silent) { console.error.apply(console, arguments); } } exports.log = log; // Converts strings to be equivalent across all platforms. Primarily responsible // for making sure we use '/' instead of '\' as path separators, but this may be // expanded in the future if necessary function convertErrorOutput(msg) { if (typeof msg !== 'string') { throw new TypeError('input must be a string'); } return msg.replace(/\\/g, '/'); } exports.convertErrorOutput = convertErrorOutput; // Shows error message. Throws if config.fatal is true function error(msg, _code, options) { // Validate input if (typeof msg !== 'string') throw new Error('msg must be a string'); var DEFAULT_OPTIONS = { continue: false, code: 1, prefix: state.currentCmd + ': ', silent: false, }; if (typeof _code === 'number' && isObject(options)) { options.code = _code; } else if (isObject(_code)) { // no 'code' options = _code; } else if (typeof _code === 'number') { // no 'options' options = { code: _code }; } else if (typeof _code !== 'number') { // only 'msg' options = {}; } options = Object.assign({}, DEFAULT_OPTIONS, options); if (!state.errorCode) state.errorCode = options.code; var logEntry = convertErrorOutput(options.prefix + msg); state.error = state.error ? state.error + '\n' : ''; state.error += logEntry; // Throw an error, or log the entry if (config.fatal) throw new Error(logEntry); if (msg.length > 0 && !options.silent) log(logEntry); if (!options.continue) { throw { msg: 'earlyExit', retValue: (new ShellString('', state.error, state.errorCode)), }; } } exports.error = error; //@ //@ ### ShellString(str) //@ //@ Examples: //@ //@ ```javascript //@ var foo = ShellString('hello world'); //@ ``` //@ //@ Turns a regular string into a string-like object similar to what each //@ command returns. This has special methods, like `.to()` and `.toEnd()`. function ShellString(stdout, stderr, code) { var that; if (stdout instanceof Array) { that = stdout; that.stdout = stdout.join('\n'); if (stdout.length > 0) that.stdout += '\n'; } else { that = new String(stdout); that.stdout = stdout; } that.stderr = stderr; that.code = code; // A list of all commands that can appear on the right-hand side of a pipe // (populated by calls to common.wrap()) pipeMethods.forEach(function (cmd) { that[cmd] = shellMethods[cmd].bind(that); }); return that; } exports.ShellString = ShellString; // Returns {'alice': true, 'bob': false} when passed a string and dictionary as follows: // parseOptions('-a', {'a':'alice', 'b':'bob'}); // Returns {'reference': 'string-value', 'bob': false} when passed two dictionaries of the form: // parseOptions({'-r': 'string-value'}, {'r':'reference', 'b':'bob'}); // Throws an error when passed a string that does not start with '-': // parseOptions('a', {'a':'alice'}); // throws function parseOptions(opt, map, errorOptions) { // Validate input if (typeof opt !== 'string' && !isObject(opt)) { throw new Error('options must be strings or key-value pairs'); } else if (!isObject(map)) { throw new Error('parseOptions() internal error: map must be an object'); } else if (errorOptions && !isObject(errorOptions)) { throw new Error('parseOptions() internal error: errorOptions must be object'); } if (opt === '--') { // This means there are no options. return {}; } // All options are false by default var options = {}; Object.keys(map).forEach(function (letter) { var optName = map[letter]; if (optName[0] !== '!') { options[optName] = false; } }); if (opt === '') return options; // defaults if (typeof opt === 'string') { if (opt[0] !== '-') { throw new Error("Options string must start with a '-'"); } // e.g. chars = ['R', 'f'] var chars = opt.slice(1).split(''); chars.forEach(function (c) { if (c in map) { var optionName = map[c]; if (optionName[0] === '!') { options[optionName.slice(1)] = false; } else { options[optionName] = true; } } else { error('option not recognized: ' + c, errorOptions || {}); } }); } else { // opt is an Object Object.keys(opt).forEach(function (key) { // key is a string of the form '-r', '-d', etc. var c = key[1]; if (c in map) { var optionName = map[c]; options[optionName] = opt[key]; // assign the given value } else { error('option not recognized: ' + c, errorOptions || {}); } }); } return options; } exports.parseOptions = parseOptions; // Expands wildcards with matching (ie. existing) file names. // For example: // expand(['file*.js']) = ['file1.js', 'file2.js', ...] // (if the files 'file1.js', 'file2.js', etc, exist in the current dir) function expand(list) { if (!Array.isArray(list)) { throw new TypeError('must be an array'); } var expanded = []; list.forEach(function (listEl) { // Don't expand non-strings if (typeof listEl !== 'string') { expanded.push(listEl); } else { var ret; try { ret = glob.sync(listEl, config.globOptions); // if nothing matched, interpret the string literally ret = ret.length > 0 ? ret : [listEl]; } catch (e) { // if glob fails, interpret the string literally ret = [listEl]; } expanded = expanded.concat(ret); } }); return expanded; } exports.expand = expand; // Normalizes Buffer creation, using Buffer.alloc if possible. // Also provides a good default buffer length for most use cases. var buffer = typeof Buffer.alloc === 'function' ? function (len) { return Buffer.alloc(len || config.bufLength); } : function (len) { return new Buffer(len || config.bufLength); }; exports.buffer = buffer; // Normalizes _unlinkSync() across platforms to match Unix behavior, i.e. // file can be unlinked even if it's read-only, see https://github.com/joyent/node/issues/3006 function unlinkSync(file) { try { fs.unlinkSync(file); } catch (e) { // Try to override file permission /* istanbul ignore next */ if (e.code === 'EPERM') { fs.chmodSync(file, '0666'); fs.unlinkSync(file); } else { throw e; } } } exports.unlinkSync = unlinkSync; // wrappers around common.statFollowLinks and common.statNoFollowLinks that clarify intent // and improve readability function statFollowLinks() { return fs.statSync.apply(fs, arguments); } exports.statFollowLinks = statFollowLinks; function statNoFollowLinks() { return fs.lstatSync.apply(fs, arguments); } exports.statNoFollowLinks = statNoFollowLinks; // e.g. 'shelljs_a5f185d0443ca...' function randomFileName() { function randomHash(count) { if (count === 1) { return parseInt(16 * Math.random(), 10).toString(16); } var hash = ''; for (var i = 0; i < count; i++) { hash += randomHash(1); } return hash; } return 'shelljs_' + randomHash(20); } exports.randomFileName = randomFileName; // Common wrapper for all Unix-like commands that performs glob expansion, // command-logging, and other nice things function wrap(cmd, fn, options) { options = options || {}; return function () { var retValue = null; state.currentCmd = cmd; state.error = null; state.errorCode = 0; try { var args = [].slice.call(arguments, 0); // Log the command to stderr, if appropriate if (config.verbose) { console.error.apply(console, [cmd].concat(args)); } // If this is coming from a pipe, let's set the pipedValue (otherwise, set // it to the empty string) state.pipedValue = (this && typeof this.stdout === 'string') ? this.stdout : ''; if (options.unix === false) { // this branch is for exec() retValue = fn.apply(this, args); } else { // and this branch is for everything else if (isObject(args[0]) && args[0].constructor.name === 'Object') { // a no-op, allowing the syntax `touch({'-r': file}, ...)` } else if (args.length === 0 || typeof args[0] !== 'string' || args[0].length <= 1 || args[0][0] !== '-') { args.unshift(''); // only add dummy option if '-option' not already present } // flatten out arrays that are arguments, to make the syntax: // `cp([file1, file2, file3], dest);` // equivalent to: // `cp(file1, file2, file3, dest);` args = args.reduce(function (accum, cur) { if (Array.isArray(cur)) { return accum.concat(cur); } accum.push(cur); return accum; }, []); // Convert ShellStrings (basically just String objects) to regular strings args = args.map(function (arg) { if (isObject(arg) && arg.constructor.name === 'String') { return arg.toString(); } return arg; }); // Expand the '~' if appropriate var homeDir = os.homedir(); args = args.map(function (arg) { if (typeof arg === 'string' && arg.slice(0, 2) === '~/' || arg === '~') { return arg.replace(/^~/, homeDir); } return arg; }); // Perform glob-expansion on all arguments after globStart, but preserve // the arguments before it (like regexes for sed and grep) if (!config.noglob && options.allowGlobbing === true) { args = args.slice(0, options.globStart).concat(expand(args.slice(options.globStart))); } try { // parse options if options are provided if (isObject(options.cmdOptions)) { args[0] = parseOptions(args[0], options.cmdOptions); } retValue = fn.apply(this, args); } catch (e) { /* istanbul ignore else */ if (e.msg === 'earlyExit') { retValue = e.retValue; } else { throw e; // this is probably a bug that should be thrown up the call stack } } } } catch (e) { /* istanbul ignore next */ if (!state.error) { // If state.error hasn't been set it's an error thrown by Node, not us - probably a bug... e.name = 'ShellJSInternalError'; throw e; } if (config.fatal) throw e; } if (options.wrapOutput && (typeof retValue === 'string' || Array.isArray(retValue))) { retValue = new ShellString(retValue, state.error, state.errorCode); } state.currentCmd = 'shell.js'; return retValue; }; } // wrap exports.wrap = wrap; // This returns all the input that is piped into the current command (or the // empty string, if this isn't on the right-hand side of a pipe function _readFromPipe() { return state.pipedValue; } exports.readFromPipe = _readFromPipe; var DEFAULT_WRAP_OPTIONS = { allowGlobbing: true, canReceivePipe: false, cmdOptions: null, globStart: 1, pipeOnly: false, wrapOutput: true, unix: true, }; // This is populated during plugin registration var pipeMethods = []; // Register a new ShellJS command function _register(name, implementation, wrapOptions) { wrapOptions = wrapOptions || {}; // Validate options Object.keys(wrapOptions).forEach(function (option) { if (!DEFAULT_WRAP_OPTIONS.hasOwnProperty(option)) { throw new Error("Unknown option '" + option + "'"); } if (typeof wrapOptions[option] !== typeof DEFAULT_WRAP_OPTIONS[option]) { throw new TypeError("Unsupported type '" + typeof wrapOptions[option] + "' for option '" + option + "'"); } }); // If an option isn't specified, use the default wrapOptions = Object.assign({}, DEFAULT_WRAP_OPTIONS, wrapOptions); if (shell.hasOwnProperty(name)) { throw new Error('Command `' + name + '` already exists'); } if (wrapOptions.pipeOnly) { wrapOptions.canReceivePipe = true; shellMethods[name] = wrap(name, implementation, wrapOptions); } else { shell[name] = wrap(name, implementation, wrapOptions); } if (wrapOptions.canReceivePipe) { pipeMethods.push(name); } } exports.register = _register; /***/ }), /***/ 34932: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var fs = __nccwpck_require__(57147); var path = __nccwpck_require__(71017); var common = __nccwpck_require__(53687); common.register('cp', _cp, { cmdOptions: { 'f': '!no_force', 'n': 'no_force', 'u': 'update', 'R': 'recursive', 'r': 'recursive', 'L': 'followsymlink', 'P': 'noFollowsymlink', }, wrapOutput: false, }); // Buffered file copy, synchronous // (Using readFileSync() + writeFileSync() could easily cause a memory overflow // with large files) function copyFileSync(srcFile, destFile, options) { if (!fs.existsSync(srcFile)) { common.error('copyFileSync: no such file or directory: ' + srcFile); } var isWindows = process.platform === 'win32'; // Check the mtimes of the files if the '-u' flag is provided try { if (options.update && common.statFollowLinks(srcFile).mtime < fs.statSync(destFile).mtime) { return; } } catch (e) { // If we're here, destFile probably doesn't exist, so just do a normal copy } if (common.statNoFollowLinks(srcFile).isSymbolicLink() && !options.followsymlink) { try { common.statNoFollowLinks(destFile); common.unlinkSync(destFile); // re-link it } catch (e) { // it doesn't exist, so no work needs to be done } var symlinkFull = fs.readlinkSync(srcFile); fs.symlinkSync(symlinkFull, destFile, isWindows ? 'junction' : null); } else { var buf = common.buffer(); var bufLength = buf.length; var bytesRead = bufLength; var pos = 0; var fdr = null; var fdw = null; try { fdr = fs.openSync(srcFile, 'r'); } catch (e) { /* istanbul ignore next */ common.error('copyFileSync: could not read src file (' + srcFile + ')'); } try { fdw = fs.openSync(destFile, 'w'); } catch (e) { /* istanbul ignore next */ common.error('copyFileSync: could not write to dest file (code=' + e.code + '):' + destFile); } while (bytesRead === bufLength) { bytesRead = fs.readSync(fdr, buf, 0, bufLength, pos); fs.writeSync(fdw, buf, 0, bytesRead); pos += bytesRead; } fs.closeSync(fdr); fs.closeSync(fdw); fs.chmodSync(destFile, common.statFollowLinks(srcFile).mode); } } // Recursively copies 'sourceDir' into 'destDir' // Adapted from https://github.com/ryanmcgrath/wrench-js // // Copyright (c) 2010 Ryan McGrath // Copyright (c) 2012 Artur Adib // // Licensed under the MIT License // http://www.opensource.org/licenses/mit-license.php function cpdirSyncRecursive(sourceDir, destDir, currentDepth, opts) { if (!opts) opts = {}; // Ensure there is not a run away recursive copy if (currentDepth >= common.config.maxdepth) return; currentDepth++; var isWindows = process.platform === 'win32'; // Create the directory where all our junk is moving to; read the mode of the // source directory and mirror it try { fs.mkdirSync(destDir); } catch (e) { // if the directory already exists, that's okay if (e.code !== 'EEXIST') throw e; } var files = fs.readdirSync(sourceDir); for (var i = 0; i < files.length; i++) { var srcFile = sourceDir + '/' + files[i]; var destFile = destDir + '/' + files[i]; var srcFileStat = common.statNoFollowLinks(srcFile); var symlinkFull; if (opts.followsymlink) { if (cpcheckcycle(sourceDir, srcFile)) { // Cycle link found. console.error('Cycle link found.'); symlinkFull = fs.readlinkSync(srcFile); fs.symlinkSync(symlinkFull, destFile, isWindows ? 'junction' : null); continue; } } if (srcFileStat.isDirectory()) { /* recursion this thing right on back. */ cpdirSyncRecursive(srcFile, destFile, currentDepth, opts); } else if (srcFileStat.isSymbolicLink() && !opts.followsymlink) { symlinkFull = fs.readlinkSync(srcFile); try { common.statNoFollowLinks(destFile); common.unlinkSync(destFile); // re-link it } catch (e) { // it doesn't exist, so no work needs to be done } fs.symlinkSync(symlinkFull, destFile, isWindows ? 'junction' : null); } else if (srcFileStat.isSymbolicLink() && opts.followsymlink) { srcFileStat = common.statFollowLinks(srcFile); if (srcFileStat.isDirectory()) { cpdirSyncRecursive(srcFile, destFile, currentDepth, opts); } else { copyFileSync(srcFile, destFile, opts); } } else { /* At this point, we've hit a file actually worth copying... so copy it on over. */ if (fs.existsSync(destFile) && opts.no_force) { common.log('skipping existing file: ' + files[i]); } else { copyFileSync(srcFile, destFile, opts); } } } // for files // finally change the mode for the newly created directory (otherwise, we // couldn't add files to a read-only directory). var checkDir = common.statFollowLinks(sourceDir); fs.chmodSync(destDir, checkDir.mode); } // cpdirSyncRecursive // Checks if cureent file was created recently function checkRecentCreated(sources, index) { var lookedSource = sources[index]; return sources.slice(0, index).some(function (src) { return path.basename(src) === path.basename(lookedSource); }); } function cpcheckcycle(sourceDir, srcFile) { var srcFileStat = common.statNoFollowLinks(srcFile); if (srcFileStat.isSymbolicLink()) { // Do cycle check. For example: // $ mkdir -p 1/2/3/4 // $ cd 1/2/3/4 // $ ln -s ../../3 link // $ cd ../../../.. // $ cp -RL 1 copy var cyclecheck = common.statFollowLinks(srcFile); if (cyclecheck.isDirectory()) { var sourcerealpath = fs.realpathSync(sourceDir); var symlinkrealpath = fs.realpathSync(srcFile); var re = new RegExp(symlinkrealpath); if (re.test(sourcerealpath)) { return true; } } } return false; } //@ //@ ### cp([options,] source [, source ...], dest) //@ ### cp([options,] source_array, dest) //@ //@ Available options: //@ //@ + `-f`: force (default behavior) //@ + `-n`: no-clobber //@ + `-u`: only copy if `source` is newer than `dest` //@ + `-r`, `-R`: recursive //@ + `-L`: follow symlinks //@ + `-P`: don't follow symlinks //@ //@ Examples: //@ //@ ```javascript //@ cp('file1', 'dir1'); //@ cp('-R', 'path/to/dir/', '~/newCopy/'); //@ cp('-Rf', '/tmp/*', '/usr/local/*', '/home/tmp'); //@ cp('-Rf', ['/tmp/*', '/usr/local/*'], '/home/tmp'); // same as above //@ ``` //@ //@ Copies files. function _cp(options, sources, dest) { // If we're missing -R, it actually implies -L (unless -P is explicit) if (options.followsymlink) { options.noFollowsymlink = false; } if (!options.recursive && !options.noFollowsymlink) { options.followsymlink = true; } // Get sources, dest if (arguments.length < 3) { common.error('missing and/or '); } else { sources = [].slice.call(arguments, 1, arguments.length - 1); dest = arguments[arguments.length - 1]; } var destExists = fs.existsSync(dest); var destStat = destExists && common.statFollowLinks(dest); // Dest is not existing dir, but multiple sources given if ((!destExists || !destStat.isDirectory()) && sources.length > 1) { common.error('dest is not a directory (too many sources)'); } // Dest is an existing file, but -n is given if (destExists && destStat.isFile() && options.no_force) { return new common.ShellString('', '', 0); } sources.forEach(function (src, srcIndex) { if (!fs.existsSync(src)) { if (src === '') src = "''"; // if src was empty string, display empty string common.error('no such file or directory: ' + src, { continue: true }); return; // skip file } var srcStat = common.statFollowLinks(src); if (!options.noFollowsymlink && srcStat.isDirectory()) { if (!options.recursive) { // Non-Recursive common.error("omitting directory '" + src + "'", { continue: true }); } else { // Recursive // 'cp /a/source dest' should create 'source' in 'dest' var newDest = (destStat && destStat.isDirectory()) ? path.join(dest, path.basename(src)) : dest; try { common.statFollowLinks(path.dirname(dest)); cpdirSyncRecursive(src, newDest, 0, { no_force: options.no_force, followsymlink: options.followsymlink }); } catch (e) { /* istanbul ignore next */ common.error("cannot create directory '" + dest + "': No such file or directory"); } } } else { // If here, src is a file // When copying to '/path/dir': // thisDest = '/path/dir/file1' var thisDest = dest; if (destStat && destStat.isDirectory()) { thisDest = path.normalize(dest + '/' + path.basename(src)); } var thisDestExists = fs.existsSync(thisDest); if (thisDestExists && checkRecentCreated(sources, srcIndex)) { // cannot overwrite file created recently in current execution, but we want to continue copying other files if (!options.no_force) { common.error("will not overwrite just-created '" + thisDest + "' with '" + src + "'", { continue: true }); } return; } if (thisDestExists && options.no_force) { return; // skip file } if (path.relative(src, thisDest) === '') { // a file cannot be copied to itself, but we want to continue copying other files common.error("'" + thisDest + "' and '" + src + "' are the same file", { continue: true }); return; } copyFileSync(src, thisDest, options); } }); // forEach(src) return new common.ShellString('', common.state.error, common.state.errorCode); } module.exports = _cp; /***/ }), /***/ 41178: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { var common = __nccwpck_require__(53687); var _cd = __nccwpck_require__(42051); var path = __nccwpck_require__(71017); common.register('dirs', _dirs, { wrapOutput: false, }); common.register('pushd', _pushd, { wrapOutput: false, }); common.register('popd', _popd, { wrapOutput: false, }); // Pushd/popd/dirs internals var _dirStack = []; function _isStackIndex(index) { return (/^[\-+]\d+$/).test(index); } function _parseStackIndex(index) { if (_isStackIndex(index)) { if (Math.abs(index) < _dirStack.length + 1) { // +1 for pwd return (/^-/).test(index) ? Number(index) - 1 : Number(index); } common.error(index + ': directory stack index out of range'); } else { common.error(index + ': invalid number'); } } function _actualDirStack() { return [process.cwd()].concat(_dirStack); } //@ //@ ### pushd([options,] [dir | '-N' | '+N']) //@ //@ Available options: //@ //@ + `-n`: Suppresses the normal change of directory when adding directories to the stack, so that only the stack is manipulated. //@ + `-q`: Supresses output to the console. //@ //@ Arguments: //@ //@ + `dir`: Sets the current working directory to the top of the stack, then executes the equivalent of `cd dir`. //@ + `+N`: Brings the Nth directory (counting from the left of the list printed by dirs, starting with zero) to the top of the list by rotating the stack. //@ + `-N`: Brings the Nth directory (counting from the right of the list printed by dirs, starting with zero) to the top of the list by rotating the stack. //@ //@ Examples: //@ //@ ```javascript //@ // process.cwd() === '/usr' //@ pushd('/etc'); // Returns /etc /usr //@ pushd('+1'); // Returns /usr /etc //@ ``` //@ //@ Save the current directory on the top of the directory stack and then `cd` to `dir`. With no arguments, `pushd` exchanges the top two directories. Returns an array of paths in the stack. function _pushd(options, dir) { if (_isStackIndex(options)) { dir = options; options = ''; } options = common.parseOptions(options, { 'n': 'no-cd', 'q': 'quiet', }); var dirs = _actualDirStack(); if (dir === '+0') { return dirs; // +0 is a noop } else if (!dir) { if (dirs.length > 1) { dirs = dirs.splice(1, 1).concat(dirs); } else { return common.error('no other directory'); } } else if (_isStackIndex(dir)) { var n = _parseStackIndex(dir); dirs = dirs.slice(n).concat(dirs.slice(0, n)); } else { if (options['no-cd']) { dirs.splice(1, 0, dir); } else { dirs.unshift(dir); } } if (options['no-cd']) { dirs = dirs.slice(1); } else { dir = path.resolve(dirs.shift()); _cd('', dir); } _dirStack = dirs; return _dirs(options.quiet ? '-q' : ''); } exports.pushd = _pushd; //@ //@ //@ ### popd([options,] ['-N' | '+N']) //@ //@ Available options: //@ //@ + `-n`: Suppress the normal directory change when removing directories from the stack, so that only the stack is manipulated. //@ + `-q`: Supresses output to the console. //@ //@ Arguments: //@ //@ + `+N`: Removes the Nth directory (counting from the left of the list printed by dirs), starting with zero. //@ + `-N`: Removes the Nth directory (counting from the right of the list printed by dirs), starting with zero. //@ //@ Examples: //@ //@ ```javascript //@ echo(process.cwd()); // '/usr' //@ pushd('/etc'); // '/etc /usr' //@ echo(process.cwd()); // '/etc' //@ popd(); // '/usr' //@ echo(process.cwd()); // '/usr' //@ ``` //@ //@ When no arguments are given, `popd` removes the top directory from the stack and performs a `cd` to the new top directory. The elements are numbered from 0, starting at the first directory listed with dirs (i.e., `popd` is equivalent to `popd +0`). Returns an array of paths in the stack. function _popd(options, index) { if (_isStackIndex(options)) { index = options; options = ''; } options = common.parseOptions(options, { 'n': 'no-cd', 'q': 'quiet', }); if (!_dirStack.length) { return common.error('directory stack empty'); } index = _parseStackIndex(index || '+0'); if (options['no-cd'] || index > 0 || _dirStack.length + index === 0) { index = index > 0 ? index - 1 : index; _dirStack.splice(index, 1); } else { var dir = path.resolve(_dirStack.shift()); _cd('', dir); } return _dirs(options.quiet ? '-q' : ''); } exports.popd = _popd; //@ //@ //@ ### dirs([options | '+N' | '-N']) //@ //@ Available options: //@ //@ + `-c`: Clears the directory stack by deleting all of the elements. //@ + `-q`: Supresses output to the console. //@ //@ Arguments: //@ //@ + `+N`: Displays the Nth directory (counting from the left of the list printed by dirs when invoked without options), starting with zero. //@ + `-N`: Displays the Nth directory (counting from the right of the list printed by dirs when invoked without options), starting with zero. //@ //@ Display the list of currently remembered directories. Returns an array of paths in the stack, or a single path if `+N` or `-N` was specified. //@ //@ See also: `pushd`, `popd` function _dirs(options, index) { if (_isStackIndex(options)) { index = options; options = ''; } options = common.parseOptions(options, { 'c': 'clear', 'q': 'quiet', }); if (options.clear) { _dirStack = []; return _dirStack; } var stack = _actualDirStack(); if (index) { index = _parseStackIndex(index); if (index < 0) { index = stack.length + index; } if (!options.quiet) { common.log(stack[index]); } return stack[index]; } if (!options.quiet) { common.log(stack.join(' ')); } return stack; } exports.dirs = _dirs; /***/ }), /***/ 10243: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var format = (__nccwpck_require__(73837).format); var common = __nccwpck_require__(53687); common.register('echo', _echo, { allowGlobbing: false, }); //@ //@ ### echo([options,] string [, string ...]) //@ //@ Available options: //@ //@ + `-e`: interpret backslash escapes (default) //@ + `-n`: remove trailing newline from output //@ //@ Examples: //@ //@ ```javascript //@ echo('hello world'); //@ var str = echo('hello world'); //@ echo('-n', 'no newline at end'); //@ ``` //@ //@ Prints `string` to stdout, and returns string with additional utility methods //@ like `.to()`. function _echo(opts) { // allow strings starting with '-', see issue #20 var messages = [].slice.call(arguments, opts ? 0 : 1); var options = {}; // If the first argument starts with '-', parse it as options string. // If parseOptions throws, it wasn't an options string. try { options = common.parseOptions(messages[0], { 'e': 'escapes', 'n': 'no_newline', }, { silent: true, }); // Allow null to be echoed if (messages[0]) { messages.shift(); } } catch (_) { // Clear out error if an error occurred common.state.error = null; } var output = format.apply(null, messages); // Add newline if -n is not passed. if (!options.no_newline) { output += '\n'; } process.stdout.write(output); return output; } module.exports = _echo; /***/ }), /***/ 10232: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var common = __nccwpck_require__(53687); //@ //@ ### error() //@ //@ Tests if error occurred in the last command. Returns a truthy value if an //@ error returned, or a falsy value otherwise. //@ //@ **Note**: do not rely on the //@ return value to be an error message. If you need the last error message, use //@ the `.stderr` attribute from the last command's return value instead. function error() { return common.state.error; } module.exports = error; /***/ }), /***/ 69607: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /* module decorator */ module = __nccwpck_require__.nmd(module); if (require.main !== module) { throw new Error('This file should not be required'); } var childProcess = __nccwpck_require__(32081); var fs = __nccwpck_require__(57147); var paramFilePath = process.argv[2]; var serializedParams = fs.readFileSync(paramFilePath, 'utf8'); var params = JSON.parse(serializedParams); var cmd = params.command; var execOptions = params.execOptions; var pipe = params.pipe; var stdoutFile = params.stdoutFile; var stderrFile = params.stderrFile; var c = childProcess.exec(cmd, execOptions, function (err) { if (!err) { process.exitCode = 0; } else if (err.code === undefined) { process.exitCode = 1; } else { process.exitCode = err.code; } }); var stdoutStream = fs.createWriteStream(stdoutFile); var stderrStream = fs.createWriteStream(stderrFile); c.stdout.pipe(stdoutStream); c.stderr.pipe(stderrStream); c.stdout.pipe(process.stdout); c.stderr.pipe(process.stderr); if (pipe) { c.stdin.end(pipe); } /***/ }), /***/ 10896: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var common = __nccwpck_require__(53687); var _tempDir = (__nccwpck_require__(76150).tempDir); var _pwd = __nccwpck_require__(58553); var path = __nccwpck_require__(71017); var fs = __nccwpck_require__(57147); var child = __nccwpck_require__(32081); var DEFAULT_MAXBUFFER_SIZE = 20 * 1024 * 1024; var DEFAULT_ERROR_CODE = 1; common.register('exec', _exec, { unix: false, canReceivePipe: true, wrapOutput: false, }); // We use this function to run `exec` synchronously while also providing realtime // output. function execSync(cmd, opts, pipe) { if (!common.config.execPath) { common.error('Unable to find a path to the node binary. Please manually set config.execPath'); } var tempDir = _tempDir(); var paramsFile = path.resolve(tempDir + '/' + common.randomFileName()); var stderrFile = path.resolve(tempDir + '/' + common.randomFileName()); var stdoutFile = path.resolve(tempDir + '/' + common.randomFileName()); opts = common.extend({ silent: common.config.silent, cwd: _pwd().toString(), env: process.env, maxBuffer: DEFAULT_MAXBUFFER_SIZE, encoding: 'utf8', }, opts); if (fs.existsSync(paramsFile)) common.unlinkSync(paramsFile); if (fs.existsSync(stderrFile)) common.unlinkSync(stderrFile); if (fs.existsSync(stdoutFile)) common.unlinkSync(stdoutFile); opts.cwd = path.resolve(opts.cwd); var paramsToSerialize = { command: cmd, execOptions: opts, pipe: pipe, stdoutFile: stdoutFile, stderrFile: stderrFile, }; // Create the files and ensure these are locked down (for read and write) to // the current user. The main concerns here are: // // * If we execute a command which prints sensitive output, then // stdoutFile/stderrFile must not be readable by other users. // * paramsFile must not be readable by other users, or else they can read it // to figure out the path for stdoutFile/stderrFile and create these first // (locked down to their own access), which will crash exec() when it tries // to write to the files. function writeFileLockedDown(filePath, data) { fs.writeFileSync(filePath, data, { encoding: 'utf8', mode: parseInt('600', 8), }); } writeFileLockedDown(stdoutFile, ''); writeFileLockedDown(stderrFile, ''); writeFileLockedDown(paramsFile, JSON.stringify(paramsToSerialize)); var execArgs = [ __nccwpck_require__.ab + "exec-child.js", paramsFile, ]; /* istanbul ignore else */ if (opts.silent) { opts.stdio = 'ignore'; } else { opts.stdio = [0, 1, 2]; } var code = 0; // Welcome to the future try { // Bad things if we pass in a `shell` option to child_process.execFileSync, // so we need to explicitly remove it here. delete opts.shell; child.execFileSync(common.config.execPath, execArgs, opts); } catch (e) { // Commands with non-zero exit code raise an exception. code = e.status || DEFAULT_ERROR_CODE; } // fs.readFileSync uses buffer encoding by default, so call // it without the encoding option if the encoding is 'buffer'. // Also, if the exec timeout is too short for node to start up, // the files will not be created, so these calls will throw. var stdout = ''; var stderr = ''; if (opts.encoding === 'buffer') { stdout = fs.readFileSync(stdoutFile); stderr = fs.readFileSync(stderrFile); } else { stdout = fs.readFileSync(stdoutFile, opts.encoding); stderr = fs.readFileSync(stderrFile, opts.encoding); } // No biggie if we can't erase the files now -- they're in a temp dir anyway // and we locked down permissions (see the note above). try { common.unlinkSync(paramsFile); } catch (e) {} try { common.unlinkSync(stderrFile); } catch (e) {} try { common.unlinkSync(stdoutFile); } catch (e) {} if (code !== 0) { // Note: `silent` should be unconditionally true to avoid double-printing // the command's stderr, and to avoid printing any stderr when the user has // set `shell.config.silent`. common.error(stderr, code, { continue: true, silent: true }); } var obj = common.ShellString(stdout, stderr, code); return obj; } // execSync() // Wrapper around exec() to enable echoing output to console in real time function execAsync(cmd, opts, pipe, callback) { opts = common.extend({ silent: common.config.silent, cwd: _pwd().toString(), env: process.env, maxBuffer: DEFAULT_MAXBUFFER_SIZE, encoding: 'utf8', }, opts); var c = child.exec(cmd, opts, function (err, stdout, stderr) { if (callback) { if (!err) { callback(0, stdout, stderr); } else if (err.code === undefined) { // See issue #536 /* istanbul ignore next */ callback(1, stdout, stderr); } else { callback(err.code, stdout, stderr); } } }); if (pipe) c.stdin.end(pipe); if (!opts.silent) { c.stdout.pipe(process.stdout); c.stderr.pipe(process.stderr); } return c; } //@ //@ ### exec(command [, options] [, callback]) //@ //@ Available options: //@ //@ + `async`: Asynchronous execution. If a callback is provided, it will be set to //@ `true`, regardless of the passed value (default: `false`). //@ + `silent`: Do not echo program output to console (default: `false`). //@ + `encoding`: Character encoding to use. Affects the values returned to stdout and stderr, and //@ what is written to stdout and stderr when not in silent mode (default: `'utf8'`). //@ + and any option available to Node.js's //@ [`child_process.exec()`](https://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback) //@ //@ Examples: //@ //@ ```javascript //@ var version = exec('node --version', {silent:true}).stdout; //@ //@ var child = exec('some_long_running_process', {async:true}); //@ child.stdout.on('data', function(data) { //@ /* ... do something with data ... */ //@ }); //@ //@ exec('some_long_running_process', function(code, stdout, stderr) { //@ console.log('Exit code:', code); //@ console.log('Program output:', stdout); //@ console.log('Program stderr:', stderr); //@ }); //@ ``` //@ //@ Executes the given `command` _synchronously_, unless otherwise specified. When in synchronous //@ mode, this returns a `ShellString` (compatible with ShellJS v0.6.x, which returns an object //@ of the form `{ code:..., stdout:... , stderr:... }`). Otherwise, this returns the child process //@ object, and the `callback` receives the arguments `(code, stdout, stderr)`. //@ //@ Not seeing the behavior you want? `exec()` runs everything through `sh` //@ by default (or `cmd.exe` on Windows), which differs from `bash`. If you //@ need bash-specific behavior, try out the `{shell: 'path/to/bash'}` option. function _exec(command, options, callback) { options = options || {}; if (!command) common.error('must specify command'); var pipe = common.readFromPipe(); // Callback is defined instead of options. if (typeof options === 'function') { callback = options; options = { async: true }; } // Callback is defined with options. if (typeof options === 'object' && typeof callback === 'function') { options.async = true; } options = common.extend({ silent: common.config.silent, async: false, }, options); if (options.async) { return execAsync(command, options, pipe, callback); } else { return execSync(command, options, pipe); } } module.exports = _exec; /***/ }), /***/ 47838: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var path = __nccwpck_require__(71017); var common = __nccwpck_require__(53687); var _ls = __nccwpck_require__(35561); common.register('find', _find, {}); //@ //@ ### find(path [, path ...]) //@ ### find(path_array) //@ //@ Examples: //@ //@ ```javascript //@ find('src', 'lib'); //@ find(['src', 'lib']); // same as above //@ find('.').filter(function(file) { return file.match(/\.js$/); }); //@ ``` //@ //@ Returns array of all files (however deep) in the given paths. //@ //@ The main difference from `ls('-R', path)` is that the resulting file names //@ include the base directories (e.g., `lib/resources/file1` instead of just `file1`). function _find(options, paths) { if (!paths) { common.error('no path specified'); } else if (typeof paths === 'string') { paths = [].slice.call(arguments, 1); } var list = []; function pushFile(file) { if (process.platform === 'win32') { file = file.replace(/\\/g, '/'); } list.push(file); } // why not simply do `ls('-R', paths)`? because the output wouldn't give the base dirs // to get the base dir in the output, we need instead `ls('-R', 'dir/*')` for every directory paths.forEach(function (file) { var stat; try { stat = common.statFollowLinks(file); } catch (e) { common.error('no such file or directory: ' + file); } pushFile(file); if (stat.isDirectory()) { _ls({ recursive: true, all: true }, file).forEach(function (subfile) { pushFile(path.join(file, subfile)); }); } }); return list; } module.exports = _find; /***/ }), /***/ 17417: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var common = __nccwpck_require__(53687); var fs = __nccwpck_require__(57147); common.register('grep', _grep, { globStart: 2, // don't glob-expand the regex canReceivePipe: true, cmdOptions: { 'v': 'inverse', 'l': 'nameOnly', 'i': 'ignoreCase', }, }); //@ //@ ### grep([options,] regex_filter, file [, file ...]) //@ ### grep([options,] regex_filter, file_array) //@ //@ Available options: //@ //@ + `-v`: Invert `regex_filter` (only print non-matching lines). //@ + `-l`: Print only filenames of matching files. //@ + `-i`: Ignore case. //@ //@ Examples: //@ //@ ```javascript //@ grep('-v', 'GLOBAL_VARIABLE', '*.js'); //@ grep('GLOBAL_VARIABLE', '*.js'); //@ ``` //@ //@ Reads input string from given files and returns a string containing all lines of the //@ file that match the given `regex_filter`. function _grep(options, regex, files) { // Check if this is coming from a pipe var pipe = common.readFromPipe(); if (!files && !pipe) common.error('no paths given', 2); files = [].slice.call(arguments, 2); if (pipe) { files.unshift('-'); } var grep = []; if (options.ignoreCase) { regex = new RegExp(regex, 'i'); } files.forEach(function (file) { if (!fs.existsSync(file) && file !== '-') { common.error('no such file or directory: ' + file, 2, { continue: true }); return; } var contents = file === '-' ? pipe : fs.readFileSync(file, 'utf8'); if (options.nameOnly) { if (contents.match(regex)) { grep.push(file); } } else { var lines = contents.split('\n'); lines.forEach(function (line) { var matched = line.match(regex); if ((options.inverse && !matched) || (!options.inverse && matched)) { grep.push(line); } }); } }); return grep.join('\n') + '\n'; } module.exports = _grep; /***/ }), /***/ 6613: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var common = __nccwpck_require__(53687); var fs = __nccwpck_require__(57147); common.register('head', _head, { canReceivePipe: true, cmdOptions: { 'n': 'numLines', }, }); // Reads |numLines| lines or the entire file, whichever is less. function readSomeLines(file, numLines) { var buf = common.buffer(); var bufLength = buf.length; var bytesRead = bufLength; var pos = 0; var fdr = fs.openSync(file, 'r'); var numLinesRead = 0; var ret = ''; while (bytesRead === bufLength && numLinesRead < numLines) { bytesRead = fs.readSync(fdr, buf, 0, bufLength, pos); var bufStr = buf.toString('utf8', 0, bytesRead); numLinesRead += bufStr.split('\n').length - 1; ret += bufStr; pos += bytesRead; } fs.closeSync(fdr); return ret; } //@ //@ ### head([{'-n': \},] file [, file ...]) //@ ### head([{'-n': \},] file_array) //@ //@ Available options: //@ //@ + `-n `: Show the first `` lines of the files //@ //@ Examples: //@ //@ ```javascript //@ var str = head({'-n': 1}, 'file*.txt'); //@ var str = head('file1', 'file2'); //@ var str = head(['file1', 'file2']); // same as above //@ ``` //@ //@ Read the start of a file. function _head(options, files) { var head = []; var pipe = common.readFromPipe(); if (!files && !pipe) common.error('no paths given'); var idx = 1; if (options.numLines === true) { idx = 2; options.numLines = Number(arguments[1]); } else if (options.numLines === false) { options.numLines = 10; } files = [].slice.call(arguments, idx); if (pipe) { files.unshift('-'); } var shouldAppendNewline = false; files.forEach(function (file) { if (file !== '-') { if (!fs.existsSync(file)) { common.error('no such file or directory: ' + file, { continue: true }); return; } else if (common.statFollowLinks(file).isDirectory()) { common.error("error reading '" + file + "': Is a directory", { continue: true, }); return; } } var contents; if (file === '-') { contents = pipe; } else if (options.numLines < 0) { contents = fs.readFileSync(file, 'utf8'); } else { contents = readSomeLines(file, options.numLines); } var lines = contents.split('\n'); var hasTrailingNewline = (lines[lines.length - 1] === ''); if (hasTrailingNewline) { lines.pop(); } shouldAppendNewline = (hasTrailingNewline || options.numLines < lines.length); head = head.concat(lines.slice(0, options.numLines)); }); if (shouldAppendNewline) { head.push(''); // to add a trailing newline once we join } return head.join('\n'); } module.exports = _head; /***/ }), /***/ 15787: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var fs = __nccwpck_require__(57147); var path = __nccwpck_require__(71017); var common = __nccwpck_require__(53687); common.register('ln', _ln, { cmdOptions: { 's': 'symlink', 'f': 'force', }, }); //@ //@ ### ln([options,] source, dest) //@ //@ Available options: //@ //@ + `-s`: symlink //@ + `-f`: force //@ //@ Examples: //@ //@ ```javascript //@ ln('file', 'newlink'); //@ ln('-sf', 'file', 'existing'); //@ ``` //@ //@ Links `source` to `dest`. Use `-f` to force the link, should `dest` already exist. function _ln(options, source, dest) { if (!source || !dest) { common.error('Missing and/or '); } source = String(source); var sourcePath = path.normalize(source).replace(RegExp(path.sep + '$'), ''); var isAbsolute = (path.resolve(source) === sourcePath); dest = path.resolve(process.cwd(), String(dest)); if (fs.existsSync(dest)) { if (!options.force) { common.error('Destination file exists', { continue: true }); } fs.unlinkSync(dest); } if (options.symlink) { var isWindows = process.platform === 'win32'; var linkType = isWindows ? 'file' : null; var resolvedSourcePath = isAbsolute ? sourcePath : path.resolve(process.cwd(), path.dirname(dest), source); if (!fs.existsSync(resolvedSourcePath)) { common.error('Source file does not exist', { continue: true }); } else if (isWindows && common.statFollowLinks(resolvedSourcePath).isDirectory()) { linkType = 'junction'; } try { fs.symlinkSync(linkType === 'junction' ? resolvedSourcePath : source, dest, linkType); } catch (err) { common.error(err.message); } } else { if (!fs.existsSync(source)) { common.error('Source file does not exist', { continue: true }); } try { fs.linkSync(source, dest); } catch (err) { common.error(err.message); } } return ''; } module.exports = _ln; /***/ }), /***/ 35561: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var path = __nccwpck_require__(71017); var fs = __nccwpck_require__(57147); var common = __nccwpck_require__(53687); var glob = __nccwpck_require__(91957); var globPatternRecursive = path.sep + '**'; common.register('ls', _ls, { cmdOptions: { 'R': 'recursive', 'A': 'all', 'L': 'link', 'a': 'all_deprecated', 'd': 'directory', 'l': 'long', }, }); //@ //@ ### ls([options,] [path, ...]) //@ ### ls([options,] path_array) //@ //@ Available options: //@ //@ + `-R`: recursive //@ + `-A`: all files (include files beginning with `.`, except for `.` and `..`) //@ + `-L`: follow symlinks //@ + `-d`: list directories themselves, not their contents //@ + `-l`: list objects representing each file, each with fields containing `ls //@ -l` output fields. See //@ [`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats) //@ for more info //@ //@ Examples: //@ //@ ```javascript //@ ls('projs/*.js'); //@ ls('-R', '/users/me', '/tmp'); //@ ls('-R', ['/users/me', '/tmp']); // same as above //@ ls('-l', 'file.txt'); // { name: 'file.txt', mode: 33188, nlink: 1, ...} //@ ``` //@ //@ Returns array of files in the given `path`, or files in //@ the current directory if no `path` is provided. function _ls(options, paths) { if (options.all_deprecated) { // We won't support the -a option as it's hard to image why it's useful // (it includes '.' and '..' in addition to '.*' files) // For backwards compatibility we'll dump a deprecated message and proceed as before common.log('ls: Option -a is deprecated. Use -A instead'); options.all = true; } if (!paths) { paths = ['.']; } else { paths = [].slice.call(arguments, 1); } var list = []; function pushFile(abs, relName, stat) { if (process.platform === 'win32') { relName = relName.replace(/\\/g, '/'); } if (options.long) { stat = stat || (options.link ? common.statFollowLinks(abs) : common.statNoFollowLinks(abs)); list.push(addLsAttributes(relName, stat)); } else { // list.push(path.relative(rel || '.', file)); list.push(relName); } } paths.forEach(function (p) { var stat; try { stat = options.link ? common.statFollowLinks(p) : common.statNoFollowLinks(p); // follow links to directories by default if (stat.isSymbolicLink()) { /* istanbul ignore next */ // workaround for https://github.com/shelljs/shelljs/issues/795 // codecov seems to have a bug that miscalculate this block as uncovered. // but according to nyc report this block does get covered. try { var _stat = common.statFollowLinks(p); if (_stat.isDirectory()) { stat = _stat; } } catch (_) {} // bad symlink, treat it like a file } } catch (e) { common.error('no such file or directory: ' + p, 2, { continue: true }); return; } // If the stat succeeded if (stat.isDirectory() && !options.directory) { if (options.recursive) { // use glob, because it's simple glob.sync(p + globPatternRecursive, { dot: options.all, follow: options.link }) .forEach(function (item) { // Glob pattern returns the directory itself and needs to be filtered out. if (path.relative(p, item)) { pushFile(item, path.relative(p, item)); } }); } else if (options.all) { // use fs.readdirSync, because it's fast fs.readdirSync(p).forEach(function (item) { pushFile(path.join(p, item), item); }); } else { // use fs.readdirSync and then filter out secret files fs.readdirSync(p).forEach(function (item) { if (item[0] !== '.') { pushFile(path.join(p, item), item); } }); } } else { pushFile(p, p, stat); } }); // Add methods, to make this more compatible with ShellStrings return list; } function addLsAttributes(pathName, stats) { // Note: this object will contain more information than .toString() returns stats.name = pathName; stats.toString = function () { // Return a string resembling unix's `ls -l` format return [this.mode, this.nlink, this.uid, this.gid, this.size, this.mtime, this.name].join(' '); }; return stats; } module.exports = _ls; /***/ }), /***/ 72695: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var common = __nccwpck_require__(53687); var fs = __nccwpck_require__(57147); var path = __nccwpck_require__(71017); common.register('mkdir', _mkdir, { cmdOptions: { 'p': 'fullpath', }, }); // Recursively creates `dir` function mkdirSyncRecursive(dir) { var baseDir = path.dirname(dir); // Prevents some potential problems arising from malformed UNCs or // insufficient permissions. /* istanbul ignore next */ if (baseDir === dir) { common.error('dirname() failed: [' + dir + ']'); } // Base dir exists, no recursion necessary if (fs.existsSync(baseDir)) { fs.mkdirSync(dir, parseInt('0777', 8)); return; } // Base dir does not exist, go recursive mkdirSyncRecursive(baseDir); // Base dir created, can create dir fs.mkdirSync(dir, parseInt('0777', 8)); } //@ //@ ### mkdir([options,] dir [, dir ...]) //@ ### mkdir([options,] dir_array) //@ //@ Available options: //@ //@ + `-p`: full path (and create intermediate directories, if necessary) //@ //@ Examples: //@ //@ ```javascript //@ mkdir('-p', '/tmp/a/b/c/d', '/tmp/e/f/g'); //@ mkdir('-p', ['/tmp/a/b/c/d', '/tmp/e/f/g']); // same as above //@ ``` //@ //@ Creates directories. function _mkdir(options, dirs) { if (!dirs) common.error('no paths given'); if (typeof dirs === 'string') { dirs = [].slice.call(arguments, 1); } // if it's array leave it as it is dirs.forEach(function (dir) { try { var stat = common.statNoFollowLinks(dir); if (!options.fullpath) { common.error('path already exists: ' + dir, { continue: true }); } else if (stat.isFile()) { common.error('cannot create directory ' + dir + ': File exists', { continue: true }); } return; // skip dir } catch (e) { // do nothing } // Base dir does not exist, and no -p option given var baseDir = path.dirname(dir); if (!fs.existsSync(baseDir) && !options.fullpath) { common.error('no such file or directory: ' + baseDir, { continue: true }); return; // skip dir } try { if (options.fullpath) { mkdirSyncRecursive(path.resolve(dir)); } else { fs.mkdirSync(dir, parseInt('0777', 8)); } } catch (e) { var reason; if (e.code === 'EACCES') { reason = 'Permission denied'; } else if (e.code === 'ENOTDIR' || e.code === 'ENOENT') { reason = 'Not a directory'; } else { /* istanbul ignore next */ throw e; } common.error('cannot create directory ' + dir + ': ' + reason, { continue: true }); } }); return ''; } // mkdir module.exports = _mkdir; /***/ }), /***/ 39849: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var fs = __nccwpck_require__(57147); var path = __nccwpck_require__(71017); var common = __nccwpck_require__(53687); var cp = __nccwpck_require__(34932); var rm = __nccwpck_require__(22830); common.register('mv', _mv, { cmdOptions: { 'f': '!no_force', 'n': 'no_force', }, }); // Checks if cureent file was created recently function checkRecentCreated(sources, index) { var lookedSource = sources[index]; return sources.slice(0, index).some(function (src) { return path.basename(src) === path.basename(lookedSource); }); } //@ //@ ### mv([options ,] source [, source ...], dest') //@ ### mv([options ,] source_array, dest') //@ //@ Available options: //@ //@ + `-f`: force (default behavior) //@ + `-n`: no-clobber //@ //@ Examples: //@ //@ ```javascript //@ mv('-n', 'file', 'dir/'); //@ mv('file1', 'file2', 'dir/'); //@ mv(['file1', 'file2'], 'dir/'); // same as above //@ ``` //@ //@ Moves `source` file(s) to `dest`. function _mv(options, sources, dest) { // Get sources, dest if (arguments.length < 3) { common.error('missing and/or '); } else if (arguments.length > 3) { sources = [].slice.call(arguments, 1, arguments.length - 1); dest = arguments[arguments.length - 1]; } else if (typeof sources === 'string') { sources = [sources]; } else { // TODO(nate): figure out if we actually need this line common.error('invalid arguments'); } var exists = fs.existsSync(dest); var stats = exists && common.statFollowLinks(dest); // Dest is not existing dir, but multiple sources given if ((!exists || !stats.isDirectory()) && sources.length > 1) { common.error('dest is not a directory (too many sources)'); } // Dest is an existing file, but no -f given if (exists && stats.isFile() && options.no_force) { common.error('dest file already exists: ' + dest); } sources.forEach(function (src, srcIndex) { if (!fs.existsSync(src)) { common.error('no such file or directory: ' + src, { continue: true }); return; // skip file } // If here, src exists // When copying to '/path/dir': // thisDest = '/path/dir/file1' var thisDest = dest; if (fs.existsSync(dest) && common.statFollowLinks(dest).isDirectory()) { thisDest = path.normalize(dest + '/' + path.basename(src)); } var thisDestExists = fs.existsSync(thisDest); if (thisDestExists && checkRecentCreated(sources, srcIndex)) { // cannot overwrite file created recently in current execution, but we want to continue copying other files if (!options.no_force) { common.error("will not overwrite just-created '" + thisDest + "' with '" + src + "'", { continue: true }); } return; } if (fs.existsSync(thisDest) && options.no_force) { common.error('dest file already exists: ' + thisDest, { continue: true }); return; // skip file } if (path.resolve(src) === path.dirname(path.resolve(thisDest))) { common.error('cannot move to self: ' + src, { continue: true }); return; // skip file } try { fs.renameSync(src, thisDest); } catch (e) { /* istanbul ignore next */ if (e.code === 'EXDEV') { // If we're trying to `mv` to an external partition, we'll actually need // to perform a copy and then clean up the original file. If either the // copy or the rm fails with an exception, we should allow this // exception to pass up to the top level. cp('-r', src, thisDest); rm('-rf', src); } } }); // forEach(src) return ''; } // mv module.exports = _mv; /***/ }), /***/ 50227: /***/ (() => { // see dirs.js /***/ }), /***/ 44177: /***/ (() => { // see dirs.js /***/ }), /***/ 58553: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var path = __nccwpck_require__(71017); var common = __nccwpck_require__(53687); common.register('pwd', _pwd, { allowGlobbing: false, }); //@ //@ ### pwd() //@ //@ Returns the current directory. function _pwd() { var pwd = path.resolve(process.cwd()); return pwd; } module.exports = _pwd; /***/ }), /***/ 22830: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var common = __nccwpck_require__(53687); var fs = __nccwpck_require__(57147); common.register('rm', _rm, { cmdOptions: { 'f': 'force', 'r': 'recursive', 'R': 'recursive', }, }); // Recursively removes 'dir' // Adapted from https://github.com/ryanmcgrath/wrench-js // // Copyright (c) 2010 Ryan McGrath // Copyright (c) 2012 Artur Adib // // Licensed under the MIT License // http://www.opensource.org/licenses/mit-license.php function rmdirSyncRecursive(dir, force, fromSymlink) { var files; files = fs.readdirSync(dir); // Loop through and delete everything in the sub-tree after checking it for (var i = 0; i < files.length; i++) { var file = dir + '/' + files[i]; var currFile = common.statNoFollowLinks(file); if (currFile.isDirectory()) { // Recursive function back to the beginning rmdirSyncRecursive(file, force); } else { // Assume it's a file - perhaps a try/catch belongs here? if (force || isWriteable(file)) { try { common.unlinkSync(file); } catch (e) { /* istanbul ignore next */ common.error('could not remove file (code ' + e.code + '): ' + file, { continue: true, }); } } } } // if was directory was referenced through a symbolic link, // the contents should be removed, but not the directory itself if (fromSymlink) return; // Now that we know everything in the sub-tree has been deleted, we can delete the main directory. // Huzzah for the shopkeep. var result; try { // Retry on windows, sometimes it takes a little time before all the files in the directory are gone var start = Date.now(); // TODO: replace this with a finite loop for (;;) { try { result = fs.rmdirSync(dir); if (fs.existsSync(dir)) throw { code: 'EAGAIN' }; break; } catch (er) { /* istanbul ignore next */ // In addition to error codes, also check if the directory still exists and loop again if true if (process.platform === 'win32' && (er.code === 'ENOTEMPTY' || er.code === 'EBUSY' || er.code === 'EPERM' || er.code === 'EAGAIN')) { if (Date.now() - start > 1000) throw er; } else if (er.code === 'ENOENT') { // Directory did not exist, deletion was successful break; } else { throw er; } } } } catch (e) { common.error('could not remove directory (code ' + e.code + '): ' + dir, { continue: true }); } return result; } // rmdirSyncRecursive // Hack to determine if file has write permissions for current user // Avoids having to check user, group, etc, but it's probably slow function isWriteable(file) { var writePermission = true; try { var __fd = fs.openSync(file, 'a'); fs.closeSync(__fd); } catch (e) { writePermission = false; } return writePermission; } function handleFile(file, options) { if (options.force || isWriteable(file)) { // -f was passed, or file is writable, so it can be removed common.unlinkSync(file); } else { common.error('permission denied: ' + file, { continue: true }); } } function handleDirectory(file, options) { if (options.recursive) { // -r was passed, so directory can be removed rmdirSyncRecursive(file, options.force); } else { common.error('path is a directory', { continue: true }); } } function handleSymbolicLink(file, options) { var stats; try { stats = common.statFollowLinks(file); } catch (e) { // symlink is broken, so remove the symlink itself common.unlinkSync(file); return; } if (stats.isFile()) { common.unlinkSync(file); } else if (stats.isDirectory()) { if (file[file.length - 1] === '/') { // trailing separator, so remove the contents, not the link if (options.recursive) { // -r was passed, so directory can be removed var fromSymlink = true; rmdirSyncRecursive(file, options.force, fromSymlink); } else { common.error('path is a directory', { continue: true }); } } else { // no trailing separator, so remove the link common.unlinkSync(file); } } } function handleFIFO(file) { common.unlinkSync(file); } //@ //@ ### rm([options,] file [, file ...]) //@ ### rm([options,] file_array) //@ //@ Available options: //@ //@ + `-f`: force //@ + `-r, -R`: recursive //@ //@ Examples: //@ //@ ```javascript //@ rm('-rf', '/tmp/*'); //@ rm('some_file.txt', 'another_file.txt'); //@ rm(['some_file.txt', 'another_file.txt']); // same as above //@ ``` //@ //@ Removes files. function _rm(options, files) { if (!files) common.error('no paths given'); // Convert to array files = [].slice.call(arguments, 1); files.forEach(function (file) { var lstats; try { var filepath = (file[file.length - 1] === '/') ? file.slice(0, -1) // remove the '/' so lstatSync can detect symlinks : file; lstats = common.statNoFollowLinks(filepath); // test for existence } catch (e) { // Path does not exist, no force flag given if (!options.force) { common.error('no such file or directory: ' + file, { continue: true }); } return; // skip file } // If here, path exists if (lstats.isFile()) { handleFile(file, options); } else if (lstats.isDirectory()) { handleDirectory(file, options); } else if (lstats.isSymbolicLink()) { handleSymbolicLink(file, options); } else if (lstats.isFIFO()) { handleFIFO(file); } }); // forEach(file) return ''; } // rm module.exports = _rm; /***/ }), /***/ 25899: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var common = __nccwpck_require__(53687); var fs = __nccwpck_require__(57147); common.register('sed', _sed, { globStart: 3, // don't glob-expand regexes canReceivePipe: true, cmdOptions: { 'i': 'inplace', }, }); //@ //@ ### sed([options,] search_regex, replacement, file [, file ...]) //@ ### sed([options,] search_regex, replacement, file_array) //@ //@ Available options: //@ //@ + `-i`: Replace contents of `file` in-place. _Note that no backups will be created!_ //@ //@ Examples: //@ //@ ```javascript //@ sed('-i', 'PROGRAM_VERSION', 'v0.1.3', 'source.js'); //@ sed(/.*DELETE_THIS_LINE.*\n/, '', 'source.js'); //@ ``` //@ //@ Reads an input string from `file`s, and performs a JavaScript `replace()` on the input //@ using the given `search_regex` and `replacement` string or function. Returns the new string after replacement. //@ //@ Note: //@ //@ Like unix `sed`, ShellJS `sed` supports capture groups. Capture groups are specified //@ using the `$n` syntax: //@ //@ ```javascript //@ sed(/(\w+)\s(\w+)/, '$2, $1', 'file.txt'); //@ ``` function _sed(options, regex, replacement, files) { // Check if this is coming from a pipe var pipe = common.readFromPipe(); if (typeof replacement !== 'string' && typeof replacement !== 'function') { if (typeof replacement === 'number') { replacement = replacement.toString(); // fallback } else { common.error('invalid replacement string'); } } // Convert all search strings to RegExp if (typeof regex === 'string') { regex = RegExp(regex); } if (!files && !pipe) { common.error('no files given'); } files = [].slice.call(arguments, 3); if (pipe) { files.unshift('-'); } var sed = []; files.forEach(function (file) { if (!fs.existsSync(file) && file !== '-') { common.error('no such file or directory: ' + file, 2, { continue: true }); return; } var contents = file === '-' ? pipe : fs.readFileSync(file, 'utf8'); var lines = contents.split('\n'); var result = lines.map(function (line) { return line.replace(regex, replacement); }).join('\n'); sed.push(result); if (options.inplace) { fs.writeFileSync(file, result, 'utf8'); } }); return sed.join('\n'); } module.exports = _sed; /***/ }), /***/ 11411: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var common = __nccwpck_require__(53687); common.register('set', _set, { allowGlobbing: false, wrapOutput: false, }); //@ //@ ### set(options) //@ //@ Available options: //@ //@ + `+/-e`: exit upon error (`config.fatal`) //@ + `+/-v`: verbose: show all commands (`config.verbose`) //@ + `+/-f`: disable filename expansion (globbing) //@ //@ Examples: //@ //@ ```javascript //@ set('-e'); // exit upon first error //@ set('+e'); // this undoes a "set('-e')" //@ ``` //@ //@ Sets global configuration variables. function _set(options) { if (!options) { var args = [].slice.call(arguments, 0); if (args.length < 2) common.error('must provide an argument'); options = args[1]; } var negate = (options[0] === '+'); if (negate) { options = '-' + options.slice(1); // parseOptions needs a '-' prefix } options = common.parseOptions(options, { 'e': 'fatal', 'v': 'verbose', 'f': 'noglob', }); if (negate) { Object.keys(options).forEach(function (key) { options[key] = !options[key]; }); } Object.keys(options).forEach(function (key) { // Only change the global config if `negate` is false and the option is true // or if `negate` is true and the option is false (aka negate !== option) if (negate !== options[key]) { common.config[key] = options[key]; } }); return; } module.exports = _set; /***/ }), /***/ 72116: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var common = __nccwpck_require__(53687); var fs = __nccwpck_require__(57147); common.register('sort', _sort, { canReceivePipe: true, cmdOptions: { 'r': 'reverse', 'n': 'numerical', }, }); // parse out the number prefix of a line function parseNumber(str) { var match = str.match(/^\s*(\d*)\s*(.*)$/); return { num: Number(match[1]), value: match[2] }; } // compare two strings case-insensitively, but examine case for strings that are // case-insensitive equivalent function unixCmp(a, b) { var aLower = a.toLowerCase(); var bLower = b.toLowerCase(); return (aLower === bLower ? -1 * a.localeCompare(b) : // unix sort treats case opposite how javascript does aLower.localeCompare(bLower)); } // compare two strings in the fashion that unix sort's -n option works function numericalCmp(a, b) { var objA = parseNumber(a); var objB = parseNumber(b); if (objA.hasOwnProperty('num') && objB.hasOwnProperty('num')) { return ((objA.num !== objB.num) ? (objA.num - objB.num) : unixCmp(objA.value, objB.value)); } else { return unixCmp(objA.value, objB.value); } } //@ //@ ### sort([options,] file [, file ...]) //@ ### sort([options,] file_array) //@ //@ Available options: //@ //@ + `-r`: Reverse the results //@ + `-n`: Compare according to numerical value //@ //@ Examples: //@ //@ ```javascript //@ sort('foo.txt', 'bar.txt'); //@ sort('-r', 'foo.txt'); //@ ``` //@ //@ Return the contents of the `file`s, sorted line-by-line. Sorting multiple //@ files mixes their content (just as unix `sort` does). function _sort(options, files) { // Check if this is coming from a pipe var pipe = common.readFromPipe(); if (!files && !pipe) common.error('no files given'); files = [].slice.call(arguments, 1); if (pipe) { files.unshift('-'); } var lines = files.reduce(function (accum, file) { if (file !== '-') { if (!fs.existsSync(file)) { common.error('no such file or directory: ' + file, { continue: true }); return accum; } else if (common.statFollowLinks(file).isDirectory()) { common.error('read failed: ' + file + ': Is a directory', { continue: true, }); return accum; } } var contents = file === '-' ? pipe : fs.readFileSync(file, 'utf8'); return accum.concat(contents.trimRight().split('\n')); }, []); var sorted = lines.sort(options.numerical ? numericalCmp : unixCmp); if (options.reverse) { sorted = sorted.reverse(); } return sorted.join('\n') + '\n'; } module.exports = _sort; /***/ }), /***/ 42284: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var common = __nccwpck_require__(53687); var fs = __nccwpck_require__(57147); common.register('tail', _tail, { canReceivePipe: true, cmdOptions: { 'n': 'numLines', }, }); //@ //@ ### tail([{'-n': \},] file [, file ...]) //@ ### tail([{'-n': \},] file_array) //@ //@ Available options: //@ //@ + `-n `: Show the last `` lines of `file`s //@ //@ Examples: //@ //@ ```javascript //@ var str = tail({'-n': 1}, 'file*.txt'); //@ var str = tail('file1', 'file2'); //@ var str = tail(['file1', 'file2']); // same as above //@ ``` //@ //@ Read the end of a `file`. function _tail(options, files) { var tail = []; var pipe = common.readFromPipe(); if (!files && !pipe) common.error('no paths given'); var idx = 1; if (options.numLines === true) { idx = 2; options.numLines = Number(arguments[1]); } else if (options.numLines === false) { options.numLines = 10; } options.numLines = -1 * Math.abs(options.numLines); files = [].slice.call(arguments, idx); if (pipe) { files.unshift('-'); } var shouldAppendNewline = false; files.forEach(function (file) { if (file !== '-') { if (!fs.existsSync(file)) { common.error('no such file or directory: ' + file, { continue: true }); return; } else if (common.statFollowLinks(file).isDirectory()) { common.error("error reading '" + file + "': Is a directory", { continue: true, }); return; } } var contents = file === '-' ? pipe : fs.readFileSync(file, 'utf8'); var lines = contents.split('\n'); if (lines[lines.length - 1] === '') { lines.pop(); shouldAppendNewline = true; } else { shouldAppendNewline = false; } tail = tail.concat(lines.slice(options.numLines)); }); if (shouldAppendNewline) { tail.push(''); // to add a trailing newline once we join } return tail.join('\n'); } module.exports = _tail; /***/ }), /***/ 76150: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var common = __nccwpck_require__(53687); var os = __nccwpck_require__(22037); var fs = __nccwpck_require__(57147); common.register('tempdir', _tempDir, { allowGlobbing: false, wrapOutput: false, }); // Returns false if 'dir' is not a writeable directory, 'dir' otherwise function writeableDir(dir) { if (!dir || !fs.existsSync(dir)) return false; if (!common.statFollowLinks(dir).isDirectory()) return false; var testFile = dir + '/' + common.randomFileName(); try { fs.writeFileSync(testFile, ' '); common.unlinkSync(testFile); return dir; } catch (e) { /* istanbul ignore next */ return false; } } // Variable to cache the tempdir value for successive lookups. var cachedTempDir; //@ //@ ### tempdir() //@ //@ Examples: //@ //@ ```javascript //@ var tmp = tempdir(); // "/tmp" for most *nix platforms //@ ``` //@ //@ Searches and returns string containing a writeable, platform-dependent temporary directory. //@ Follows Python's [tempfile algorithm](http://docs.python.org/library/tempfile.html#tempfile.tempdir). function _tempDir() { if (cachedTempDir) return cachedTempDir; cachedTempDir = writeableDir(os.tmpdir()) || writeableDir(process.env.TMPDIR) || writeableDir(process.env.TEMP) || writeableDir(process.env.TMP) || writeableDir(process.env.Wimp$ScrapDir) || // RiscOS writeableDir('C:\\TEMP') || // Windows writeableDir('C:\\TMP') || // Windows writeableDir('\\TEMP') || // Windows writeableDir('\\TMP') || // Windows writeableDir('/tmp') || writeableDir('/var/tmp') || writeableDir('/usr/tmp') || writeableDir('.'); // last resort return cachedTempDir; } // Indicates if the tempdir value is currently cached. This is exposed for tests // only. The return value should only be tested for truthiness. function isCached() { return cachedTempDir; } // Clears the cached tempDir value, if one is cached. This is exposed for tests // only. function clearCache() { cachedTempDir = undefined; } module.exports.tempDir = _tempDir; module.exports.isCached = isCached; module.exports.clearCache = clearCache; /***/ }), /***/ 79723: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var common = __nccwpck_require__(53687); var fs = __nccwpck_require__(57147); common.register('test', _test, { cmdOptions: { 'b': 'block', 'c': 'character', 'd': 'directory', 'e': 'exists', 'f': 'file', 'L': 'link', 'p': 'pipe', 'S': 'socket', }, wrapOutput: false, allowGlobbing: false, }); //@ //@ ### test(expression) //@ //@ Available expression primaries: //@ //@ + `'-b', 'path'`: true if path is a block device //@ + `'-c', 'path'`: true if path is a character device //@ + `'-d', 'path'`: true if path is a directory //@ + `'-e', 'path'`: true if path exists //@ + `'-f', 'path'`: true if path is a regular file //@ + `'-L', 'path'`: true if path is a symbolic link //@ + `'-p', 'path'`: true if path is a pipe (FIFO) //@ + `'-S', 'path'`: true if path is a socket //@ //@ Examples: //@ //@ ```javascript //@ if (test('-d', path)) { /* do something with dir */ }; //@ if (!test('-f', path)) continue; // skip if it's a regular file //@ ``` //@ //@ Evaluates `expression` using the available primaries and returns corresponding value. function _test(options, path) { if (!path) common.error('no path given'); var canInterpret = false; Object.keys(options).forEach(function (key) { if (options[key] === true) { canInterpret = true; } }); if (!canInterpret) common.error('could not interpret expression'); if (options.link) { try { return common.statNoFollowLinks(path).isSymbolicLink(); } catch (e) { return false; } } if (!fs.existsSync(path)) return false; if (options.exists) return true; var stats = common.statFollowLinks(path); if (options.block) return stats.isBlockDevice(); if (options.character) return stats.isCharacterDevice(); if (options.directory) return stats.isDirectory(); if (options.file) return stats.isFile(); /* istanbul ignore next */ if (options.pipe) return stats.isFIFO(); /* istanbul ignore next */ if (options.socket) return stats.isSocket(); /* istanbul ignore next */ return false; // fallback } // test module.exports = _test; /***/ }), /***/ 71961: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var common = __nccwpck_require__(53687); var fs = __nccwpck_require__(57147); var path = __nccwpck_require__(71017); common.register('to', _to, { pipeOnly: true, wrapOutput: false, }); //@ //@ ### ShellString.prototype.to(file) //@ //@ Examples: //@ //@ ```javascript //@ cat('input.txt').to('output.txt'); //@ ``` //@ //@ Analogous to the redirection operator `>` in Unix, but works with //@ `ShellStrings` (such as those returned by `cat`, `grep`, etc.). _Like Unix //@ redirections, `to()` will overwrite any existing file!_ function _to(options, file) { if (!file) common.error('wrong arguments'); if (!fs.existsSync(path.dirname(file))) { common.error('no such file or directory: ' + path.dirname(file)); } try { fs.writeFileSync(file, this.stdout || this.toString(), 'utf8'); return this; } catch (e) { /* istanbul ignore next */ common.error('could not write to file (code ' + e.code + '): ' + file, { continue: true }); } } module.exports = _to; /***/ }), /***/ 33736: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var common = __nccwpck_require__(53687); var fs = __nccwpck_require__(57147); var path = __nccwpck_require__(71017); common.register('toEnd', _toEnd, { pipeOnly: true, wrapOutput: false, }); //@ //@ ### ShellString.prototype.toEnd(file) //@ //@ Examples: //@ //@ ```javascript //@ cat('input.txt').toEnd('output.txt'); //@ ``` //@ //@ Analogous to the redirect-and-append operator `>>` in Unix, but works with //@ `ShellStrings` (such as those returned by `cat`, `grep`, etc.). function _toEnd(options, file) { if (!file) common.error('wrong arguments'); if (!fs.existsSync(path.dirname(file))) { common.error('no such file or directory: ' + path.dirname(file)); } try { fs.appendFileSync(file, this.stdout || this.toString(), 'utf8'); return this; } catch (e) { /* istanbul ignore next */ common.error('could not append to file (code ' + e.code + '): ' + file, { continue: true }); } } module.exports = _toEnd; /***/ }), /***/ 28358: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var common = __nccwpck_require__(53687); var fs = __nccwpck_require__(57147); common.register('touch', _touch, { cmdOptions: { 'a': 'atime_only', 'c': 'no_create', 'd': 'date', 'm': 'mtime_only', 'r': 'reference', }, }); //@ //@ ### touch([options,] file [, file ...]) //@ ### touch([options,] file_array) //@ //@ Available options: //@ //@ + `-a`: Change only the access time //@ + `-c`: Do not create any files //@ + `-m`: Change only the modification time //@ + `-d DATE`: Parse `DATE` and use it instead of current time //@ + `-r FILE`: Use `FILE`'s times instead of current time //@ //@ Examples: //@ //@ ```javascript //@ touch('source.js'); //@ touch('-c', '/path/to/some/dir/source.js'); //@ touch({ '-r': FILE }, '/path/to/some/dir/source.js'); //@ ``` //@ //@ Update the access and modification times of each `FILE` to the current time. //@ A `FILE` argument that does not exist is created empty, unless `-c` is supplied. //@ This is a partial implementation of [`touch(1)`](http://linux.die.net/man/1/touch). function _touch(opts, files) { if (!files) { common.error('no files given'); } else if (typeof files === 'string') { files = [].slice.call(arguments, 1); } else { common.error('file arg should be a string file path or an Array of string file paths'); } files.forEach(function (f) { touchFile(opts, f); }); return ''; } function touchFile(opts, file) { var stat = tryStatFile(file); if (stat && stat.isDirectory()) { // don't error just exit return; } // if the file doesn't already exist and the user has specified --no-create then // this script is finished if (!stat && opts.no_create) { return; } // open the file and then close it. this will create it if it doesn't exist but will // not truncate the file fs.closeSync(fs.openSync(file, 'a')); // // Set timestamps // // setup some defaults var now = new Date(); var mtime = opts.date || now; var atime = opts.date || now; // use reference file if (opts.reference) { var refStat = tryStatFile(opts.reference); if (!refStat) { common.error('failed to get attributess of ' + opts.reference); } mtime = refStat.mtime; atime = refStat.atime; } else if (opts.date) { mtime = opts.date; atime = opts.date; } if (opts.atime_only && opts.mtime_only) { // keep the new values of mtime and atime like GNU } else if (opts.atime_only) { mtime = stat.mtime; } else if (opts.mtime_only) { atime = stat.atime; } fs.utimesSync(file, atime, mtime); } module.exports = _touch; function tryStatFile(filePath) { try { return common.statFollowLinks(filePath); } catch (e) { return null; } } /***/ }), /***/ 77286: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var common = __nccwpck_require__(53687); var fs = __nccwpck_require__(57147); // add c spaces to the left of str function lpad(c, str) { var res = '' + str; if (res.length < c) { res = Array((c - res.length) + 1).join(' ') + res; } return res; } common.register('uniq', _uniq, { canReceivePipe: true, cmdOptions: { 'i': 'ignoreCase', 'c': 'count', 'd': 'duplicates', }, }); //@ //@ ### uniq([options,] [input, [output]]) //@ //@ Available options: //@ //@ + `-i`: Ignore case while comparing //@ + `-c`: Prefix lines by the number of occurrences //@ + `-d`: Only print duplicate lines, one for each group of identical lines //@ //@ Examples: //@ //@ ```javascript //@ uniq('foo.txt'); //@ uniq('-i', 'foo.txt'); //@ uniq('-cd', 'foo.txt', 'bar.txt'); //@ ``` //@ //@ Filter adjacent matching lines from `input`. function _uniq(options, input, output) { // Check if this is coming from a pipe var pipe = common.readFromPipe(); if (!pipe) { if (!input) common.error('no input given'); if (!fs.existsSync(input)) { common.error(input + ': No such file or directory'); } else if (common.statFollowLinks(input).isDirectory()) { common.error("error reading '" + input + "'"); } } if (output && fs.existsSync(output) && common.statFollowLinks(output).isDirectory()) { common.error(output + ': Is a directory'); } var lines = (input ? fs.readFileSync(input, 'utf8') : pipe). trimRight(). split('\n'); var compare = function (a, b) { return options.ignoreCase ? a.toLocaleLowerCase().localeCompare(b.toLocaleLowerCase()) : a.localeCompare(b); }; var uniqed = lines.reduceRight(function (res, e) { // Perform uniq -c on the input if (res.length === 0) { return [{ count: 1, ln: e }]; } else if (compare(res[0].ln, e) === 0) { return [{ count: res[0].count + 1, ln: e }].concat(res.slice(1)); } else { return [{ count: 1, ln: e }].concat(res); } }, []).filter(function (obj) { // Do we want only duplicated objects? return options.duplicates ? obj.count > 1 : true; }).map(function (obj) { // Are we tracking the counts of each line? return (options.count ? (lpad(7, obj.count) + ' ') : '') + obj.ln; }).join('\n') + '\n'; if (output) { (new common.ShellString(uniqed)).to(output); // if uniq writes to output, nothing is passed to the next command in the pipeline (if any) return ''; } else { return uniqed; } } module.exports = _uniq; /***/ }), /***/ 64766: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var common = __nccwpck_require__(53687); var fs = __nccwpck_require__(57147); var path = __nccwpck_require__(71017); common.register('which', _which, { allowGlobbing: false, cmdOptions: { 'a': 'all', }, }); // XP's system default value for `PATHEXT` system variable, just in case it's not // set on Windows. var XP_DEFAULT_PATHEXT = '.com;.exe;.bat;.cmd;.vbs;.vbe;.js;.jse;.wsf;.wsh'; // For earlier versions of NodeJS that doesn't have a list of constants (< v6) var FILE_EXECUTABLE_MODE = 1; function isWindowsPlatform() { return process.platform === 'win32'; } // Cross-platform method for splitting environment `PATH` variables function splitPath(p) { return p ? p.split(path.delimiter) : []; } // Tests are running all cases for this func but it stays uncovered by codecov due to unknown reason /* istanbul ignore next */ function isExecutable(pathName) { try { // TODO(node-support): replace with fs.constants.X_OK once remove support for node < v6 fs.accessSync(pathName, FILE_EXECUTABLE_MODE); } catch (err) { return false; } return true; } function checkPath(pathName) { return fs.existsSync(pathName) && !common.statFollowLinks(pathName).isDirectory() && (isWindowsPlatform() || isExecutable(pathName)); } //@ //@ ### which(command) //@ //@ Examples: //@ //@ ```javascript //@ var nodeExec = which('node'); //@ ``` //@ //@ Searches for `command` in the system's `PATH`. On Windows, this uses the //@ `PATHEXT` variable to append the extension if it's not already executable. //@ Returns string containing the absolute path to `command`. function _which(options, cmd) { if (!cmd) common.error('must specify command'); var isWindows = isWindowsPlatform(); var pathArray = splitPath(process.env.PATH); var queryMatches = []; // No relative/absolute paths provided? if (cmd.indexOf('/') === -1) { // Assume that there are no extensions to append to queries (this is the // case for unix) var pathExtArray = ['']; if (isWindows) { // In case the PATHEXT variable is somehow not set (e.g. // child_process.spawn with an empty environment), use the XP default. var pathExtEnv = process.env.PATHEXT || XP_DEFAULT_PATHEXT; pathExtArray = splitPath(pathExtEnv.toUpperCase()); } // Search for command in PATH for (var k = 0; k < pathArray.length; k++) { // already found it if (queryMatches.length > 0 && !options.all) break; var attempt = path.resolve(pathArray[k], cmd); if (isWindows) { attempt = attempt.toUpperCase(); } var match = attempt.match(/\.[^<>:"/\|?*.]+$/); if (match && pathExtArray.indexOf(match[0]) >= 0) { // this is Windows-only // The user typed a query with the file extension, like // `which('node.exe')` if (checkPath(attempt)) { queryMatches.push(attempt); break; } } else { // All-platforms // Cycle through the PATHEXT array, and check each extension // Note: the array is always [''] on Unix for (var i = 0; i < pathExtArray.length; i++) { var ext = pathExtArray[i]; var newAttempt = attempt + ext; if (checkPath(newAttempt)) { queryMatches.push(newAttempt); break; } } } } } else if (checkPath(cmd)) { // a valid absolute or relative path queryMatches.push(path.resolve(cmd)); } if (queryMatches.length > 0) { return options.all ? queryMatches : queryMatches[0]; } return options.all ? [] : null; } module.exports = _which; /***/ }), /***/ 24931: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // Note: since nyc uses this module to output coverage, any lines // that are in the direct sync flow of nyc's outputCoverage are // ignored, since we can never get coverage for them. // grab a reference to node's real process object right away var process = global.process const processOk = function (process) { return process && typeof process === 'object' && typeof process.removeListener === 'function' && typeof process.emit === 'function' && typeof process.reallyExit === 'function' && typeof process.listeners === 'function' && typeof process.kill === 'function' && typeof process.pid === 'number' && typeof process.on === 'function' } // some kind of non-node environment, just no-op /* istanbul ignore if */ if (!processOk(process)) { module.exports = function () { return function () {} } } else { var assert = __nccwpck_require__(39491) var signals = __nccwpck_require__(63710) var isWin = /^win/i.test(process.platform) var EE = __nccwpck_require__(82361) /* istanbul ignore if */ if (typeof EE !== 'function') { EE = EE.EventEmitter } var emitter if (process.__signal_exit_emitter__) { emitter = process.__signal_exit_emitter__ } else { emitter = process.__signal_exit_emitter__ = new EE() emitter.count = 0 emitter.emitted = {} } // Because this emitter is a global, we have to check to see if a // previous version of this library failed to enable infinite listeners. // I know what you're about to say. But literally everything about // signal-exit is a compromise with evil. Get used to it. if (!emitter.infinite) { emitter.setMaxListeners(Infinity) emitter.infinite = true } module.exports = function (cb, opts) { /* istanbul ignore if */ if (!processOk(global.process)) { return function () {} } assert.equal(typeof cb, 'function', 'a callback must be provided for exit handler') if (loaded === false) { load() } var ev = 'exit' if (opts && opts.alwaysLast) { ev = 'afterexit' } var remove = function () { emitter.removeListener(ev, cb) if (emitter.listeners('exit').length === 0 && emitter.listeners('afterexit').length === 0) { unload() } } emitter.on(ev, cb) return remove } var unload = function unload () { if (!loaded || !processOk(global.process)) { return } loaded = false signals.forEach(function (sig) { try { process.removeListener(sig, sigListeners[sig]) } catch (er) {} }) process.emit = originalProcessEmit process.reallyExit = originalProcessReallyExit emitter.count -= 1 } module.exports.unload = unload var emit = function emit (event, code, signal) { /* istanbul ignore if */ if (emitter.emitted[event]) { return } emitter.emitted[event] = true emitter.emit(event, code, signal) } // { : , ... } var sigListeners = {} signals.forEach(function (sig) { sigListeners[sig] = function listener () { /* istanbul ignore if */ if (!processOk(global.process)) { return } // If there are no other listeners, an exit is coming! // Simplest way: remove us and then re-send the signal. // We know that this will kill the process, so we can // safely emit now. var listeners = process.listeners(sig) if (listeners.length === emitter.count) { unload() emit('exit', null, sig) /* istanbul ignore next */ emit('afterexit', null, sig) /* istanbul ignore next */ if (isWin && sig === 'SIGHUP') { // "SIGHUP" throws an `ENOSYS` error on Windows, // so use a supported signal instead sig = 'SIGINT' } /* istanbul ignore next */ process.kill(process.pid, sig) } } }) module.exports.signals = function () { return signals } var loaded = false var load = function load () { if (loaded || !processOk(global.process)) { return } loaded = true // This is the number of onSignalExit's that are in play. // It's important so that we can count the correct number of // listeners on signals, and don't wait for the other one to // handle it instead of us. emitter.count += 1 signals = signals.filter(function (sig) { try { process.on(sig, sigListeners[sig]) return true } catch (er) { return false } }) process.emit = processEmit process.reallyExit = processReallyExit } module.exports.load = load var originalProcessReallyExit = process.reallyExit var processReallyExit = function processReallyExit (code) { /* istanbul ignore if */ if (!processOk(global.process)) { return } process.exitCode = code || /* istanbul ignore next */ 0 emit('exit', process.exitCode, null) /* istanbul ignore next */ emit('afterexit', process.exitCode, null) /* istanbul ignore next */ originalProcessReallyExit.call(process, process.exitCode) } var originalProcessEmit = process.emit var processEmit = function processEmit (ev, arg) { if (ev === 'exit' && processOk(global.process)) { /* istanbul ignore else */ if (arg !== undefined) { process.exitCode = arg } var ret = originalProcessEmit.apply(this, arguments) /* istanbul ignore next */ emit('exit', process.exitCode, null) /* istanbul ignore next */ emit('afterexit', process.exitCode, null) /* istanbul ignore next */ return ret } else { return originalProcessEmit.apply(this, arguments) } } } /***/ }), /***/ 63710: /***/ ((module) => { // This is not the set of all possible signals. // // It IS, however, the set of all signals that trigger // an exit on either Linux or BSD systems. Linux is a // superset of the signal names supported on BSD, and // the unknown signals just fail to register, so we can // catch that easily enough. // // Don't bother with SIGKILL. It's uncatchable, which // means that we can't fire any callbacks anyway. // // If a user does happen to register a handler on a non- // fatal signal like SIGWINCH or something, and then // exit, it'll end up firing `process.emit('exit')`, so // the handler will be fired anyway. // // SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised // artificially, inherently leave the process in a // state from which it is not safe to try and enter JS // listeners. module.exports = [ 'SIGABRT', 'SIGALRM', 'SIGHUP', 'SIGINT', 'SIGTERM' ] if (process.platform !== 'win32') { module.exports.push( 'SIGVTALRM', 'SIGXCPU', 'SIGXFSZ', 'SIGUSR2', 'SIGTRAP', 'SIGSYS', 'SIGQUIT', 'SIGIOT' // should detect profiler and enable/disable accordingly. // see #21 // 'SIGPROF' ) } if (process.platform === 'linux') { module.exports.push( 'SIGIO', 'SIGPOLL', 'SIGPWR', 'SIGSTKFLT', 'SIGUNUSED' ) } /***/ }), /***/ 66126: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // Copyright 2015 Joyent, Inc. var Buffer = (__nccwpck_require__(15118).Buffer); var algInfo = { 'dsa': { parts: ['p', 'q', 'g', 'y'], sizePart: 'p' }, 'rsa': { parts: ['e', 'n'], sizePart: 'n' }, 'ecdsa': { parts: ['curve', 'Q'], sizePart: 'Q' }, 'ed25519': { parts: ['A'], sizePart: 'A' } }; algInfo['curve25519'] = algInfo['ed25519']; var algPrivInfo = { 'dsa': { parts: ['p', 'q', 'g', 'y', 'x'] }, 'rsa': { parts: ['n', 'e', 'd', 'iqmp', 'p', 'q'] }, 'ecdsa': { parts: ['curve', 'Q', 'd'] }, 'ed25519': { parts: ['A', 'k'] } }; algPrivInfo['curve25519'] = algPrivInfo['ed25519']; var hashAlgs = { 'md5': true, 'sha1': true, 'sha256': true, 'sha384': true, 'sha512': true }; /* * Taken from * http://csrc.nist.gov/groups/ST/toolkit/documents/dss/NISTReCur.pdf */ var curves = { 'nistp256': { size: 256, pkcs8oid: '1.2.840.10045.3.1.7', p: Buffer.from(('00' + 'ffffffff 00000001 00000000 00000000' + '00000000 ffffffff ffffffff ffffffff'). replace(/ /g, ''), 'hex'), a: Buffer.from(('00' + 'FFFFFFFF 00000001 00000000 00000000' + '00000000 FFFFFFFF FFFFFFFF FFFFFFFC'). replace(/ /g, ''), 'hex'), b: Buffer.from(( '5ac635d8 aa3a93e7 b3ebbd55 769886bc' + '651d06b0 cc53b0f6 3bce3c3e 27d2604b'). replace(/ /g, ''), 'hex'), s: Buffer.from(('00' + 'c49d3608 86e70493 6a6678e1 139d26b7' + '819f7e90'). replace(/ /g, ''), 'hex'), n: Buffer.from(('00' + 'ffffffff 00000000 ffffffff ffffffff' + 'bce6faad a7179e84 f3b9cac2 fc632551'). replace(/ /g, ''), 'hex'), G: Buffer.from(('04' + '6b17d1f2 e12c4247 f8bce6e5 63a440f2' + '77037d81 2deb33a0 f4a13945 d898c296' + '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16' + '2bce3357 6b315ece cbb64068 37bf51f5'). replace(/ /g, ''), 'hex') }, 'nistp384': { size: 384, pkcs8oid: '1.3.132.0.34', p: Buffer.from(('00' + 'ffffffff ffffffff ffffffff ffffffff' + 'ffffffff ffffffff ffffffff fffffffe' + 'ffffffff 00000000 00000000 ffffffff'). replace(/ /g, ''), 'hex'), a: Buffer.from(('00' + 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF' + 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE' + 'FFFFFFFF 00000000 00000000 FFFFFFFC'). replace(/ /g, ''), 'hex'), b: Buffer.from(( 'b3312fa7 e23ee7e4 988e056b e3f82d19' + '181d9c6e fe814112 0314088f 5013875a' + 'c656398d 8a2ed19d 2a85c8ed d3ec2aef'). replace(/ /g, ''), 'hex'), s: Buffer.from(('00' + 'a335926a a319a27a 1d00896a 6773a482' + '7acdac73'). replace(/ /g, ''), 'hex'), n: Buffer.from(('00' + 'ffffffff ffffffff ffffffff ffffffff' + 'ffffffff ffffffff c7634d81 f4372ddf' + '581a0db2 48b0a77a ecec196a ccc52973'). replace(/ /g, ''), 'hex'), G: Buffer.from(('04' + 'aa87ca22 be8b0537 8eb1c71e f320ad74' + '6e1d3b62 8ba79b98 59f741e0 82542a38' + '5502f25d bf55296c 3a545e38 72760ab7' + '3617de4a 96262c6f 5d9e98bf 9292dc29' + 'f8f41dbd 289a147c e9da3113 b5f0b8c0' + '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f'). replace(/ /g, ''), 'hex') }, 'nistp521': { size: 521, pkcs8oid: '1.3.132.0.35', p: Buffer.from(( '01ffffff ffffffff ffffffff ffffffff' + 'ffffffff ffffffff ffffffff ffffffff' + 'ffffffff ffffffff ffffffff ffffffff' + 'ffffffff ffffffff ffffffff ffffffff' + 'ffff').replace(/ /g, ''), 'hex'), a: Buffer.from(('01FF' + 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF' + 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF' + 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF' + 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFC'). replace(/ /g, ''), 'hex'), b: Buffer.from(('51' + '953eb961 8e1c9a1f 929a21a0 b68540ee' + 'a2da725b 99b315f3 b8b48991 8ef109e1' + '56193951 ec7e937b 1652c0bd 3bb1bf07' + '3573df88 3d2c34f1 ef451fd4 6b503f00'). replace(/ /g, ''), 'hex'), s: Buffer.from(('00' + 'd09e8800 291cb853 96cc6717 393284aa' + 'a0da64ba').replace(/ /g, ''), 'hex'), n: Buffer.from(('01ff' + 'ffffffff ffffffff ffffffff ffffffff' + 'ffffffff ffffffff ffffffff fffffffa' + '51868783 bf2f966b 7fcc0148 f709a5d0' + '3bb5c9b8 899c47ae bb6fb71e 91386409'). replace(/ /g, ''), 'hex'), G: Buffer.from(('04' + '00c6 858e06b7 0404e9cd 9e3ecb66 2395b442' + '9c648139 053fb521 f828af60 6b4d3dba' + 'a14b5e77 efe75928 fe1dc127 a2ffa8de' + '3348b3c1 856a429b f97e7e31 c2e5bd66' + '0118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9' + '98f54449 579b4468 17afbd17 273e662c' + '97ee7299 5ef42640 c550b901 3fad0761' + '353c7086 a272c240 88be9476 9fd16650'). replace(/ /g, ''), 'hex') } }; module.exports = { info: algInfo, privInfo: algPrivInfo, hashAlgs: hashAlgs, curves: curves }; /***/ }), /***/ 7406: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // Copyright 2016 Joyent, Inc. module.exports = Certificate; var assert = __nccwpck_require__(66631); var Buffer = (__nccwpck_require__(15118).Buffer); var algs = __nccwpck_require__(66126); var crypto = __nccwpck_require__(6113); var Fingerprint = __nccwpck_require__(13079); var Signature = __nccwpck_require__(91394); var errs = __nccwpck_require__(27979); var util = __nccwpck_require__(73837); var utils = __nccwpck_require__(80575); var Key = __nccwpck_require__(36814); var PrivateKey = __nccwpck_require__(29602); var Identity = __nccwpck_require__(70508); var formats = {}; formats['openssh'] = __nccwpck_require__(94033); formats['x509'] = __nccwpck_require__(10267); formats['pem'] = __nccwpck_require__(30217); var CertificateParseError = errs.CertificateParseError; var InvalidAlgorithmError = errs.InvalidAlgorithmError; function Certificate(opts) { assert.object(opts, 'options'); assert.arrayOfObject(opts.subjects, 'options.subjects'); utils.assertCompatible(opts.subjects[0], Identity, [1, 0], 'options.subjects'); utils.assertCompatible(opts.subjectKey, Key, [1, 0], 'options.subjectKey'); utils.assertCompatible(opts.issuer, Identity, [1, 0], 'options.issuer'); if (opts.issuerKey !== undefined) { utils.assertCompatible(opts.issuerKey, Key, [1, 0], 'options.issuerKey'); } assert.object(opts.signatures, 'options.signatures'); assert.buffer(opts.serial, 'options.serial'); assert.date(opts.validFrom, 'options.validFrom'); assert.date(opts.validUntil, 'optons.validUntil'); assert.optionalArrayOfString(opts.purposes, 'options.purposes'); this._hashCache = {}; this.subjects = opts.subjects; this.issuer = opts.issuer; this.subjectKey = opts.subjectKey; this.issuerKey = opts.issuerKey; this.signatures = opts.signatures; this.serial = opts.serial; this.validFrom = opts.validFrom; this.validUntil = opts.validUntil; this.purposes = opts.purposes; } Certificate.formats = formats; Certificate.prototype.toBuffer = function (format, options) { if (format === undefined) format = 'x509'; assert.string(format, 'format'); assert.object(formats[format], 'formats[format]'); assert.optionalObject(options, 'options'); return (formats[format].write(this, options)); }; Certificate.prototype.toString = function (format, options) { if (format === undefined) format = 'pem'; return (this.toBuffer(format, options).toString()); }; Certificate.prototype.fingerprint = function (algo) { if (algo === undefined) algo = 'sha256'; assert.string(algo, 'algorithm'); var opts = { type: 'certificate', hash: this.hash(algo), algorithm: algo }; return (new Fingerprint(opts)); }; Certificate.prototype.hash = function (algo) { assert.string(algo, 'algorithm'); algo = algo.toLowerCase(); if (algs.hashAlgs[algo] === undefined) throw (new InvalidAlgorithmError(algo)); if (this._hashCache[algo]) return (this._hashCache[algo]); var hash = crypto.createHash(algo). update(this.toBuffer('x509')).digest(); this._hashCache[algo] = hash; return (hash); }; Certificate.prototype.isExpired = function (when) { if (when === undefined) when = new Date(); return (!((when.getTime() >= this.validFrom.getTime()) && (when.getTime() < this.validUntil.getTime()))); }; Certificate.prototype.isSignedBy = function (issuerCert) { utils.assertCompatible(issuerCert, Certificate, [1, 0], 'issuer'); if (!this.issuer.equals(issuerCert.subjects[0])) return (false); if (this.issuer.purposes && this.issuer.purposes.length > 0 && this.issuer.purposes.indexOf('ca') === -1) { return (false); } return (this.isSignedByKey(issuerCert.subjectKey)); }; Certificate.prototype.getExtension = function (keyOrOid) { assert.string(keyOrOid, 'keyOrOid'); var ext = this.getExtensions().filter(function (maybeExt) { if (maybeExt.format === 'x509') return (maybeExt.oid === keyOrOid); if (maybeExt.format === 'openssh') return (maybeExt.name === keyOrOid); return (false); })[0]; return (ext); }; Certificate.prototype.getExtensions = function () { var exts = []; var x509 = this.signatures.x509; if (x509 && x509.extras && x509.extras.exts) { x509.extras.exts.forEach(function (ext) { ext.format = 'x509'; exts.push(ext); }); } var openssh = this.signatures.openssh; if (openssh && openssh.exts) { openssh.exts.forEach(function (ext) { ext.format = 'openssh'; exts.push(ext); }); } return (exts); }; Certificate.prototype.isSignedByKey = function (issuerKey) { utils.assertCompatible(issuerKey, Key, [1, 2], 'issuerKey'); if (this.issuerKey !== undefined) { return (this.issuerKey. fingerprint('sha512').matches(issuerKey)); } var fmt = Object.keys(this.signatures)[0]; var valid = formats[fmt].verify(this, issuerKey); if (valid) this.issuerKey = issuerKey; return (valid); }; Certificate.prototype.signWith = function (key) { utils.assertCompatible(key, PrivateKey, [1, 2], 'key'); var fmts = Object.keys(formats); var didOne = false; for (var i = 0; i < fmts.length; ++i) { if (fmts[i] !== 'pem') { var ret = formats[fmts[i]].sign(this, key); if (ret === true) didOne = true; } } if (!didOne) { throw (new Error('Failed to sign the certificate for any ' + 'available certificate formats')); } }; Certificate.createSelfSigned = function (subjectOrSubjects, key, options) { var subjects; if (Array.isArray(subjectOrSubjects)) subjects = subjectOrSubjects; else subjects = [subjectOrSubjects]; assert.arrayOfObject(subjects); subjects.forEach(function (subject) { utils.assertCompatible(subject, Identity, [1, 0], 'subject'); }); utils.assertCompatible(key, PrivateKey, [1, 2], 'private key'); assert.optionalObject(options, 'options'); if (options === undefined) options = {}; assert.optionalObject(options.validFrom, 'options.validFrom'); assert.optionalObject(options.validUntil, 'options.validUntil'); var validFrom = options.validFrom; var validUntil = options.validUntil; if (validFrom === undefined) validFrom = new Date(); if (validUntil === undefined) { assert.optionalNumber(options.lifetime, 'options.lifetime'); var lifetime = options.lifetime; if (lifetime === undefined) lifetime = 10*365*24*3600; validUntil = new Date(); validUntil.setTime(validUntil.getTime() + lifetime*1000); } assert.optionalBuffer(options.serial, 'options.serial'); var serial = options.serial; if (serial === undefined) serial = Buffer.from('0000000000000001', 'hex'); var purposes = options.purposes; if (purposes === undefined) purposes = []; if (purposes.indexOf('signature') === -1) purposes.push('signature'); /* Self-signed certs are always CAs. */ if (purposes.indexOf('ca') === -1) purposes.push('ca'); if (purposes.indexOf('crl') === -1) purposes.push('crl'); /* * If we weren't explicitly given any other purposes, do the sensible * thing and add some basic ones depending on the subject type. */ if (purposes.length <= 3) { var hostSubjects = subjects.filter(function (subject) { return (subject.type === 'host'); }); var userSubjects = subjects.filter(function (subject) { return (subject.type === 'user'); }); if (hostSubjects.length > 0) { if (purposes.indexOf('serverAuth') === -1) purposes.push('serverAuth'); } if (userSubjects.length > 0) { if (purposes.indexOf('clientAuth') === -1) purposes.push('clientAuth'); } if (userSubjects.length > 0 || hostSubjects.length > 0) { if (purposes.indexOf('keyAgreement') === -1) purposes.push('keyAgreement'); if (key.type === 'rsa' && purposes.indexOf('encryption') === -1) purposes.push('encryption'); } } var cert = new Certificate({ subjects: subjects, issuer: subjects[0], subjectKey: key.toPublic(), issuerKey: key.toPublic(), signatures: {}, serial: serial, validFrom: validFrom, validUntil: validUntil, purposes: purposes }); cert.signWith(key); return (cert); }; Certificate.create = function (subjectOrSubjects, key, issuer, issuerKey, options) { var subjects; if (Array.isArray(subjectOrSubjects)) subjects = subjectOrSubjects; else subjects = [subjectOrSubjects]; assert.arrayOfObject(subjects); subjects.forEach(function (subject) { utils.assertCompatible(subject, Identity, [1, 0], 'subject'); }); utils.assertCompatible(key, Key, [1, 0], 'key'); if (PrivateKey.isPrivateKey(key)) key = key.toPublic(); utils.assertCompatible(issuer, Identity, [1, 0], 'issuer'); utils.assertCompatible(issuerKey, PrivateKey, [1, 2], 'issuer key'); assert.optionalObject(options, 'options'); if (options === undefined) options = {}; assert.optionalObject(options.validFrom, 'options.validFrom'); assert.optionalObject(options.validUntil, 'options.validUntil'); var validFrom = options.validFrom; var validUntil = options.validUntil; if (validFrom === undefined) validFrom = new Date(); if (validUntil === undefined) { assert.optionalNumber(options.lifetime, 'options.lifetime'); var lifetime = options.lifetime; if (lifetime === undefined) lifetime = 10*365*24*3600; validUntil = new Date(); validUntil.setTime(validUntil.getTime() + lifetime*1000); } assert.optionalBuffer(options.serial, 'options.serial'); var serial = options.serial; if (serial === undefined) serial = Buffer.from('0000000000000001', 'hex'); var purposes = options.purposes; if (purposes === undefined) purposes = []; if (purposes.indexOf('signature') === -1) purposes.push('signature'); if (options.ca === true) { if (purposes.indexOf('ca') === -1) purposes.push('ca'); if (purposes.indexOf('crl') === -1) purposes.push('crl'); } var hostSubjects = subjects.filter(function (subject) { return (subject.type === 'host'); }); var userSubjects = subjects.filter(function (subject) { return (subject.type === 'user'); }); if (hostSubjects.length > 0) { if (purposes.indexOf('serverAuth') === -1) purposes.push('serverAuth'); } if (userSubjects.length > 0) { if (purposes.indexOf('clientAuth') === -1) purposes.push('clientAuth'); } if (userSubjects.length > 0 || hostSubjects.length > 0) { if (purposes.indexOf('keyAgreement') === -1) purposes.push('keyAgreement'); if (key.type === 'rsa' && purposes.indexOf('encryption') === -1) purposes.push('encryption'); } var cert = new Certificate({ subjects: subjects, issuer: issuer, subjectKey: key, issuerKey: issuerKey.toPublic(), signatures: {}, serial: serial, validFrom: validFrom, validUntil: validUntil, purposes: purposes }); cert.signWith(issuerKey); return (cert); }; Certificate.parse = function (data, format, options) { if (typeof (data) !== 'string') assert.buffer(data, 'data'); if (format === undefined) format = 'auto'; assert.string(format, 'format'); if (typeof (options) === 'string') options = { filename: options }; assert.optionalObject(options, 'options'); if (options === undefined) options = {}; assert.optionalString(options.filename, 'options.filename'); if (options.filename === undefined) options.filename = '(unnamed)'; assert.object(formats[format], 'formats[format]'); try { var k = formats[format].read(data, options); return (k); } catch (e) { throw (new CertificateParseError(options.filename, format, e)); } }; Certificate.isCertificate = function (obj, ver) { return (utils.isCompatible(obj, Certificate, ver)); }; /* * API versions for Certificate: * [1,0] -- initial ver * [1,1] -- openssh format now unpacks extensions */ Certificate.prototype._sshpkApiVersion = [1, 1]; Certificate._oldVersionDetect = function (obj) { return ([1, 0]); }; /***/ }), /***/ 57602: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // Copyright 2017 Joyent, Inc. module.exports = { DiffieHellman: DiffieHellman, generateECDSA: generateECDSA, generateED25519: generateED25519 }; var assert = __nccwpck_require__(66631); var crypto = __nccwpck_require__(6113); var Buffer = (__nccwpck_require__(15118).Buffer); var algs = __nccwpck_require__(66126); var utils = __nccwpck_require__(80575); var nacl = __nccwpck_require__(68729); var Key = __nccwpck_require__(36814); var PrivateKey = __nccwpck_require__(29602); var CRYPTO_HAVE_ECDH = (crypto.createECDH !== undefined); var ecdh = __nccwpck_require__(49865); var ec = __nccwpck_require__(3943); var jsbn = (__nccwpck_require__(85587).BigInteger); function DiffieHellman(key) { utils.assertCompatible(key, Key, [1, 4], 'key'); this._isPriv = PrivateKey.isPrivateKey(key, [1, 3]); this._algo = key.type; this._curve = key.curve; this._key = key; if (key.type === 'dsa') { if (!CRYPTO_HAVE_ECDH) { throw (new Error('Due to bugs in the node 0.10 ' + 'crypto API, node 0.12.x or later is required ' + 'to use DH')); } this._dh = crypto.createDiffieHellman( key.part.p.data, undefined, key.part.g.data, undefined); this._p = key.part.p; this._g = key.part.g; if (this._isPriv) this._dh.setPrivateKey(key.part.x.data); this._dh.setPublicKey(key.part.y.data); } else if (key.type === 'ecdsa') { if (!CRYPTO_HAVE_ECDH) { this._ecParams = new X9ECParameters(this._curve); if (this._isPriv) { this._priv = new ECPrivate( this._ecParams, key.part.d.data); } return; } var curve = { 'nistp256': 'prime256v1', 'nistp384': 'secp384r1', 'nistp521': 'secp521r1' }[key.curve]; this._dh = crypto.createECDH(curve); if (typeof (this._dh) !== 'object' || typeof (this._dh.setPrivateKey) !== 'function') { CRYPTO_HAVE_ECDH = false; DiffieHellman.call(this, key); return; } if (this._isPriv) this._dh.setPrivateKey(key.part.d.data); this._dh.setPublicKey(key.part.Q.data); } else if (key.type === 'curve25519') { if (this._isPriv) { utils.assertCompatible(key, PrivateKey, [1, 5], 'key'); this._priv = key.part.k.data; } } else { throw (new Error('DH not supported for ' + key.type + ' keys')); } } DiffieHellman.prototype.getPublicKey = function () { if (this._isPriv) return (this._key.toPublic()); return (this._key); }; DiffieHellman.prototype.getPrivateKey = function () { if (this._isPriv) return (this._key); else return (undefined); }; DiffieHellman.prototype.getKey = DiffieHellman.prototype.getPrivateKey; DiffieHellman.prototype._keyCheck = function (pk, isPub) { assert.object(pk, 'key'); if (!isPub) utils.assertCompatible(pk, PrivateKey, [1, 3], 'key'); utils.assertCompatible(pk, Key, [1, 4], 'key'); if (pk.type !== this._algo) { throw (new Error('A ' + pk.type + ' key cannot be used in ' + this._algo + ' Diffie-Hellman')); } if (pk.curve !== this._curve) { throw (new Error('A key from the ' + pk.curve + ' curve ' + 'cannot be used with a ' + this._curve + ' Diffie-Hellman')); } if (pk.type === 'dsa') { assert.deepEqual(pk.part.p, this._p, 'DSA key prime does not match'); assert.deepEqual(pk.part.g, this._g, 'DSA key generator does not match'); } }; DiffieHellman.prototype.setKey = function (pk) { this._keyCheck(pk); if (pk.type === 'dsa') { this._dh.setPrivateKey(pk.part.x.data); this._dh.setPublicKey(pk.part.y.data); } else if (pk.type === 'ecdsa') { if (CRYPTO_HAVE_ECDH) { this._dh.setPrivateKey(pk.part.d.data); this._dh.setPublicKey(pk.part.Q.data); } else { this._priv = new ECPrivate( this._ecParams, pk.part.d.data); } } else if (pk.type === 'curve25519') { var k = pk.part.k; if (!pk.part.k) k = pk.part.r; this._priv = k.data; if (this._priv[0] === 0x00) this._priv = this._priv.slice(1); this._priv = this._priv.slice(0, 32); } this._key = pk; this._isPriv = true; }; DiffieHellman.prototype.setPrivateKey = DiffieHellman.prototype.setKey; DiffieHellman.prototype.computeSecret = function (otherpk) { this._keyCheck(otherpk, true); if (!this._isPriv) throw (new Error('DH exchange has not been initialized with ' + 'a private key yet')); var pub; if (this._algo === 'dsa') { return (this._dh.computeSecret( otherpk.part.y.data)); } else if (this._algo === 'ecdsa') { if (CRYPTO_HAVE_ECDH) { return (this._dh.computeSecret( otherpk.part.Q.data)); } else { pub = new ECPublic( this._ecParams, otherpk.part.Q.data); return (this._priv.deriveSharedSecret(pub)); } } else if (this._algo === 'curve25519') { pub = otherpk.part.A.data; while (pub[0] === 0x00 && pub.length > 32) pub = pub.slice(1); var priv = this._priv; assert.strictEqual(pub.length, 32); assert.strictEqual(priv.length, 32); var secret = nacl.box.before(new Uint8Array(pub), new Uint8Array(priv)); return (Buffer.from(secret)); } throw (new Error('Invalid algorithm: ' + this._algo)); }; DiffieHellman.prototype.generateKey = function () { var parts = []; var priv, pub; if (this._algo === 'dsa') { this._dh.generateKeys(); parts.push({name: 'p', data: this._p.data}); parts.push({name: 'q', data: this._key.part.q.data}); parts.push({name: 'g', data: this._g.data}); parts.push({name: 'y', data: this._dh.getPublicKey()}); parts.push({name: 'x', data: this._dh.getPrivateKey()}); this._key = new PrivateKey({ type: 'dsa', parts: parts }); this._isPriv = true; return (this._key); } else if (this._algo === 'ecdsa') { if (CRYPTO_HAVE_ECDH) { this._dh.generateKeys(); parts.push({name: 'curve', data: Buffer.from(this._curve)}); parts.push({name: 'Q', data: this._dh.getPublicKey()}); parts.push({name: 'd', data: this._dh.getPrivateKey()}); this._key = new PrivateKey({ type: 'ecdsa', curve: this._curve, parts: parts }); this._isPriv = true; return (this._key); } else { var n = this._ecParams.getN(); var r = new jsbn(crypto.randomBytes(n.bitLength())); var n1 = n.subtract(jsbn.ONE); priv = r.mod(n1).add(jsbn.ONE); pub = this._ecParams.getG().multiply(priv); priv = Buffer.from(priv.toByteArray()); pub = Buffer.from(this._ecParams.getCurve(). encodePointHex(pub), 'hex'); this._priv = new ECPrivate(this._ecParams, priv); parts.push({name: 'curve', data: Buffer.from(this._curve)}); parts.push({name: 'Q', data: pub}); parts.push({name: 'd', data: priv}); this._key = new PrivateKey({ type: 'ecdsa', curve: this._curve, parts: parts }); this._isPriv = true; return (this._key); } } else if (this._algo === 'curve25519') { var pair = nacl.box.keyPair(); priv = Buffer.from(pair.secretKey); pub = Buffer.from(pair.publicKey); priv = Buffer.concat([priv, pub]); assert.strictEqual(priv.length, 64); assert.strictEqual(pub.length, 32); parts.push({name: 'A', data: pub}); parts.push({name: 'k', data: priv}); this._key = new PrivateKey({ type: 'curve25519', parts: parts }); this._isPriv = true; return (this._key); } throw (new Error('Invalid algorithm: ' + this._algo)); }; DiffieHellman.prototype.generateKeys = DiffieHellman.prototype.generateKey; /* These are helpers for using ecc-jsbn (for node 0.10 compatibility). */ function X9ECParameters(name) { var params = algs.curves[name]; assert.object(params); var p = new jsbn(params.p); var a = new jsbn(params.a); var b = new jsbn(params.b); var n = new jsbn(params.n); var h = jsbn.ONE; var curve = new ec.ECCurveFp(p, a, b); var G = curve.decodePointHex(params.G.toString('hex')); this.curve = curve; this.g = G; this.n = n; this.h = h; } X9ECParameters.prototype.getCurve = function () { return (this.curve); }; X9ECParameters.prototype.getG = function () { return (this.g); }; X9ECParameters.prototype.getN = function () { return (this.n); }; X9ECParameters.prototype.getH = function () { return (this.h); }; function ECPublic(params, buffer) { this._params = params; if (buffer[0] === 0x00) buffer = buffer.slice(1); this._pub = params.getCurve().decodePointHex(buffer.toString('hex')); } function ECPrivate(params, buffer) { this._params = params; this._priv = new jsbn(utils.mpNormalize(buffer)); } ECPrivate.prototype.deriveSharedSecret = function (pubKey) { assert.ok(pubKey instanceof ECPublic); var S = pubKey._pub.multiply(this._priv); return (Buffer.from(S.getX().toBigInteger().toByteArray())); }; function generateED25519() { var pair = nacl.sign.keyPair(); var priv = Buffer.from(pair.secretKey); var pub = Buffer.from(pair.publicKey); assert.strictEqual(priv.length, 64); assert.strictEqual(pub.length, 32); var parts = []; parts.push({name: 'A', data: pub}); parts.push({name: 'k', data: priv.slice(0, 32)}); var key = new PrivateKey({ type: 'ed25519', parts: parts }); return (key); } /* Generates a new ECDSA private key on a given curve. */ function generateECDSA(curve) { var parts = []; var key; if (CRYPTO_HAVE_ECDH) { /* * Node crypto doesn't expose key generation directly, but the * ECDH instances can generate keys. It turns out this just * calls into the OpenSSL generic key generator, and we can * read its output happily without doing an actual DH. So we * use that here. */ var osCurve = { 'nistp256': 'prime256v1', 'nistp384': 'secp384r1', 'nistp521': 'secp521r1' }[curve]; var dh = crypto.createECDH(osCurve); dh.generateKeys(); parts.push({name: 'curve', data: Buffer.from(curve)}); parts.push({name: 'Q', data: dh.getPublicKey()}); parts.push({name: 'd', data: dh.getPrivateKey()}); key = new PrivateKey({ type: 'ecdsa', curve: curve, parts: parts }); return (key); } else { var ecParams = new X9ECParameters(curve); /* This algorithm taken from FIPS PUB 186-4 (section B.4.1) */ var n = ecParams.getN(); /* * The crypto.randomBytes() function can only give us whole * bytes, so taking a nod from X9.62, we round up. */ var cByteLen = Math.ceil((n.bitLength() + 64) / 8); var c = new jsbn(crypto.randomBytes(cByteLen)); var n1 = n.subtract(jsbn.ONE); var priv = c.mod(n1).add(jsbn.ONE); var pub = ecParams.getG().multiply(priv); priv = Buffer.from(priv.toByteArray()); pub = Buffer.from(ecParams.getCurve(). encodePointHex(pub), 'hex'); parts.push({name: 'curve', data: Buffer.from(curve)}); parts.push({name: 'Q', data: pub}); parts.push({name: 'd', data: priv}); key = new PrivateKey({ type: 'ecdsa', curve: curve, parts: parts }); return (key); } } /***/ }), /***/ 14694: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // Copyright 2015 Joyent, Inc. module.exports = { Verifier: Verifier, Signer: Signer }; var nacl = __nccwpck_require__(68729); var stream = __nccwpck_require__(12781); var util = __nccwpck_require__(73837); var assert = __nccwpck_require__(66631); var Buffer = (__nccwpck_require__(15118).Buffer); var Signature = __nccwpck_require__(91394); function Verifier(key, hashAlgo) { if (hashAlgo.toLowerCase() !== 'sha512') throw (new Error('ED25519 only supports the use of ' + 'SHA-512 hashes')); this.key = key; this.chunks = []; stream.Writable.call(this, {}); } util.inherits(Verifier, stream.Writable); Verifier.prototype._write = function (chunk, enc, cb) { this.chunks.push(chunk); cb(); }; Verifier.prototype.update = function (chunk) { if (typeof (chunk) === 'string') chunk = Buffer.from(chunk, 'binary'); this.chunks.push(chunk); }; Verifier.prototype.verify = function (signature, fmt) { var sig; if (Signature.isSignature(signature, [2, 0])) { if (signature.type !== 'ed25519') return (false); sig = signature.toBuffer('raw'); } else if (typeof (signature) === 'string') { sig = Buffer.from(signature, 'base64'); } else if (Signature.isSignature(signature, [1, 0])) { throw (new Error('signature was created by too old ' + 'a version of sshpk and cannot be verified')); } assert.buffer(sig); return (nacl.sign.detached.verify( new Uint8Array(Buffer.concat(this.chunks)), new Uint8Array(sig), new Uint8Array(this.key.part.A.data))); }; function Signer(key, hashAlgo) { if (hashAlgo.toLowerCase() !== 'sha512') throw (new Error('ED25519 only supports the use of ' + 'SHA-512 hashes')); this.key = key; this.chunks = []; stream.Writable.call(this, {}); } util.inherits(Signer, stream.Writable); Signer.prototype._write = function (chunk, enc, cb) { this.chunks.push(chunk); cb(); }; Signer.prototype.update = function (chunk) { if (typeof (chunk) === 'string') chunk = Buffer.from(chunk, 'binary'); this.chunks.push(chunk); }; Signer.prototype.sign = function () { var sig = nacl.sign.detached( new Uint8Array(Buffer.concat(this.chunks)), new Uint8Array(Buffer.concat([ this.key.part.k.data, this.key.part.A.data]))); var sigBuf = Buffer.from(sig); var sigObj = Signature.parse(sigBuf, 'ed25519', 'raw'); sigObj.hashAlgorithm = 'sha512'; return (sigObj); }; /***/ }), /***/ 27979: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // Copyright 2015 Joyent, Inc. var assert = __nccwpck_require__(66631); var util = __nccwpck_require__(73837); function FingerprintFormatError(fp, format) { if (Error.captureStackTrace) Error.captureStackTrace(this, FingerprintFormatError); this.name = 'FingerprintFormatError'; this.fingerprint = fp; this.format = format; this.message = 'Fingerprint format is not supported, or is invalid: '; if (fp !== undefined) this.message += ' fingerprint = ' + fp; if (format !== undefined) this.message += ' format = ' + format; } util.inherits(FingerprintFormatError, Error); function InvalidAlgorithmError(alg) { if (Error.captureStackTrace) Error.captureStackTrace(this, InvalidAlgorithmError); this.name = 'InvalidAlgorithmError'; this.algorithm = alg; this.message = 'Algorithm "' + alg + '" is not supported'; } util.inherits(InvalidAlgorithmError, Error); function KeyParseError(name, format, innerErr) { if (Error.captureStackTrace) Error.captureStackTrace(this, KeyParseError); this.name = 'KeyParseError'; this.format = format; this.keyName = name; this.innerErr = innerErr; this.message = 'Failed to parse ' + name + ' as a valid ' + format + ' format key: ' + innerErr.message; } util.inherits(KeyParseError, Error); function SignatureParseError(type, format, innerErr) { if (Error.captureStackTrace) Error.captureStackTrace(this, SignatureParseError); this.name = 'SignatureParseError'; this.type = type; this.format = format; this.innerErr = innerErr; this.message = 'Failed to parse the given data as a ' + type + ' signature in ' + format + ' format: ' + innerErr.message; } util.inherits(SignatureParseError, Error); function CertificateParseError(name, format, innerErr) { if (Error.captureStackTrace) Error.captureStackTrace(this, CertificateParseError); this.name = 'CertificateParseError'; this.format = format; this.certName = name; this.innerErr = innerErr; this.message = 'Failed to parse ' + name + ' as a valid ' + format + ' format certificate: ' + innerErr.message; } util.inherits(CertificateParseError, Error); function KeyEncryptedError(name, format) { if (Error.captureStackTrace) Error.captureStackTrace(this, KeyEncryptedError); this.name = 'KeyEncryptedError'; this.format = format; this.keyName = name; this.message = 'The ' + format + ' format key ' + name + ' is ' + 'encrypted (password-protected), and no passphrase was ' + 'provided in `options`'; } util.inherits(KeyEncryptedError, Error); module.exports = { FingerprintFormatError: FingerprintFormatError, InvalidAlgorithmError: InvalidAlgorithmError, KeyParseError: KeyParseError, SignatureParseError: SignatureParseError, KeyEncryptedError: KeyEncryptedError, CertificateParseError: CertificateParseError }; /***/ }), /***/ 13079: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // Copyright 2018 Joyent, Inc. module.exports = Fingerprint; var assert = __nccwpck_require__(66631); var Buffer = (__nccwpck_require__(15118).Buffer); var algs = __nccwpck_require__(66126); var crypto = __nccwpck_require__(6113); var errs = __nccwpck_require__(27979); var Key = __nccwpck_require__(36814); var PrivateKey = __nccwpck_require__(29602); var Certificate = __nccwpck_require__(7406); var utils = __nccwpck_require__(80575); var FingerprintFormatError = errs.FingerprintFormatError; var InvalidAlgorithmError = errs.InvalidAlgorithmError; function Fingerprint(opts) { assert.object(opts, 'options'); assert.string(opts.type, 'options.type'); assert.buffer(opts.hash, 'options.hash'); assert.string(opts.algorithm, 'options.algorithm'); this.algorithm = opts.algorithm.toLowerCase(); if (algs.hashAlgs[this.algorithm] !== true) throw (new InvalidAlgorithmError(this.algorithm)); this.hash = opts.hash; this.type = opts.type; this.hashType = opts.hashType; } Fingerprint.prototype.toString = function (format) { if (format === undefined) { if (this.algorithm === 'md5' || this.hashType === 'spki') format = 'hex'; else format = 'base64'; } assert.string(format); switch (format) { case 'hex': if (this.hashType === 'spki') return (this.hash.toString('hex')); return (addColons(this.hash.toString('hex'))); case 'base64': if (this.hashType === 'spki') return (this.hash.toString('base64')); return (sshBase64Format(this.algorithm, this.hash.toString('base64'))); default: throw (new FingerprintFormatError(undefined, format)); } }; Fingerprint.prototype.matches = function (other) { assert.object(other, 'key or certificate'); if (this.type === 'key' && this.hashType !== 'ssh') { utils.assertCompatible(other, Key, [1, 7], 'key with spki'); if (PrivateKey.isPrivateKey(other)) { utils.assertCompatible(other, PrivateKey, [1, 6], 'privatekey with spki support'); } } else if (this.type === 'key') { utils.assertCompatible(other, Key, [1, 0], 'key'); } else { utils.assertCompatible(other, Certificate, [1, 0], 'certificate'); } var theirHash = other.hash(this.algorithm, this.hashType); var theirHash2 = crypto.createHash(this.algorithm). update(theirHash).digest('base64'); if (this.hash2 === undefined) this.hash2 = crypto.createHash(this.algorithm). update(this.hash).digest('base64'); return (this.hash2 === theirHash2); }; /*JSSTYLED*/ var base64RE = /^[A-Za-z0-9+\/=]+$/; /*JSSTYLED*/ var hexRE = /^[a-fA-F0-9]+$/; Fingerprint.parse = function (fp, options) { assert.string(fp, 'fingerprint'); var alg, hash, enAlgs; if (Array.isArray(options)) { enAlgs = options; options = {}; } assert.optionalObject(options, 'options'); if (options === undefined) options = {}; if (options.enAlgs !== undefined) enAlgs = options.enAlgs; if (options.algorithms !== undefined) enAlgs = options.algorithms; assert.optionalArrayOfString(enAlgs, 'algorithms'); var hashType = 'ssh'; if (options.hashType !== undefined) hashType = options.hashType; assert.string(hashType, 'options.hashType'); var parts = fp.split(':'); if (parts.length == 2) { alg = parts[0].toLowerCase(); if (!base64RE.test(parts[1])) throw (new FingerprintFormatError(fp)); try { hash = Buffer.from(parts[1], 'base64'); } catch (e) { throw (new FingerprintFormatError(fp)); } } else if (parts.length > 2) { alg = 'md5'; if (parts[0].toLowerCase() === 'md5') parts = parts.slice(1); parts = parts.map(function (p) { while (p.length < 2) p = '0' + p; if (p.length > 2) throw (new FingerprintFormatError(fp)); return (p); }); parts = parts.join(''); if (!hexRE.test(parts) || parts.length % 2 !== 0) throw (new FingerprintFormatError(fp)); try { hash = Buffer.from(parts, 'hex'); } catch (e) { throw (new FingerprintFormatError(fp)); } } else { if (hexRE.test(fp)) { hash = Buffer.from(fp, 'hex'); } else if (base64RE.test(fp)) { hash = Buffer.from(fp, 'base64'); } else { throw (new FingerprintFormatError(fp)); } switch (hash.length) { case 32: alg = 'sha256'; break; case 16: alg = 'md5'; break; case 20: alg = 'sha1'; break; case 64: alg = 'sha512'; break; default: throw (new FingerprintFormatError(fp)); } /* Plain hex/base64: guess it's probably SPKI unless told. */ if (options.hashType === undefined) hashType = 'spki'; } if (alg === undefined) throw (new FingerprintFormatError(fp)); if (algs.hashAlgs[alg] === undefined) throw (new InvalidAlgorithmError(alg)); if (enAlgs !== undefined) { enAlgs = enAlgs.map(function (a) { return a.toLowerCase(); }); if (enAlgs.indexOf(alg) === -1) throw (new InvalidAlgorithmError(alg)); } return (new Fingerprint({ algorithm: alg, hash: hash, type: options.type || 'key', hashType: hashType })); }; function addColons(s) { /*JSSTYLED*/ return (s.replace(/(.{2})(?=.)/g, '$1:')); } function base64Strip(s) { /*JSSTYLED*/ return (s.replace(/=*$/, '')); } function sshBase64Format(alg, h) { return (alg.toUpperCase() + ':' + base64Strip(h)); } Fingerprint.isFingerprint = function (obj, ver) { return (utils.isCompatible(obj, Fingerprint, ver)); }; /* * API versions for Fingerprint: * [1,0] -- initial ver * [1,1] -- first tagged ver * [1,2] -- hashType and spki support */ Fingerprint.prototype._sshpkApiVersion = [1, 2]; Fingerprint._oldVersionDetect = function (obj) { assert.func(obj.toString); assert.func(obj.matches); return ([1, 0]); }; /***/ }), /***/ 8243: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // Copyright 2018 Joyent, Inc. module.exports = { read: read, write: write }; var assert = __nccwpck_require__(66631); var Buffer = (__nccwpck_require__(15118).Buffer); var utils = __nccwpck_require__(80575); var Key = __nccwpck_require__(36814); var PrivateKey = __nccwpck_require__(29602); var pem = __nccwpck_require__(14324); var ssh = __nccwpck_require__(68927); var rfc4253 = __nccwpck_require__(88688); var dnssec = __nccwpck_require__(63561); var putty = __nccwpck_require__(80974); var DNSSEC_PRIVKEY_HEADER_PREFIX = 'Private-key-format: v1'; function read(buf, options) { if (typeof (buf) === 'string') { if (buf.trim().match(/^[-]+[ ]*BEGIN/)) return (pem.read(buf, options)); if (buf.match(/^\s*ssh-[a-z]/)) return (ssh.read(buf, options)); if (buf.match(/^\s*ecdsa-/)) return (ssh.read(buf, options)); if (buf.match(/^putty-user-key-file-2:/i)) return (putty.read(buf, options)); if (findDNSSECHeader(buf)) return (dnssec.read(buf, options)); buf = Buffer.from(buf, 'binary'); } else { assert.buffer(buf); if (findPEMHeader(buf)) return (pem.read(buf, options)); if (findSSHHeader(buf)) return (ssh.read(buf, options)); if (findPuTTYHeader(buf)) return (putty.read(buf, options)); if (findDNSSECHeader(buf)) return (dnssec.read(buf, options)); } if (buf.readUInt32BE(0) < buf.length) return (rfc4253.read(buf, options)); throw (new Error('Failed to auto-detect format of key')); } function findPuTTYHeader(buf) { var offset = 0; while (offset < buf.length && (buf[offset] === 32 || buf[offset] === 10 || buf[offset] === 9)) ++offset; if (offset + 22 <= buf.length && buf.slice(offset, offset + 22).toString('ascii').toLowerCase() === 'putty-user-key-file-2:') return (true); return (false); } function findSSHHeader(buf) { var offset = 0; while (offset < buf.length && (buf[offset] === 32 || buf[offset] === 10 || buf[offset] === 9)) ++offset; if (offset + 4 <= buf.length && buf.slice(offset, offset + 4).toString('ascii') === 'ssh-') return (true); if (offset + 6 <= buf.length && buf.slice(offset, offset + 6).toString('ascii') === 'ecdsa-') return (true); return (false); } function findPEMHeader(buf) { var offset = 0; while (offset < buf.length && (buf[offset] === 32 || buf[offset] === 10)) ++offset; if (buf[offset] !== 45) return (false); while (offset < buf.length && (buf[offset] === 45)) ++offset; while (offset < buf.length && (buf[offset] === 32)) ++offset; if (offset + 5 > buf.length || buf.slice(offset, offset + 5).toString('ascii') !== 'BEGIN') return (false); return (true); } function findDNSSECHeader(buf) { // private case first if (buf.length <= DNSSEC_PRIVKEY_HEADER_PREFIX.length) return (false); var headerCheck = buf.slice(0, DNSSEC_PRIVKEY_HEADER_PREFIX.length); if (headerCheck.toString('ascii') === DNSSEC_PRIVKEY_HEADER_PREFIX) return (true); // public-key RFC3110 ? // 'domain.com. IN KEY ...' or 'domain.com. IN DNSKEY ...' // skip any comment-lines if (typeof (buf) !== 'string') { buf = buf.toString('ascii'); } var lines = buf.split('\n'); var line = 0; /* JSSTYLED */ while (lines[line].match(/^\;/)) line++; if (lines[line].toString('ascii').match(/\. IN KEY /)) return (true); if (lines[line].toString('ascii').match(/\. IN DNSKEY /)) return (true); return (false); } function write(key, options) { throw (new Error('"auto" format cannot be used for writing')); } /***/ }), /***/ 63561: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // Copyright 2017 Joyent, Inc. module.exports = { read: read, write: write }; var assert = __nccwpck_require__(66631); var Buffer = (__nccwpck_require__(15118).Buffer); var Key = __nccwpck_require__(36814); var PrivateKey = __nccwpck_require__(29602); var utils = __nccwpck_require__(80575); var SSHBuffer = __nccwpck_require__(25621); var Dhe = __nccwpck_require__(57602); var supportedAlgos = { 'rsa-sha1' : 5, 'rsa-sha256' : 8, 'rsa-sha512' : 10, 'ecdsa-p256-sha256' : 13, 'ecdsa-p384-sha384' : 14 /* * ed25519 is hypothetically supported with id 15 * but the common tools available don't appear to be * capable of generating/using ed25519 keys */ }; var supportedAlgosById = {}; Object.keys(supportedAlgos).forEach(function (k) { supportedAlgosById[supportedAlgos[k]] = k.toUpperCase(); }); function read(buf, options) { if (typeof (buf) !== 'string') { assert.buffer(buf, 'buf'); buf = buf.toString('ascii'); } var lines = buf.split('\n'); if (lines[0].match(/^Private-key-format\: v1/)) { var algElems = lines[1].split(' '); var algoNum = parseInt(algElems[1], 10); var algoName = algElems[2]; if (!supportedAlgosById[algoNum]) throw (new Error('Unsupported algorithm: ' + algoName)); return (readDNSSECPrivateKey(algoNum, lines.slice(2))); } // skip any comment-lines var line = 0; /* JSSTYLED */ while (lines[line].match(/^\;/)) line++; // we should now have *one single* line left with our KEY on it. if ((lines[line].match(/\. IN KEY /) || lines[line].match(/\. IN DNSKEY /)) && lines[line+1].length === 0) { return (readRFC3110(lines[line])); } throw (new Error('Cannot parse dnssec key')); } function readRFC3110(keyString) { var elems = keyString.split(' '); //unused var flags = parseInt(elems[3], 10); //unused var protocol = parseInt(elems[4], 10); var algorithm = parseInt(elems[5], 10); if (!supportedAlgosById[algorithm]) throw (new Error('Unsupported algorithm: ' + algorithm)); var base64key = elems.slice(6, elems.length).join(); var keyBuffer = Buffer.from(base64key, 'base64'); if (supportedAlgosById[algorithm].match(/^RSA-/)) { // join the rest of the body into a single base64-blob var publicExponentLen = keyBuffer.readUInt8(0); if (publicExponentLen != 3 && publicExponentLen != 1) throw (new Error('Cannot parse dnssec key: ' + 'unsupported exponent length')); var publicExponent = keyBuffer.slice(1, publicExponentLen+1); publicExponent = utils.mpNormalize(publicExponent); var modulus = keyBuffer.slice(1+publicExponentLen); modulus = utils.mpNormalize(modulus); // now, make the key var rsaKey = { type: 'rsa', parts: [] }; rsaKey.parts.push({ name: 'e', data: publicExponent}); rsaKey.parts.push({ name: 'n', data: modulus}); return (new Key(rsaKey)); } if (supportedAlgosById[algorithm] === 'ECDSA-P384-SHA384' || supportedAlgosById[algorithm] === 'ECDSA-P256-SHA256') { var curve = 'nistp384'; var size = 384; if (supportedAlgosById[algorithm].match(/^ECDSA-P256-SHA256/)) { curve = 'nistp256'; size = 256; } var ecdsaKey = { type: 'ecdsa', curve: curve, size: size, parts: [ {name: 'curve', data: Buffer.from(curve) }, {name: 'Q', data: utils.ecNormalize(keyBuffer) } ] }; return (new Key(ecdsaKey)); } throw (new Error('Unsupported algorithm: ' + supportedAlgosById[algorithm])); } function elementToBuf(e) { return (Buffer.from(e.split(' ')[1], 'base64')); } function readDNSSECRSAPrivateKey(elements) { var rsaParams = {}; elements.forEach(function (element) { if (element.split(' ')[0] === 'Modulus:') rsaParams['n'] = elementToBuf(element); else if (element.split(' ')[0] === 'PublicExponent:') rsaParams['e'] = elementToBuf(element); else if (element.split(' ')[0] === 'PrivateExponent:') rsaParams['d'] = elementToBuf(element); else if (element.split(' ')[0] === 'Prime1:') rsaParams['p'] = elementToBuf(element); else if (element.split(' ')[0] === 'Prime2:') rsaParams['q'] = elementToBuf(element); else if (element.split(' ')[0] === 'Exponent1:') rsaParams['dmodp'] = elementToBuf(element); else if (element.split(' ')[0] === 'Exponent2:') rsaParams['dmodq'] = elementToBuf(element); else if (element.split(' ')[0] === 'Coefficient:') rsaParams['iqmp'] = elementToBuf(element); }); // now, make the key var key = { type: 'rsa', parts: [ { name: 'e', data: utils.mpNormalize(rsaParams['e'])}, { name: 'n', data: utils.mpNormalize(rsaParams['n'])}, { name: 'd', data: utils.mpNormalize(rsaParams['d'])}, { name: 'p', data: utils.mpNormalize(rsaParams['p'])}, { name: 'q', data: utils.mpNormalize(rsaParams['q'])}, { name: 'dmodp', data: utils.mpNormalize(rsaParams['dmodp'])}, { name: 'dmodq', data: utils.mpNormalize(rsaParams['dmodq'])}, { name: 'iqmp', data: utils.mpNormalize(rsaParams['iqmp'])} ] }; return (new PrivateKey(key)); } function readDNSSECPrivateKey(alg, elements) { if (supportedAlgosById[alg].match(/^RSA-/)) { return (readDNSSECRSAPrivateKey(elements)); } if (supportedAlgosById[alg] === 'ECDSA-P384-SHA384' || supportedAlgosById[alg] === 'ECDSA-P256-SHA256') { var d = Buffer.from(elements[0].split(' ')[1], 'base64'); var curve = 'nistp384'; var size = 384; if (supportedAlgosById[alg] === 'ECDSA-P256-SHA256') { curve = 'nistp256'; size = 256; } // DNSSEC generates the public-key on the fly (go calculate it) var publicKey = utils.publicFromPrivateECDSA(curve, d); var Q = publicKey.part['Q'].data; var ecdsaKey = { type: 'ecdsa', curve: curve, size: size, parts: [ {name: 'curve', data: Buffer.from(curve) }, {name: 'd', data: d }, {name: 'Q', data: Q } ] }; return (new PrivateKey(ecdsaKey)); } throw (new Error('Unsupported algorithm: ' + supportedAlgosById[alg])); } function dnssecTimestamp(date) { var year = date.getFullYear() + ''; //stringify var month = (date.getMonth() + 1); var timestampStr = year + month + date.getUTCDate(); timestampStr += '' + date.getUTCHours() + date.getUTCMinutes(); timestampStr += date.getUTCSeconds(); return (timestampStr); } function rsaAlgFromOptions(opts) { if (!opts || !opts.hashAlgo || opts.hashAlgo === 'sha1') return ('5 (RSASHA1)'); else if (opts.hashAlgo === 'sha256') return ('8 (RSASHA256)'); else if (opts.hashAlgo === 'sha512') return ('10 (RSASHA512)'); else throw (new Error('Unknown or unsupported hash: ' + opts.hashAlgo)); } function writeRSA(key, options) { // if we're missing parts, add them. if (!key.part.dmodp || !key.part.dmodq) { utils.addRSAMissing(key); } var out = ''; out += 'Private-key-format: v1.3\n'; out += 'Algorithm: ' + rsaAlgFromOptions(options) + '\n'; var n = utils.mpDenormalize(key.part['n'].data); out += 'Modulus: ' + n.toString('base64') + '\n'; var e = utils.mpDenormalize(key.part['e'].data); out += 'PublicExponent: ' + e.toString('base64') + '\n'; var d = utils.mpDenormalize(key.part['d'].data); out += 'PrivateExponent: ' + d.toString('base64') + '\n'; var p = utils.mpDenormalize(key.part['p'].data); out += 'Prime1: ' + p.toString('base64') + '\n'; var q = utils.mpDenormalize(key.part['q'].data); out += 'Prime2: ' + q.toString('base64') + '\n'; var dmodp = utils.mpDenormalize(key.part['dmodp'].data); out += 'Exponent1: ' + dmodp.toString('base64') + '\n'; var dmodq = utils.mpDenormalize(key.part['dmodq'].data); out += 'Exponent2: ' + dmodq.toString('base64') + '\n'; var iqmp = utils.mpDenormalize(key.part['iqmp'].data); out += 'Coefficient: ' + iqmp.toString('base64') + '\n'; // Assume that we're valid as-of now var timestamp = new Date(); out += 'Created: ' + dnssecTimestamp(timestamp) + '\n'; out += 'Publish: ' + dnssecTimestamp(timestamp) + '\n'; out += 'Activate: ' + dnssecTimestamp(timestamp) + '\n'; return (Buffer.from(out, 'ascii')); } function writeECDSA(key, options) { var out = ''; out += 'Private-key-format: v1.3\n'; if (key.curve === 'nistp256') { out += 'Algorithm: 13 (ECDSAP256SHA256)\n'; } else if (key.curve === 'nistp384') { out += 'Algorithm: 14 (ECDSAP384SHA384)\n'; } else { throw (new Error('Unsupported curve')); } var base64Key = key.part['d'].data.toString('base64'); out += 'PrivateKey: ' + base64Key + '\n'; // Assume that we're valid as-of now var timestamp = new Date(); out += 'Created: ' + dnssecTimestamp(timestamp) + '\n'; out += 'Publish: ' + dnssecTimestamp(timestamp) + '\n'; out += 'Activate: ' + dnssecTimestamp(timestamp) + '\n'; return (Buffer.from(out, 'ascii')); } function write(key, options) { if (PrivateKey.isPrivateKey(key)) { if (key.type === 'rsa') { return (writeRSA(key, options)); } else if (key.type === 'ecdsa') { return (writeECDSA(key, options)); } else { throw (new Error('Unsupported algorithm: ' + key.type)); } } else if (Key.isKey(key)) { /* * RFC3110 requires a keyname, and a keytype, which we * don't really have a mechanism for specifying such * additional metadata. */ throw (new Error('Format "dnssec" only supports ' + 'writing private keys')); } else { throw (new Error('key is not a Key or PrivateKey')); } } /***/ }), /***/ 94033: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // Copyright 2017 Joyent, Inc. module.exports = { read: read, verify: verify, sign: sign, signAsync: signAsync, write: write, /* Internal private API */ fromBuffer: fromBuffer, toBuffer: toBuffer }; var assert = __nccwpck_require__(66631); var SSHBuffer = __nccwpck_require__(25621); var crypto = __nccwpck_require__(6113); var Buffer = (__nccwpck_require__(15118).Buffer); var algs = __nccwpck_require__(66126); var Key = __nccwpck_require__(36814); var PrivateKey = __nccwpck_require__(29602); var Identity = __nccwpck_require__(70508); var rfc4253 = __nccwpck_require__(88688); var Signature = __nccwpck_require__(91394); var utils = __nccwpck_require__(80575); var Certificate = __nccwpck_require__(7406); function verify(cert, key) { /* * We always give an issuerKey, so if our verify() is being called then * there was no signature. Return false. */ return (false); } var TYPES = { 'user': 1, 'host': 2 }; Object.keys(TYPES).forEach(function (k) { TYPES[TYPES[k]] = k; }); var ECDSA_ALGO = /^ecdsa-sha2-([^@-]+)-cert-v01@openssh.com$/; function read(buf, options) { if (Buffer.isBuffer(buf)) buf = buf.toString('ascii'); var parts = buf.trim().split(/[ \t\n]+/g); if (parts.length < 2 || parts.length > 3) throw (new Error('Not a valid SSH certificate line')); var algo = parts[0]; var data = parts[1]; data = Buffer.from(data, 'base64'); return (fromBuffer(data, algo)); } function fromBuffer(data, algo, partial) { var sshbuf = new SSHBuffer({ buffer: data }); var innerAlgo = sshbuf.readString(); if (algo !== undefined && innerAlgo !== algo) throw (new Error('SSH certificate algorithm mismatch')); if (algo === undefined) algo = innerAlgo; var cert = {}; cert.signatures = {}; cert.signatures.openssh = {}; cert.signatures.openssh.nonce = sshbuf.readBuffer(); var key = {}; var parts = (key.parts = []); key.type = getAlg(algo); var partCount = algs.info[key.type].parts.length; while (parts.length < partCount) parts.push(sshbuf.readPart()); assert.ok(parts.length >= 1, 'key must have at least one part'); var algInfo = algs.info[key.type]; if (key.type === 'ecdsa') { var res = ECDSA_ALGO.exec(algo); assert.ok(res !== null); assert.strictEqual(res[1], parts[0].data.toString()); } for (var i = 0; i < algInfo.parts.length; ++i) { parts[i].name = algInfo.parts[i]; if (parts[i].name !== 'curve' && algInfo.normalize !== false) { var p = parts[i]; p.data = utils.mpNormalize(p.data); } } cert.subjectKey = new Key(key); cert.serial = sshbuf.readInt64(); var type = TYPES[sshbuf.readInt()]; assert.string(type, 'valid cert type'); cert.signatures.openssh.keyId = sshbuf.readString(); var principals = []; var pbuf = sshbuf.readBuffer(); var psshbuf = new SSHBuffer({ buffer: pbuf }); while (!psshbuf.atEnd()) principals.push(psshbuf.readString()); if (principals.length === 0) principals = ['*']; cert.subjects = principals.map(function (pr) { if (type === 'user') return (Identity.forUser(pr)); else if (type === 'host') return (Identity.forHost(pr)); throw (new Error('Unknown identity type ' + type)); }); cert.validFrom = int64ToDate(sshbuf.readInt64()); cert.validUntil = int64ToDate(sshbuf.readInt64()); var exts = []; var extbuf = new SSHBuffer({ buffer: sshbuf.readBuffer() }); var ext; while (!extbuf.atEnd()) { ext = { critical: true }; ext.name = extbuf.readString(); ext.data = extbuf.readBuffer(); exts.push(ext); } extbuf = new SSHBuffer({ buffer: sshbuf.readBuffer() }); while (!extbuf.atEnd()) { ext = { critical: false }; ext.name = extbuf.readString(); ext.data = extbuf.readBuffer(); exts.push(ext); } cert.signatures.openssh.exts = exts; /* reserved */ sshbuf.readBuffer(); var signingKeyBuf = sshbuf.readBuffer(); cert.issuerKey = rfc4253.read(signingKeyBuf); /* * OpenSSH certs don't give the identity of the issuer, just their * public key. So, we use an Identity that matches anything. The * isSignedBy() function will later tell you if the key matches. */ cert.issuer = Identity.forHost('**'); var sigBuf = sshbuf.readBuffer(); cert.signatures.openssh.signature = Signature.parse(sigBuf, cert.issuerKey.type, 'ssh'); if (partial !== undefined) { partial.remainder = sshbuf.remainder(); partial.consumed = sshbuf._offset; } return (new Certificate(cert)); } function int64ToDate(buf) { var i = buf.readUInt32BE(0) * 4294967296; i += buf.readUInt32BE(4); var d = new Date(); d.setTime(i * 1000); d.sourceInt64 = buf; return (d); } function dateToInt64(date) { if (date.sourceInt64 !== undefined) return (date.sourceInt64); var i = Math.round(date.getTime() / 1000); var upper = Math.floor(i / 4294967296); var lower = Math.floor(i % 4294967296); var buf = Buffer.alloc(8); buf.writeUInt32BE(upper, 0); buf.writeUInt32BE(lower, 4); return (buf); } function sign(cert, key) { if (cert.signatures.openssh === undefined) cert.signatures.openssh = {}; try { var blob = toBuffer(cert, true); } catch (e) { delete (cert.signatures.openssh); return (false); } var sig = cert.signatures.openssh; var hashAlgo = undefined; if (key.type === 'rsa' || key.type === 'dsa') hashAlgo = 'sha1'; var signer = key.createSign(hashAlgo); signer.write(blob); sig.signature = signer.sign(); return (true); } function signAsync(cert, signer, done) { if (cert.signatures.openssh === undefined) cert.signatures.openssh = {}; try { var blob = toBuffer(cert, true); } catch (e) { delete (cert.signatures.openssh); done(e); return; } var sig = cert.signatures.openssh; signer(blob, function (err, signature) { if (err) { done(err); return; } try { /* * This will throw if the signature isn't of a * type/algo that can be used for SSH. */ signature.toBuffer('ssh'); } catch (e) { done(e); return; } sig.signature = signature; done(); }); } function write(cert, options) { if (options === undefined) options = {}; var blob = toBuffer(cert); var out = getCertType(cert.subjectKey) + ' ' + blob.toString('base64'); if (options.comment) out = out + ' ' + options.comment; return (out); } function toBuffer(cert, noSig) { assert.object(cert.signatures.openssh, 'signature for openssh format'); var sig = cert.signatures.openssh; if (sig.nonce === undefined) sig.nonce = crypto.randomBytes(16); var buf = new SSHBuffer({}); buf.writeString(getCertType(cert.subjectKey)); buf.writeBuffer(sig.nonce); var key = cert.subjectKey; var algInfo = algs.info[key.type]; algInfo.parts.forEach(function (part) { buf.writePart(key.part[part]); }); buf.writeInt64(cert.serial); var type = cert.subjects[0].type; assert.notStrictEqual(type, 'unknown'); cert.subjects.forEach(function (id) { assert.strictEqual(id.type, type); }); type = TYPES[type]; buf.writeInt(type); if (sig.keyId === undefined) { sig.keyId = cert.subjects[0].type + '_' + (cert.subjects[0].uid || cert.subjects[0].hostname); } buf.writeString(sig.keyId); var sub = new SSHBuffer({}); cert.subjects.forEach(function (id) { if (type === TYPES.host) sub.writeString(id.hostname); else if (type === TYPES.user) sub.writeString(id.uid); }); buf.writeBuffer(sub.toBuffer()); buf.writeInt64(dateToInt64(cert.validFrom)); buf.writeInt64(dateToInt64(cert.validUntil)); var exts = sig.exts; if (exts === undefined) exts = []; var extbuf = new SSHBuffer({}); exts.forEach(function (ext) { if (ext.critical !== true) return; extbuf.writeString(ext.name); extbuf.writeBuffer(ext.data); }); buf.writeBuffer(extbuf.toBuffer()); extbuf = new SSHBuffer({}); exts.forEach(function (ext) { if (ext.critical === true) return; extbuf.writeString(ext.name); extbuf.writeBuffer(ext.data); }); buf.writeBuffer(extbuf.toBuffer()); /* reserved */ buf.writeBuffer(Buffer.alloc(0)); sub = rfc4253.write(cert.issuerKey); buf.writeBuffer(sub); if (!noSig) buf.writeBuffer(sig.signature.toBuffer('ssh')); return (buf.toBuffer()); } function getAlg(certType) { if (certType === 'ssh-rsa-cert-v01@openssh.com') return ('rsa'); if (certType === 'ssh-dss-cert-v01@openssh.com') return ('dsa'); if (certType.match(ECDSA_ALGO)) return ('ecdsa'); if (certType === 'ssh-ed25519-cert-v01@openssh.com') return ('ed25519'); throw (new Error('Unsupported cert type ' + certType)); } function getCertType(key) { if (key.type === 'rsa') return ('ssh-rsa-cert-v01@openssh.com'); if (key.type === 'dsa') return ('ssh-dss-cert-v01@openssh.com'); if (key.type === 'ecdsa') return ('ecdsa-sha2-' + key.curve + '-cert-v01@openssh.com'); if (key.type === 'ed25519') return ('ssh-ed25519-cert-v01@openssh.com'); throw (new Error('Unsupported key type ' + key.type)); } /***/ }), /***/ 14324: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // Copyright 2018 Joyent, Inc. module.exports = { read: read, write: write }; var assert = __nccwpck_require__(66631); var asn1 = __nccwpck_require__(80970); var crypto = __nccwpck_require__(6113); var Buffer = (__nccwpck_require__(15118).Buffer); var algs = __nccwpck_require__(66126); var utils = __nccwpck_require__(80575); var Key = __nccwpck_require__(36814); var PrivateKey = __nccwpck_require__(29602); var pkcs1 = __nccwpck_require__(69367); var pkcs8 = __nccwpck_require__(4173); var sshpriv = __nccwpck_require__(3923); var rfc4253 = __nccwpck_require__(88688); var errors = __nccwpck_require__(27979); var OID_PBES2 = '1.2.840.113549.1.5.13'; var OID_PBKDF2 = '1.2.840.113549.1.5.12'; var OID_TO_CIPHER = { '1.2.840.113549.3.7': '3des-cbc', '2.16.840.1.101.3.4.1.2': 'aes128-cbc', '2.16.840.1.101.3.4.1.42': 'aes256-cbc' }; var CIPHER_TO_OID = {}; Object.keys(OID_TO_CIPHER).forEach(function (k) { CIPHER_TO_OID[OID_TO_CIPHER[k]] = k; }); var OID_TO_HASH = { '1.2.840.113549.2.7': 'sha1', '1.2.840.113549.2.9': 'sha256', '1.2.840.113549.2.11': 'sha512' }; var HASH_TO_OID = {}; Object.keys(OID_TO_HASH).forEach(function (k) { HASH_TO_OID[OID_TO_HASH[k]] = k; }); /* * For reading we support both PKCS#1 and PKCS#8. If we find a private key, * we just take the public component of it and use that. */ function read(buf, options, forceType) { var input = buf; if (typeof (buf) !== 'string') { assert.buffer(buf, 'buf'); buf = buf.toString('ascii'); } var lines = buf.trim().split(/[\r\n]+/g); var m; var si = -1; while (!m && si < lines.length) { m = lines[++si].match(/*JSSTYLED*/ /[-]+[ ]*BEGIN ([A-Z0-9][A-Za-z0-9]+ )?(PUBLIC|PRIVATE) KEY[ ]*[-]+/); } assert.ok(m, 'invalid PEM header'); var m2; var ei = lines.length; while (!m2 && ei > 0) { m2 = lines[--ei].match(/*JSSTYLED*/ /[-]+[ ]*END ([A-Z0-9][A-Za-z0-9]+ )?(PUBLIC|PRIVATE) KEY[ ]*[-]+/); } assert.ok(m2, 'invalid PEM footer'); /* Begin and end banners must match key type */ assert.equal(m[2], m2[2]); var type = m[2].toLowerCase(); var alg; if (m[1]) { /* They also must match algorithms, if given */ assert.equal(m[1], m2[1], 'PEM header and footer mismatch'); alg = m[1].trim(); } lines = lines.slice(si, ei + 1); var headers = {}; while (true) { lines = lines.slice(1); m = lines[0].match(/*JSSTYLED*/ /^([A-Za-z0-9-]+): (.+)$/); if (!m) break; headers[m[1].toLowerCase()] = m[2]; } /* Chop off the first and last lines */ lines = lines.slice(0, -1).join(''); buf = Buffer.from(lines, 'base64'); var cipher, key, iv; if (headers['proc-type']) { var parts = headers['proc-type'].split(','); if (parts[0] === '4' && parts[1] === 'ENCRYPTED') { if (typeof (options.passphrase) === 'string') { options.passphrase = Buffer.from( options.passphrase, 'utf-8'); } if (!Buffer.isBuffer(options.passphrase)) { throw (new errors.KeyEncryptedError( options.filename, 'PEM')); } else { parts = headers['dek-info'].split(','); assert.ok(parts.length === 2); cipher = parts[0].toLowerCase(); iv = Buffer.from(parts[1], 'hex'); key = utils.opensslKeyDeriv(cipher, iv, options.passphrase, 1).key; } } } if (alg && alg.toLowerCase() === 'encrypted') { var eder = new asn1.BerReader(buf); var pbesEnd; eder.readSequence(); eder.readSequence(); pbesEnd = eder.offset + eder.length; var method = eder.readOID(); if (method !== OID_PBES2) { throw (new Error('Unsupported PEM/PKCS8 encryption ' + 'scheme: ' + method)); } eder.readSequence(); /* PBES2-params */ eder.readSequence(); /* keyDerivationFunc */ var kdfEnd = eder.offset + eder.length; var kdfOid = eder.readOID(); if (kdfOid !== OID_PBKDF2) throw (new Error('Unsupported PBES2 KDF: ' + kdfOid)); eder.readSequence(); var salt = eder.readString(asn1.Ber.OctetString, true); var iterations = eder.readInt(); var hashAlg = 'sha1'; if (eder.offset < kdfEnd) { eder.readSequence(); var hashAlgOid = eder.readOID(); hashAlg = OID_TO_HASH[hashAlgOid]; if (hashAlg === undefined) { throw (new Error('Unsupported PBKDF2 hash: ' + hashAlgOid)); } } eder._offset = kdfEnd; eder.readSequence(); /* encryptionScheme */ var cipherOid = eder.readOID(); cipher = OID_TO_CIPHER[cipherOid]; if (cipher === undefined) { throw (new Error('Unsupported PBES2 cipher: ' + cipherOid)); } iv = eder.readString(asn1.Ber.OctetString, true); eder._offset = pbesEnd; buf = eder.readString(asn1.Ber.OctetString, true); if (typeof (options.passphrase) === 'string') { options.passphrase = Buffer.from( options.passphrase, 'utf-8'); } if (!Buffer.isBuffer(options.passphrase)) { throw (new errors.KeyEncryptedError( options.filename, 'PEM')); } var cinfo = utils.opensshCipherInfo(cipher); cipher = cinfo.opensslName; key = utils.pbkdf2(hashAlg, salt, iterations, cinfo.keySize, options.passphrase); alg = undefined; } if (cipher && key && iv) { var cipherStream = crypto.createDecipheriv(cipher, key, iv); var chunk, chunks = []; cipherStream.once('error', function (e) { if (e.toString().indexOf('bad decrypt') !== -1) { throw (new Error('Incorrect passphrase ' + 'supplied, could not decrypt key')); } throw (e); }); cipherStream.write(buf); cipherStream.end(); while ((chunk = cipherStream.read()) !== null) chunks.push(chunk); buf = Buffer.concat(chunks); } /* The new OpenSSH internal format abuses PEM headers */ if (alg && alg.toLowerCase() === 'openssh') return (sshpriv.readSSHPrivate(type, buf, options)); if (alg && alg.toLowerCase() === 'ssh2') return (rfc4253.readType(type, buf, options)); var der = new asn1.BerReader(buf); der.originalInput = input; /* * All of the PEM file types start with a sequence tag, so chop it * off here */ der.readSequence(); /* PKCS#1 type keys name an algorithm in the banner explicitly */ if (alg) { if (forceType) assert.strictEqual(forceType, 'pkcs1'); return (pkcs1.readPkcs1(alg, type, der)); } else { if (forceType) assert.strictEqual(forceType, 'pkcs8'); return (pkcs8.readPkcs8(alg, type, der)); } } function write(key, options, type) { assert.object(key); var alg = { 'ecdsa': 'EC', 'rsa': 'RSA', 'dsa': 'DSA', 'ed25519': 'EdDSA' }[key.type]; var header; var der = new asn1.BerWriter(); if (PrivateKey.isPrivateKey(key)) { if (type && type === 'pkcs8') { header = 'PRIVATE KEY'; pkcs8.writePkcs8(der, key); } else { if (type) assert.strictEqual(type, 'pkcs1'); header = alg + ' PRIVATE KEY'; pkcs1.writePkcs1(der, key); } } else if (Key.isKey(key)) { if (type && type === 'pkcs1') { header = alg + ' PUBLIC KEY'; pkcs1.writePkcs1(der, key); } else { if (type) assert.strictEqual(type, 'pkcs8'); header = 'PUBLIC KEY'; pkcs8.writePkcs8(der, key); } } else { throw (new Error('key is not a Key or PrivateKey')); } var tmp = der.buffer.toString('base64'); var len = tmp.length + (tmp.length / 64) + 18 + 16 + header.length*2 + 10; var buf = Buffer.alloc(len); var o = 0; o += buf.write('-----BEGIN ' + header + '-----\n', o); for (var i = 0; i < tmp.length; ) { var limit = i + 64; if (limit > tmp.length) limit = tmp.length; o += buf.write(tmp.slice(i, limit), o); buf[o++] = 10; i = limit; } o += buf.write('-----END ' + header + '-----\n', o); return (buf.slice(0, o)); } /***/ }), /***/ 69367: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // Copyright 2015 Joyent, Inc. module.exports = { read: read, readPkcs1: readPkcs1, write: write, writePkcs1: writePkcs1 }; var assert = __nccwpck_require__(66631); var asn1 = __nccwpck_require__(80970); var Buffer = (__nccwpck_require__(15118).Buffer); var algs = __nccwpck_require__(66126); var utils = __nccwpck_require__(80575); var Key = __nccwpck_require__(36814); var PrivateKey = __nccwpck_require__(29602); var pem = __nccwpck_require__(14324); var pkcs8 = __nccwpck_require__(4173); var readECDSACurve = pkcs8.readECDSACurve; function read(buf, options) { return (pem.read(buf, options, 'pkcs1')); } function write(key, options) { return (pem.write(key, options, 'pkcs1')); } /* Helper to read in a single mpint */ function readMPInt(der, nm) { assert.strictEqual(der.peek(), asn1.Ber.Integer, nm + ' is not an Integer'); return (utils.mpNormalize(der.readString(asn1.Ber.Integer, true))); } function readPkcs1(alg, type, der) { switch (alg) { case 'RSA': if (type === 'public') return (readPkcs1RSAPublic(der)); else if (type === 'private') return (readPkcs1RSAPrivate(der)); throw (new Error('Unknown key type: ' + type)); case 'DSA': if (type === 'public') return (readPkcs1DSAPublic(der)); else if (type === 'private') return (readPkcs1DSAPrivate(der)); throw (new Error('Unknown key type: ' + type)); case 'EC': case 'ECDSA': if (type === 'private') return (readPkcs1ECDSAPrivate(der)); else if (type === 'public') return (readPkcs1ECDSAPublic(der)); throw (new Error('Unknown key type: ' + type)); case 'EDDSA': case 'EdDSA': if (type === 'private') return (readPkcs1EdDSAPrivate(der)); throw (new Error(type + ' keys not supported with EdDSA')); default: throw (new Error('Unknown key algo: ' + alg)); } } function readPkcs1RSAPublic(der) { // modulus and exponent var n = readMPInt(der, 'modulus'); var e = readMPInt(der, 'exponent'); // now, make the key var key = { type: 'rsa', parts: [ { name: 'e', data: e }, { name: 'n', data: n } ] }; return (new Key(key)); } function readPkcs1RSAPrivate(der) { var version = readMPInt(der, 'version'); assert.strictEqual(version[0], 0); // modulus then public exponent var n = readMPInt(der, 'modulus'); var e = readMPInt(der, 'public exponent'); var d = readMPInt(der, 'private exponent'); var p = readMPInt(der, 'prime1'); var q = readMPInt(der, 'prime2'); var dmodp = readMPInt(der, 'exponent1'); var dmodq = readMPInt(der, 'exponent2'); var iqmp = readMPInt(der, 'iqmp'); // now, make the key var key = { type: 'rsa', parts: [ { name: 'n', data: n }, { name: 'e', data: e }, { name: 'd', data: d }, { name: 'iqmp', data: iqmp }, { name: 'p', data: p }, { name: 'q', data: q }, { name: 'dmodp', data: dmodp }, { name: 'dmodq', data: dmodq } ] }; return (new PrivateKey(key)); } function readPkcs1DSAPrivate(der) { var version = readMPInt(der, 'version'); assert.strictEqual(version.readUInt8(0), 0); var p = readMPInt(der, 'p'); var q = readMPInt(der, 'q'); var g = readMPInt(der, 'g'); var y = readMPInt(der, 'y'); var x = readMPInt(der, 'x'); // now, make the key var key = { type: 'dsa', parts: [ { name: 'p', data: p }, { name: 'q', data: q }, { name: 'g', data: g }, { name: 'y', data: y }, { name: 'x', data: x } ] }; return (new PrivateKey(key)); } function readPkcs1EdDSAPrivate(der) { var version = readMPInt(der, 'version'); assert.strictEqual(version.readUInt8(0), 1); // private key var k = der.readString(asn1.Ber.OctetString, true); der.readSequence(0xa0); var oid = der.readOID(); assert.strictEqual(oid, '1.3.101.112', 'the ed25519 curve identifier'); der.readSequence(0xa1); var A = utils.readBitString(der); var key = { type: 'ed25519', parts: [ { name: 'A', data: utils.zeroPadToLength(A, 32) }, { name: 'k', data: k } ] }; return (new PrivateKey(key)); } function readPkcs1DSAPublic(der) { var y = readMPInt(der, 'y'); var p = readMPInt(der, 'p'); var q = readMPInt(der, 'q'); var g = readMPInt(der, 'g'); var key = { type: 'dsa', parts: [ { name: 'y', data: y }, { name: 'p', data: p }, { name: 'q', data: q }, { name: 'g', data: g } ] }; return (new Key(key)); } function readPkcs1ECDSAPublic(der) { der.readSequence(); var oid = der.readOID(); assert.strictEqual(oid, '1.2.840.10045.2.1', 'must be ecPublicKey'); var curveOid = der.readOID(); var curve; var curves = Object.keys(algs.curves); for (var j = 0; j < curves.length; ++j) { var c = curves[j]; var cd = algs.curves[c]; if (cd.pkcs8oid === curveOid) { curve = c; break; } } assert.string(curve, 'a known ECDSA named curve'); var Q = der.readString(asn1.Ber.BitString, true); Q = utils.ecNormalize(Q); var key = { type: 'ecdsa', parts: [ { name: 'curve', data: Buffer.from(curve) }, { name: 'Q', data: Q } ] }; return (new Key(key)); } function readPkcs1ECDSAPrivate(der) { var version = readMPInt(der, 'version'); assert.strictEqual(version.readUInt8(0), 1); // private key var d = der.readString(asn1.Ber.OctetString, true); der.readSequence(0xa0); var curve = readECDSACurve(der); assert.string(curve, 'a known elliptic curve'); der.readSequence(0xa1); var Q = der.readString(asn1.Ber.BitString, true); Q = utils.ecNormalize(Q); var key = { type: 'ecdsa', parts: [ { name: 'curve', data: Buffer.from(curve) }, { name: 'Q', data: Q }, { name: 'd', data: d } ] }; return (new PrivateKey(key)); } function writePkcs1(der, key) { der.startSequence(); switch (key.type) { case 'rsa': if (PrivateKey.isPrivateKey(key)) writePkcs1RSAPrivate(der, key); else writePkcs1RSAPublic(der, key); break; case 'dsa': if (PrivateKey.isPrivateKey(key)) writePkcs1DSAPrivate(der, key); else writePkcs1DSAPublic(der, key); break; case 'ecdsa': if (PrivateKey.isPrivateKey(key)) writePkcs1ECDSAPrivate(der, key); else writePkcs1ECDSAPublic(der, key); break; case 'ed25519': if (PrivateKey.isPrivateKey(key)) writePkcs1EdDSAPrivate(der, key); else writePkcs1EdDSAPublic(der, key); break; default: throw (new Error('Unknown key algo: ' + key.type)); } der.endSequence(); } function writePkcs1RSAPublic(der, key) { der.writeBuffer(key.part.n.data, asn1.Ber.Integer); der.writeBuffer(key.part.e.data, asn1.Ber.Integer); } function writePkcs1RSAPrivate(der, key) { var ver = Buffer.from([0]); der.writeBuffer(ver, asn1.Ber.Integer); der.writeBuffer(key.part.n.data, asn1.Ber.Integer); der.writeBuffer(key.part.e.data, asn1.Ber.Integer); der.writeBuffer(key.part.d.data, asn1.Ber.Integer); der.writeBuffer(key.part.p.data, asn1.Ber.Integer); der.writeBuffer(key.part.q.data, asn1.Ber.Integer); if (!key.part.dmodp || !key.part.dmodq) utils.addRSAMissing(key); der.writeBuffer(key.part.dmodp.data, asn1.Ber.Integer); der.writeBuffer(key.part.dmodq.data, asn1.Ber.Integer); der.writeBuffer(key.part.iqmp.data, asn1.Ber.Integer); } function writePkcs1DSAPrivate(der, key) { var ver = Buffer.from([0]); der.writeBuffer(ver, asn1.Ber.Integer); der.writeBuffer(key.part.p.data, asn1.Ber.Integer); der.writeBuffer(key.part.q.data, asn1.Ber.Integer); der.writeBuffer(key.part.g.data, asn1.Ber.Integer); der.writeBuffer(key.part.y.data, asn1.Ber.Integer); der.writeBuffer(key.part.x.data, asn1.Ber.Integer); } function writePkcs1DSAPublic(der, key) { der.writeBuffer(key.part.y.data, asn1.Ber.Integer); der.writeBuffer(key.part.p.data, asn1.Ber.Integer); der.writeBuffer(key.part.q.data, asn1.Ber.Integer); der.writeBuffer(key.part.g.data, asn1.Ber.Integer); } function writePkcs1ECDSAPublic(der, key) { der.startSequence(); der.writeOID('1.2.840.10045.2.1'); /* ecPublicKey */ var curve = key.part.curve.data.toString(); var curveOid = algs.curves[curve].pkcs8oid; assert.string(curveOid, 'a known ECDSA named curve'); der.writeOID(curveOid); der.endSequence(); var Q = utils.ecNormalize(key.part.Q.data, true); der.writeBuffer(Q, asn1.Ber.BitString); } function writePkcs1ECDSAPrivate(der, key) { var ver = Buffer.from([1]); der.writeBuffer(ver, asn1.Ber.Integer); der.writeBuffer(key.part.d.data, asn1.Ber.OctetString); der.startSequence(0xa0); var curve = key.part.curve.data.toString(); var curveOid = algs.curves[curve].pkcs8oid; assert.string(curveOid, 'a known ECDSA named curve'); der.writeOID(curveOid); der.endSequence(); der.startSequence(0xa1); var Q = utils.ecNormalize(key.part.Q.data, true); der.writeBuffer(Q, asn1.Ber.BitString); der.endSequence(); } function writePkcs1EdDSAPrivate(der, key) { var ver = Buffer.from([1]); der.writeBuffer(ver, asn1.Ber.Integer); der.writeBuffer(key.part.k.data, asn1.Ber.OctetString); der.startSequence(0xa0); der.writeOID('1.3.101.112'); der.endSequence(); der.startSequence(0xa1); utils.writeBitString(der, key.part.A.data); der.endSequence(); } function writePkcs1EdDSAPublic(der, key) { throw (new Error('Public keys are not supported for EdDSA PKCS#1')); } /***/ }), /***/ 4173: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // Copyright 2018 Joyent, Inc. module.exports = { read: read, readPkcs8: readPkcs8, write: write, writePkcs8: writePkcs8, pkcs8ToBuffer: pkcs8ToBuffer, readECDSACurve: readECDSACurve, writeECDSACurve: writeECDSACurve }; var assert = __nccwpck_require__(66631); var asn1 = __nccwpck_require__(80970); var Buffer = (__nccwpck_require__(15118).Buffer); var algs = __nccwpck_require__(66126); var utils = __nccwpck_require__(80575); var Key = __nccwpck_require__(36814); var PrivateKey = __nccwpck_require__(29602); var pem = __nccwpck_require__(14324); function read(buf, options) { return (pem.read(buf, options, 'pkcs8')); } function write(key, options) { return (pem.write(key, options, 'pkcs8')); } /* Helper to read in a single mpint */ function readMPInt(der, nm) { assert.strictEqual(der.peek(), asn1.Ber.Integer, nm + ' is not an Integer'); return (utils.mpNormalize(der.readString(asn1.Ber.Integer, true))); } function readPkcs8(alg, type, der) { /* Private keys in pkcs#8 format have a weird extra int */ if (der.peek() === asn1.Ber.Integer) { assert.strictEqual(type, 'private', 'unexpected Integer at start of public key'); der.readString(asn1.Ber.Integer, true); } der.readSequence(); var next = der.offset + der.length; var oid = der.readOID(); switch (oid) { case '1.2.840.113549.1.1.1': der._offset = next; if (type === 'public') return (readPkcs8RSAPublic(der)); else return (readPkcs8RSAPrivate(der)); case '1.2.840.10040.4.1': if (type === 'public') return (readPkcs8DSAPublic(der)); else return (readPkcs8DSAPrivate(der)); case '1.2.840.10045.2.1': if (type === 'public') return (readPkcs8ECDSAPublic(der)); else return (readPkcs8ECDSAPrivate(der)); case '1.3.101.112': if (type === 'public') { return (readPkcs8EdDSAPublic(der)); } else { return (readPkcs8EdDSAPrivate(der)); } case '1.3.101.110': if (type === 'public') { return (readPkcs8X25519Public(der)); } else { return (readPkcs8X25519Private(der)); } default: throw (new Error('Unknown key type OID ' + oid)); } } function readPkcs8RSAPublic(der) { // bit string sequence der.readSequence(asn1.Ber.BitString); der.readByte(); der.readSequence(); // modulus var n = readMPInt(der, 'modulus'); var e = readMPInt(der, 'exponent'); // now, make the key var key = { type: 'rsa', source: der.originalInput, parts: [ { name: 'e', data: e }, { name: 'n', data: n } ] }; return (new Key(key)); } function readPkcs8RSAPrivate(der) { der.readSequence(asn1.Ber.OctetString); der.readSequence(); var ver = readMPInt(der, 'version'); assert.equal(ver[0], 0x0, 'unknown RSA private key version'); // modulus then public exponent var n = readMPInt(der, 'modulus'); var e = readMPInt(der, 'public exponent'); var d = readMPInt(der, 'private exponent'); var p = readMPInt(der, 'prime1'); var q = readMPInt(der, 'prime2'); var dmodp = readMPInt(der, 'exponent1'); var dmodq = readMPInt(der, 'exponent2'); var iqmp = readMPInt(der, 'iqmp'); // now, make the key var key = { type: 'rsa', parts: [ { name: 'n', data: n }, { name: 'e', data: e }, { name: 'd', data: d }, { name: 'iqmp', data: iqmp }, { name: 'p', data: p }, { name: 'q', data: q }, { name: 'dmodp', data: dmodp }, { name: 'dmodq', data: dmodq } ] }; return (new PrivateKey(key)); } function readPkcs8DSAPublic(der) { der.readSequence(); var p = readMPInt(der, 'p'); var q = readMPInt(der, 'q'); var g = readMPInt(der, 'g'); // bit string sequence der.readSequence(asn1.Ber.BitString); der.readByte(); var y = readMPInt(der, 'y'); // now, make the key var key = { type: 'dsa', parts: [ { name: 'p', data: p }, { name: 'q', data: q }, { name: 'g', data: g }, { name: 'y', data: y } ] }; return (new Key(key)); } function readPkcs8DSAPrivate(der) { der.readSequence(); var p = readMPInt(der, 'p'); var q = readMPInt(der, 'q'); var g = readMPInt(der, 'g'); der.readSequence(asn1.Ber.OctetString); var x = readMPInt(der, 'x'); /* The pkcs#8 format does not include the public key */ var y = utils.calculateDSAPublic(g, p, x); var key = { type: 'dsa', parts: [ { name: 'p', data: p }, { name: 'q', data: q }, { name: 'g', data: g }, { name: 'y', data: y }, { name: 'x', data: x } ] }; return (new PrivateKey(key)); } function readECDSACurve(der) { var curveName, curveNames; var j, c, cd; if (der.peek() === asn1.Ber.OID) { var oid = der.readOID(); curveNames = Object.keys(algs.curves); for (j = 0; j < curveNames.length; ++j) { c = curveNames[j]; cd = algs.curves[c]; if (cd.pkcs8oid === oid) { curveName = c; break; } } } else { // ECParameters sequence der.readSequence(); var version = der.readString(asn1.Ber.Integer, true); assert.strictEqual(version[0], 1, 'ECDSA key not version 1'); var curve = {}; // FieldID sequence der.readSequence(); var fieldTypeOid = der.readOID(); assert.strictEqual(fieldTypeOid, '1.2.840.10045.1.1', 'ECDSA key is not from a prime-field'); var p = curve.p = utils.mpNormalize( der.readString(asn1.Ber.Integer, true)); /* * p always starts with a 1 bit, so count the zeros to get its * real size. */ curve.size = p.length * 8 - utils.countZeros(p); // Curve sequence der.readSequence(); curve.a = utils.mpNormalize( der.readString(asn1.Ber.OctetString, true)); curve.b = utils.mpNormalize( der.readString(asn1.Ber.OctetString, true)); if (der.peek() === asn1.Ber.BitString) curve.s = der.readString(asn1.Ber.BitString, true); // Combined Gx and Gy curve.G = der.readString(asn1.Ber.OctetString, true); assert.strictEqual(curve.G[0], 0x4, 'uncompressed G is required'); curve.n = utils.mpNormalize( der.readString(asn1.Ber.Integer, true)); curve.h = utils.mpNormalize( der.readString(asn1.Ber.Integer, true)); assert.strictEqual(curve.h[0], 0x1, 'a cofactor=1 curve is ' + 'required'); curveNames = Object.keys(algs.curves); var ks = Object.keys(curve); for (j = 0; j < curveNames.length; ++j) { c = curveNames[j]; cd = algs.curves[c]; var equal = true; for (var i = 0; i < ks.length; ++i) { var k = ks[i]; if (cd[k] === undefined) continue; if (typeof (cd[k]) === 'object' && cd[k].equals !== undefined) { if (!cd[k].equals(curve[k])) { equal = false; break; } } else if (Buffer.isBuffer(cd[k])) { if (cd[k].toString('binary') !== curve[k].toString('binary')) { equal = false; break; } } else { if (cd[k] !== curve[k]) { equal = false; break; } } } if (equal) { curveName = c; break; } } } return (curveName); } function readPkcs8ECDSAPrivate(der) { var curveName = readECDSACurve(der); assert.string(curveName, 'a known elliptic curve'); der.readSequence(asn1.Ber.OctetString); der.readSequence(); var version = readMPInt(der, 'version'); assert.equal(version[0], 1, 'unknown version of ECDSA key'); var d = der.readString(asn1.Ber.OctetString, true); var Q; if (der.peek() == 0xa0) { der.readSequence(0xa0); der._offset += der.length; } if (der.peek() == 0xa1) { der.readSequence(0xa1); Q = der.readString(asn1.Ber.BitString, true); Q = utils.ecNormalize(Q); } if (Q === undefined) { var pub = utils.publicFromPrivateECDSA(curveName, d); Q = pub.part.Q.data; } var key = { type: 'ecdsa', parts: [ { name: 'curve', data: Buffer.from(curveName) }, { name: 'Q', data: Q }, { name: 'd', data: d } ] }; return (new PrivateKey(key)); } function readPkcs8ECDSAPublic(der) { var curveName = readECDSACurve(der); assert.string(curveName, 'a known elliptic curve'); var Q = der.readString(asn1.Ber.BitString, true); Q = utils.ecNormalize(Q); var key = { type: 'ecdsa', parts: [ { name: 'curve', data: Buffer.from(curveName) }, { name: 'Q', data: Q } ] }; return (new Key(key)); } function readPkcs8EdDSAPublic(der) { if (der.peek() === 0x00) der.readByte(); var A = utils.readBitString(der); var key = { type: 'ed25519', parts: [ { name: 'A', data: utils.zeroPadToLength(A, 32) } ] }; return (new Key(key)); } function readPkcs8X25519Public(der) { var A = utils.readBitString(der); var key = { type: 'curve25519', parts: [ { name: 'A', data: utils.zeroPadToLength(A, 32) } ] }; return (new Key(key)); } function readPkcs8EdDSAPrivate(der) { if (der.peek() === 0x00) der.readByte(); der.readSequence(asn1.Ber.OctetString); var k = der.readString(asn1.Ber.OctetString, true); k = utils.zeroPadToLength(k, 32); var A; if (der.peek() === asn1.Ber.BitString) { A = utils.readBitString(der); A = utils.zeroPadToLength(A, 32); } else { A = utils.calculateED25519Public(k); } var key = { type: 'ed25519', parts: [ { name: 'A', data: utils.zeroPadToLength(A, 32) }, { name: 'k', data: utils.zeroPadToLength(k, 32) } ] }; return (new PrivateKey(key)); } function readPkcs8X25519Private(der) { if (der.peek() === 0x00) der.readByte(); der.readSequence(asn1.Ber.OctetString); var k = der.readString(asn1.Ber.OctetString, true); k = utils.zeroPadToLength(k, 32); var A = utils.calculateX25519Public(k); var key = { type: 'curve25519', parts: [ { name: 'A', data: utils.zeroPadToLength(A, 32) }, { name: 'k', data: utils.zeroPadToLength(k, 32) } ] }; return (new PrivateKey(key)); } function pkcs8ToBuffer(key) { var der = new asn1.BerWriter(); writePkcs8(der, key); return (der.buffer); } function writePkcs8(der, key) { der.startSequence(); if (PrivateKey.isPrivateKey(key)) { var sillyInt = Buffer.from([0]); der.writeBuffer(sillyInt, asn1.Ber.Integer); } der.startSequence(); switch (key.type) { case 'rsa': der.writeOID('1.2.840.113549.1.1.1'); if (PrivateKey.isPrivateKey(key)) writePkcs8RSAPrivate(key, der); else writePkcs8RSAPublic(key, der); break; case 'dsa': der.writeOID('1.2.840.10040.4.1'); if (PrivateKey.isPrivateKey(key)) writePkcs8DSAPrivate(key, der); else writePkcs8DSAPublic(key, der); break; case 'ecdsa': der.writeOID('1.2.840.10045.2.1'); if (PrivateKey.isPrivateKey(key)) writePkcs8ECDSAPrivate(key, der); else writePkcs8ECDSAPublic(key, der); break; case 'ed25519': der.writeOID('1.3.101.112'); if (PrivateKey.isPrivateKey(key)) throw (new Error('Ed25519 private keys in pkcs8 ' + 'format are not supported')); writePkcs8EdDSAPublic(key, der); break; default: throw (new Error('Unsupported key type: ' + key.type)); } der.endSequence(); } function writePkcs8RSAPrivate(key, der) { der.writeNull(); der.endSequence(); der.startSequence(asn1.Ber.OctetString); der.startSequence(); var version = Buffer.from([0]); der.writeBuffer(version, asn1.Ber.Integer); der.writeBuffer(key.part.n.data, asn1.Ber.Integer); der.writeBuffer(key.part.e.data, asn1.Ber.Integer); der.writeBuffer(key.part.d.data, asn1.Ber.Integer); der.writeBuffer(key.part.p.data, asn1.Ber.Integer); der.writeBuffer(key.part.q.data, asn1.Ber.Integer); if (!key.part.dmodp || !key.part.dmodq) utils.addRSAMissing(key); der.writeBuffer(key.part.dmodp.data, asn1.Ber.Integer); der.writeBuffer(key.part.dmodq.data, asn1.Ber.Integer); der.writeBuffer(key.part.iqmp.data, asn1.Ber.Integer); der.endSequence(); der.endSequence(); } function writePkcs8RSAPublic(key, der) { der.writeNull(); der.endSequence(); der.startSequence(asn1.Ber.BitString); der.writeByte(0x00); der.startSequence(); der.writeBuffer(key.part.n.data, asn1.Ber.Integer); der.writeBuffer(key.part.e.data, asn1.Ber.Integer); der.endSequence(); der.endSequence(); } function writePkcs8DSAPrivate(key, der) { der.startSequence(); der.writeBuffer(key.part.p.data, asn1.Ber.Integer); der.writeBuffer(key.part.q.data, asn1.Ber.Integer); der.writeBuffer(key.part.g.data, asn1.Ber.Integer); der.endSequence(); der.endSequence(); der.startSequence(asn1.Ber.OctetString); der.writeBuffer(key.part.x.data, asn1.Ber.Integer); der.endSequence(); } function writePkcs8DSAPublic(key, der) { der.startSequence(); der.writeBuffer(key.part.p.data, asn1.Ber.Integer); der.writeBuffer(key.part.q.data, asn1.Ber.Integer); der.writeBuffer(key.part.g.data, asn1.Ber.Integer); der.endSequence(); der.endSequence(); der.startSequence(asn1.Ber.BitString); der.writeByte(0x00); der.writeBuffer(key.part.y.data, asn1.Ber.Integer); der.endSequence(); } function writeECDSACurve(key, der) { var curve = algs.curves[key.curve]; if (curve.pkcs8oid) { /* This one has a name in pkcs#8, so just write the oid */ der.writeOID(curve.pkcs8oid); } else { // ECParameters sequence der.startSequence(); var version = Buffer.from([1]); der.writeBuffer(version, asn1.Ber.Integer); // FieldID sequence der.startSequence(); der.writeOID('1.2.840.10045.1.1'); // prime-field der.writeBuffer(curve.p, asn1.Ber.Integer); der.endSequence(); // Curve sequence der.startSequence(); var a = curve.p; if (a[0] === 0x0) a = a.slice(1); der.writeBuffer(a, asn1.Ber.OctetString); der.writeBuffer(curve.b, asn1.Ber.OctetString); der.writeBuffer(curve.s, asn1.Ber.BitString); der.endSequence(); der.writeBuffer(curve.G, asn1.Ber.OctetString); der.writeBuffer(curve.n, asn1.Ber.Integer); var h = curve.h; if (!h) { h = Buffer.from([1]); } der.writeBuffer(h, asn1.Ber.Integer); // ECParameters der.endSequence(); } } function writePkcs8ECDSAPublic(key, der) { writeECDSACurve(key, der); der.endSequence(); var Q = utils.ecNormalize(key.part.Q.data, true); der.writeBuffer(Q, asn1.Ber.BitString); } function writePkcs8ECDSAPrivate(key, der) { writeECDSACurve(key, der); der.endSequence(); der.startSequence(asn1.Ber.OctetString); der.startSequence(); var version = Buffer.from([1]); der.writeBuffer(version, asn1.Ber.Integer); der.writeBuffer(key.part.d.data, asn1.Ber.OctetString); der.startSequence(0xa1); var Q = utils.ecNormalize(key.part.Q.data, true); der.writeBuffer(Q, asn1.Ber.BitString); der.endSequence(); der.endSequence(); der.endSequence(); } function writePkcs8EdDSAPublic(key, der) { der.endSequence(); utils.writeBitString(der, key.part.A.data); } function writePkcs8EdDSAPrivate(key, der) { der.endSequence(); var k = utils.mpNormalize(key.part.k.data, true); der.startSequence(asn1.Ber.OctetString); der.writeBuffer(k, asn1.Ber.OctetString); der.endSequence(); } /***/ }), /***/ 80974: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // Copyright 2018 Joyent, Inc. module.exports = { read: read, write: write }; var assert = __nccwpck_require__(66631); var Buffer = (__nccwpck_require__(15118).Buffer); var rfc4253 = __nccwpck_require__(88688); var Key = __nccwpck_require__(36814); var SSHBuffer = __nccwpck_require__(25621); var crypto = __nccwpck_require__(6113); var PrivateKey = __nccwpck_require__(29602); var errors = __nccwpck_require__(27979); // https://tartarus.org/~simon/putty-prerel-snapshots/htmldoc/AppendixC.html function read(buf, options) { var lines = buf.toString('ascii').split(/[\r\n]+/); var found = false; var parts; var si = 0; var formatVersion; while (si < lines.length) { parts = splitHeader(lines[si++]); if (parts) { formatVersion = { 'putty-user-key-file-2': 2, 'putty-user-key-file-3': 3 }[parts[0].toLowerCase()]; if (formatVersion) { found = true; break; } } } if (!found) { throw (new Error('No PuTTY format first line found')); } var alg = parts[1]; parts = splitHeader(lines[si++]); assert.equal(parts[0].toLowerCase(), 'encryption'); var encryption = parts[1]; parts = splitHeader(lines[si++]); assert.equal(parts[0].toLowerCase(), 'comment'); var comment = parts[1]; parts = splitHeader(lines[si++]); assert.equal(parts[0].toLowerCase(), 'public-lines'); var publicLines = parseInt(parts[1], 10); if (!isFinite(publicLines) || publicLines < 0 || publicLines > lines.length) { throw (new Error('Invalid public-lines count')); } var publicBuf = Buffer.from( lines.slice(si, si + publicLines).join(''), 'base64'); var keyType = rfc4253.algToKeyType(alg); var key = rfc4253.read(publicBuf); if (key.type !== keyType) { throw (new Error('Outer key algorithm mismatch')); } si += publicLines; if (lines[si]) { parts = splitHeader(lines[si++]); assert.equal(parts[0].toLowerCase(), 'private-lines'); var privateLines = parseInt(parts[1], 10); if (!isFinite(privateLines) || privateLines < 0 || privateLines > lines.length) { throw (new Error('Invalid private-lines count')); } var privateBuf = Buffer.from( lines.slice(si, si + privateLines).join(''), 'base64'); if (encryption !== 'none' && formatVersion === 3) { throw new Error('Encrypted keys arenot supported for' + ' PuTTY format version 3'); } if (encryption === 'aes256-cbc') { if (!options.passphrase) { throw (new errors.KeyEncryptedError( options.filename, 'PEM')); } var iv = Buffer.alloc(16, 0); var decipher = crypto.createDecipheriv( 'aes-256-cbc', derivePPK2EncryptionKey(options.passphrase), iv); decipher.setAutoPadding(false); privateBuf = Buffer.concat([ decipher.update(privateBuf), decipher.final()]); } key = new PrivateKey(key); if (key.type !== keyType) { throw (new Error('Outer key algorithm mismatch')); } var sshbuf = new SSHBuffer({buffer: privateBuf}); var privateKeyParts; if (alg === 'ssh-dss') { privateKeyParts = [ { name: 'x', data: sshbuf.readBuffer() }]; } else if (alg === 'ssh-rsa') { privateKeyParts = [ { name: 'd', data: sshbuf.readBuffer() }, { name: 'p', data: sshbuf.readBuffer() }, { name: 'q', data: sshbuf.readBuffer() }, { name: 'iqmp', data: sshbuf.readBuffer() } ]; } else if (alg.match(/^ecdsa-sha2-nistp/)) { privateKeyParts = [ { name: 'd', data: sshbuf.readBuffer() } ]; } else if (alg === 'ssh-ed25519') { privateKeyParts = [ { name: 'k', data: sshbuf.readBuffer() } ]; } else { throw new Error('Unsupported PPK key type: ' + alg); } key = new PrivateKey({ type: key.type, parts: key.parts.concat(privateKeyParts) }); } key.comment = comment; return (key); } function derivePPK2EncryptionKey(passphrase) { var hash1 = crypto.createHash('sha1').update(Buffer.concat([ Buffer.from([0, 0, 0, 0]), Buffer.from(passphrase) ])).digest(); var hash2 = crypto.createHash('sha1').update(Buffer.concat([ Buffer.from([0, 0, 0, 1]), Buffer.from(passphrase) ])).digest(); return (Buffer.concat([hash1, hash2]).slice(0, 32)); } function splitHeader(line) { var idx = line.indexOf(':'); if (idx === -1) return (null); var header = line.slice(0, idx); ++idx; while (line[idx] === ' ') ++idx; var rest = line.slice(idx); return ([header, rest]); } function write(key, options) { assert.object(key); if (!Key.isKey(key)) throw (new Error('Must be a public key')); var alg = rfc4253.keyTypeToAlg(key); var buf = rfc4253.write(key); var comment = key.comment || ''; var b64 = buf.toString('base64'); var lines = wrap(b64, 64); lines.unshift('Public-Lines: ' + lines.length); lines.unshift('Comment: ' + comment); lines.unshift('Encryption: none'); lines.unshift('PuTTY-User-Key-File-2: ' + alg); return (Buffer.from(lines.join('\n') + '\n')); } function wrap(txt, len) { var lines = []; var pos = 0; while (pos < txt.length) { lines.push(txt.slice(pos, pos + 64)); pos += 64; } return (lines); } /***/ }), /***/ 88688: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // Copyright 2015 Joyent, Inc. module.exports = { read: read.bind(undefined, false, undefined), readType: read.bind(undefined, false), write: write, /* semi-private api, used by sshpk-agent */ readPartial: read.bind(undefined, true), /* shared with ssh format */ readInternal: read, keyTypeToAlg: keyTypeToAlg, algToKeyType: algToKeyType }; var assert = __nccwpck_require__(66631); var Buffer = (__nccwpck_require__(15118).Buffer); var algs = __nccwpck_require__(66126); var utils = __nccwpck_require__(80575); var Key = __nccwpck_require__(36814); var PrivateKey = __nccwpck_require__(29602); var SSHBuffer = __nccwpck_require__(25621); function algToKeyType(alg) { assert.string(alg); if (alg === 'ssh-dss') return ('dsa'); else if (alg === 'ssh-rsa') return ('rsa'); else if (alg === 'ssh-ed25519') return ('ed25519'); else if (alg === 'ssh-curve25519') return ('curve25519'); else if (alg.match(/^ecdsa-sha2-/)) return ('ecdsa'); else throw (new Error('Unknown algorithm ' + alg)); } function keyTypeToAlg(key) { assert.object(key); if (key.type === 'dsa') return ('ssh-dss'); else if (key.type === 'rsa') return ('ssh-rsa'); else if (key.type === 'ed25519') return ('ssh-ed25519'); else if (key.type === 'curve25519') return ('ssh-curve25519'); else if (key.type === 'ecdsa') return ('ecdsa-sha2-' + key.part.curve.data.toString()); else throw (new Error('Unknown key type ' + key.type)); } function read(partial, type, buf, options) { if (typeof (buf) === 'string') buf = Buffer.from(buf); assert.buffer(buf, 'buf'); var key = {}; var parts = key.parts = []; var sshbuf = new SSHBuffer({buffer: buf}); var alg = sshbuf.readString(); assert.ok(!sshbuf.atEnd(), 'key must have at least one part'); key.type = algToKeyType(alg); var partCount = algs.info[key.type].parts.length; if (type && type === 'private') partCount = algs.privInfo[key.type].parts.length; while (!sshbuf.atEnd() && parts.length < partCount) parts.push(sshbuf.readPart()); while (!partial && !sshbuf.atEnd()) parts.push(sshbuf.readPart()); assert.ok(parts.length >= 1, 'key must have at least one part'); assert.ok(partial || sshbuf.atEnd(), 'leftover bytes at end of key'); var Constructor = Key; var algInfo = algs.info[key.type]; if (type === 'private' || algInfo.parts.length !== parts.length) { algInfo = algs.privInfo[key.type]; Constructor = PrivateKey; } assert.strictEqual(algInfo.parts.length, parts.length); if (key.type === 'ecdsa') { var res = /^ecdsa-sha2-(.+)$/.exec(alg); assert.ok(res !== null); assert.strictEqual(res[1], parts[0].data.toString()); } var normalized = true; for (var i = 0; i < algInfo.parts.length; ++i) { var p = parts[i]; p.name = algInfo.parts[i]; /* * OpenSSH stores ed25519 "private" keys as seed + public key * concat'd together (k followed by A). We want to keep them * separate for other formats that don't do this. */ if (key.type === 'ed25519' && p.name === 'k') p.data = p.data.slice(0, 32); if (p.name !== 'curve' && algInfo.normalize !== false) { var nd; if (key.type === 'ed25519') { nd = utils.zeroPadToLength(p.data, 32); } else { nd = utils.mpNormalize(p.data); } if (nd.toString('binary') !== p.data.toString('binary')) { p.data = nd; normalized = false; } } } if (normalized) key._rfc4253Cache = sshbuf.toBuffer(); if (partial && typeof (partial) === 'object') { partial.remainder = sshbuf.remainder(); partial.consumed = sshbuf._offset; } return (new Constructor(key)); } function write(key, options) { assert.object(key); var alg = keyTypeToAlg(key); var i; var algInfo = algs.info[key.type]; if (PrivateKey.isPrivateKey(key)) algInfo = algs.privInfo[key.type]; var parts = algInfo.parts; var buf = new SSHBuffer({}); buf.writeString(alg); for (i = 0; i < parts.length; ++i) { var data = key.part[parts[i]].data; if (algInfo.normalize !== false) { if (key.type === 'ed25519') data = utils.zeroPadToLength(data, 32); else data = utils.mpNormalize(data); } if (key.type === 'ed25519' && parts[i] === 'k') data = Buffer.concat([data, key.part.A.data]); buf.writeBuffer(data); } return (buf.toBuffer()); } /***/ }), /***/ 3923: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // Copyright 2015 Joyent, Inc. module.exports = { read: read, readSSHPrivate: readSSHPrivate, write: write }; var assert = __nccwpck_require__(66631); var asn1 = __nccwpck_require__(80970); var Buffer = (__nccwpck_require__(15118).Buffer); var algs = __nccwpck_require__(66126); var utils = __nccwpck_require__(80575); var crypto = __nccwpck_require__(6113); var Key = __nccwpck_require__(36814); var PrivateKey = __nccwpck_require__(29602); var pem = __nccwpck_require__(14324); var rfc4253 = __nccwpck_require__(88688); var SSHBuffer = __nccwpck_require__(25621); var errors = __nccwpck_require__(27979); var bcrypt; function read(buf, options) { return (pem.read(buf, options)); } var MAGIC = 'openssh-key-v1'; function readSSHPrivate(type, buf, options) { buf = new SSHBuffer({buffer: buf}); var magic = buf.readCString(); assert.strictEqual(magic, MAGIC, 'bad magic string'); var cipher = buf.readString(); var kdf = buf.readString(); var kdfOpts = buf.readBuffer(); var nkeys = buf.readInt(); if (nkeys !== 1) { throw (new Error('OpenSSH-format key file contains ' + 'multiple keys: this is unsupported.')); } var pubKey = buf.readBuffer(); if (type === 'public') { assert.ok(buf.atEnd(), 'excess bytes left after key'); return (rfc4253.read(pubKey)); } var privKeyBlob = buf.readBuffer(); assert.ok(buf.atEnd(), 'excess bytes left after key'); var kdfOptsBuf = new SSHBuffer({ buffer: kdfOpts }); switch (kdf) { case 'none': if (cipher !== 'none') { throw (new Error('OpenSSH-format key uses KDF "none" ' + 'but specifies a cipher other than "none"')); } break; case 'bcrypt': var salt = kdfOptsBuf.readBuffer(); var rounds = kdfOptsBuf.readInt(); var cinf = utils.opensshCipherInfo(cipher); if (bcrypt === undefined) { bcrypt = __nccwpck_require__(45447); } if (typeof (options.passphrase) === 'string') { options.passphrase = Buffer.from(options.passphrase, 'utf-8'); } if (!Buffer.isBuffer(options.passphrase)) { throw (new errors.KeyEncryptedError( options.filename, 'OpenSSH')); } var pass = new Uint8Array(options.passphrase); var salti = new Uint8Array(salt); /* Use the pbkdf to derive both the key and the IV. */ var out = new Uint8Array(cinf.keySize + cinf.blockSize); var res = bcrypt.pbkdf(pass, pass.length, salti, salti.length, out, out.length, rounds); if (res !== 0) { throw (new Error('bcrypt_pbkdf function returned ' + 'failure, parameters invalid')); } out = Buffer.from(out); var ckey = out.slice(0, cinf.keySize); var iv = out.slice(cinf.keySize, cinf.keySize + cinf.blockSize); var cipherStream = crypto.createDecipheriv(cinf.opensslName, ckey, iv); cipherStream.setAutoPadding(false); var chunk, chunks = []; cipherStream.once('error', function (e) { if (e.toString().indexOf('bad decrypt') !== -1) { throw (new Error('Incorrect passphrase ' + 'supplied, could not decrypt key')); } throw (e); }); cipherStream.write(privKeyBlob); cipherStream.end(); while ((chunk = cipherStream.read()) !== null) chunks.push(chunk); privKeyBlob = Buffer.concat(chunks); break; default: throw (new Error( 'OpenSSH-format key uses unknown KDF "' + kdf + '"')); } buf = new SSHBuffer({buffer: privKeyBlob}); var checkInt1 = buf.readInt(); var checkInt2 = buf.readInt(); if (checkInt1 !== checkInt2) { throw (new Error('Incorrect passphrase supplied, could not ' + 'decrypt key')); } var ret = {}; var key = rfc4253.readInternal(ret, 'private', buf.remainder()); buf.skip(ret.consumed); var comment = buf.readString(); key.comment = comment; return (key); } function write(key, options) { var pubKey; if (PrivateKey.isPrivateKey(key)) pubKey = key.toPublic(); else pubKey = key; var cipher = 'none'; var kdf = 'none'; var kdfopts = Buffer.alloc(0); var cinf = { blockSize: 8 }; var passphrase; if (options !== undefined) { passphrase = options.passphrase; if (typeof (passphrase) === 'string') passphrase = Buffer.from(passphrase, 'utf-8'); if (passphrase !== undefined) { assert.buffer(passphrase, 'options.passphrase'); assert.optionalString(options.cipher, 'options.cipher'); cipher = options.cipher; if (cipher === undefined) cipher = 'aes128-ctr'; cinf = utils.opensshCipherInfo(cipher); kdf = 'bcrypt'; } } var privBuf; if (PrivateKey.isPrivateKey(key)) { privBuf = new SSHBuffer({}); var checkInt = crypto.randomBytes(4).readUInt32BE(0); privBuf.writeInt(checkInt); privBuf.writeInt(checkInt); privBuf.write(key.toBuffer('rfc4253')); privBuf.writeString(key.comment || ''); var n = 1; while (privBuf._offset % cinf.blockSize !== 0) privBuf.writeChar(n++); privBuf = privBuf.toBuffer(); } switch (kdf) { case 'none': break; case 'bcrypt': var salt = crypto.randomBytes(16); var rounds = 16; var kdfssh = new SSHBuffer({}); kdfssh.writeBuffer(salt); kdfssh.writeInt(rounds); kdfopts = kdfssh.toBuffer(); if (bcrypt === undefined) { bcrypt = __nccwpck_require__(45447); } var pass = new Uint8Array(passphrase); var salti = new Uint8Array(salt); /* Use the pbkdf to derive both the key and the IV. */ var out = new Uint8Array(cinf.keySize + cinf.blockSize); var res = bcrypt.pbkdf(pass, pass.length, salti, salti.length, out, out.length, rounds); if (res !== 0) { throw (new Error('bcrypt_pbkdf function returned ' + 'failure, parameters invalid')); } out = Buffer.from(out); var ckey = out.slice(0, cinf.keySize); var iv = out.slice(cinf.keySize, cinf.keySize + cinf.blockSize); var cipherStream = crypto.createCipheriv(cinf.opensslName, ckey, iv); cipherStream.setAutoPadding(false); var chunk, chunks = []; cipherStream.once('error', function (e) { throw (e); }); cipherStream.write(privBuf); cipherStream.end(); while ((chunk = cipherStream.read()) !== null) chunks.push(chunk); privBuf = Buffer.concat(chunks); break; default: throw (new Error('Unsupported kdf ' + kdf)); } var buf = new SSHBuffer({}); buf.writeCString(MAGIC); buf.writeString(cipher); /* cipher */ buf.writeString(kdf); /* kdf */ buf.writeBuffer(kdfopts); /* kdfoptions */ buf.writeInt(1); /* nkeys */ buf.writeBuffer(pubKey.toBuffer('rfc4253')); if (privBuf) buf.writeBuffer(privBuf); buf = buf.toBuffer(); var header; if (PrivateKey.isPrivateKey(key)) header = 'OPENSSH PRIVATE KEY'; else header = 'OPENSSH PUBLIC KEY'; var tmp = buf.toString('base64'); var len = tmp.length + (tmp.length / 70) + 18 + 16 + header.length*2 + 10; buf = Buffer.alloc(len); var o = 0; o += buf.write('-----BEGIN ' + header + '-----\n', o); for (var i = 0; i < tmp.length; ) { var limit = i + 70; if (limit > tmp.length) limit = tmp.length; o += buf.write(tmp.slice(i, limit), o); buf[o++] = 10; i = limit; } o += buf.write('-----END ' + header + '-----\n', o); return (buf.slice(0, o)); } /***/ }), /***/ 68927: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // Copyright 2015 Joyent, Inc. module.exports = { read: read, write: write }; var assert = __nccwpck_require__(66631); var Buffer = (__nccwpck_require__(15118).Buffer); var rfc4253 = __nccwpck_require__(88688); var utils = __nccwpck_require__(80575); var Key = __nccwpck_require__(36814); var PrivateKey = __nccwpck_require__(29602); var sshpriv = __nccwpck_require__(3923); /*JSSTYLED*/ var SSHKEY_RE = /^([a-z0-9-]+)[ \t]+([a-zA-Z0-9+\/]+[=]*)([ \t]+([^ \t][^\n]*[\n]*)?)?$/; /*JSSTYLED*/ var SSHKEY_RE2 = /^([a-z0-9-]+)[ \t\n]+([a-zA-Z0-9+\/][a-zA-Z0-9+\/ \t\n=]*)([^a-zA-Z0-9+\/ \t\n=].*)?$/; function read(buf, options) { if (typeof (buf) !== 'string') { assert.buffer(buf, 'buf'); buf = buf.toString('ascii'); } var trimmed = buf.trim().replace(/[\\\r]/g, ''); var m = trimmed.match(SSHKEY_RE); if (!m) m = trimmed.match(SSHKEY_RE2); assert.ok(m, 'key must match regex'); var type = rfc4253.algToKeyType(m[1]); var kbuf = Buffer.from(m[2], 'base64'); /* * This is a bit tricky. If we managed to parse the key and locate the * key comment with the regex, then do a non-partial read and assert * that we have consumed all bytes. If we couldn't locate the key * comment, though, there may be whitespace shenanigans going on that * have conjoined the comment to the rest of the key. We do a partial * read in this case to try to make the best out of a sorry situation. */ var key; var ret = {}; if (m[4]) { try { key = rfc4253.read(kbuf); } catch (e) { m = trimmed.match(SSHKEY_RE2); assert.ok(m, 'key must match regex'); kbuf = Buffer.from(m[2], 'base64'); key = rfc4253.readInternal(ret, 'public', kbuf); } } else { key = rfc4253.readInternal(ret, 'public', kbuf); } assert.strictEqual(type, key.type); if (m[4] && m[4].length > 0) { key.comment = m[4]; } else if (ret.consumed) { /* * Now the magic: trying to recover the key comment when it's * gotten conjoined to the key or otherwise shenanigan'd. * * Work out how much base64 we used, then drop all non-base64 * chars from the beginning up to this point in the the string. * Then offset in this and try to make up for missing = chars. */ var data = m[2] + (m[3] ? m[3] : ''); var realOffset = Math.ceil(ret.consumed / 3) * 4; data = data.slice(0, realOffset - 2). /*JSSTYLED*/ replace(/[^a-zA-Z0-9+\/=]/g, '') + data.slice(realOffset - 2); var padding = ret.consumed % 3; if (padding > 0 && data.slice(realOffset - 1, realOffset) !== '=') realOffset--; while (data.slice(realOffset, realOffset + 1) === '=') realOffset++; /* Finally, grab what we think is the comment & clean it up. */ var trailer = data.slice(realOffset); trailer = trailer.replace(/[\r\n]/g, ' '). replace(/^\s+/, ''); if (trailer.match(/^[a-zA-Z0-9]/)) key.comment = trailer; } return (key); } function write(key, options) { assert.object(key); if (!Key.isKey(key)) throw (new Error('Must be a public key')); var parts = []; var alg = rfc4253.keyTypeToAlg(key); parts.push(alg); var buf = rfc4253.write(key); parts.push(buf.toString('base64')); if (key.comment) parts.push(key.comment); return (Buffer.from(parts.join(' '))); } /***/ }), /***/ 30217: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // Copyright 2016 Joyent, Inc. var x509 = __nccwpck_require__(10267); module.exports = { read: read, verify: x509.verify, sign: x509.sign, write: write }; var assert = __nccwpck_require__(66631); var asn1 = __nccwpck_require__(80970); var Buffer = (__nccwpck_require__(15118).Buffer); var algs = __nccwpck_require__(66126); var utils = __nccwpck_require__(80575); var Key = __nccwpck_require__(36814); var PrivateKey = __nccwpck_require__(29602); var pem = __nccwpck_require__(14324); var Identity = __nccwpck_require__(70508); var Signature = __nccwpck_require__(91394); var Certificate = __nccwpck_require__(7406); function read(buf, options) { if (typeof (buf) !== 'string') { assert.buffer(buf, 'buf'); buf = buf.toString('ascii'); } var lines = buf.trim().split(/[\r\n]+/g); var m; var si = -1; while (!m && si < lines.length) { m = lines[++si].match(/*JSSTYLED*/ /[-]+[ ]*BEGIN CERTIFICATE[ ]*[-]+/); } assert.ok(m, 'invalid PEM header'); var m2; var ei = lines.length; while (!m2 && ei > 0) { m2 = lines[--ei].match(/*JSSTYLED*/ /[-]+[ ]*END CERTIFICATE[ ]*[-]+/); } assert.ok(m2, 'invalid PEM footer'); lines = lines.slice(si, ei + 1); var headers = {}; while (true) { lines = lines.slice(1); m = lines[0].match(/*JSSTYLED*/ /^([A-Za-z0-9-]+): (.+)$/); if (!m) break; headers[m[1].toLowerCase()] = m[2]; } /* Chop off the first and last lines */ lines = lines.slice(0, -1).join(''); buf = Buffer.from(lines, 'base64'); return (x509.read(buf, options)); } function write(cert, options) { var dbuf = x509.write(cert, options); var header = 'CERTIFICATE'; var tmp = dbuf.toString('base64'); var len = tmp.length + (tmp.length / 64) + 18 + 16 + header.length*2 + 10; var buf = Buffer.alloc(len); var o = 0; o += buf.write('-----BEGIN ' + header + '-----\n', o); for (var i = 0; i < tmp.length; ) { var limit = i + 64; if (limit > tmp.length) limit = tmp.length; o += buf.write(tmp.slice(i, limit), o); buf[o++] = 10; i = limit; } o += buf.write('-----END ' + header + '-----\n', o); return (buf.slice(0, o)); } /***/ }), /***/ 10267: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // Copyright 2017 Joyent, Inc. module.exports = { read: read, verify: verify, sign: sign, signAsync: signAsync, write: write }; var assert = __nccwpck_require__(66631); var asn1 = __nccwpck_require__(80970); var Buffer = (__nccwpck_require__(15118).Buffer); var algs = __nccwpck_require__(66126); var utils = __nccwpck_require__(80575); var Key = __nccwpck_require__(36814); var PrivateKey = __nccwpck_require__(29602); var pem = __nccwpck_require__(14324); var Identity = __nccwpck_require__(70508); var Signature = __nccwpck_require__(91394); var Certificate = __nccwpck_require__(7406); var pkcs8 = __nccwpck_require__(4173); /* * This file is based on RFC5280 (X.509). */ /* Helper to read in a single mpint */ function readMPInt(der, nm) { assert.strictEqual(der.peek(), asn1.Ber.Integer, nm + ' is not an Integer'); return (utils.mpNormalize(der.readString(asn1.Ber.Integer, true))); } function verify(cert, key) { var sig = cert.signatures.x509; assert.object(sig, 'x509 signature'); var algParts = sig.algo.split('-'); if (algParts[0] !== key.type) return (false); var blob = sig.cache; if (blob === undefined) { var der = new asn1.BerWriter(); writeTBSCert(cert, der); blob = der.buffer; } var verifier = key.createVerify(algParts[1]); verifier.write(blob); return (verifier.verify(sig.signature)); } function Local(i) { return (asn1.Ber.Context | asn1.Ber.Constructor | i); } function Context(i) { return (asn1.Ber.Context | i); } var SIGN_ALGS = { 'rsa-md5': '1.2.840.113549.1.1.4', 'rsa-sha1': '1.2.840.113549.1.1.5', 'rsa-sha256': '1.2.840.113549.1.1.11', 'rsa-sha384': '1.2.840.113549.1.1.12', 'rsa-sha512': '1.2.840.113549.1.1.13', 'dsa-sha1': '1.2.840.10040.4.3', 'dsa-sha256': '2.16.840.1.101.3.4.3.2', 'ecdsa-sha1': '1.2.840.10045.4.1', 'ecdsa-sha256': '1.2.840.10045.4.3.2', 'ecdsa-sha384': '1.2.840.10045.4.3.3', 'ecdsa-sha512': '1.2.840.10045.4.3.4', 'ed25519-sha512': '1.3.101.112' }; Object.keys(SIGN_ALGS).forEach(function (k) { SIGN_ALGS[SIGN_ALGS[k]] = k; }); SIGN_ALGS['1.3.14.3.2.3'] = 'rsa-md5'; SIGN_ALGS['1.3.14.3.2.29'] = 'rsa-sha1'; var EXTS = { 'issuerKeyId': '2.5.29.35', 'altName': '2.5.29.17', 'basicConstraints': '2.5.29.19', 'keyUsage': '2.5.29.15', 'extKeyUsage': '2.5.29.37' }; function read(buf, options) { if (typeof (buf) === 'string') { buf = Buffer.from(buf, 'binary'); } assert.buffer(buf, 'buf'); var der = new asn1.BerReader(buf); der.readSequence(); if (Math.abs(der.length - der.remain) > 1) { throw (new Error('DER sequence does not contain whole byte ' + 'stream')); } var tbsStart = der.offset; der.readSequence(); var sigOffset = der.offset + der.length; var tbsEnd = sigOffset; if (der.peek() === Local(0)) { der.readSequence(Local(0)); var version = der.readInt(); assert.ok(version <= 3, 'only x.509 versions up to v3 supported'); } var cert = {}; cert.signatures = {}; var sig = (cert.signatures.x509 = {}); sig.extras = {}; cert.serial = readMPInt(der, 'serial'); der.readSequence(); var after = der.offset + der.length; var certAlgOid = der.readOID(); var certAlg = SIGN_ALGS[certAlgOid]; if (certAlg === undefined) throw (new Error('unknown signature algorithm ' + certAlgOid)); der._offset = after; cert.issuer = Identity.parseAsn1(der); der.readSequence(); cert.validFrom = readDate(der); cert.validUntil = readDate(der); cert.subjects = [Identity.parseAsn1(der)]; der.readSequence(); after = der.offset + der.length; cert.subjectKey = pkcs8.readPkcs8(undefined, 'public', der); der._offset = after; /* issuerUniqueID */ if (der.peek() === Local(1)) { der.readSequence(Local(1)); sig.extras.issuerUniqueID = buf.slice(der.offset, der.offset + der.length); der._offset += der.length; } /* subjectUniqueID */ if (der.peek() === Local(2)) { der.readSequence(Local(2)); sig.extras.subjectUniqueID = buf.slice(der.offset, der.offset + der.length); der._offset += der.length; } /* extensions */ if (der.peek() === Local(3)) { der.readSequence(Local(3)); var extEnd = der.offset + der.length; der.readSequence(); while (der.offset < extEnd) readExtension(cert, buf, der); assert.strictEqual(der.offset, extEnd); } assert.strictEqual(der.offset, sigOffset); der.readSequence(); after = der.offset + der.length; var sigAlgOid = der.readOID(); var sigAlg = SIGN_ALGS[sigAlgOid]; if (sigAlg === undefined) throw (new Error('unknown signature algorithm ' + sigAlgOid)); der._offset = after; var sigData = der.readString(asn1.Ber.BitString, true); if (sigData[0] === 0) sigData = sigData.slice(1); var algParts = sigAlg.split('-'); sig.signature = Signature.parse(sigData, algParts[0], 'asn1'); sig.signature.hashAlgorithm = algParts[1]; sig.algo = sigAlg; sig.cache = buf.slice(tbsStart, tbsEnd); return (new Certificate(cert)); } function readDate(der) { if (der.peek() === asn1.Ber.UTCTime) { return (utcTimeToDate(der.readString(asn1.Ber.UTCTime))); } else if (der.peek() === asn1.Ber.GeneralizedTime) { return (gTimeToDate(der.readString(asn1.Ber.GeneralizedTime))); } else { throw (new Error('Unsupported date format')); } } function writeDate(der, date) { if (date.getUTCFullYear() >= 2050 || date.getUTCFullYear() < 1950) { der.writeString(dateToGTime(date), asn1.Ber.GeneralizedTime); } else { der.writeString(dateToUTCTime(date), asn1.Ber.UTCTime); } } /* RFC5280, section 4.2.1.6 (GeneralName type) */ var ALTNAME = { OtherName: Local(0), RFC822Name: Context(1), DNSName: Context(2), X400Address: Local(3), DirectoryName: Local(4), EDIPartyName: Local(5), URI: Context(6), IPAddress: Context(7), OID: Context(8) }; /* RFC5280, section 4.2.1.12 (KeyPurposeId) */ var EXTPURPOSE = { 'serverAuth': '1.3.6.1.5.5.7.3.1', 'clientAuth': '1.3.6.1.5.5.7.3.2', 'codeSigning': '1.3.6.1.5.5.7.3.3', /* See https://github.com/joyent/oid-docs/blob/master/root.md */ 'joyentDocker': '1.3.6.1.4.1.38678.1.4.1', 'joyentCmon': '1.3.6.1.4.1.38678.1.4.2' }; var EXTPURPOSE_REV = {}; Object.keys(EXTPURPOSE).forEach(function (k) { EXTPURPOSE_REV[EXTPURPOSE[k]] = k; }); var KEYUSEBITS = [ 'signature', 'identity', 'keyEncryption', 'encryption', 'keyAgreement', 'ca', 'crl' ]; function readExtension(cert, buf, der) { der.readSequence(); var after = der.offset + der.length; var extId = der.readOID(); var id; var sig = cert.signatures.x509; if (!sig.extras.exts) sig.extras.exts = []; var critical; if (der.peek() === asn1.Ber.Boolean) critical = der.readBoolean(); switch (extId) { case (EXTS.basicConstraints): der.readSequence(asn1.Ber.OctetString); der.readSequence(); var bcEnd = der.offset + der.length; var ca = false; if (der.peek() === asn1.Ber.Boolean) ca = der.readBoolean(); if (cert.purposes === undefined) cert.purposes = []; if (ca === true) cert.purposes.push('ca'); var bc = { oid: extId, critical: critical }; if (der.offset < bcEnd && der.peek() === asn1.Ber.Integer) bc.pathLen = der.readInt(); sig.extras.exts.push(bc); break; case (EXTS.extKeyUsage): der.readSequence(asn1.Ber.OctetString); der.readSequence(); if (cert.purposes === undefined) cert.purposes = []; var ekEnd = der.offset + der.length; while (der.offset < ekEnd) { var oid = der.readOID(); cert.purposes.push(EXTPURPOSE_REV[oid] || oid); } /* * This is a bit of a hack: in the case where we have a cert * that's only allowed to do serverAuth or clientAuth (and not * the other), we want to make sure all our Subjects are of * the right type. But we already parsed our Subjects and * decided if they were hosts or users earlier (since it appears * first in the cert). * * So we go through and mutate them into the right kind here if * it doesn't match. This might not be hugely beneficial, as it * seems that single-purpose certs are not often seen in the * wild. */ if (cert.purposes.indexOf('serverAuth') !== -1 && cert.purposes.indexOf('clientAuth') === -1) { cert.subjects.forEach(function (ide) { if (ide.type !== 'host') { ide.type = 'host'; ide.hostname = ide.uid || ide.email || ide.components[0].value; } }); } else if (cert.purposes.indexOf('clientAuth') !== -1 && cert.purposes.indexOf('serverAuth') === -1) { cert.subjects.forEach(function (ide) { if (ide.type !== 'user') { ide.type = 'user'; ide.uid = ide.hostname || ide.email || ide.components[0].value; } }); } sig.extras.exts.push({ oid: extId, critical: critical }); break; case (EXTS.keyUsage): der.readSequence(asn1.Ber.OctetString); var bits = der.readString(asn1.Ber.BitString, true); var setBits = readBitField(bits, KEYUSEBITS); setBits.forEach(function (bit) { if (cert.purposes === undefined) cert.purposes = []; if (cert.purposes.indexOf(bit) === -1) cert.purposes.push(bit); }); sig.extras.exts.push({ oid: extId, critical: critical, bits: bits }); break; case (EXTS.altName): der.readSequence(asn1.Ber.OctetString); der.readSequence(); var aeEnd = der.offset + der.length; while (der.offset < aeEnd) { switch (der.peek()) { case ALTNAME.OtherName: case ALTNAME.EDIPartyName: der.readSequence(); der._offset += der.length; break; case ALTNAME.OID: der.readOID(ALTNAME.OID); break; case ALTNAME.RFC822Name: /* RFC822 specifies email addresses */ var email = der.readString(ALTNAME.RFC822Name); id = Identity.forEmail(email); if (!cert.subjects[0].equals(id)) cert.subjects.push(id); break; case ALTNAME.DirectoryName: der.readSequence(ALTNAME.DirectoryName); id = Identity.parseAsn1(der); if (!cert.subjects[0].equals(id)) cert.subjects.push(id); break; case ALTNAME.DNSName: var host = der.readString( ALTNAME.DNSName); id = Identity.forHost(host); if (!cert.subjects[0].equals(id)) cert.subjects.push(id); break; default: der.readString(der.peek()); break; } } sig.extras.exts.push({ oid: extId, critical: critical }); break; default: sig.extras.exts.push({ oid: extId, critical: critical, data: der.readString(asn1.Ber.OctetString, true) }); break; } der._offset = after; } var UTCTIME_RE = /^([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})?Z$/; function utcTimeToDate(t) { var m = t.match(UTCTIME_RE); assert.ok(m, 'timestamps must be in UTC'); var d = new Date(); var thisYear = d.getUTCFullYear(); var century = Math.floor(thisYear / 100) * 100; var year = parseInt(m[1], 10); if (thisYear % 100 < 50 && year >= 60) year += (century - 1); else year += century; d.setUTCFullYear(year, parseInt(m[2], 10) - 1, parseInt(m[3], 10)); d.setUTCHours(parseInt(m[4], 10), parseInt(m[5], 10)); if (m[6] && m[6].length > 0) d.setUTCSeconds(parseInt(m[6], 10)); return (d); } var GTIME_RE = /^([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})?Z$/; function gTimeToDate(t) { var m = t.match(GTIME_RE); assert.ok(m); var d = new Date(); d.setUTCFullYear(parseInt(m[1], 10), parseInt(m[2], 10) - 1, parseInt(m[3], 10)); d.setUTCHours(parseInt(m[4], 10), parseInt(m[5], 10)); if (m[6] && m[6].length > 0) d.setUTCSeconds(parseInt(m[6], 10)); return (d); } function zeroPad(n, m) { if (m === undefined) m = 2; var s = '' + n; while (s.length < m) s = '0' + s; return (s); } function dateToUTCTime(d) { var s = ''; s += zeroPad(d.getUTCFullYear() % 100); s += zeroPad(d.getUTCMonth() + 1); s += zeroPad(d.getUTCDate()); s += zeroPad(d.getUTCHours()); s += zeroPad(d.getUTCMinutes()); s += zeroPad(d.getUTCSeconds()); s += 'Z'; return (s); } function dateToGTime(d) { var s = ''; s += zeroPad(d.getUTCFullYear(), 4); s += zeroPad(d.getUTCMonth() + 1); s += zeroPad(d.getUTCDate()); s += zeroPad(d.getUTCHours()); s += zeroPad(d.getUTCMinutes()); s += zeroPad(d.getUTCSeconds()); s += 'Z'; return (s); } function sign(cert, key) { if (cert.signatures.x509 === undefined) cert.signatures.x509 = {}; var sig = cert.signatures.x509; sig.algo = key.type + '-' + key.defaultHashAlgorithm(); if (SIGN_ALGS[sig.algo] === undefined) return (false); var der = new asn1.BerWriter(); writeTBSCert(cert, der); var blob = der.buffer; sig.cache = blob; var signer = key.createSign(); signer.write(blob); cert.signatures.x509.signature = signer.sign(); return (true); } function signAsync(cert, signer, done) { if (cert.signatures.x509 === undefined) cert.signatures.x509 = {}; var sig = cert.signatures.x509; var der = new asn1.BerWriter(); writeTBSCert(cert, der); var blob = der.buffer; sig.cache = blob; signer(blob, function (err, signature) { if (err) { done(err); return; } sig.algo = signature.type + '-' + signature.hashAlgorithm; if (SIGN_ALGS[sig.algo] === undefined) { done(new Error('Invalid signing algorithm "' + sig.algo + '"')); return; } sig.signature = signature; done(); }); } function write(cert, options) { var sig = cert.signatures.x509; assert.object(sig, 'x509 signature'); var der = new asn1.BerWriter(); der.startSequence(); if (sig.cache) { der._ensure(sig.cache.length); sig.cache.copy(der._buf, der._offset); der._offset += sig.cache.length; } else { writeTBSCert(cert, der); } der.startSequence(); der.writeOID(SIGN_ALGS[sig.algo]); if (sig.algo.match(/^rsa-/)) der.writeNull(); der.endSequence(); var sigData = sig.signature.toBuffer('asn1'); var data = Buffer.alloc(sigData.length + 1); data[0] = 0; sigData.copy(data, 1); der.writeBuffer(data, asn1.Ber.BitString); der.endSequence(); return (der.buffer); } function writeTBSCert(cert, der) { var sig = cert.signatures.x509; assert.object(sig, 'x509 signature'); der.startSequence(); der.startSequence(Local(0)); der.writeInt(2); der.endSequence(); der.writeBuffer(utils.mpNormalize(cert.serial), asn1.Ber.Integer); der.startSequence(); der.writeOID(SIGN_ALGS[sig.algo]); if (sig.algo.match(/^rsa-/)) der.writeNull(); der.endSequence(); cert.issuer.toAsn1(der); der.startSequence(); writeDate(der, cert.validFrom); writeDate(der, cert.validUntil); der.endSequence(); var subject = cert.subjects[0]; var altNames = cert.subjects.slice(1); subject.toAsn1(der); pkcs8.writePkcs8(der, cert.subjectKey); if (sig.extras && sig.extras.issuerUniqueID) { der.writeBuffer(sig.extras.issuerUniqueID, Local(1)); } if (sig.extras && sig.extras.subjectUniqueID) { der.writeBuffer(sig.extras.subjectUniqueID, Local(2)); } if (altNames.length > 0 || subject.type === 'host' || (cert.purposes !== undefined && cert.purposes.length > 0) || (sig.extras && sig.extras.exts)) { der.startSequence(Local(3)); der.startSequence(); var exts = []; if (cert.purposes !== undefined && cert.purposes.length > 0) { exts.push({ oid: EXTS.basicConstraints, critical: true }); exts.push({ oid: EXTS.keyUsage, critical: true }); exts.push({ oid: EXTS.extKeyUsage, critical: true }); } exts.push({ oid: EXTS.altName }); if (sig.extras && sig.extras.exts) exts = sig.extras.exts; for (var i = 0; i < exts.length; ++i) { der.startSequence(); der.writeOID(exts[i].oid); if (exts[i].critical !== undefined) der.writeBoolean(exts[i].critical); if (exts[i].oid === EXTS.altName) { der.startSequence(asn1.Ber.OctetString); der.startSequence(); if (subject.type === 'host') { der.writeString(subject.hostname, Context(2)); } for (var j = 0; j < altNames.length; ++j) { if (altNames[j].type === 'host') { der.writeString( altNames[j].hostname, ALTNAME.DNSName); } else if (altNames[j].type === 'email') { der.writeString( altNames[j].email, ALTNAME.RFC822Name); } else { /* * Encode anything else as a * DN style name for now. */ der.startSequence( ALTNAME.DirectoryName); altNames[j].toAsn1(der); der.endSequence(); } } der.endSequence(); der.endSequence(); } else if (exts[i].oid === EXTS.basicConstraints) { der.startSequence(asn1.Ber.OctetString); der.startSequence(); var ca = (cert.purposes.indexOf('ca') !== -1); var pathLen = exts[i].pathLen; der.writeBoolean(ca); if (pathLen !== undefined) der.writeInt(pathLen); der.endSequence(); der.endSequence(); } else if (exts[i].oid === EXTS.extKeyUsage) { der.startSequence(asn1.Ber.OctetString); der.startSequence(); cert.purposes.forEach(function (purpose) { if (purpose === 'ca') return; if (KEYUSEBITS.indexOf(purpose) !== -1) return; var oid = purpose; if (EXTPURPOSE[purpose] !== undefined) oid = EXTPURPOSE[purpose]; der.writeOID(oid); }); der.endSequence(); der.endSequence(); } else if (exts[i].oid === EXTS.keyUsage) { der.startSequence(asn1.Ber.OctetString); /* * If we parsed this certificate from a byte * stream (i.e. we didn't generate it in sshpk) * then we'll have a ".bits" property on the * ext with the original raw byte contents. * * If we have this, use it here instead of * regenerating it. This guarantees we output * the same data we parsed, so signatures still * validate. */ if (exts[i].bits !== undefined) { der.writeBuffer(exts[i].bits, asn1.Ber.BitString); } else { var bits = writeBitField(cert.purposes, KEYUSEBITS); der.writeBuffer(bits, asn1.Ber.BitString); } der.endSequence(); } else { der.writeBuffer(exts[i].data, asn1.Ber.OctetString); } der.endSequence(); } der.endSequence(); der.endSequence(); } der.endSequence(); } /* * Reads an ASN.1 BER bitfield out of the Buffer produced by doing * `BerReader#readString(asn1.Ber.BitString)`. That function gives us the raw * contents of the BitString tag, which is a count of unused bits followed by * the bits as a right-padded byte string. * * `bits` is the Buffer, `bitIndex` should contain an array of string names * for the bits in the string, ordered starting with bit #0 in the ASN.1 spec. * * Returns an array of Strings, the names of the bits that were set to 1. */ function readBitField(bits, bitIndex) { var bitLen = 8 * (bits.length - 1) - bits[0]; var setBits = {}; for (var i = 0; i < bitLen; ++i) { var byteN = 1 + Math.floor(i / 8); var bit = 7 - (i % 8); var mask = 1 << bit; var bitVal = ((bits[byteN] & mask) !== 0); var name = bitIndex[i]; if (bitVal && typeof (name) === 'string') { setBits[name] = true; } } return (Object.keys(setBits)); } /* * `setBits` is an array of strings, containing the names for each bit that * sould be set to 1. `bitIndex` is same as in `readBitField()`. * * Returns a Buffer, ready to be written out with `BerWriter#writeString()`. */ function writeBitField(setBits, bitIndex) { var bitLen = bitIndex.length; var blen = Math.ceil(bitLen / 8); var unused = blen * 8 - bitLen; var bits = Buffer.alloc(1 + blen); // zero-filled bits[0] = unused; for (var i = 0; i < bitLen; ++i) { var byteN = 1 + Math.floor(i / 8); var bit = 7 - (i % 8); var mask = 1 << bit; var name = bitIndex[i]; if (name === undefined) continue; var bitVal = (setBits.indexOf(name) !== -1); if (bitVal) { bits[byteN] |= mask; } } return (bits); } /***/ }), /***/ 70508: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // Copyright 2017 Joyent, Inc. module.exports = Identity; var assert = __nccwpck_require__(66631); var algs = __nccwpck_require__(66126); var crypto = __nccwpck_require__(6113); var Fingerprint = __nccwpck_require__(13079); var Signature = __nccwpck_require__(91394); var errs = __nccwpck_require__(27979); var util = __nccwpck_require__(73837); var utils = __nccwpck_require__(80575); var asn1 = __nccwpck_require__(80970); var Buffer = (__nccwpck_require__(15118).Buffer); /*JSSTYLED*/ var DNS_NAME_RE = /^([*]|[a-z0-9][a-z0-9\-]{0,62})(?:\.([*]|[a-z0-9][a-z0-9\-]{0,62}))*$/i; var oids = {}; oids.cn = '2.5.4.3'; oids.o = '2.5.4.10'; oids.ou = '2.5.4.11'; oids.l = '2.5.4.7'; oids.s = '2.5.4.8'; oids.c = '2.5.4.6'; oids.sn = '2.5.4.4'; oids.postalCode = '2.5.4.17'; oids.serialNumber = '2.5.4.5'; oids.street = '2.5.4.9'; oids.x500UniqueIdentifier = '2.5.4.45'; oids.role = '2.5.4.72'; oids.telephoneNumber = '2.5.4.20'; oids.description = '2.5.4.13'; oids.dc = '0.9.2342.19200300.100.1.25'; oids.uid = '0.9.2342.19200300.100.1.1'; oids.mail = '0.9.2342.19200300.100.1.3'; oids.title = '2.5.4.12'; oids.gn = '2.5.4.42'; oids.initials = '2.5.4.43'; oids.pseudonym = '2.5.4.65'; oids.emailAddress = '1.2.840.113549.1.9.1'; var unoids = {}; Object.keys(oids).forEach(function (k) { unoids[oids[k]] = k; }); function Identity(opts) { var self = this; assert.object(opts, 'options'); assert.arrayOfObject(opts.components, 'options.components'); this.components = opts.components; this.componentLookup = {}; this.components.forEach(function (c) { if (c.name && !c.oid) c.oid = oids[c.name]; if (c.oid && !c.name) c.name = unoids[c.oid]; if (self.componentLookup[c.name] === undefined) self.componentLookup[c.name] = []; self.componentLookup[c.name].push(c); }); if (this.componentLookup.cn && this.componentLookup.cn.length > 0) { this.cn = this.componentLookup.cn[0].value; } assert.optionalString(opts.type, 'options.type'); if (opts.type === undefined) { if (this.components.length === 1 && this.componentLookup.cn && this.componentLookup.cn.length === 1 && this.componentLookup.cn[0].value.match(DNS_NAME_RE)) { this.type = 'host'; this.hostname = this.componentLookup.cn[0].value; } else if (this.componentLookup.dc && this.components.length === this.componentLookup.dc.length) { this.type = 'host'; this.hostname = this.componentLookup.dc.map( function (c) { return (c.value); }).join('.'); } else if (this.componentLookup.uid && this.components.length === this.componentLookup.uid.length) { this.type = 'user'; this.uid = this.componentLookup.uid[0].value; } else if (this.componentLookup.cn && this.componentLookup.cn.length === 1 && this.componentLookup.cn[0].value.match(DNS_NAME_RE)) { this.type = 'host'; this.hostname = this.componentLookup.cn[0].value; } else if (this.componentLookup.uid && this.componentLookup.uid.length === 1) { this.type = 'user'; this.uid = this.componentLookup.uid[0].value; } else if (this.componentLookup.mail && this.componentLookup.mail.length === 1) { this.type = 'email'; this.email = this.componentLookup.mail[0].value; } else if (this.componentLookup.cn && this.componentLookup.cn.length === 1) { this.type = 'user'; this.uid = this.componentLookup.cn[0].value; } else { this.type = 'unknown'; } } else { this.type = opts.type; if (this.type === 'host') this.hostname = opts.hostname; else if (this.type === 'user') this.uid = opts.uid; else if (this.type === 'email') this.email = opts.email; else throw (new Error('Unknown type ' + this.type)); } } Identity.prototype.toString = function () { return (this.components.map(function (c) { var n = c.name.toUpperCase(); /*JSSTYLED*/ n = n.replace(/=/g, '\\='); var v = c.value; /*JSSTYLED*/ v = v.replace(/,/g, '\\,'); return (n + '=' + v); }).join(', ')); }; Identity.prototype.get = function (name, asArray) { assert.string(name, 'name'); var arr = this.componentLookup[name]; if (arr === undefined || arr.length === 0) return (undefined); if (!asArray && arr.length > 1) throw (new Error('Multiple values for attribute ' + name)); if (!asArray) return (arr[0].value); return (arr.map(function (c) { return (c.value); })); }; Identity.prototype.toArray = function (idx) { return (this.components.map(function (c) { return ({ name: c.name, value: c.value }); })); }; /* * These are from X.680 -- PrintableString allowed chars are in section 37.4 * table 8. Spec for IA5Strings is "1,6 + SPACE + DEL" where 1 refers to * ISO IR #001 (standard ASCII control characters) and 6 refers to ISO IR #006 * (the basic ASCII character set). */ /* JSSTYLED */ var NOT_PRINTABLE = /[^a-zA-Z0-9 '(),+.\/:=?-]/; /* JSSTYLED */ var NOT_IA5 = /[^\x00-\x7f]/; Identity.prototype.toAsn1 = function (der, tag) { der.startSequence(tag); this.components.forEach(function (c) { der.startSequence(asn1.Ber.Constructor | asn1.Ber.Set); der.startSequence(); der.writeOID(c.oid); /* * If we fit in a PrintableString, use that. Otherwise use an * IA5String or UTF8String. * * If this identity was parsed from a DN, use the ASN.1 types * from the original representation (otherwise this might not * be a full match for the original in some validators). */ if (c.asn1type === asn1.Ber.Utf8String || c.value.match(NOT_IA5)) { var v = Buffer.from(c.value, 'utf8'); der.writeBuffer(v, asn1.Ber.Utf8String); } else if (c.asn1type === asn1.Ber.IA5String || c.value.match(NOT_PRINTABLE)) { der.writeString(c.value, asn1.Ber.IA5String); } else { var type = asn1.Ber.PrintableString; if (c.asn1type !== undefined) type = c.asn1type; der.writeString(c.value, type); } der.endSequence(); der.endSequence(); }); der.endSequence(); }; function globMatch(a, b) { if (a === '**' || b === '**') return (true); var aParts = a.split('.'); var bParts = b.split('.'); if (aParts.length !== bParts.length) return (false); for (var i = 0; i < aParts.length; ++i) { if (aParts[i] === '*' || bParts[i] === '*') continue; if (aParts[i] !== bParts[i]) return (false); } return (true); } Identity.prototype.equals = function (other) { if (!Identity.isIdentity(other, [1, 0])) return (false); if (other.components.length !== this.components.length) return (false); for (var i = 0; i < this.components.length; ++i) { if (this.components[i].oid !== other.components[i].oid) return (false); if (!globMatch(this.components[i].value, other.components[i].value)) { return (false); } } return (true); }; Identity.forHost = function (hostname) { assert.string(hostname, 'hostname'); return (new Identity({ type: 'host', hostname: hostname, components: [ { name: 'cn', value: hostname } ] })); }; Identity.forUser = function (uid) { assert.string(uid, 'uid'); return (new Identity({ type: 'user', uid: uid, components: [ { name: 'uid', value: uid } ] })); }; Identity.forEmail = function (email) { assert.string(email, 'email'); return (new Identity({ type: 'email', email: email, components: [ { name: 'mail', value: email } ] })); }; Identity.parseDN = function (dn) { assert.string(dn, 'dn'); var parts = ['']; var idx = 0; var rem = dn; while (rem.length > 0) { var m; /*JSSTYLED*/ if ((m = /^,/.exec(rem)) !== null) { parts[++idx] = ''; rem = rem.slice(m[0].length); /*JSSTYLED*/ } else if ((m = /^\\,/.exec(rem)) !== null) { parts[idx] += ','; rem = rem.slice(m[0].length); /*JSSTYLED*/ } else if ((m = /^\\./.exec(rem)) !== null) { parts[idx] += m[0]; rem = rem.slice(m[0].length); /*JSSTYLED*/ } else if ((m = /^[^\\,]+/.exec(rem)) !== null) { parts[idx] += m[0]; rem = rem.slice(m[0].length); } else { throw (new Error('Failed to parse DN')); } } var cmps = parts.map(function (c) { c = c.trim(); var eqPos = c.indexOf('='); while (eqPos > 0 && c.charAt(eqPos - 1) === '\\') eqPos = c.indexOf('=', eqPos + 1); if (eqPos === -1) { throw (new Error('Failed to parse DN')); } /*JSSTYLED*/ var name = c.slice(0, eqPos).toLowerCase().replace(/\\=/g, '='); var value = c.slice(eqPos + 1); return ({ name: name, value: value }); }); return (new Identity({ components: cmps })); }; Identity.fromArray = function (components) { assert.arrayOfObject(components, 'components'); components.forEach(function (cmp) { assert.object(cmp, 'component'); assert.string(cmp.name, 'component.name'); if (!Buffer.isBuffer(cmp.value) && !(typeof (cmp.value) === 'string')) { throw (new Error('Invalid component value')); } }); return (new Identity({ components: components })); }; Identity.parseAsn1 = function (der, top) { var components = []; der.readSequence(top); var end = der.offset + der.length; while (der.offset < end) { der.readSequence(asn1.Ber.Constructor | asn1.Ber.Set); var after = der.offset + der.length; der.readSequence(); var oid = der.readOID(); var type = der.peek(); var value; switch (type) { case asn1.Ber.PrintableString: case asn1.Ber.IA5String: case asn1.Ber.OctetString: case asn1.Ber.T61String: value = der.readString(type); break; case asn1.Ber.Utf8String: value = der.readString(type, true); value = value.toString('utf8'); break; case asn1.Ber.CharacterString: case asn1.Ber.BMPString: value = der.readString(type, true); value = value.toString('utf16le'); break; default: throw (new Error('Unknown asn1 type ' + type)); } components.push({ oid: oid, asn1type: type, value: value }); der._offset = after; } der._offset = end; return (new Identity({ components: components })); }; Identity.isIdentity = function (obj, ver) { return (utils.isCompatible(obj, Identity, ver)); }; /* * API versions for Identity: * [1,0] -- initial ver */ Identity.prototype._sshpkApiVersion = [1, 0]; Identity._oldVersionDetect = function (obj) { return ([1, 0]); }; /***/ }), /***/ 87022: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // Copyright 2015 Joyent, Inc. var Key = __nccwpck_require__(36814); var Fingerprint = __nccwpck_require__(13079); var Signature = __nccwpck_require__(91394); var PrivateKey = __nccwpck_require__(29602); var Certificate = __nccwpck_require__(7406); var Identity = __nccwpck_require__(70508); var errs = __nccwpck_require__(27979); module.exports = { /* top-level classes */ Key: Key, parseKey: Key.parse, Fingerprint: Fingerprint, parseFingerprint: Fingerprint.parse, Signature: Signature, parseSignature: Signature.parse, PrivateKey: PrivateKey, parsePrivateKey: PrivateKey.parse, generatePrivateKey: PrivateKey.generate, Certificate: Certificate, parseCertificate: Certificate.parse, createSelfSignedCertificate: Certificate.createSelfSigned, createCertificate: Certificate.create, Identity: Identity, identityFromDN: Identity.parseDN, identityForHost: Identity.forHost, identityForUser: Identity.forUser, identityForEmail: Identity.forEmail, identityFromArray: Identity.fromArray, /* errors */ FingerprintFormatError: errs.FingerprintFormatError, InvalidAlgorithmError: errs.InvalidAlgorithmError, KeyParseError: errs.KeyParseError, SignatureParseError: errs.SignatureParseError, KeyEncryptedError: errs.KeyEncryptedError, CertificateParseError: errs.CertificateParseError }; /***/ }), /***/ 36814: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // Copyright 2018 Joyent, Inc. module.exports = Key; var assert = __nccwpck_require__(66631); var algs = __nccwpck_require__(66126); var crypto = __nccwpck_require__(6113); var Fingerprint = __nccwpck_require__(13079); var Signature = __nccwpck_require__(91394); var DiffieHellman = (__nccwpck_require__(57602).DiffieHellman); var errs = __nccwpck_require__(27979); var utils = __nccwpck_require__(80575); var PrivateKey = __nccwpck_require__(29602); var edCompat; try { edCompat = __nccwpck_require__(14694); } catch (e) { /* Just continue through, and bail out if we try to use it. */ } var InvalidAlgorithmError = errs.InvalidAlgorithmError; var KeyParseError = errs.KeyParseError; var formats = {}; formats['auto'] = __nccwpck_require__(8243); formats['pem'] = __nccwpck_require__(14324); formats['pkcs1'] = __nccwpck_require__(69367); formats['pkcs8'] = __nccwpck_require__(4173); formats['rfc4253'] = __nccwpck_require__(88688); formats['ssh'] = __nccwpck_require__(68927); formats['ssh-private'] = __nccwpck_require__(3923); formats['openssh'] = formats['ssh-private']; formats['dnssec'] = __nccwpck_require__(63561); formats['putty'] = __nccwpck_require__(80974); formats['ppk'] = formats['putty']; function Key(opts) { assert.object(opts, 'options'); assert.arrayOfObject(opts.parts, 'options.parts'); assert.string(opts.type, 'options.type'); assert.optionalString(opts.comment, 'options.comment'); var algInfo = algs.info[opts.type]; if (typeof (algInfo) !== 'object') throw (new InvalidAlgorithmError(opts.type)); var partLookup = {}; for (var i = 0; i < opts.parts.length; ++i) { var part = opts.parts[i]; partLookup[part.name] = part; } this.type = opts.type; this.parts = opts.parts; this.part = partLookup; this.comment = undefined; this.source = opts.source; /* for speeding up hashing/fingerprint operations */ this._rfc4253Cache = opts._rfc4253Cache; this._hashCache = {}; var sz; this.curve = undefined; if (this.type === 'ecdsa') { var curve = this.part.curve.data.toString(); this.curve = curve; sz = algs.curves[curve].size; } else if (this.type === 'ed25519' || this.type === 'curve25519') { sz = 256; this.curve = 'curve25519'; } else { var szPart = this.part[algInfo.sizePart]; sz = szPart.data.length; sz = sz * 8 - utils.countZeros(szPart.data); } this.size = sz; } Key.formats = formats; Key.prototype.toBuffer = function (format, options) { if (format === undefined) format = 'ssh'; assert.string(format, 'format'); assert.object(formats[format], 'formats[format]'); assert.optionalObject(options, 'options'); if (format === 'rfc4253') { if (this._rfc4253Cache === undefined) this._rfc4253Cache = formats['rfc4253'].write(this); return (this._rfc4253Cache); } return (formats[format].write(this, options)); }; Key.prototype.toString = function (format, options) { return (this.toBuffer(format, options).toString()); }; Key.prototype.hash = function (algo, type) { assert.string(algo, 'algorithm'); assert.optionalString(type, 'type'); if (type === undefined) type = 'ssh'; algo = algo.toLowerCase(); if (algs.hashAlgs[algo] === undefined) throw (new InvalidAlgorithmError(algo)); var cacheKey = algo + '||' + type; if (this._hashCache[cacheKey]) return (this._hashCache[cacheKey]); var buf; if (type === 'ssh') { buf = this.toBuffer('rfc4253'); } else if (type === 'spki') { buf = formats.pkcs8.pkcs8ToBuffer(this); } else { throw (new Error('Hash type ' + type + ' not supported')); } var hash = crypto.createHash(algo).update(buf).digest(); this._hashCache[cacheKey] = hash; return (hash); }; Key.prototype.fingerprint = function (algo, type) { if (algo === undefined) algo = 'sha256'; if (type === undefined) type = 'ssh'; assert.string(algo, 'algorithm'); assert.string(type, 'type'); var opts = { type: 'key', hash: this.hash(algo, type), algorithm: algo, hashType: type }; return (new Fingerprint(opts)); }; Key.prototype.defaultHashAlgorithm = function () { var hashAlgo = 'sha1'; if (this.type === 'rsa') hashAlgo = 'sha256'; if (this.type === 'dsa' && this.size > 1024) hashAlgo = 'sha256'; if (this.type === 'ed25519') hashAlgo = 'sha512'; if (this.type === 'ecdsa') { if (this.size <= 256) hashAlgo = 'sha256'; else if (this.size <= 384) hashAlgo = 'sha384'; else hashAlgo = 'sha512'; } return (hashAlgo); }; Key.prototype.createVerify = function (hashAlgo) { if (hashAlgo === undefined) hashAlgo = this.defaultHashAlgorithm(); assert.string(hashAlgo, 'hash algorithm'); /* ED25519 is not supported by OpenSSL, use a javascript impl. */ if (this.type === 'ed25519' && edCompat !== undefined) return (new edCompat.Verifier(this, hashAlgo)); if (this.type === 'curve25519') throw (new Error('Curve25519 keys are not suitable for ' + 'signing or verification')); var v, nm, err; try { nm = hashAlgo.toUpperCase(); v = crypto.createVerify(nm); } catch (e) { err = e; } if (v === undefined || (err instanceof Error && err.message.match(/Unknown message digest/))) { nm = 'RSA-'; nm += hashAlgo.toUpperCase(); v = crypto.createVerify(nm); } assert.ok(v, 'failed to create verifier'); var oldVerify = v.verify.bind(v); var key = this.toBuffer('pkcs8'); var curve = this.curve; var self = this; v.verify = function (signature, fmt) { if (Signature.isSignature(signature, [2, 0])) { if (signature.type !== self.type) return (false); if (signature.hashAlgorithm && signature.hashAlgorithm !== hashAlgo) return (false); if (signature.curve && self.type === 'ecdsa' && signature.curve !== curve) return (false); return (oldVerify(key, signature.toBuffer('asn1'))); } else if (typeof (signature) === 'string' || Buffer.isBuffer(signature)) { return (oldVerify(key, signature, fmt)); /* * Avoid doing this on valid arguments, walking the prototype * chain can be quite slow. */ } else if (Signature.isSignature(signature, [1, 0])) { throw (new Error('signature was created by too old ' + 'a version of sshpk and cannot be verified')); } else { throw (new TypeError('signature must be a string, ' + 'Buffer, or Signature object')); } }; return (v); }; Key.prototype.createDiffieHellman = function () { if (this.type === 'rsa') throw (new Error('RSA keys do not support Diffie-Hellman')); return (new DiffieHellman(this)); }; Key.prototype.createDH = Key.prototype.createDiffieHellman; Key.parse = function (data, format, options) { if (typeof (data) !== 'string') assert.buffer(data, 'data'); if (format === undefined) format = 'auto'; assert.string(format, 'format'); if (typeof (options) === 'string') options = { filename: options }; assert.optionalObject(options, 'options'); if (options === undefined) options = {}; assert.optionalString(options.filename, 'options.filename'); if (options.filename === undefined) options.filename = '(unnamed)'; assert.object(formats[format], 'formats[format]'); try { var k = formats[format].read(data, options); if (k instanceof PrivateKey) k = k.toPublic(); if (!k.comment) k.comment = options.filename; return (k); } catch (e) { if (e.name === 'KeyEncryptedError') throw (e); throw (new KeyParseError(options.filename, format, e)); } }; Key.isKey = function (obj, ver) { return (utils.isCompatible(obj, Key, ver)); }; /* * API versions for Key: * [1,0] -- initial ver, may take Signature for createVerify or may not * [1,1] -- added pkcs1, pkcs8 formats * [1,2] -- added auto, ssh-private, openssh formats * [1,3] -- added defaultHashAlgorithm * [1,4] -- added ed support, createDH * [1,5] -- first explicitly tagged version * [1,6] -- changed ed25519 part names * [1,7] -- spki hash types */ Key.prototype._sshpkApiVersion = [1, 7]; Key._oldVersionDetect = function (obj) { assert.func(obj.toBuffer); assert.func(obj.fingerprint); if (obj.createDH) return ([1, 4]); if (obj.defaultHashAlgorithm) return ([1, 3]); if (obj.formats['auto']) return ([1, 2]); if (obj.formats['pkcs1']) return ([1, 1]); return ([1, 0]); }; /***/ }), /***/ 29602: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // Copyright 2017 Joyent, Inc. module.exports = PrivateKey; var assert = __nccwpck_require__(66631); var Buffer = (__nccwpck_require__(15118).Buffer); var algs = __nccwpck_require__(66126); var crypto = __nccwpck_require__(6113); var Fingerprint = __nccwpck_require__(13079); var Signature = __nccwpck_require__(91394); var errs = __nccwpck_require__(27979); var util = __nccwpck_require__(73837); var utils = __nccwpck_require__(80575); var dhe = __nccwpck_require__(57602); var generateECDSA = dhe.generateECDSA; var generateED25519 = dhe.generateED25519; var edCompat = __nccwpck_require__(14694); var nacl = __nccwpck_require__(68729); var Key = __nccwpck_require__(36814); var InvalidAlgorithmError = errs.InvalidAlgorithmError; var KeyParseError = errs.KeyParseError; var KeyEncryptedError = errs.KeyEncryptedError; var formats = {}; formats['auto'] = __nccwpck_require__(8243); formats['pem'] = __nccwpck_require__(14324); formats['pkcs1'] = __nccwpck_require__(69367); formats['pkcs8'] = __nccwpck_require__(4173); formats['rfc4253'] = __nccwpck_require__(88688); formats['ssh-private'] = __nccwpck_require__(3923); formats['openssh'] = formats['ssh-private']; formats['ssh'] = formats['ssh-private']; formats['dnssec'] = __nccwpck_require__(63561); formats['putty'] = __nccwpck_require__(80974); function PrivateKey(opts) { assert.object(opts, 'options'); Key.call(this, opts); this._pubCache = undefined; } util.inherits(PrivateKey, Key); PrivateKey.formats = formats; PrivateKey.prototype.toBuffer = function (format, options) { if (format === undefined) format = 'pkcs1'; assert.string(format, 'format'); assert.object(formats[format], 'formats[format]'); assert.optionalObject(options, 'options'); return (formats[format].write(this, options)); }; PrivateKey.prototype.hash = function (algo, type) { return (this.toPublic().hash(algo, type)); }; PrivateKey.prototype.fingerprint = function (algo, type) { return (this.toPublic().fingerprint(algo, type)); }; PrivateKey.prototype.toPublic = function () { if (this._pubCache) return (this._pubCache); var algInfo = algs.info[this.type]; var pubParts = []; for (var i = 0; i < algInfo.parts.length; ++i) { var p = algInfo.parts[i]; pubParts.push(this.part[p]); } this._pubCache = new Key({ type: this.type, source: this, parts: pubParts }); if (this.comment) this._pubCache.comment = this.comment; return (this._pubCache); }; PrivateKey.prototype.derive = function (newType) { assert.string(newType, 'type'); var priv, pub, pair; if (this.type === 'ed25519' && newType === 'curve25519') { priv = this.part.k.data; if (priv[0] === 0x00) priv = priv.slice(1); pair = nacl.box.keyPair.fromSecretKey(new Uint8Array(priv)); pub = Buffer.from(pair.publicKey); return (new PrivateKey({ type: 'curve25519', parts: [ { name: 'A', data: utils.mpNormalize(pub) }, { name: 'k', data: utils.mpNormalize(priv) } ] })); } else if (this.type === 'curve25519' && newType === 'ed25519') { priv = this.part.k.data; if (priv[0] === 0x00) priv = priv.slice(1); pair = nacl.sign.keyPair.fromSeed(new Uint8Array(priv)); pub = Buffer.from(pair.publicKey); return (new PrivateKey({ type: 'ed25519', parts: [ { name: 'A', data: utils.mpNormalize(pub) }, { name: 'k', data: utils.mpNormalize(priv) } ] })); } throw (new Error('Key derivation not supported from ' + this.type + ' to ' + newType)); }; PrivateKey.prototype.createVerify = function (hashAlgo) { return (this.toPublic().createVerify(hashAlgo)); }; PrivateKey.prototype.createSign = function (hashAlgo) { if (hashAlgo === undefined) hashAlgo = this.defaultHashAlgorithm(); assert.string(hashAlgo, 'hash algorithm'); /* ED25519 is not supported by OpenSSL, use a javascript impl. */ if (this.type === 'ed25519' && edCompat !== undefined) return (new edCompat.Signer(this, hashAlgo)); if (this.type === 'curve25519') throw (new Error('Curve25519 keys are not suitable for ' + 'signing or verification')); var v, nm, err; try { nm = hashAlgo.toUpperCase(); v = crypto.createSign(nm); } catch (e) { err = e; } if (v === undefined || (err instanceof Error && err.message.match(/Unknown message digest/))) { nm = 'RSA-'; nm += hashAlgo.toUpperCase(); v = crypto.createSign(nm); } assert.ok(v, 'failed to create verifier'); var oldSign = v.sign.bind(v); var key = this.toBuffer('pkcs1'); var type = this.type; var curve = this.curve; v.sign = function () { var sig = oldSign(key); if (typeof (sig) === 'string') sig = Buffer.from(sig, 'binary'); sig = Signature.parse(sig, type, 'asn1'); sig.hashAlgorithm = hashAlgo; sig.curve = curve; return (sig); }; return (v); }; PrivateKey.parse = function (data, format, options) { if (typeof (data) !== 'string') assert.buffer(data, 'data'); if (format === undefined) format = 'auto'; assert.string(format, 'format'); if (typeof (options) === 'string') options = { filename: options }; assert.optionalObject(options, 'options'); if (options === undefined) options = {}; assert.optionalString(options.filename, 'options.filename'); if (options.filename === undefined) options.filename = '(unnamed)'; assert.object(formats[format], 'formats[format]'); try { var k = formats[format].read(data, options); assert.ok(k instanceof PrivateKey, 'key is not a private key'); if (!k.comment) k.comment = options.filename; return (k); } catch (e) { if (e.name === 'KeyEncryptedError') throw (e); throw (new KeyParseError(options.filename, format, e)); } }; PrivateKey.isPrivateKey = function (obj, ver) { return (utils.isCompatible(obj, PrivateKey, ver)); }; PrivateKey.generate = function (type, options) { if (options === undefined) options = {}; assert.object(options, 'options'); switch (type) { case 'ecdsa': if (options.curve === undefined) options.curve = 'nistp256'; assert.string(options.curve, 'options.curve'); return (generateECDSA(options.curve)); case 'ed25519': return (generateED25519()); default: throw (new Error('Key generation not supported with key ' + 'type "' + type + '"')); } }; /* * API versions for PrivateKey: * [1,0] -- initial ver * [1,1] -- added auto, pkcs[18], openssh/ssh-private formats * [1,2] -- added defaultHashAlgorithm * [1,3] -- added derive, ed, createDH * [1,4] -- first tagged version * [1,5] -- changed ed25519 part names and format * [1,6] -- type arguments for hash() and fingerprint() */ PrivateKey.prototype._sshpkApiVersion = [1, 6]; PrivateKey._oldVersionDetect = function (obj) { assert.func(obj.toPublic); assert.func(obj.createSign); if (obj.derive) return ([1, 3]); if (obj.defaultHashAlgorithm) return ([1, 2]); if (obj.formats['auto']) return ([1, 1]); return ([1, 0]); }; /***/ }), /***/ 91394: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // Copyright 2015 Joyent, Inc. module.exports = Signature; var assert = __nccwpck_require__(66631); var Buffer = (__nccwpck_require__(15118).Buffer); var algs = __nccwpck_require__(66126); var crypto = __nccwpck_require__(6113); var errs = __nccwpck_require__(27979); var utils = __nccwpck_require__(80575); var asn1 = __nccwpck_require__(80970); var SSHBuffer = __nccwpck_require__(25621); var InvalidAlgorithmError = errs.InvalidAlgorithmError; var SignatureParseError = errs.SignatureParseError; function Signature(opts) { assert.object(opts, 'options'); assert.arrayOfObject(opts.parts, 'options.parts'); assert.string(opts.type, 'options.type'); var partLookup = {}; for (var i = 0; i < opts.parts.length; ++i) { var part = opts.parts[i]; partLookup[part.name] = part; } this.type = opts.type; this.hashAlgorithm = opts.hashAlgo; this.curve = opts.curve; this.parts = opts.parts; this.part = partLookup; } Signature.prototype.toBuffer = function (format) { if (format === undefined) format = 'asn1'; assert.string(format, 'format'); var buf; var stype = 'ssh-' + this.type; switch (this.type) { case 'rsa': switch (this.hashAlgorithm) { case 'sha256': stype = 'rsa-sha2-256'; break; case 'sha512': stype = 'rsa-sha2-512'; break; case 'sha1': case undefined: break; default: throw (new Error('SSH signature ' + 'format does not support hash ' + 'algorithm ' + this.hashAlgorithm)); } if (format === 'ssh') { buf = new SSHBuffer({}); buf.writeString(stype); buf.writePart(this.part.sig); return (buf.toBuffer()); } else { return (this.part.sig.data); } break; case 'ed25519': if (format === 'ssh') { buf = new SSHBuffer({}); buf.writeString(stype); buf.writePart(this.part.sig); return (buf.toBuffer()); } else { return (this.part.sig.data); } break; case 'dsa': case 'ecdsa': var r, s; if (format === 'asn1') { var der = new asn1.BerWriter(); der.startSequence(); r = utils.mpNormalize(this.part.r.data); s = utils.mpNormalize(this.part.s.data); der.writeBuffer(r, asn1.Ber.Integer); der.writeBuffer(s, asn1.Ber.Integer); der.endSequence(); return (der.buffer); } else if (format === 'ssh' && this.type === 'dsa') { buf = new SSHBuffer({}); buf.writeString('ssh-dss'); r = this.part.r.data; if (r.length > 20 && r[0] === 0x00) r = r.slice(1); s = this.part.s.data; if (s.length > 20 && s[0] === 0x00) s = s.slice(1); if ((this.hashAlgorithm && this.hashAlgorithm !== 'sha1') || r.length + s.length !== 40) { throw (new Error('OpenSSH only supports ' + 'DSA signatures with SHA1 hash')); } buf.writeBuffer(Buffer.concat([r, s])); return (buf.toBuffer()); } else if (format === 'ssh' && this.type === 'ecdsa') { var inner = new SSHBuffer({}); r = this.part.r.data; inner.writeBuffer(r); inner.writePart(this.part.s); buf = new SSHBuffer({}); /* XXX: find a more proper way to do this? */ var curve; if (r[0] === 0x00) r = r.slice(1); var sz = r.length * 8; if (sz === 256) curve = 'nistp256'; else if (sz === 384) curve = 'nistp384'; else if (sz === 528) curve = 'nistp521'; buf.writeString('ecdsa-sha2-' + curve); buf.writeBuffer(inner.toBuffer()); return (buf.toBuffer()); } throw (new Error('Invalid signature format')); default: throw (new Error('Invalid signature data')); } }; Signature.prototype.toString = function (format) { assert.optionalString(format, 'format'); return (this.toBuffer(format).toString('base64')); }; Signature.parse = function (data, type, format) { if (typeof (data) === 'string') data = Buffer.from(data, 'base64'); assert.buffer(data, 'data'); assert.string(format, 'format'); assert.string(type, 'type'); var opts = {}; opts.type = type.toLowerCase(); opts.parts = []; try { assert.ok(data.length > 0, 'signature must not be empty'); switch (opts.type) { case 'rsa': return (parseOneNum(data, type, format, opts)); case 'ed25519': return (parseOneNum(data, type, format, opts)); case 'dsa': case 'ecdsa': if (format === 'asn1') return (parseDSAasn1(data, type, format, opts)); else if (opts.type === 'dsa') return (parseDSA(data, type, format, opts)); else return (parseECDSA(data, type, format, opts)); default: throw (new InvalidAlgorithmError(type)); } } catch (e) { if (e instanceof InvalidAlgorithmError) throw (e); throw (new SignatureParseError(type, format, e)); } }; function parseOneNum(data, type, format, opts) { if (format === 'ssh') { try { var buf = new SSHBuffer({buffer: data}); var head = buf.readString(); } catch (e) { /* fall through */ } if (buf !== undefined) { var msg = 'SSH signature does not match expected ' + 'type (expected ' + type + ', got ' + head + ')'; switch (head) { case 'ssh-rsa': assert.strictEqual(type, 'rsa', msg); opts.hashAlgo = 'sha1'; break; case 'rsa-sha2-256': assert.strictEqual(type, 'rsa', msg); opts.hashAlgo = 'sha256'; break; case 'rsa-sha2-512': assert.strictEqual(type, 'rsa', msg); opts.hashAlgo = 'sha512'; break; case 'ssh-ed25519': assert.strictEqual(type, 'ed25519', msg); opts.hashAlgo = 'sha512'; break; default: throw (new Error('Unknown SSH signature ' + 'type: ' + head)); } var sig = buf.readPart(); assert.ok(buf.atEnd(), 'extra trailing bytes'); sig.name = 'sig'; opts.parts.push(sig); return (new Signature(opts)); } } opts.parts.push({name: 'sig', data: data}); return (new Signature(opts)); } function parseDSAasn1(data, type, format, opts) { var der = new asn1.BerReader(data); der.readSequence(); var r = der.readString(asn1.Ber.Integer, true); var s = der.readString(asn1.Ber.Integer, true); opts.parts.push({name: 'r', data: utils.mpNormalize(r)}); opts.parts.push({name: 's', data: utils.mpNormalize(s)}); return (new Signature(opts)); } function parseDSA(data, type, format, opts) { if (data.length != 40) { var buf = new SSHBuffer({buffer: data}); var d = buf.readBuffer(); if (d.toString('ascii') === 'ssh-dss') d = buf.readBuffer(); assert.ok(buf.atEnd(), 'extra trailing bytes'); assert.strictEqual(d.length, 40, 'invalid inner length'); data = d; } opts.parts.push({name: 'r', data: data.slice(0, 20)}); opts.parts.push({name: 's', data: data.slice(20, 40)}); return (new Signature(opts)); } function parseECDSA(data, type, format, opts) { var buf = new SSHBuffer({buffer: data}); var r, s; var inner = buf.readBuffer(); var stype = inner.toString('ascii'); if (stype.slice(0, 6) === 'ecdsa-') { var parts = stype.split('-'); assert.strictEqual(parts[0], 'ecdsa'); assert.strictEqual(parts[1], 'sha2'); opts.curve = parts[2]; switch (opts.curve) { case 'nistp256': opts.hashAlgo = 'sha256'; break; case 'nistp384': opts.hashAlgo = 'sha384'; break; case 'nistp521': opts.hashAlgo = 'sha512'; break; default: throw (new Error('Unsupported ECDSA curve: ' + opts.curve)); } inner = buf.readBuffer(); assert.ok(buf.atEnd(), 'extra trailing bytes on outer'); buf = new SSHBuffer({buffer: inner}); r = buf.readPart(); } else { r = {data: inner}; } s = buf.readPart(); assert.ok(buf.atEnd(), 'extra trailing bytes'); r.name = 'r'; s.name = 's'; opts.parts.push(r); opts.parts.push(s); return (new Signature(opts)); } Signature.isSignature = function (obj, ver) { return (utils.isCompatible(obj, Signature, ver)); }; /* * API versions for Signature: * [1,0] -- initial ver * [2,0] -- support for rsa in full ssh format, compat with sshpk-agent * hashAlgorithm property * [2,1] -- first tagged version */ Signature.prototype._sshpkApiVersion = [2, 1]; Signature._oldVersionDetect = function (obj) { assert.func(obj.toBuffer); if (obj.hasOwnProperty('hashAlgorithm')) return ([2, 0]); return ([1, 0]); }; /***/ }), /***/ 25621: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // Copyright 2015 Joyent, Inc. module.exports = SSHBuffer; var assert = __nccwpck_require__(66631); var Buffer = (__nccwpck_require__(15118).Buffer); function SSHBuffer(opts) { assert.object(opts, 'options'); if (opts.buffer !== undefined) assert.buffer(opts.buffer, 'options.buffer'); this._size = opts.buffer ? opts.buffer.length : 1024; this._buffer = opts.buffer || Buffer.alloc(this._size); this._offset = 0; } SSHBuffer.prototype.toBuffer = function () { return (this._buffer.slice(0, this._offset)); }; SSHBuffer.prototype.atEnd = function () { return (this._offset >= this._buffer.length); }; SSHBuffer.prototype.remainder = function () { return (this._buffer.slice(this._offset)); }; SSHBuffer.prototype.skip = function (n) { this._offset += n; }; SSHBuffer.prototype.expand = function () { this._size *= 2; var buf = Buffer.alloc(this._size); this._buffer.copy(buf, 0); this._buffer = buf; }; SSHBuffer.prototype.readPart = function () { return ({data: this.readBuffer()}); }; SSHBuffer.prototype.readBuffer = function () { var len = this._buffer.readUInt32BE(this._offset); this._offset += 4; assert.ok(this._offset + len <= this._buffer.length, 'length out of bounds at +0x' + this._offset.toString(16) + ' (data truncated?)'); var buf = this._buffer.slice(this._offset, this._offset + len); this._offset += len; return (buf); }; SSHBuffer.prototype.readString = function () { return (this.readBuffer().toString()); }; SSHBuffer.prototype.readCString = function () { var offset = this._offset; while (offset < this._buffer.length && this._buffer[offset] !== 0x00) offset++; assert.ok(offset < this._buffer.length, 'c string does not terminate'); var str = this._buffer.slice(this._offset, offset).toString(); this._offset = offset + 1; return (str); }; SSHBuffer.prototype.readInt = function () { var v = this._buffer.readUInt32BE(this._offset); this._offset += 4; return (v); }; SSHBuffer.prototype.readInt64 = function () { assert.ok(this._offset + 8 < this._buffer.length, 'buffer not long enough to read Int64'); var v = this._buffer.slice(this._offset, this._offset + 8); this._offset += 8; return (v); }; SSHBuffer.prototype.readChar = function () { var v = this._buffer[this._offset++]; return (v); }; SSHBuffer.prototype.writeBuffer = function (buf) { while (this._offset + 4 + buf.length > this._size) this.expand(); this._buffer.writeUInt32BE(buf.length, this._offset); this._offset += 4; buf.copy(this._buffer, this._offset); this._offset += buf.length; }; SSHBuffer.prototype.writeString = function (str) { this.writeBuffer(Buffer.from(str, 'utf8')); }; SSHBuffer.prototype.writeCString = function (str) { while (this._offset + 1 + str.length > this._size) this.expand(); this._buffer.write(str, this._offset); this._offset += str.length; this._buffer[this._offset++] = 0; }; SSHBuffer.prototype.writeInt = function (v) { while (this._offset + 4 > this._size) this.expand(); this._buffer.writeUInt32BE(v, this._offset); this._offset += 4; }; SSHBuffer.prototype.writeInt64 = function (v) { assert.buffer(v, 'value'); if (v.length > 8) { var lead = v.slice(0, v.length - 8); for (var i = 0; i < lead.length; ++i) { assert.strictEqual(lead[i], 0, 'must fit in 64 bits of precision'); } v = v.slice(v.length - 8, v.length); } while (this._offset + 8 > this._size) this.expand(); v.copy(this._buffer, this._offset); this._offset += 8; }; SSHBuffer.prototype.writeChar = function (v) { while (this._offset + 1 > this._size) this.expand(); this._buffer[this._offset++] = v; }; SSHBuffer.prototype.writePart = function (p) { this.writeBuffer(p.data); }; SSHBuffer.prototype.write = function (buf) { while (this._offset + buf.length > this._size) this.expand(); buf.copy(this._buffer, this._offset); this._offset += buf.length; }; /***/ }), /***/ 80575: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // Copyright 2015 Joyent, Inc. module.exports = { bufferSplit: bufferSplit, addRSAMissing: addRSAMissing, calculateDSAPublic: calculateDSAPublic, calculateED25519Public: calculateED25519Public, calculateX25519Public: calculateX25519Public, mpNormalize: mpNormalize, mpDenormalize: mpDenormalize, ecNormalize: ecNormalize, countZeros: countZeros, assertCompatible: assertCompatible, isCompatible: isCompatible, opensslKeyDeriv: opensslKeyDeriv, opensshCipherInfo: opensshCipherInfo, publicFromPrivateECDSA: publicFromPrivateECDSA, zeroPadToLength: zeroPadToLength, writeBitString: writeBitString, readBitString: readBitString, pbkdf2: pbkdf2 }; var assert = __nccwpck_require__(66631); var Buffer = (__nccwpck_require__(15118).Buffer); var PrivateKey = __nccwpck_require__(29602); var Key = __nccwpck_require__(36814); var crypto = __nccwpck_require__(6113); var algs = __nccwpck_require__(66126); var asn1 = __nccwpck_require__(80970); var ec = __nccwpck_require__(3943); var jsbn = (__nccwpck_require__(85587).BigInteger); var nacl = __nccwpck_require__(68729); var MAX_CLASS_DEPTH = 3; function isCompatible(obj, klass, needVer) { if (obj === null || typeof (obj) !== 'object') return (false); if (needVer === undefined) needVer = klass.prototype._sshpkApiVersion; if (obj instanceof klass && klass.prototype._sshpkApiVersion[0] == needVer[0]) return (true); var proto = Object.getPrototypeOf(obj); var depth = 0; while (proto.constructor.name !== klass.name) { proto = Object.getPrototypeOf(proto); if (!proto || ++depth > MAX_CLASS_DEPTH) return (false); } if (proto.constructor.name !== klass.name) return (false); var ver = proto._sshpkApiVersion; if (ver === undefined) ver = klass._oldVersionDetect(obj); if (ver[0] != needVer[0] || ver[1] < needVer[1]) return (false); return (true); } function assertCompatible(obj, klass, needVer, name) { if (name === undefined) name = 'object'; assert.ok(obj, name + ' must not be null'); assert.object(obj, name + ' must be an object'); if (needVer === undefined) needVer = klass.prototype._sshpkApiVersion; if (obj instanceof klass && klass.prototype._sshpkApiVersion[0] == needVer[0]) return; var proto = Object.getPrototypeOf(obj); var depth = 0; while (proto.constructor.name !== klass.name) { proto = Object.getPrototypeOf(proto); assert.ok(proto && ++depth <= MAX_CLASS_DEPTH, name + ' must be a ' + klass.name + ' instance'); } assert.strictEqual(proto.constructor.name, klass.name, name + ' must be a ' + klass.name + ' instance'); var ver = proto._sshpkApiVersion; if (ver === undefined) ver = klass._oldVersionDetect(obj); assert.ok(ver[0] == needVer[0] && ver[1] >= needVer[1], name + ' must be compatible with ' + klass.name + ' klass ' + 'version ' + needVer[0] + '.' + needVer[1]); } var CIPHER_LEN = { 'des-ede3-cbc': { key: 24, iv: 8 }, 'aes-128-cbc': { key: 16, iv: 16 }, 'aes-256-cbc': { key: 32, iv: 16 } }; var PKCS5_SALT_LEN = 8; function opensslKeyDeriv(cipher, salt, passphrase, count) { assert.buffer(salt, 'salt'); assert.buffer(passphrase, 'passphrase'); assert.number(count, 'iteration count'); var clen = CIPHER_LEN[cipher]; assert.object(clen, 'supported cipher'); salt = salt.slice(0, PKCS5_SALT_LEN); var D, D_prev, bufs; var material = Buffer.alloc(0); while (material.length < clen.key + clen.iv) { bufs = []; if (D_prev) bufs.push(D_prev); bufs.push(passphrase); bufs.push(salt); D = Buffer.concat(bufs); for (var j = 0; j < count; ++j) D = crypto.createHash('md5').update(D).digest(); material = Buffer.concat([material, D]); D_prev = D; } return ({ key: material.slice(0, clen.key), iv: material.slice(clen.key, clen.key + clen.iv) }); } /* See: RFC2898 */ function pbkdf2(hashAlg, salt, iterations, size, passphrase) { var hkey = Buffer.alloc(salt.length + 4); salt.copy(hkey); var gen = 0, ts = []; var i = 1; while (gen < size) { var t = T(i++); gen += t.length; ts.push(t); } return (Buffer.concat(ts).slice(0, size)); function T(I) { hkey.writeUInt32BE(I, hkey.length - 4); var hmac = crypto.createHmac(hashAlg, passphrase); hmac.update(hkey); var Ti = hmac.digest(); var Uc = Ti; var c = 1; while (c++ < iterations) { hmac = crypto.createHmac(hashAlg, passphrase); hmac.update(Uc); Uc = hmac.digest(); for (var x = 0; x < Ti.length; ++x) Ti[x] ^= Uc[x]; } return (Ti); } } /* Count leading zero bits on a buffer */ function countZeros(buf) { var o = 0, obit = 8; while (o < buf.length) { var mask = (1 << obit); if ((buf[o] & mask) === mask) break; obit--; if (obit < 0) { o++; obit = 8; } } return (o*8 + (8 - obit) - 1); } function bufferSplit(buf, chr) { assert.buffer(buf); assert.string(chr); var parts = []; var lastPart = 0; var matches = 0; for (var i = 0; i < buf.length; ++i) { if (buf[i] === chr.charCodeAt(matches)) ++matches; else if (buf[i] === chr.charCodeAt(0)) matches = 1; else matches = 0; if (matches >= chr.length) { var newPart = i + 1; parts.push(buf.slice(lastPart, newPart - matches)); lastPart = newPart; matches = 0; } } if (lastPart <= buf.length) parts.push(buf.slice(lastPart, buf.length)); return (parts); } function ecNormalize(buf, addZero) { assert.buffer(buf); if (buf[0] === 0x00 && buf[1] === 0x04) { if (addZero) return (buf); return (buf.slice(1)); } else if (buf[0] === 0x04) { if (!addZero) return (buf); } else { while (buf[0] === 0x00) buf = buf.slice(1); if (buf[0] === 0x02 || buf[0] === 0x03) throw (new Error('Compressed elliptic curve points ' + 'are not supported')); if (buf[0] !== 0x04) throw (new Error('Not a valid elliptic curve point')); if (!addZero) return (buf); } var b = Buffer.alloc(buf.length + 1); b[0] = 0x0; buf.copy(b, 1); return (b); } function readBitString(der, tag) { if (tag === undefined) tag = asn1.Ber.BitString; var buf = der.readString(tag, true); assert.strictEqual(buf[0], 0x00, 'bit strings with unused bits are ' + 'not supported (0x' + buf[0].toString(16) + ')'); return (buf.slice(1)); } function writeBitString(der, buf, tag) { if (tag === undefined) tag = asn1.Ber.BitString; var b = Buffer.alloc(buf.length + 1); b[0] = 0x00; buf.copy(b, 1); der.writeBuffer(b, tag); } function mpNormalize(buf) { assert.buffer(buf); while (buf.length > 1 && buf[0] === 0x00 && (buf[1] & 0x80) === 0x00) buf = buf.slice(1); if ((buf[0] & 0x80) === 0x80) { var b = Buffer.alloc(buf.length + 1); b[0] = 0x00; buf.copy(b, 1); buf = b; } return (buf); } function mpDenormalize(buf) { assert.buffer(buf); while (buf.length > 1 && buf[0] === 0x00) buf = buf.slice(1); return (buf); } function zeroPadToLength(buf, len) { assert.buffer(buf); assert.number(len); while (buf.length > len) { assert.equal(buf[0], 0x00); buf = buf.slice(1); } while (buf.length < len) { var b = Buffer.alloc(buf.length + 1); b[0] = 0x00; buf.copy(b, 1); buf = b; } return (buf); } function bigintToMpBuf(bigint) { var buf = Buffer.from(bigint.toByteArray()); buf = mpNormalize(buf); return (buf); } function calculateDSAPublic(g, p, x) { assert.buffer(g); assert.buffer(p); assert.buffer(x); g = new jsbn(g); p = new jsbn(p); x = new jsbn(x); var y = g.modPow(x, p); var ybuf = bigintToMpBuf(y); return (ybuf); } function calculateED25519Public(k) { assert.buffer(k); var kp = nacl.sign.keyPair.fromSeed(new Uint8Array(k)); return (Buffer.from(kp.publicKey)); } function calculateX25519Public(k) { assert.buffer(k); var kp = nacl.box.keyPair.fromSeed(new Uint8Array(k)); return (Buffer.from(kp.publicKey)); } function addRSAMissing(key) { assert.object(key); assertCompatible(key, PrivateKey, [1, 1]); var d = new jsbn(key.part.d.data); var buf; if (!key.part.dmodp) { var p = new jsbn(key.part.p.data); var dmodp = d.mod(p.subtract(1)); buf = bigintToMpBuf(dmodp); key.part.dmodp = {name: 'dmodp', data: buf}; key.parts.push(key.part.dmodp); } if (!key.part.dmodq) { var q = new jsbn(key.part.q.data); var dmodq = d.mod(q.subtract(1)); buf = bigintToMpBuf(dmodq); key.part.dmodq = {name: 'dmodq', data: buf}; key.parts.push(key.part.dmodq); } } function publicFromPrivateECDSA(curveName, priv) { assert.string(curveName, 'curveName'); assert.buffer(priv); var params = algs.curves[curveName]; var p = new jsbn(params.p); var a = new jsbn(params.a); var b = new jsbn(params.b); var curve = new ec.ECCurveFp(p, a, b); var G = curve.decodePointHex(params.G.toString('hex')); var d = new jsbn(mpNormalize(priv)); var pub = G.multiply(d); pub = Buffer.from(curve.encodePointHex(pub), 'hex'); var parts = []; parts.push({name: 'curve', data: Buffer.from(curveName)}); parts.push({name: 'Q', data: pub}); var key = new Key({type: 'ecdsa', curve: curve, parts: parts}); return (key); } function opensshCipherInfo(cipher) { var inf = {}; switch (cipher) { case '3des-cbc': inf.keySize = 24; inf.blockSize = 8; inf.opensslName = 'des-ede3-cbc'; break; case 'blowfish-cbc': inf.keySize = 16; inf.blockSize = 8; inf.opensslName = 'bf-cbc'; break; case 'aes128-cbc': case 'aes128-ctr': case 'aes128-gcm@openssh.com': inf.keySize = 16; inf.blockSize = 16; inf.opensslName = 'aes-128-' + cipher.slice(7, 10); break; case 'aes192-cbc': case 'aes192-ctr': case 'aes192-gcm@openssh.com': inf.keySize = 24; inf.blockSize = 16; inf.opensslName = 'aes-192-' + cipher.slice(7, 10); break; case 'aes256-cbc': case 'aes256-ctr': case 'aes256-gcm@openssh.com': inf.keySize = 32; inf.blockSize = 16; inf.opensslName = 'aes-256-' + cipher.slice(7, 10); break; default: throw (new Error( 'Unsupported openssl cipher "' + cipher + '"')); } return (inf); } /***/ }), /***/ 2619: /***/ ((module) => { "use strict"; module.exports = { DEFAULT_INITIAL_SIZE: (8 * 1024), DEFAULT_INCREMENT_AMOUNT: (8 * 1024), DEFAULT_FREQUENCY: 1, DEFAULT_CHUNK_SIZE: 1024 }; /***/ }), /***/ 18838: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var stream = __nccwpck_require__(12781); var constants = __nccwpck_require__(2619); var util = __nccwpck_require__(73837); var ReadableStreamBuffer = module.exports = function(opts) { var that = this; opts = opts || {}; stream.Readable.call(this, opts); this.stopped = false; var frequency = opts.hasOwnProperty('frequency') ? opts.frequency : constants.DEFAULT_FREQUENCY; var chunkSize = opts.chunkSize || constants.DEFAULT_CHUNK_SIZE; var initialSize = opts.initialSize || constants.DEFAULT_INITIAL_SIZE; var incrementAmount = opts.incrementAmount || constants.DEFAULT_INCREMENT_AMOUNT; var size = 0; var buffer = new Buffer(initialSize); var allowPush = false; var sendData = function() { var amount = Math.min(chunkSize, size); var sendMore = false; if (amount > 0) { var chunk = null; chunk = new Buffer(amount); buffer.copy(chunk, 0, 0, amount); sendMore = that.push(chunk) !== false; allowPush = sendMore; buffer.copy(buffer, 0, amount, size); size -= amount; } if(size === 0 && that.stopped) { that.push(null); } if (sendMore) { sendData.timeout = setTimeout(sendData, frequency); } else { sendData.timeout = null; } }; this.stop = function() { if (this.stopped) { throw new Error('stop() called on already stopped ReadableStreamBuffer'); } this.stopped = true; if (size === 0) { this.push(null); } }; this.size = function() { return size; }; this.maxSize = function() { return buffer.length; }; var increaseBufferIfNecessary = function(incomingDataSize) { if((buffer.length - size) < incomingDataSize) { var factor = Math.ceil((incomingDataSize - (buffer.length - size)) / incrementAmount); var newBuffer = new Buffer(buffer.length + (incrementAmount * factor)); buffer.copy(newBuffer, 0, 0, size); buffer = newBuffer; } }; var kickSendDataTask = function () { if (!sendData.timeout && allowPush) { sendData.timeout = setTimeout(sendData, frequency); } } this.put = function(data, encoding) { if (that.stopped) { throw new Error('Tried to write data to a stopped ReadableStreamBuffer'); } if(Buffer.isBuffer(data)) { increaseBufferIfNecessary(data.length); data.copy(buffer, size, 0); size += data.length; } else { data = data + ''; var dataSizeInBytes = Buffer.byteLength(data); increaseBufferIfNecessary(dataSizeInBytes); buffer.write(data, size, encoding || 'utf8'); size += dataSizeInBytes; } kickSendDataTask(); }; this._read = function() { allowPush = true; kickSendDataTask(); }; }; util.inherits(ReadableStreamBuffer, stream.Readable); /***/ }), /***/ 48168: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; module.exports = __nccwpck_require__(2619); module.exports.ReadableStreamBuffer = __nccwpck_require__(18838); module.exports.WritableStreamBuffer = __nccwpck_require__(86055); /***/ }), /***/ 86055: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var util = __nccwpck_require__(73837); var stream = __nccwpck_require__(12781); var constants = __nccwpck_require__(2619); var WritableStreamBuffer = module.exports = function(opts) { opts = opts || {}; opts.decodeStrings = true; stream.Writable.call(this, opts); var initialSize = opts.initialSize || constants.DEFAULT_INITIAL_SIZE; var incrementAmount = opts.incrementAmount || constants.DEFAULT_INCREMENT_AMOUNT; var buffer = new Buffer(initialSize); var size = 0; this.size = function() { return size; }; this.maxSize = function() { return buffer.length; }; this.getContents = function(length) { if(!size) return false; var data = new Buffer(Math.min(length || size, size)); buffer.copy(data, 0, 0, data.length); if(data.length < size) buffer.copy(buffer, 0, data.length); size -= data.length; return data; }; this.getContentsAsString = function(encoding, length) { if(!size) return false; var data = buffer.toString(encoding || 'utf8', 0, Math.min(length || size, size)); var dataLength = Buffer.byteLength(data); if(dataLength < size) buffer.copy(buffer, 0, dataLength); size -= dataLength; return data; }; var increaseBufferIfNecessary = function(incomingDataSize) { if((buffer.length - size) < incomingDataSize) { var factor = Math.ceil((incomingDataSize - (buffer.length - size)) / incrementAmount); var newBuffer = new Buffer(buffer.length + (incrementAmount * factor)); buffer.copy(newBuffer, 0, 0, size); buffer = newBuffer; } }; this._write = function(chunk, encoding, callback) { increaseBufferIfNecessary(chunk.length); chunk.copy(buffer, size, 0); size += chunk.length; callback(); }; }; util.inherits(WritableStreamBuffer, stream.Writable); /***/ }), /***/ 88174: /***/ ((module) => { "use strict"; module.exports = input => { const LF = typeof input === 'string' ? '\n' : '\n'.charCodeAt(); const CR = typeof input === 'string' ? '\r' : '\r'.charCodeAt(); if (input[input.length - 1] === LF) { input = input.slice(0, input.length - 1); } if (input[input.length - 1] === CR) { input = input.slice(0, input.length - 1); } return input; }; /***/ }), /***/ 14526: /***/ ((module) => { const hexRegex = /^[-+]?0x[a-fA-F0-9]+$/; const numRegex = /^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/; // const octRegex = /^0x[a-z0-9]+/; // const binRegex = /0x[a-z0-9]+/; const consider = { hex : true, // oct: false, leadingZeros: true, decimalPoint: "\.", eNotation: true, //skipLike: /regex/ }; function toNumber(str, options = {}){ options = Object.assign({}, consider, options ); if(!str || typeof str !== "string" ) return str; let trimmedStr = str.trim(); if(options.skipLike !== undefined && options.skipLike.test(trimmedStr)) return str; else if(str==="0") return 0; else if (options.hex && hexRegex.test(trimmedStr)) { return parse_int(trimmedStr, 16); // }else if (options.oct && octRegex.test(str)) { // return Number.parseInt(val, 8); }else if (trimmedStr.search(/[eE]/)!== -1) { //eNotation const notation = trimmedStr.match(/^([-\+])?(0*)([0-9]*(\.[0-9]*)?[eE][-\+]?[0-9]+)$/); // +00.123 => [ , '+', '00', '.123', .. if(notation){ // console.log(notation) if(options.leadingZeros){ //accept with leading zeros trimmedStr = (notation[1] || "") + notation[3]; }else{ if(notation[2] === "0" && notation[3][0]=== "."){ //valid number }else{ return str; } } return options.eNotation ? Number(trimmedStr) : str; }else{ return str; } // }else if (options.parseBin && binRegex.test(str)) { // return Number.parseInt(val, 2); }else{ //separate negative sign, leading zeros, and rest number const match = numRegex.exec(trimmedStr); // +00.123 => [ , '+', '00', '.123', .. if(match){ const sign = match[1]; const leadingZeros = match[2]; let numTrimmedByZeros = trimZeros(match[3]); //complete num without leading zeros //trim ending zeros for floating number if(!options.leadingZeros && leadingZeros.length > 0 && sign && trimmedStr[2] !== ".") return str; //-0123 else if(!options.leadingZeros && leadingZeros.length > 0 && !sign && trimmedStr[1] !== ".") return str; //0123 else if(options.leadingZeros && leadingZeros===str) return 0; //00 else{//no leading zeros or leading zeros are allowed const num = Number(trimmedStr); const numStr = "" + num; if(numStr.search(/[eE]/) !== -1){ //given number is long and parsed to eNotation if(options.eNotation) return num; else return str; }else if(trimmedStr.indexOf(".") !== -1){ //floating number if(numStr === "0" && (numTrimmedByZeros === "") ) return num; //0.0 else if(numStr === numTrimmedByZeros) return num; //0.456. 0.79000 else if( sign && numStr === "-"+numTrimmedByZeros) return num; else return str; } if(leadingZeros){ return (numTrimmedByZeros === numStr) || (sign+numTrimmedByZeros === numStr) ? num : str }else { return (trimmedStr === numStr) || (trimmedStr === sign+numStr) ? num : str } } }else{ //non-numeric string return str; } } } /** * * @param {string} numStr without leading zeros * @returns */ function trimZeros(numStr){ if(numStr && numStr.indexOf(".") !== -1){//float numStr = numStr.replace(/0+$/, ""); //remove ending zeros if(numStr === ".") numStr = "0"; else if(numStr[0] === ".") numStr = "0"+numStr; else if(numStr[numStr.length-1] === ".") numStr = numStr.substr(0,numStr.length-1); return numStr; } return numStr; } function parse_int(numStr, base){ //polyfill if(parseInt) return parseInt(numStr, base); else if(Number.parseInt) return Number.parseInt(numStr, base); else if(window && window.parseInt) return window.parseInt(numStr, base); else throw new Error("parseInt, Number.parseInt, window.parseInt are not supported") } module.exports = toNumber; /***/ }), /***/ 74674: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // high-level commands exports.c = exports.create = __nccwpck_require__(44016) exports.r = exports.replace = __nccwpck_require__(45923) exports.t = exports.list = __nccwpck_require__(51525) exports.u = exports.update = __nccwpck_require__(94404) exports.x = exports.extract = __nccwpck_require__(75317) // classes exports.Pack = __nccwpck_require__(7900) exports.Unpack = __nccwpck_require__(17628) exports.Parse = __nccwpck_require__(68917) exports.ReadEntry = __nccwpck_require__(38116) exports.WriteEntry = __nccwpck_require__(55450) exports.Header = __nccwpck_require__(66043) exports.Pax = __nccwpck_require__(77996) exports.types = __nccwpck_require__(24173) /***/ }), /***/ 44016: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // tar -c const hlo = __nccwpck_require__(95274) const Pack = __nccwpck_require__(7900) const fsm = __nccwpck_require__(27714) const t = __nccwpck_require__(51525) const path = __nccwpck_require__(71017) module.exports = (opt_, files, cb) => { if (typeof files === 'function') { cb = files } if (Array.isArray(opt_)) { files = opt_, opt_ = {} } if (!files || !Array.isArray(files) || !files.length) { throw new TypeError('no files or directories specified') } files = Array.from(files) const opt = hlo(opt_) if (opt.sync && typeof cb === 'function') { throw new TypeError('callback not supported for sync tar functions') } if (!opt.file && typeof cb === 'function') { throw new TypeError('callback only supported with file option') } return opt.file && opt.sync ? createFileSync(opt, files) : opt.file ? createFile(opt, files, cb) : opt.sync ? createSync(opt, files) : create(opt, files) } const createFileSync = (opt, files) => { const p = new Pack.Sync(opt) const stream = new fsm.WriteStreamSync(opt.file, { mode: opt.mode || 0o666, }) p.pipe(stream) addFilesSync(p, files) } const createFile = (opt, files, cb) => { const p = new Pack(opt) const stream = new fsm.WriteStream(opt.file, { mode: opt.mode || 0o666, }) p.pipe(stream) const promise = new Promise((res, rej) => { stream.on('error', rej) stream.on('close', res) p.on('error', rej) }) addFilesAsync(p, files) return cb ? promise.then(cb, cb) : promise } const addFilesSync = (p, files) => { files.forEach(file => { if (file.charAt(0) === '@') { t({ file: path.resolve(p.cwd, file.slice(1)), sync: true, noResume: true, onentry: entry => p.add(entry), }) } else { p.add(file) } }) p.end() } const addFilesAsync = (p, files) => { while (files.length) { const file = files.shift() if (file.charAt(0) === '@') { return t({ file: path.resolve(p.cwd, file.slice(1)), noResume: true, onentry: entry => p.add(entry), }).then(_ => addFilesAsync(p, files)) } else { p.add(file) } } p.end() } const createSync = (opt, files) => { const p = new Pack.Sync(opt) addFilesSync(p, files) return p } const create = (opt, files) => { const p = new Pack(opt) addFilesAsync(p, files) return p } /***/ }), /***/ 75317: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // tar -x const hlo = __nccwpck_require__(95274) const Unpack = __nccwpck_require__(17628) const fs = __nccwpck_require__(57147) const fsm = __nccwpck_require__(27714) const path = __nccwpck_require__(71017) const stripSlash = __nccwpck_require__(88886) module.exports = (opt_, files, cb) => { if (typeof opt_ === 'function') { cb = opt_, files = null, opt_ = {} } else if (Array.isArray(opt_)) { files = opt_, opt_ = {} } if (typeof files === 'function') { cb = files, files = null } if (!files) { files = [] } else { files = Array.from(files) } const opt = hlo(opt_) if (opt.sync && typeof cb === 'function') { throw new TypeError('callback not supported for sync tar functions') } if (!opt.file && typeof cb === 'function') { throw new TypeError('callback only supported with file option') } if (files.length) { filesFilter(opt, files) } return opt.file && opt.sync ? extractFileSync(opt) : opt.file ? extractFile(opt, cb) : opt.sync ? extractSync(opt) : extract(opt) } // construct a filter that limits the file entries listed // include child entries if a dir is included const filesFilter = (opt, files) => { const map = new Map(files.map(f => [stripSlash(f), true])) const filter = opt.filter const mapHas = (file, r) => { const root = r || path.parse(file).root || '.' const ret = file === root ? false : map.has(file) ? map.get(file) : mapHas(path.dirname(file), root) map.set(file, ret) return ret } opt.filter = filter ? (file, entry) => filter(file, entry) && mapHas(stripSlash(file)) : file => mapHas(stripSlash(file)) } const extractFileSync = opt => { const u = new Unpack.Sync(opt) const file = opt.file const stat = fs.statSync(file) // This trades a zero-byte read() syscall for a stat // However, it will usually result in less memory allocation const readSize = opt.maxReadSize || 16 * 1024 * 1024 const stream = new fsm.ReadStreamSync(file, { readSize: readSize, size: stat.size, }) stream.pipe(u) } const extractFile = (opt, cb) => { const u = new Unpack(opt) const readSize = opt.maxReadSize || 16 * 1024 * 1024 const file = opt.file const p = new Promise((resolve, reject) => { u.on('error', reject) u.on('close', resolve) // This trades a zero-byte read() syscall for a stat // However, it will usually result in less memory allocation fs.stat(file, (er, stat) => { if (er) { reject(er) } else { const stream = new fsm.ReadStream(file, { readSize: readSize, size: stat.size, }) stream.on('error', reject) stream.pipe(u) } }) }) return cb ? p.then(cb, cb) : p } const extractSync = opt => new Unpack.Sync(opt) const extract = opt => new Unpack(opt) /***/ }), /***/ 91172: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // Get the appropriate flag to use for creating files // We use fmap on Windows platforms for files less than // 512kb. This is a fairly low limit, but avoids making // things slower in some cases. Since most of what this // library is used for is extracting tarballs of many // relatively small files in npm packages and the like, // it can be a big boost on Windows platforms. // Only supported in Node v12.9.0 and above. const platform = process.env.__FAKE_PLATFORM__ || process.platform const isWindows = platform === 'win32' const fs = global.__FAKE_TESTING_FS__ || __nccwpck_require__(57147) /* istanbul ignore next */ const { O_CREAT, O_TRUNC, O_WRONLY, UV_FS_O_FILEMAP = 0 } = fs.constants const fMapEnabled = isWindows && !!UV_FS_O_FILEMAP const fMapLimit = 512 * 1024 const fMapFlag = UV_FS_O_FILEMAP | O_TRUNC | O_CREAT | O_WRONLY module.exports = !fMapEnabled ? () => 'w' : size => size < fMapLimit ? fMapFlag : 'w' /***/ }), /***/ 66043: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // parse a 512-byte header block to a data object, or vice-versa // encode returns `true` if a pax extended header is needed, because // the data could not be faithfully encoded in a simple header. // (Also, check header.needPax to see if it needs a pax header.) const types = __nccwpck_require__(24173) const pathModule = (__nccwpck_require__(71017).posix) const large = __nccwpck_require__(52370) const SLURP = Symbol('slurp') const TYPE = Symbol('type') class Header { constructor (data, off, ex, gex) { this.cksumValid = false this.needPax = false this.nullBlock = false this.block = null this.path = null this.mode = null this.uid = null this.gid = null this.size = null this.mtime = null this.cksum = null this[TYPE] = '0' this.linkpath = null this.uname = null this.gname = null this.devmaj = 0 this.devmin = 0 this.atime = null this.ctime = null if (Buffer.isBuffer(data)) { this.decode(data, off || 0, ex, gex) } else if (data) { this.set(data) } } decode (buf, off, ex, gex) { if (!off) { off = 0 } if (!buf || !(buf.length >= off + 512)) { throw new Error('need 512 bytes for header') } this.path = decString(buf, off, 100) this.mode = decNumber(buf, off + 100, 8) this.uid = decNumber(buf, off + 108, 8) this.gid = decNumber(buf, off + 116, 8) this.size = decNumber(buf, off + 124, 12) this.mtime = decDate(buf, off + 136, 12) this.cksum = decNumber(buf, off + 148, 12) // if we have extended or global extended headers, apply them now // See https://github.com/npm/node-tar/pull/187 this[SLURP](ex) this[SLURP](gex, true) // old tar versions marked dirs as a file with a trailing / this[TYPE] = decString(buf, off + 156, 1) if (this[TYPE] === '') { this[TYPE] = '0' } if (this[TYPE] === '0' && this.path.slice(-1) === '/') { this[TYPE] = '5' } // tar implementations sometimes incorrectly put the stat(dir).size // as the size in the tarball, even though Directory entries are // not able to have any body at all. In the very rare chance that // it actually DOES have a body, we weren't going to do anything with // it anyway, and it'll just be a warning about an invalid header. if (this[TYPE] === '5') { this.size = 0 } this.linkpath = decString(buf, off + 157, 100) if (buf.slice(off + 257, off + 265).toString() === 'ustar\u000000') { this.uname = decString(buf, off + 265, 32) this.gname = decString(buf, off + 297, 32) this.devmaj = decNumber(buf, off + 329, 8) this.devmin = decNumber(buf, off + 337, 8) if (buf[off + 475] !== 0) { // definitely a prefix, definitely >130 chars. const prefix = decString(buf, off + 345, 155) this.path = prefix + '/' + this.path } else { const prefix = decString(buf, off + 345, 130) if (prefix) { this.path = prefix + '/' + this.path } this.atime = decDate(buf, off + 476, 12) this.ctime = decDate(buf, off + 488, 12) } } let sum = 8 * 0x20 for (let i = off; i < off + 148; i++) { sum += buf[i] } for (let i = off + 156; i < off + 512; i++) { sum += buf[i] } this.cksumValid = sum === this.cksum if (this.cksum === null && sum === 8 * 0x20) { this.nullBlock = true } } [SLURP] (ex, global) { for (const k in ex) { // we slurp in everything except for the path attribute in // a global extended header, because that's weird. if (ex[k] !== null && ex[k] !== undefined && !(global && k === 'path')) { this[k] = ex[k] } } } encode (buf, off) { if (!buf) { buf = this.block = Buffer.alloc(512) off = 0 } if (!off) { off = 0 } if (!(buf.length >= off + 512)) { throw new Error('need 512 bytes for header') } const prefixSize = this.ctime || this.atime ? 130 : 155 const split = splitPrefix(this.path || '', prefixSize) const path = split[0] const prefix = split[1] this.needPax = split[2] this.needPax = encString(buf, off, 100, path) || this.needPax this.needPax = encNumber(buf, off + 100, 8, this.mode) || this.needPax this.needPax = encNumber(buf, off + 108, 8, this.uid) || this.needPax this.needPax = encNumber(buf, off + 116, 8, this.gid) || this.needPax this.needPax = encNumber(buf, off + 124, 12, this.size) || this.needPax this.needPax = encDate(buf, off + 136, 12, this.mtime) || this.needPax buf[off + 156] = this[TYPE].charCodeAt(0) this.needPax = encString(buf, off + 157, 100, this.linkpath) || this.needPax buf.write('ustar\u000000', off + 257, 8) this.needPax = encString(buf, off + 265, 32, this.uname) || this.needPax this.needPax = encString(buf, off + 297, 32, this.gname) || this.needPax this.needPax = encNumber(buf, off + 329, 8, this.devmaj) || this.needPax this.needPax = encNumber(buf, off + 337, 8, this.devmin) || this.needPax this.needPax = encString(buf, off + 345, prefixSize, prefix) || this.needPax if (buf[off + 475] !== 0) { this.needPax = encString(buf, off + 345, 155, prefix) || this.needPax } else { this.needPax = encString(buf, off + 345, 130, prefix) || this.needPax this.needPax = encDate(buf, off + 476, 12, this.atime) || this.needPax this.needPax = encDate(buf, off + 488, 12, this.ctime) || this.needPax } let sum = 8 * 0x20 for (let i = off; i < off + 148; i++) { sum += buf[i] } for (let i = off + 156; i < off + 512; i++) { sum += buf[i] } this.cksum = sum encNumber(buf, off + 148, 8, this.cksum) this.cksumValid = true return this.needPax } set (data) { for (const i in data) { if (data[i] !== null && data[i] !== undefined) { this[i] = data[i] } } } get type () { return types.name.get(this[TYPE]) || this[TYPE] } get typeKey () { return this[TYPE] } set type (type) { if (types.code.has(type)) { this[TYPE] = types.code.get(type) } else { this[TYPE] = type } } } const splitPrefix = (p, prefixSize) => { const pathSize = 100 let pp = p let prefix = '' let ret const root = pathModule.parse(p).root || '.' if (Buffer.byteLength(pp) < pathSize) { ret = [pp, prefix, false] } else { // first set prefix to the dir, and path to the base prefix = pathModule.dirname(pp) pp = pathModule.basename(pp) do { if (Buffer.byteLength(pp) <= pathSize && Buffer.byteLength(prefix) <= prefixSize) { // both fit! ret = [pp, prefix, false] } else if (Buffer.byteLength(pp) > pathSize && Buffer.byteLength(prefix) <= prefixSize) { // prefix fits in prefix, but path doesn't fit in path ret = [pp.slice(0, pathSize - 1), prefix, true] } else { // make path take a bit from prefix pp = pathModule.join(pathModule.basename(prefix), pp) prefix = pathModule.dirname(prefix) } } while (prefix !== root && !ret) // at this point, found no resolution, just truncate if (!ret) { ret = [p.slice(0, pathSize - 1), '', true] } } return ret } const decString = (buf, off, size) => buf.slice(off, off + size).toString('utf8').replace(/\0.*/, '') const decDate = (buf, off, size) => numToDate(decNumber(buf, off, size)) const numToDate = num => num === null ? null : new Date(num * 1000) const decNumber = (buf, off, size) => buf[off] & 0x80 ? large.parse(buf.slice(off, off + size)) : decSmallNumber(buf, off, size) const nanNull = value => isNaN(value) ? null : value const decSmallNumber = (buf, off, size) => nanNull(parseInt( buf.slice(off, off + size) .toString('utf8').replace(/\0.*$/, '').trim(), 8)) // the maximum encodable as a null-terminated octal, by field size const MAXNUM = { 12: 0o77777777777, 8: 0o7777777, } const encNumber = (buf, off, size, number) => number === null ? false : number > MAXNUM[size] || number < 0 ? (large.encode(number, buf.slice(off, off + size)), true) : (encSmallNumber(buf, off, size, number), false) const encSmallNumber = (buf, off, size, number) => buf.write(octalString(number, size), off, size, 'ascii') const octalString = (number, size) => padOctal(Math.floor(number).toString(8), size) const padOctal = (string, size) => (string.length === size - 1 ? string : new Array(size - string.length - 1).join('0') + string + ' ') + '\0' const encDate = (buf, off, size, date) => date === null ? false : encNumber(buf, off, size, date.getTime() / 1000) // enough to fill the longest string we've got const NULLS = new Array(156).join('\0') // pad with nulls, return true if it's longer or non-ascii const encString = (buf, off, size, string) => string === null ? false : (buf.write(string + NULLS, off, size, 'utf8'), string.length !== Buffer.byteLength(string) || string.length > size) module.exports = Header /***/ }), /***/ 95274: /***/ ((module) => { "use strict"; // turn tar(1) style args like `C` into the more verbose things like `cwd` const argmap = new Map([ ['C', 'cwd'], ['f', 'file'], ['z', 'gzip'], ['P', 'preservePaths'], ['U', 'unlink'], ['strip-components', 'strip'], ['stripComponents', 'strip'], ['keep-newer', 'newer'], ['keepNewer', 'newer'], ['keep-newer-files', 'newer'], ['keepNewerFiles', 'newer'], ['k', 'keep'], ['keep-existing', 'keep'], ['keepExisting', 'keep'], ['m', 'noMtime'], ['no-mtime', 'noMtime'], ['p', 'preserveOwner'], ['L', 'follow'], ['h', 'follow'], ]) module.exports = opt => opt ? Object.keys(opt).map(k => [ argmap.has(k) ? argmap.get(k) : k, opt[k], ]).reduce((set, kv) => (set[kv[0]] = kv[1], set), Object.create(null)) : {} /***/ }), /***/ 52370: /***/ ((module) => { "use strict"; // Tar can encode large and negative numbers using a leading byte of // 0xff for negative, and 0x80 for positive. const encode = (num, buf) => { if (!Number.isSafeInteger(num)) { // The number is so large that javascript cannot represent it with integer // precision. throw Error('cannot encode number outside of javascript safe integer range') } else if (num < 0) { encodeNegative(num, buf) } else { encodePositive(num, buf) } return buf } const encodePositive = (num, buf) => { buf[0] = 0x80 for (var i = buf.length; i > 1; i--) { buf[i - 1] = num & 0xff num = Math.floor(num / 0x100) } } const encodeNegative = (num, buf) => { buf[0] = 0xff var flipped = false num = num * -1 for (var i = buf.length; i > 1; i--) { var byte = num & 0xff num = Math.floor(num / 0x100) if (flipped) { buf[i - 1] = onesComp(byte) } else if (byte === 0) { buf[i - 1] = 0 } else { flipped = true buf[i - 1] = twosComp(byte) } } } const parse = (buf) => { const pre = buf[0] const value = pre === 0x80 ? pos(buf.slice(1, buf.length)) : pre === 0xff ? twos(buf) : null if (value === null) { throw Error('invalid base256 encoding') } if (!Number.isSafeInteger(value)) { // The number is so large that javascript cannot represent it with integer // precision. throw Error('parsed number outside of javascript safe integer range') } return value } const twos = (buf) => { var len = buf.length var sum = 0 var flipped = false for (var i = len - 1; i > -1; i--) { var byte = buf[i] var f if (flipped) { f = onesComp(byte) } else if (byte === 0) { f = byte } else { flipped = true f = twosComp(byte) } if (f !== 0) { sum -= f * Math.pow(256, len - i - 1) } } return sum } const pos = (buf) => { var len = buf.length var sum = 0 for (var i = len - 1; i > -1; i--) { var byte = buf[i] if (byte !== 0) { sum += byte * Math.pow(256, len - i - 1) } } return sum } const onesComp = byte => (0xff ^ byte) & 0xff const twosComp = byte => ((0xff ^ byte) + 1) & 0xff module.exports = { encode, parse, } /***/ }), /***/ 51525: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // XXX: This shares a lot in common with extract.js // maybe some DRY opportunity here? // tar -t const hlo = __nccwpck_require__(95274) const Parser = __nccwpck_require__(68917) const fs = __nccwpck_require__(57147) const fsm = __nccwpck_require__(27714) const path = __nccwpck_require__(71017) const stripSlash = __nccwpck_require__(88886) module.exports = (opt_, files, cb) => { if (typeof opt_ === 'function') { cb = opt_, files = null, opt_ = {} } else if (Array.isArray(opt_)) { files = opt_, opt_ = {} } if (typeof files === 'function') { cb = files, files = null } if (!files) { files = [] } else { files = Array.from(files) } const opt = hlo(opt_) if (opt.sync && typeof cb === 'function') { throw new TypeError('callback not supported for sync tar functions') } if (!opt.file && typeof cb === 'function') { throw new TypeError('callback only supported with file option') } if (files.length) { filesFilter(opt, files) } if (!opt.noResume) { onentryFunction(opt) } return opt.file && opt.sync ? listFileSync(opt) : opt.file ? listFile(opt, cb) : list(opt) } const onentryFunction = opt => { const onentry = opt.onentry opt.onentry = onentry ? e => { onentry(e) e.resume() } : e => e.resume() } // construct a filter that limits the file entries listed // include child entries if a dir is included const filesFilter = (opt, files) => { const map = new Map(files.map(f => [stripSlash(f), true])) const filter = opt.filter const mapHas = (file, r) => { const root = r || path.parse(file).root || '.' const ret = file === root ? false : map.has(file) ? map.get(file) : mapHas(path.dirname(file), root) map.set(file, ret) return ret } opt.filter = filter ? (file, entry) => filter(file, entry) && mapHas(stripSlash(file)) : file => mapHas(stripSlash(file)) } const listFileSync = opt => { const p = list(opt) const file = opt.file let threw = true let fd try { const stat = fs.statSync(file) const readSize = opt.maxReadSize || 16 * 1024 * 1024 if (stat.size < readSize) { p.end(fs.readFileSync(file)) } else { let pos = 0 const buf = Buffer.allocUnsafe(readSize) fd = fs.openSync(file, 'r') while (pos < stat.size) { const bytesRead = fs.readSync(fd, buf, 0, readSize, pos) pos += bytesRead p.write(buf.slice(0, bytesRead)) } p.end() } threw = false } finally { if (threw && fd) { try { fs.closeSync(fd) } catch (er) {} } } } const listFile = (opt, cb) => { const parse = new Parser(opt) const readSize = opt.maxReadSize || 16 * 1024 * 1024 const file = opt.file const p = new Promise((resolve, reject) => { parse.on('error', reject) parse.on('end', resolve) fs.stat(file, (er, stat) => { if (er) { reject(er) } else { const stream = new fsm.ReadStream(file, { readSize: readSize, size: stat.size, }) stream.on('error', reject) stream.pipe(parse) } }) }) return cb ? p.then(cb, cb) : p } const list = opt => new Parser(opt) /***/ }), /***/ 69624: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // wrapper around mkdirp for tar's needs. // TODO: This should probably be a class, not functionally // passing around state in a gazillion args. const mkdirp = __nccwpck_require__(66186) const fs = __nccwpck_require__(57147) const path = __nccwpck_require__(71017) const chownr = __nccwpck_require__(59051) const normPath = __nccwpck_require__(56843) class SymlinkError extends Error { constructor (symlink, path) { super('Cannot extract through symbolic link') this.path = path this.symlink = symlink } get name () { return 'SylinkError' } } class CwdError extends Error { constructor (path, code) { super(code + ': Cannot cd into \'' + path + '\'') this.path = path this.code = code } get name () { return 'CwdError' } } const cGet = (cache, key) => cache.get(normPath(key)) const cSet = (cache, key, val) => cache.set(normPath(key), val) const checkCwd = (dir, cb) => { fs.stat(dir, (er, st) => { if (er || !st.isDirectory()) { er = new CwdError(dir, er && er.code || 'ENOTDIR') } cb(er) }) } module.exports = (dir, opt, cb) => { dir = normPath(dir) // if there's any overlap between mask and mode, // then we'll need an explicit chmod const umask = opt.umask const mode = opt.mode | 0o0700 const needChmod = (mode & umask) !== 0 const uid = opt.uid const gid = opt.gid const doChown = typeof uid === 'number' && typeof gid === 'number' && (uid !== opt.processUid || gid !== opt.processGid) const preserve = opt.preserve const unlink = opt.unlink const cache = opt.cache const cwd = normPath(opt.cwd) const done = (er, created) => { if (er) { cb(er) } else { cSet(cache, dir, true) if (created && doChown) { chownr(created, uid, gid, er => done(er)) } else if (needChmod) { fs.chmod(dir, mode, cb) } else { cb() } } } if (cache && cGet(cache, dir) === true) { return done() } if (dir === cwd) { return checkCwd(dir, done) } if (preserve) { return mkdirp(dir, { mode }).then(made => done(null, made), done) } const sub = normPath(path.relative(cwd, dir)) const parts = sub.split('/') mkdir_(cwd, parts, mode, cache, unlink, cwd, null, done) } const mkdir_ = (base, parts, mode, cache, unlink, cwd, created, cb) => { if (!parts.length) { return cb(null, created) } const p = parts.shift() const part = normPath(path.resolve(base + '/' + p)) if (cGet(cache, part)) { return mkdir_(part, parts, mode, cache, unlink, cwd, created, cb) } fs.mkdir(part, mode, onmkdir(part, parts, mode, cache, unlink, cwd, created, cb)) } const onmkdir = (part, parts, mode, cache, unlink, cwd, created, cb) => er => { if (er) { fs.lstat(part, (statEr, st) => { if (statEr) { statEr.path = statEr.path && normPath(statEr.path) cb(statEr) } else if (st.isDirectory()) { mkdir_(part, parts, mode, cache, unlink, cwd, created, cb) } else if (unlink) { fs.unlink(part, er => { if (er) { return cb(er) } fs.mkdir(part, mode, onmkdir(part, parts, mode, cache, unlink, cwd, created, cb)) }) } else if (st.isSymbolicLink()) { return cb(new SymlinkError(part, part + '/' + parts.join('/'))) } else { cb(er) } }) } else { created = created || part mkdir_(part, parts, mode, cache, unlink, cwd, created, cb) } } const checkCwdSync = dir => { let ok = false let code = 'ENOTDIR' try { ok = fs.statSync(dir).isDirectory() } catch (er) { code = er.code } finally { if (!ok) { throw new CwdError(dir, code) } } } module.exports.sync = (dir, opt) => { dir = normPath(dir) // if there's any overlap between mask and mode, // then we'll need an explicit chmod const umask = opt.umask const mode = opt.mode | 0o0700 const needChmod = (mode & umask) !== 0 const uid = opt.uid const gid = opt.gid const doChown = typeof uid === 'number' && typeof gid === 'number' && (uid !== opt.processUid || gid !== opt.processGid) const preserve = opt.preserve const unlink = opt.unlink const cache = opt.cache const cwd = normPath(opt.cwd) const done = (created) => { cSet(cache, dir, true) if (created && doChown) { chownr.sync(created, uid, gid) } if (needChmod) { fs.chmodSync(dir, mode) } } if (cache && cGet(cache, dir) === true) { return done() } if (dir === cwd) { checkCwdSync(cwd) return done() } if (preserve) { return done(mkdirp.sync(dir, mode)) } const sub = normPath(path.relative(cwd, dir)) const parts = sub.split('/') let created = null for (let p = parts.shift(), part = cwd; p && (part += '/' + p); p = parts.shift()) { part = normPath(path.resolve(part)) if (cGet(cache, part)) { continue } try { fs.mkdirSync(part, mode) created = created || part cSet(cache, part, true) } catch (er) { const st = fs.lstatSync(part) if (st.isDirectory()) { cSet(cache, part, true) continue } else if (unlink) { fs.unlinkSync(part) fs.mkdirSync(part, mode) created = created || part cSet(cache, part, true) continue } else if (st.isSymbolicLink()) { return new SymlinkError(part, part + '/' + parts.join('/')) } } } return done(created) } /***/ }), /***/ 88371: /***/ ((module) => { "use strict"; module.exports = (mode, isDir, portable) => { mode &= 0o7777 // in portable mode, use the minimum reasonable umask // if this system creates files with 0o664 by default // (as some linux distros do), then we'll write the // archive with 0o644 instead. Also, don't ever create // a file that is not readable/writable by the owner. if (portable) { mode = (mode | 0o600) & ~0o22 } // if dirs are readable, then they should be listable if (isDir) { if (mode & 0o400) { mode |= 0o100 } if (mode & 0o40) { mode |= 0o10 } if (mode & 0o4) { mode |= 0o1 } } return mode } /***/ }), /***/ 47118: /***/ ((module) => { // warning: extremely hot code path. // This has been meticulously optimized for use // within npm install on large package trees. // Do not edit without careful benchmarking. const normalizeCache = Object.create(null) const { hasOwnProperty } = Object.prototype module.exports = s => { if (!hasOwnProperty.call(normalizeCache, s)) { normalizeCache[s] = s.normalize('NFD') } return normalizeCache[s] } /***/ }), /***/ 56843: /***/ ((module) => { // on windows, either \ or / are valid directory separators. // on unix, \ is a valid character in filenames. // so, on windows, and only on windows, we replace all \ chars with /, // so that we can use / as our one and only directory separator char. const platform = process.env.TESTING_TAR_FAKE_PLATFORM || process.platform module.exports = platform !== 'win32' ? p => p : p => p && p.replace(/\\/g, '/') /***/ }), /***/ 7900: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // A readable tar stream creator // Technically, this is a transform stream that you write paths into, // and tar format comes out of. // The `add()` method is like `write()` but returns this, // and end() return `this` as well, so you can // do `new Pack(opt).add('files').add('dir').end().pipe(output) // You could also do something like: // streamOfPaths().pipe(new Pack()).pipe(new fs.WriteStream('out.tar')) class PackJob { constructor (path, absolute) { this.path = path || './' this.absolute = absolute this.entry = null this.stat = null this.readdir = null this.pending = false this.ignore = false this.piped = false } } const { Minipass } = __nccwpck_require__(96684) const zlib = __nccwpck_require__(33486) const ReadEntry = __nccwpck_require__(38116) const WriteEntry = __nccwpck_require__(55450) const WriteEntrySync = WriteEntry.Sync const WriteEntryTar = WriteEntry.Tar const Yallist = __nccwpck_require__(40665) const EOF = Buffer.alloc(1024) const ONSTAT = Symbol('onStat') const ENDED = Symbol('ended') const QUEUE = Symbol('queue') const CURRENT = Symbol('current') const PROCESS = Symbol('process') const PROCESSING = Symbol('processing') const PROCESSJOB = Symbol('processJob') const JOBS = Symbol('jobs') const JOBDONE = Symbol('jobDone') const ADDFSENTRY = Symbol('addFSEntry') const ADDTARENTRY = Symbol('addTarEntry') const STAT = Symbol('stat') const READDIR = Symbol('readdir') const ONREADDIR = Symbol('onreaddir') const PIPE = Symbol('pipe') const ENTRY = Symbol('entry') const ENTRYOPT = Symbol('entryOpt') const WRITEENTRYCLASS = Symbol('writeEntryClass') const WRITE = Symbol('write') const ONDRAIN = Symbol('ondrain') const fs = __nccwpck_require__(57147) const path = __nccwpck_require__(71017) const warner = __nccwpck_require__(85899) const normPath = __nccwpck_require__(56843) const Pack = warner(class Pack extends Minipass { constructor (opt) { super(opt) opt = opt || Object.create(null) this.opt = opt this.file = opt.file || '' this.cwd = opt.cwd || process.cwd() this.maxReadSize = opt.maxReadSize this.preservePaths = !!opt.preservePaths this.strict = !!opt.strict this.noPax = !!opt.noPax this.prefix = normPath(opt.prefix || '') this.linkCache = opt.linkCache || new Map() this.statCache = opt.statCache || new Map() this.readdirCache = opt.readdirCache || new Map() this[WRITEENTRYCLASS] = WriteEntry if (typeof opt.onwarn === 'function') { this.on('warn', opt.onwarn) } this.portable = !!opt.portable this.zip = null if (opt.gzip) { if (typeof opt.gzip !== 'object') { opt.gzip = {} } if (this.portable) { opt.gzip.portable = true } this.zip = new zlib.Gzip(opt.gzip) this.zip.on('data', chunk => super.write(chunk)) this.zip.on('end', _ => super.end()) this.zip.on('drain', _ => this[ONDRAIN]()) this.on('resume', _ => this.zip.resume()) } else { this.on('drain', this[ONDRAIN]) } this.noDirRecurse = !!opt.noDirRecurse this.follow = !!opt.follow this.noMtime = !!opt.noMtime this.mtime = opt.mtime || null this.filter = typeof opt.filter === 'function' ? opt.filter : _ => true this[QUEUE] = new Yallist() this[JOBS] = 0 this.jobs = +opt.jobs || 4 this[PROCESSING] = false this[ENDED] = false } [WRITE] (chunk) { return super.write(chunk) } add (path) { this.write(path) return this } end (path) { if (path) { this.write(path) } this[ENDED] = true this[PROCESS]() return this } write (path) { if (this[ENDED]) { throw new Error('write after end') } if (path instanceof ReadEntry) { this[ADDTARENTRY](path) } else { this[ADDFSENTRY](path) } return this.flowing } [ADDTARENTRY] (p) { const absolute = normPath(path.resolve(this.cwd, p.path)) // in this case, we don't have to wait for the stat if (!this.filter(p.path, p)) { p.resume() } else { const job = new PackJob(p.path, absolute, false) job.entry = new WriteEntryTar(p, this[ENTRYOPT](job)) job.entry.on('end', _ => this[JOBDONE](job)) this[JOBS] += 1 this[QUEUE].push(job) } this[PROCESS]() } [ADDFSENTRY] (p) { const absolute = normPath(path.resolve(this.cwd, p)) this[QUEUE].push(new PackJob(p, absolute)) this[PROCESS]() } [STAT] (job) { job.pending = true this[JOBS] += 1 const stat = this.follow ? 'stat' : 'lstat' fs[stat](job.absolute, (er, stat) => { job.pending = false this[JOBS] -= 1 if (er) { this.emit('error', er) } else { this[ONSTAT](job, stat) } }) } [ONSTAT] (job, stat) { this.statCache.set(job.absolute, stat) job.stat = stat // now we have the stat, we can filter it. if (!this.filter(job.path, stat)) { job.ignore = true } this[PROCESS]() } [READDIR] (job) { job.pending = true this[JOBS] += 1 fs.readdir(job.absolute, (er, entries) => { job.pending = false this[JOBS] -= 1 if (er) { return this.emit('error', er) } this[ONREADDIR](job, entries) }) } [ONREADDIR] (job, entries) { this.readdirCache.set(job.absolute, entries) job.readdir = entries this[PROCESS]() } [PROCESS] () { if (this[PROCESSING]) { return } this[PROCESSING] = true for (let w = this[QUEUE].head; w !== null && this[JOBS] < this.jobs; w = w.next) { this[PROCESSJOB](w.value) if (w.value.ignore) { const p = w.next this[QUEUE].removeNode(w) w.next = p } } this[PROCESSING] = false if (this[ENDED] && !this[QUEUE].length && this[JOBS] === 0) { if (this.zip) { this.zip.end(EOF) } else { super.write(EOF) super.end() } } } get [CURRENT] () { return this[QUEUE] && this[QUEUE].head && this[QUEUE].head.value } [JOBDONE] (job) { this[QUEUE].shift() this[JOBS] -= 1 this[PROCESS]() } [PROCESSJOB] (job) { if (job.pending) { return } if (job.entry) { if (job === this[CURRENT] && !job.piped) { this[PIPE](job) } return } if (!job.stat) { if (this.statCache.has(job.absolute)) { this[ONSTAT](job, this.statCache.get(job.absolute)) } else { this[STAT](job) } } if (!job.stat) { return } // filtered out! if (job.ignore) { return } if (!this.noDirRecurse && job.stat.isDirectory() && !job.readdir) { if (this.readdirCache.has(job.absolute)) { this[ONREADDIR](job, this.readdirCache.get(job.absolute)) } else { this[READDIR](job) } if (!job.readdir) { return } } // we know it doesn't have an entry, because that got checked above job.entry = this[ENTRY](job) if (!job.entry) { job.ignore = true return } if (job === this[CURRENT] && !job.piped) { this[PIPE](job) } } [ENTRYOPT] (job) { return { onwarn: (code, msg, data) => this.warn(code, msg, data), noPax: this.noPax, cwd: this.cwd, absolute: job.absolute, preservePaths: this.preservePaths, maxReadSize: this.maxReadSize, strict: this.strict, portable: this.portable, linkCache: this.linkCache, statCache: this.statCache, noMtime: this.noMtime, mtime: this.mtime, prefix: this.prefix, } } [ENTRY] (job) { this[JOBS] += 1 try { return new this[WRITEENTRYCLASS](job.path, this[ENTRYOPT](job)) .on('end', () => this[JOBDONE](job)) .on('error', er => this.emit('error', er)) } catch (er) { this.emit('error', er) } } [ONDRAIN] () { if (this[CURRENT] && this[CURRENT].entry) { this[CURRENT].entry.resume() } } // like .pipe() but using super, because our write() is special [PIPE] (job) { job.piped = true if (job.readdir) { job.readdir.forEach(entry => { const p = job.path const base = p === './' ? '' : p.replace(/\/*$/, '/') this[ADDFSENTRY](base + entry) }) } const source = job.entry const zip = this.zip if (zip) { source.on('data', chunk => { if (!zip.write(chunk)) { source.pause() } }) } else { source.on('data', chunk => { if (!super.write(chunk)) { source.pause() } }) } } pause () { if (this.zip) { this.zip.pause() } return super.pause() } }) class PackSync extends Pack { constructor (opt) { super(opt) this[WRITEENTRYCLASS] = WriteEntrySync } // pause/resume are no-ops in sync streams. pause () {} resume () {} [STAT] (job) { const stat = this.follow ? 'statSync' : 'lstatSync' this[ONSTAT](job, fs[stat](job.absolute)) } [READDIR] (job, stat) { this[ONREADDIR](job, fs.readdirSync(job.absolute)) } // gotta get it all in this tick [PIPE] (job) { const source = job.entry const zip = this.zip if (job.readdir) { job.readdir.forEach(entry => { const p = job.path const base = p === './' ? '' : p.replace(/\/*$/, '/') this[ADDFSENTRY](base + entry) }) } if (zip) { source.on('data', chunk => { zip.write(chunk) }) } else { source.on('data', chunk => { super[WRITE](chunk) }) } } } Pack.Sync = PackSync module.exports = Pack /***/ }), /***/ 68917: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // this[BUFFER] is the remainder of a chunk if we're waiting for // the full 512 bytes of a header to come in. We will Buffer.concat() // it to the next write(), which is a mem copy, but a small one. // // this[QUEUE] is a Yallist of entries that haven't been emitted // yet this can only get filled up if the user keeps write()ing after // a write() returns false, or does a write() with more than one entry // // We don't buffer chunks, we always parse them and either create an // entry, or push it into the active entry. The ReadEntry class knows // to throw data away if .ignore=true // // Shift entry off the buffer when it emits 'end', and emit 'entry' for // the next one in the list. // // At any time, we're pushing body chunks into the entry at WRITEENTRY, // and waiting for 'end' on the entry at READENTRY // // ignored entries get .resume() called on them straight away const warner = __nccwpck_require__(85899) const Header = __nccwpck_require__(66043) const EE = __nccwpck_require__(82361) const Yallist = __nccwpck_require__(40665) const maxMetaEntrySize = 1024 * 1024 const Entry = __nccwpck_require__(38116) const Pax = __nccwpck_require__(77996) const zlib = __nccwpck_require__(33486) const { nextTick } = __nccwpck_require__(77282) const gzipHeader = Buffer.from([0x1f, 0x8b]) const STATE = Symbol('state') const WRITEENTRY = Symbol('writeEntry') const READENTRY = Symbol('readEntry') const NEXTENTRY = Symbol('nextEntry') const PROCESSENTRY = Symbol('processEntry') const EX = Symbol('extendedHeader') const GEX = Symbol('globalExtendedHeader') const META = Symbol('meta') const EMITMETA = Symbol('emitMeta') const BUFFER = Symbol('buffer') const QUEUE = Symbol('queue') const ENDED = Symbol('ended') const EMITTEDEND = Symbol('emittedEnd') const EMIT = Symbol('emit') const UNZIP = Symbol('unzip') const CONSUMECHUNK = Symbol('consumeChunk') const CONSUMECHUNKSUB = Symbol('consumeChunkSub') const CONSUMEBODY = Symbol('consumeBody') const CONSUMEMETA = Symbol('consumeMeta') const CONSUMEHEADER = Symbol('consumeHeader') const CONSUMING = Symbol('consuming') const BUFFERCONCAT = Symbol('bufferConcat') const MAYBEEND = Symbol('maybeEnd') const WRITING = Symbol('writing') const ABORTED = Symbol('aborted') const DONE = Symbol('onDone') const SAW_VALID_ENTRY = Symbol('sawValidEntry') const SAW_NULL_BLOCK = Symbol('sawNullBlock') const SAW_EOF = Symbol('sawEOF') const CLOSESTREAM = Symbol('closeStream') const noop = _ => true module.exports = warner(class Parser extends EE { constructor (opt) { opt = opt || {} super(opt) this.file = opt.file || '' // set to boolean false when an entry starts. 1024 bytes of \0 // is technically a valid tarball, albeit a boring one. this[SAW_VALID_ENTRY] = null // these BADARCHIVE errors can't be detected early. listen on DONE. this.on(DONE, _ => { if (this[STATE] === 'begin' || this[SAW_VALID_ENTRY] === false) { // either less than 1 block of data, or all entries were invalid. // Either way, probably not even a tarball. this.warn('TAR_BAD_ARCHIVE', 'Unrecognized archive format') } }) if (opt.ondone) { this.on(DONE, opt.ondone) } else { this.on(DONE, _ => { this.emit('prefinish') this.emit('finish') this.emit('end') }) } this.strict = !!opt.strict this.maxMetaEntrySize = opt.maxMetaEntrySize || maxMetaEntrySize this.filter = typeof opt.filter === 'function' ? opt.filter : noop // have to set this so that streams are ok piping into it this.writable = true this.readable = false this[QUEUE] = new Yallist() this[BUFFER] = null this[READENTRY] = null this[WRITEENTRY] = null this[STATE] = 'begin' this[META] = '' this[EX] = null this[GEX] = null this[ENDED] = false this[UNZIP] = null this[ABORTED] = false this[SAW_NULL_BLOCK] = false this[SAW_EOF] = false this.on('end', () => this[CLOSESTREAM]()) if (typeof opt.onwarn === 'function') { this.on('warn', opt.onwarn) } if (typeof opt.onentry === 'function') { this.on('entry', opt.onentry) } } [CONSUMEHEADER] (chunk, position) { if (this[SAW_VALID_ENTRY] === null) { this[SAW_VALID_ENTRY] = false } let header try { header = new Header(chunk, position, this[EX], this[GEX]) } catch (er) { return this.warn('TAR_ENTRY_INVALID', er) } if (header.nullBlock) { if (this[SAW_NULL_BLOCK]) { this[SAW_EOF] = true // ending an archive with no entries. pointless, but legal. if (this[STATE] === 'begin') { this[STATE] = 'header' } this[EMIT]('eof') } else { this[SAW_NULL_BLOCK] = true this[EMIT]('nullBlock') } } else { this[SAW_NULL_BLOCK] = false if (!header.cksumValid) { this.warn('TAR_ENTRY_INVALID', 'checksum failure', { header }) } else if (!header.path) { this.warn('TAR_ENTRY_INVALID', 'path is required', { header }) } else { const type = header.type if (/^(Symbolic)?Link$/.test(type) && !header.linkpath) { this.warn('TAR_ENTRY_INVALID', 'linkpath required', { header }) } else if (!/^(Symbolic)?Link$/.test(type) && header.linkpath) { this.warn('TAR_ENTRY_INVALID', 'linkpath forbidden', { header }) } else { const entry = this[WRITEENTRY] = new Entry(header, this[EX], this[GEX]) // we do this for meta & ignored entries as well, because they // are still valid tar, or else we wouldn't know to ignore them if (!this[SAW_VALID_ENTRY]) { if (entry.remain) { // this might be the one! const onend = () => { if (!entry.invalid) { this[SAW_VALID_ENTRY] = true } } entry.on('end', onend) } else { this[SAW_VALID_ENTRY] = true } } if (entry.meta) { if (entry.size > this.maxMetaEntrySize) { entry.ignore = true this[EMIT]('ignoredEntry', entry) this[STATE] = 'ignore' entry.resume() } else if (entry.size > 0) { this[META] = '' entry.on('data', c => this[META] += c) this[STATE] = 'meta' } } else { this[EX] = null entry.ignore = entry.ignore || !this.filter(entry.path, entry) if (entry.ignore) { // probably valid, just not something we care about this[EMIT]('ignoredEntry', entry) this[STATE] = entry.remain ? 'ignore' : 'header' entry.resume() } else { if (entry.remain) { this[STATE] = 'body' } else { this[STATE] = 'header' entry.end() } if (!this[READENTRY]) { this[QUEUE].push(entry) this[NEXTENTRY]() } else { this[QUEUE].push(entry) } } } } } } } [CLOSESTREAM] () { nextTick(() => this.emit('close')) } [PROCESSENTRY] (entry) { let go = true if (!entry) { this[READENTRY] = null go = false } else if (Array.isArray(entry)) { this.emit.apply(this, entry) } else { this[READENTRY] = entry this.emit('entry', entry) if (!entry.emittedEnd) { entry.on('end', _ => this[NEXTENTRY]()) go = false } } return go } [NEXTENTRY] () { do {} while (this[PROCESSENTRY](this[QUEUE].shift())) if (!this[QUEUE].length) { // At this point, there's nothing in the queue, but we may have an // entry which is being consumed (readEntry). // If we don't, then we definitely can handle more data. // If we do, and either it's flowing, or it has never had any data // written to it, then it needs more. // The only other possibility is that it has returned false from a // write() call, so we wait for the next drain to continue. const re = this[READENTRY] const drainNow = !re || re.flowing || re.size === re.remain if (drainNow) { if (!this[WRITING]) { this.emit('drain') } } else { re.once('drain', _ => this.emit('drain')) } } } [CONSUMEBODY] (chunk, position) { // write up to but no more than writeEntry.blockRemain const entry = this[WRITEENTRY] const br = entry.blockRemain const c = (br >= chunk.length && position === 0) ? chunk : chunk.slice(position, position + br) entry.write(c) if (!entry.blockRemain) { this[STATE] = 'header' this[WRITEENTRY] = null entry.end() } return c.length } [CONSUMEMETA] (chunk, position) { const entry = this[WRITEENTRY] const ret = this[CONSUMEBODY](chunk, position) // if we finished, then the entry is reset if (!this[WRITEENTRY]) { this[EMITMETA](entry) } return ret } [EMIT] (ev, data, extra) { if (!this[QUEUE].length && !this[READENTRY]) { this.emit(ev, data, extra) } else { this[QUEUE].push([ev, data, extra]) } } [EMITMETA] (entry) { this[EMIT]('meta', this[META]) switch (entry.type) { case 'ExtendedHeader': case 'OldExtendedHeader': this[EX] = Pax.parse(this[META], this[EX], false) break case 'GlobalExtendedHeader': this[GEX] = Pax.parse(this[META], this[GEX], true) break case 'NextFileHasLongPath': case 'OldGnuLongPath': this[EX] = this[EX] || Object.create(null) this[EX].path = this[META].replace(/\0.*/, '') break case 'NextFileHasLongLinkpath': this[EX] = this[EX] || Object.create(null) this[EX].linkpath = this[META].replace(/\0.*/, '') break /* istanbul ignore next */ default: throw new Error('unknown meta: ' + entry.type) } } abort (error) { this[ABORTED] = true this.emit('abort', error) // always throws, even in non-strict mode this.warn('TAR_ABORT', error, { recoverable: false }) } write (chunk) { if (this[ABORTED]) { return } // first write, might be gzipped if (this[UNZIP] === null && chunk) { if (this[BUFFER]) { chunk = Buffer.concat([this[BUFFER], chunk]) this[BUFFER] = null } if (chunk.length < gzipHeader.length) { this[BUFFER] = chunk return true } for (let i = 0; this[UNZIP] === null && i < gzipHeader.length; i++) { if (chunk[i] !== gzipHeader[i]) { this[UNZIP] = false } } if (this[UNZIP] === null) { const ended = this[ENDED] this[ENDED] = false this[UNZIP] = new zlib.Unzip() this[UNZIP].on('data', chunk => this[CONSUMECHUNK](chunk)) this[UNZIP].on('error', er => this.abort(er)) this[UNZIP].on('end', _ => { this[ENDED] = true this[CONSUMECHUNK]() }) this[WRITING] = true const ret = this[UNZIP][ended ? 'end' : 'write'](chunk) this[WRITING] = false return ret } } this[WRITING] = true if (this[UNZIP]) { this[UNZIP].write(chunk) } else { this[CONSUMECHUNK](chunk) } this[WRITING] = false // return false if there's a queue, or if the current entry isn't flowing const ret = this[QUEUE].length ? false : this[READENTRY] ? this[READENTRY].flowing : true // if we have no queue, then that means a clogged READENTRY if (!ret && !this[QUEUE].length) { this[READENTRY].once('drain', _ => this.emit('drain')) } return ret } [BUFFERCONCAT] (c) { if (c && !this[ABORTED]) { this[BUFFER] = this[BUFFER] ? Buffer.concat([this[BUFFER], c]) : c } } [MAYBEEND] () { if (this[ENDED] && !this[EMITTEDEND] && !this[ABORTED] && !this[CONSUMING]) { this[EMITTEDEND] = true const entry = this[WRITEENTRY] if (entry && entry.blockRemain) { // truncated, likely a damaged file const have = this[BUFFER] ? this[BUFFER].length : 0 this.warn('TAR_BAD_ARCHIVE', `Truncated input (needed ${ entry.blockRemain} more bytes, only ${have} available)`, { entry }) if (this[BUFFER]) { entry.write(this[BUFFER]) } entry.end() } this[EMIT](DONE) } } [CONSUMECHUNK] (chunk) { if (this[CONSUMING]) { this[BUFFERCONCAT](chunk) } else if (!chunk && !this[BUFFER]) { this[MAYBEEND]() } else { this[CONSUMING] = true if (this[BUFFER]) { this[BUFFERCONCAT](chunk) const c = this[BUFFER] this[BUFFER] = null this[CONSUMECHUNKSUB](c) } else { this[CONSUMECHUNKSUB](chunk) } while (this[BUFFER] && this[BUFFER].length >= 512 && !this[ABORTED] && !this[SAW_EOF]) { const c = this[BUFFER] this[BUFFER] = null this[CONSUMECHUNKSUB](c) } this[CONSUMING] = false } if (!this[BUFFER] || this[ENDED]) { this[MAYBEEND]() } } [CONSUMECHUNKSUB] (chunk) { // we know that we are in CONSUMING mode, so anything written goes into // the buffer. Advance the position and put any remainder in the buffer. let position = 0 const length = chunk.length while (position + 512 <= length && !this[ABORTED] && !this[SAW_EOF]) { switch (this[STATE]) { case 'begin': case 'header': this[CONSUMEHEADER](chunk, position) position += 512 break case 'ignore': case 'body': position += this[CONSUMEBODY](chunk, position) break case 'meta': position += this[CONSUMEMETA](chunk, position) break /* istanbul ignore next */ default: throw new Error('invalid state: ' + this[STATE]) } } if (position < length) { if (this[BUFFER]) { this[BUFFER] = Buffer.concat([chunk.slice(position), this[BUFFER]]) } else { this[BUFFER] = chunk.slice(position) } } } end (chunk) { if (!this[ABORTED]) { if (this[UNZIP]) { this[UNZIP].end(chunk) } else { this[ENDED] = true this.write(chunk) } } } }) /***/ }), /***/ 99587: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // A path exclusive reservation system // reserve([list, of, paths], fn) // When the fn is first in line for all its paths, it // is called with a cb that clears the reservation. // // Used by async unpack to avoid clobbering paths in use, // while still allowing maximal safe parallelization. const assert = __nccwpck_require__(39491) const normalize = __nccwpck_require__(47118) const stripSlashes = __nccwpck_require__(88886) const { join } = __nccwpck_require__(71017) const platform = process.env.TESTING_TAR_FAKE_PLATFORM || process.platform const isWindows = platform === 'win32' module.exports = () => { // path => [function or Set] // A Set object means a directory reservation // A fn is a direct reservation on that path const queues = new Map() // fn => {paths:[path,...], dirs:[path, ...]} const reservations = new Map() // return a set of parent dirs for a given path // '/a/b/c/d' -> ['/', '/a', '/a/b', '/a/b/c', '/a/b/c/d'] const getDirs = path => { const dirs = path.split('/').slice(0, -1).reduce((set, path) => { if (set.length) { path = join(set[set.length - 1], path) } set.push(path || '/') return set }, []) return dirs } // functions currently running const running = new Set() // return the queues for each path the function cares about // fn => {paths, dirs} const getQueues = fn => { const res = reservations.get(fn) /* istanbul ignore if - unpossible */ if (!res) { throw new Error('function does not have any path reservations') } return { paths: res.paths.map(path => queues.get(path)), dirs: [...res.dirs].map(path => queues.get(path)), } } // check if fn is first in line for all its paths, and is // included in the first set for all its dir queues const check = fn => { const { paths, dirs } = getQueues(fn) return paths.every(q => q[0] === fn) && dirs.every(q => q[0] instanceof Set && q[0].has(fn)) } // run the function if it's first in line and not already running const run = fn => { if (running.has(fn) || !check(fn)) { return false } running.add(fn) fn(() => clear(fn)) return true } const clear = fn => { if (!running.has(fn)) { return false } const { paths, dirs } = reservations.get(fn) const next = new Set() paths.forEach(path => { const q = queues.get(path) assert.equal(q[0], fn) if (q.length === 1) { queues.delete(path) } else { q.shift() if (typeof q[0] === 'function') { next.add(q[0]) } else { q[0].forEach(fn => next.add(fn)) } } }) dirs.forEach(dir => { const q = queues.get(dir) assert(q[0] instanceof Set) if (q[0].size === 1 && q.length === 1) { queues.delete(dir) } else if (q[0].size === 1) { q.shift() // must be a function or else the Set would've been reused next.add(q[0]) } else { q[0].delete(fn) } }) running.delete(fn) next.forEach(fn => run(fn)) return true } const reserve = (paths, fn) => { // collide on matches across case and unicode normalization // On windows, thanks to the magic of 8.3 shortnames, it is fundamentally // impossible to determine whether two paths refer to the same thing on // disk, without asking the kernel for a shortname. // So, we just pretend that every path matches every other path here, // effectively removing all parallelization on windows. paths = isWindows ? ['win32 parallelization disabled'] : paths.map(p => { // don't need normPath, because we skip this entirely for windows return stripSlashes(join(normalize(p))).toLowerCase() }) const dirs = new Set( paths.map(path => getDirs(path)).reduce((a, b) => a.concat(b)) ) reservations.set(fn, { dirs, paths }) paths.forEach(path => { const q = queues.get(path) if (!q) { queues.set(path, [fn]) } else { q.push(fn) } }) dirs.forEach(dir => { const q = queues.get(dir) if (!q) { queues.set(dir, [new Set([fn])]) } else if (q[q.length - 1] instanceof Set) { q[q.length - 1].add(fn) } else { q.push(new Set([fn])) } }) return run(fn) } return { check, reserve } } /***/ }), /***/ 77996: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const Header = __nccwpck_require__(66043) const path = __nccwpck_require__(71017) class Pax { constructor (obj, global) { this.atime = obj.atime || null this.charset = obj.charset || null this.comment = obj.comment || null this.ctime = obj.ctime || null this.gid = obj.gid || null this.gname = obj.gname || null this.linkpath = obj.linkpath || null this.mtime = obj.mtime || null this.path = obj.path || null this.size = obj.size || null this.uid = obj.uid || null this.uname = obj.uname || null this.dev = obj.dev || null this.ino = obj.ino || null this.nlink = obj.nlink || null this.global = global || false } encode () { const body = this.encodeBody() if (body === '') { return null } const bodyLen = Buffer.byteLength(body) // round up to 512 bytes // add 512 for header const bufLen = 512 * Math.ceil(1 + bodyLen / 512) const buf = Buffer.allocUnsafe(bufLen) // 0-fill the header section, it might not hit every field for (let i = 0; i < 512; i++) { buf[i] = 0 } new Header({ // XXX split the path // then the path should be PaxHeader + basename, but less than 99, // prepend with the dirname path: ('PaxHeader/' + path.basename(this.path)).slice(0, 99), mode: this.mode || 0o644, uid: this.uid || null, gid: this.gid || null, size: bodyLen, mtime: this.mtime || null, type: this.global ? 'GlobalExtendedHeader' : 'ExtendedHeader', linkpath: '', uname: this.uname || '', gname: this.gname || '', devmaj: 0, devmin: 0, atime: this.atime || null, ctime: this.ctime || null, }).encode(buf) buf.write(body, 512, bodyLen, 'utf8') // null pad after the body for (let i = bodyLen + 512; i < buf.length; i++) { buf[i] = 0 } return buf } encodeBody () { return ( this.encodeField('path') + this.encodeField('ctime') + this.encodeField('atime') + this.encodeField('dev') + this.encodeField('ino') + this.encodeField('nlink') + this.encodeField('charset') + this.encodeField('comment') + this.encodeField('gid') + this.encodeField('gname') + this.encodeField('linkpath') + this.encodeField('mtime') + this.encodeField('size') + this.encodeField('uid') + this.encodeField('uname') ) } encodeField (field) { if (this[field] === null || this[field] === undefined) { return '' } const v = this[field] instanceof Date ? this[field].getTime() / 1000 : this[field] const s = ' ' + (field === 'dev' || field === 'ino' || field === 'nlink' ? 'SCHILY.' : '') + field + '=' + v + '\n' const byteLen = Buffer.byteLength(s) // the digits includes the length of the digits in ascii base-10 // so if it's 9 characters, then adding 1 for the 9 makes it 10 // which makes it 11 chars. let digits = Math.floor(Math.log(byteLen) / Math.log(10)) + 1 if (byteLen + digits >= Math.pow(10, digits)) { digits += 1 } const len = digits + byteLen return len + s } } Pax.parse = (string, ex, g) => new Pax(merge(parseKV(string), ex), g) const merge = (a, b) => b ? Object.keys(a).reduce((s, k) => (s[k] = a[k], s), b) : a const parseKV = string => string .replace(/\n$/, '') .split('\n') .reduce(parseKVLine, Object.create(null)) const parseKVLine = (set, line) => { const n = parseInt(line, 10) // XXX Values with \n in them will fail this. // Refactor to not be a naive line-by-line parse. if (n !== Buffer.byteLength(line) + 1) { return set } line = line.slice((n + ' ').length) const kv = line.split('=') const k = kv.shift().replace(/^SCHILY\.(dev|ino|nlink)/, '$1') if (!k) { return set } const v = kv.join('=') set[k] = /^([A-Z]+\.)?([mac]|birth|creation)time$/.test(k) ? new Date(v * 1000) : /^[0-9]+$/.test(v) ? +v : v return set } module.exports = Pax /***/ }), /***/ 38116: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { Minipass } = __nccwpck_require__(96684) const normPath = __nccwpck_require__(56843) const SLURP = Symbol('slurp') module.exports = class ReadEntry extends Minipass { constructor (header, ex, gex) { super() // read entries always start life paused. this is to avoid the // situation where Minipass's auto-ending empty streams results // in an entry ending before we're ready for it. this.pause() this.extended = ex this.globalExtended = gex this.header = header this.startBlockSize = 512 * Math.ceil(header.size / 512) this.blockRemain = this.startBlockSize this.remain = header.size this.type = header.type this.meta = false this.ignore = false switch (this.type) { case 'File': case 'OldFile': case 'Link': case 'SymbolicLink': case 'CharacterDevice': case 'BlockDevice': case 'Directory': case 'FIFO': case 'ContiguousFile': case 'GNUDumpDir': break case 'NextFileHasLongLinkpath': case 'NextFileHasLongPath': case 'OldGnuLongPath': case 'GlobalExtendedHeader': case 'ExtendedHeader': case 'OldExtendedHeader': this.meta = true break // NOTE: gnutar and bsdtar treat unrecognized types as 'File' // it may be worth doing the same, but with a warning. default: this.ignore = true } this.path = normPath(header.path) this.mode = header.mode if (this.mode) { this.mode = this.mode & 0o7777 } this.uid = header.uid this.gid = header.gid this.uname = header.uname this.gname = header.gname this.size = header.size this.mtime = header.mtime this.atime = header.atime this.ctime = header.ctime this.linkpath = normPath(header.linkpath) this.uname = header.uname this.gname = header.gname if (ex) { this[SLURP](ex) } if (gex) { this[SLURP](gex, true) } } write (data) { const writeLen = data.length if (writeLen > this.blockRemain) { throw new Error('writing more to entry than is appropriate') } const r = this.remain const br = this.blockRemain this.remain = Math.max(0, r - writeLen) this.blockRemain = Math.max(0, br - writeLen) if (this.ignore) { return true } if (r >= writeLen) { return super.write(data) } // r < writeLen return super.write(data.slice(0, r)) } [SLURP] (ex, global) { for (const k in ex) { // we slurp in everything except for the path attribute in // a global extended header, because that's weird. if (ex[k] !== null && ex[k] !== undefined && !(global && k === 'path')) { this[k] = k === 'path' || k === 'linkpath' ? normPath(ex[k]) : ex[k] } } } } /***/ }), /***/ 45923: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // tar -r const hlo = __nccwpck_require__(95274) const Pack = __nccwpck_require__(7900) const fs = __nccwpck_require__(57147) const fsm = __nccwpck_require__(27714) const t = __nccwpck_require__(51525) const path = __nccwpck_require__(71017) // starting at the head of the file, read a Header // If the checksum is invalid, that's our position to start writing // If it is, jump forward by the specified size (round up to 512) // and try again. // Write the new Pack stream starting there. const Header = __nccwpck_require__(66043) module.exports = (opt_, files, cb) => { const opt = hlo(opt_) if (!opt.file) { throw new TypeError('file is required') } if (opt.gzip) { throw new TypeError('cannot append to compressed archives') } if (!files || !Array.isArray(files) || !files.length) { throw new TypeError('no files or directories specified') } files = Array.from(files) return opt.sync ? replaceSync(opt, files) : replace(opt, files, cb) } const replaceSync = (opt, files) => { const p = new Pack.Sync(opt) let threw = true let fd let position try { try { fd = fs.openSync(opt.file, 'r+') } catch (er) { if (er.code === 'ENOENT') { fd = fs.openSync(opt.file, 'w+') } else { throw er } } const st = fs.fstatSync(fd) const headBuf = Buffer.alloc(512) POSITION: for (position = 0; position < st.size; position += 512) { for (let bufPos = 0, bytes = 0; bufPos < 512; bufPos += bytes) { bytes = fs.readSync( fd, headBuf, bufPos, headBuf.length - bufPos, position + bufPos ) if (position === 0 && headBuf[0] === 0x1f && headBuf[1] === 0x8b) { throw new Error('cannot append to compressed archives') } if (!bytes) { break POSITION } } const h = new Header(headBuf) if (!h.cksumValid) { break } const entryBlockSize = 512 * Math.ceil(h.size / 512) if (position + entryBlockSize + 512 > st.size) { break } // the 512 for the header we just parsed will be added as well // also jump ahead all the blocks for the body position += entryBlockSize if (opt.mtimeCache) { opt.mtimeCache.set(h.path, h.mtime) } } threw = false streamSync(opt, p, position, fd, files) } finally { if (threw) { try { fs.closeSync(fd) } catch (er) {} } } } const streamSync = (opt, p, position, fd, files) => { const stream = new fsm.WriteStreamSync(opt.file, { fd: fd, start: position, }) p.pipe(stream) addFilesSync(p, files) } const replace = (opt, files, cb) => { files = Array.from(files) const p = new Pack(opt) const getPos = (fd, size, cb_) => { const cb = (er, pos) => { if (er) { fs.close(fd, _ => cb_(er)) } else { cb_(null, pos) } } let position = 0 if (size === 0) { return cb(null, 0) } let bufPos = 0 const headBuf = Buffer.alloc(512) const onread = (er, bytes) => { if (er) { return cb(er) } bufPos += bytes if (bufPos < 512 && bytes) { return fs.read( fd, headBuf, bufPos, headBuf.length - bufPos, position + bufPos, onread ) } if (position === 0 && headBuf[0] === 0x1f && headBuf[1] === 0x8b) { return cb(new Error('cannot append to compressed archives')) } // truncated header if (bufPos < 512) { return cb(null, position) } const h = new Header(headBuf) if (!h.cksumValid) { return cb(null, position) } const entryBlockSize = 512 * Math.ceil(h.size / 512) if (position + entryBlockSize + 512 > size) { return cb(null, position) } position += entryBlockSize + 512 if (position >= size) { return cb(null, position) } if (opt.mtimeCache) { opt.mtimeCache.set(h.path, h.mtime) } bufPos = 0 fs.read(fd, headBuf, 0, 512, position, onread) } fs.read(fd, headBuf, 0, 512, position, onread) } const promise = new Promise((resolve, reject) => { p.on('error', reject) let flag = 'r+' const onopen = (er, fd) => { if (er && er.code === 'ENOENT' && flag === 'r+') { flag = 'w+' return fs.open(opt.file, flag, onopen) } if (er) { return reject(er) } fs.fstat(fd, (er, st) => { if (er) { return fs.close(fd, () => reject(er)) } getPos(fd, st.size, (er, position) => { if (er) { return reject(er) } const stream = new fsm.WriteStream(opt.file, { fd: fd, start: position, }) p.pipe(stream) stream.on('error', reject) stream.on('close', resolve) addFilesAsync(p, files) }) }) } fs.open(opt.file, flag, onopen) }) return cb ? promise.then(cb, cb) : promise } const addFilesSync = (p, files) => { files.forEach(file => { if (file.charAt(0) === '@') { t({ file: path.resolve(p.cwd, file.slice(1)), sync: true, noResume: true, onentry: entry => p.add(entry), }) } else { p.add(file) } }) p.end() } const addFilesAsync = (p, files) => { while (files.length) { const file = files.shift() if (file.charAt(0) === '@') { return t({ file: path.resolve(p.cwd, file.slice(1)), noResume: true, onentry: entry => p.add(entry), }).then(_ => addFilesAsync(p, files)) } else { p.add(file) } } p.end() } /***/ }), /***/ 37111: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // unix absolute paths are also absolute on win32, so we use this for both const { isAbsolute, parse } = (__nccwpck_require__(71017).win32) // returns [root, stripped] // Note that windows will think that //x/y/z/a has a "root" of //x/y, and in // those cases, we want to sanitize it to x/y/z/a, not z/a, so we strip / // explicitly if it's the first character. // drive-specific relative paths on Windows get their root stripped off even // though they are not absolute, so `c:../foo` becomes ['c:', '../foo'] module.exports = path => { let r = '' let parsed = parse(path) while (isAbsolute(path) || parsed.root) { // windows will think that //x/y/z has a "root" of //x/y/ // but strip the //?/C:/ off of //?/C:/path const root = path.charAt(0) === '/' && path.slice(0, 4) !== '//?/' ? '/' : parsed.root path = path.slice(root.length) r += root parsed = parse(path) } return [r, path] } /***/ }), /***/ 88886: /***/ ((module) => { // warning: extremely hot code path. // This has been meticulously optimized for use // within npm install on large package trees. // Do not edit without careful benchmarking. module.exports = str => { let i = str.length - 1 let slashesStart = -1 while (i > -1 && str.charAt(i) === '/') { slashesStart = i i-- } return slashesStart === -1 ? str : str.slice(0, slashesStart) } /***/ }), /***/ 24173: /***/ ((__unused_webpack_module, exports) => { "use strict"; // map types from key to human-friendly name exports.name = new Map([ ['0', 'File'], // same as File ['', 'OldFile'], ['1', 'Link'], ['2', 'SymbolicLink'], // Devices and FIFOs aren't fully supported // they are parsed, but skipped when unpacking ['3', 'CharacterDevice'], ['4', 'BlockDevice'], ['5', 'Directory'], ['6', 'FIFO'], // same as File ['7', 'ContiguousFile'], // pax headers ['g', 'GlobalExtendedHeader'], ['x', 'ExtendedHeader'], // vendor-specific stuff // skip ['A', 'SolarisACL'], // like 5, but with data, which should be skipped ['D', 'GNUDumpDir'], // metadata only, skip ['I', 'Inode'], // data = link path of next file ['K', 'NextFileHasLongLinkpath'], // data = path of next file ['L', 'NextFileHasLongPath'], // skip ['M', 'ContinuationFile'], // like L ['N', 'OldGnuLongPath'], // skip ['S', 'SparseFile'], // skip ['V', 'TapeVolumeHeader'], // like x ['X', 'OldExtendedHeader'], ]) // map the other direction exports.code = new Map(Array.from(exports.name).map(kv => [kv[1], kv[0]])) /***/ }), /***/ 17628: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // the PEND/UNPEND stuff tracks whether we're ready to emit end/close yet. // but the path reservations are required to avoid race conditions where // parallelized unpack ops may mess with one another, due to dependencies // (like a Link depending on its target) or destructive operations (like // clobbering an fs object to create one of a different type.) const assert = __nccwpck_require__(39491) const Parser = __nccwpck_require__(68917) const fs = __nccwpck_require__(57147) const fsm = __nccwpck_require__(27714) const path = __nccwpck_require__(71017) const mkdir = __nccwpck_require__(69624) const wc = __nccwpck_require__(44808) const pathReservations = __nccwpck_require__(99587) const stripAbsolutePath = __nccwpck_require__(37111) const normPath = __nccwpck_require__(56843) const stripSlash = __nccwpck_require__(88886) const normalize = __nccwpck_require__(47118) const ONENTRY = Symbol('onEntry') const CHECKFS = Symbol('checkFs') const CHECKFS2 = Symbol('checkFs2') const PRUNECACHE = Symbol('pruneCache') const ISREUSABLE = Symbol('isReusable') const MAKEFS = Symbol('makeFs') const FILE = Symbol('file') const DIRECTORY = Symbol('directory') const LINK = Symbol('link') const SYMLINK = Symbol('symlink') const HARDLINK = Symbol('hardlink') const UNSUPPORTED = Symbol('unsupported') const CHECKPATH = Symbol('checkPath') const MKDIR = Symbol('mkdir') const ONERROR = Symbol('onError') const PENDING = Symbol('pending') const PEND = Symbol('pend') const UNPEND = Symbol('unpend') const ENDED = Symbol('ended') const MAYBECLOSE = Symbol('maybeClose') const SKIP = Symbol('skip') const DOCHOWN = Symbol('doChown') const UID = Symbol('uid') const GID = Symbol('gid') const CHECKED_CWD = Symbol('checkedCwd') const crypto = __nccwpck_require__(6113) const getFlag = __nccwpck_require__(91172) const platform = process.env.TESTING_TAR_FAKE_PLATFORM || process.platform const isWindows = platform === 'win32' // Unlinks on Windows are not atomic. // // This means that if you have a file entry, followed by another // file entry with an identical name, and you cannot re-use the file // (because it's a hardlink, or because unlink:true is set, or it's // Windows, which does not have useful nlink values), then the unlink // will be committed to the disk AFTER the new file has been written // over the old one, deleting the new file. // // To work around this, on Windows systems, we rename the file and then // delete the renamed file. It's a sloppy kludge, but frankly, I do not // know of a better way to do this, given windows' non-atomic unlink // semantics. // // See: https://github.com/npm/node-tar/issues/183 /* istanbul ignore next */ const unlinkFile = (path, cb) => { if (!isWindows) { return fs.unlink(path, cb) } const name = path + '.DELETE.' + crypto.randomBytes(16).toString('hex') fs.rename(path, name, er => { if (er) { return cb(er) } fs.unlink(name, cb) }) } /* istanbul ignore next */ const unlinkFileSync = path => { if (!isWindows) { return fs.unlinkSync(path) } const name = path + '.DELETE.' + crypto.randomBytes(16).toString('hex') fs.renameSync(path, name) fs.unlinkSync(name) } // this.gid, entry.gid, this.processUid const uint32 = (a, b, c) => a === a >>> 0 ? a : b === b >>> 0 ? b : c // clear the cache if it's a case-insensitive unicode-squashing match. // we can't know if the current file system is case-sensitive or supports // unicode fully, so we check for similarity on the maximally compatible // representation. Err on the side of pruning, since all it's doing is // preventing lstats, and it's not the end of the world if we get a false // positive. // Note that on windows, we always drop the entire cache whenever a // symbolic link is encountered, because 8.3 filenames are impossible // to reason about, and collisions are hazards rather than just failures. const cacheKeyNormalize = path => stripSlash(normPath(normalize(path))) .toLowerCase() const pruneCache = (cache, abs) => { abs = cacheKeyNormalize(abs) for (const path of cache.keys()) { const pnorm = cacheKeyNormalize(path) if (pnorm === abs || pnorm.indexOf(abs + '/') === 0) { cache.delete(path) } } } const dropCache = cache => { for (const key of cache.keys()) { cache.delete(key) } } class Unpack extends Parser { constructor (opt) { if (!opt) { opt = {} } opt.ondone = _ => { this[ENDED] = true this[MAYBECLOSE]() } super(opt) this[CHECKED_CWD] = false this.reservations = pathReservations() this.transform = typeof opt.transform === 'function' ? opt.transform : null this.writable = true this.readable = false this[PENDING] = 0 this[ENDED] = false this.dirCache = opt.dirCache || new Map() if (typeof opt.uid === 'number' || typeof opt.gid === 'number') { // need both or neither if (typeof opt.uid !== 'number' || typeof opt.gid !== 'number') { throw new TypeError('cannot set owner without number uid and gid') } if (opt.preserveOwner) { throw new TypeError( 'cannot preserve owner in archive and also set owner explicitly') } this.uid = opt.uid this.gid = opt.gid this.setOwner = true } else { this.uid = null this.gid = null this.setOwner = false } // default true for root if (opt.preserveOwner === undefined && typeof opt.uid !== 'number') { this.preserveOwner = process.getuid && process.getuid() === 0 } else { this.preserveOwner = !!opt.preserveOwner } this.processUid = (this.preserveOwner || this.setOwner) && process.getuid ? process.getuid() : null this.processGid = (this.preserveOwner || this.setOwner) && process.getgid ? process.getgid() : null // mostly just for testing, but useful in some cases. // Forcibly trigger a chown on every entry, no matter what this.forceChown = opt.forceChown === true // turn > this[ONENTRY](entry)) } // a bad or damaged archive is a warning for Parser, but an error // when extracting. Mark those errors as unrecoverable, because // the Unpack contract cannot be met. warn (code, msg, data = {}) { if (code === 'TAR_BAD_ARCHIVE' || code === 'TAR_ABORT') { data.recoverable = false } return super.warn(code, msg, data) } [MAYBECLOSE] () { if (this[ENDED] && this[PENDING] === 0) { this.emit('prefinish') this.emit('finish') this.emit('end') } } [CHECKPATH] (entry) { if (this.strip) { const parts = normPath(entry.path).split('/') if (parts.length < this.strip) { return false } entry.path = parts.slice(this.strip).join('/') if (entry.type === 'Link') { const linkparts = normPath(entry.linkpath).split('/') if (linkparts.length >= this.strip) { entry.linkpath = linkparts.slice(this.strip).join('/') } else { return false } } } if (!this.preservePaths) { const p = normPath(entry.path) const parts = p.split('/') if (parts.includes('..') || isWindows && /^[a-z]:\.\.$/i.test(parts[0])) { this.warn('TAR_ENTRY_ERROR', `path contains '..'`, { entry, path: p, }) return false } // strip off the root const [root, stripped] = stripAbsolutePath(p) if (root) { entry.path = stripped this.warn('TAR_ENTRY_INFO', `stripping ${root} from absolute path`, { entry, path: p, }) } } if (path.isAbsolute(entry.path)) { entry.absolute = normPath(path.resolve(entry.path)) } else { entry.absolute = normPath(path.resolve(this.cwd, entry.path)) } // if we somehow ended up with a path that escapes the cwd, and we are // not in preservePaths mode, then something is fishy! This should have // been prevented above, so ignore this for coverage. /* istanbul ignore if - defense in depth */ if (!this.preservePaths && entry.absolute.indexOf(this.cwd + '/') !== 0 && entry.absolute !== this.cwd) { this.warn('TAR_ENTRY_ERROR', 'path escaped extraction target', { entry, path: normPath(entry.path), resolvedPath: entry.absolute, cwd: this.cwd, }) return false } // an archive can set properties on the extraction directory, but it // may not replace the cwd with a different kind of thing entirely. if (entry.absolute === this.cwd && entry.type !== 'Directory' && entry.type !== 'GNUDumpDir') { return false } // only encode : chars that aren't drive letter indicators if (this.win32) { const { root: aRoot } = path.win32.parse(entry.absolute) entry.absolute = aRoot + wc.encode(entry.absolute.slice(aRoot.length)) const { root: pRoot } = path.win32.parse(entry.path) entry.path = pRoot + wc.encode(entry.path.slice(pRoot.length)) } return true } [ONENTRY] (entry) { if (!this[CHECKPATH](entry)) { return entry.resume() } assert.equal(typeof entry.absolute, 'string') switch (entry.type) { case 'Directory': case 'GNUDumpDir': if (entry.mode) { entry.mode = entry.mode | 0o700 } // eslint-disable-next-line no-fallthrough case 'File': case 'OldFile': case 'ContiguousFile': case 'Link': case 'SymbolicLink': return this[CHECKFS](entry) case 'CharacterDevice': case 'BlockDevice': case 'FIFO': default: return this[UNSUPPORTED](entry) } } [ONERROR] (er, entry) { // Cwd has to exist, or else nothing works. That's serious. // Other errors are warnings, which raise the error in strict // mode, but otherwise continue on. if (er.name === 'CwdError') { this.emit('error', er) } else { this.warn('TAR_ENTRY_ERROR', er, { entry }) this[UNPEND]() entry.resume() } } [MKDIR] (dir, mode, cb) { mkdir(normPath(dir), { uid: this.uid, gid: this.gid, processUid: this.processUid, processGid: this.processGid, umask: this.processUmask, preserve: this.preservePaths, unlink: this.unlink, cache: this.dirCache, cwd: this.cwd, mode: mode, noChmod: this.noChmod, }, cb) } [DOCHOWN] (entry) { // in preserve owner mode, chown if the entry doesn't match process // in set owner mode, chown if setting doesn't match process return this.forceChown || this.preserveOwner && (typeof entry.uid === 'number' && entry.uid !== this.processUid || typeof entry.gid === 'number' && entry.gid !== this.processGid) || (typeof this.uid === 'number' && this.uid !== this.processUid || typeof this.gid === 'number' && this.gid !== this.processGid) } [UID] (entry) { return uint32(this.uid, entry.uid, this.processUid) } [GID] (entry) { return uint32(this.gid, entry.gid, this.processGid) } [FILE] (entry, fullyDone) { const mode = entry.mode & 0o7777 || this.fmode const stream = new fsm.WriteStream(entry.absolute, { flags: getFlag(entry.size), mode: mode, autoClose: false, }) stream.on('error', er => { if (stream.fd) { fs.close(stream.fd, () => {}) } // flush all the data out so that we aren't left hanging // if the error wasn't actually fatal. otherwise the parse // is blocked, and we never proceed. stream.write = () => true this[ONERROR](er, entry) fullyDone() }) let actions = 1 const done = er => { if (er) { /* istanbul ignore else - we should always have a fd by now */ if (stream.fd) { fs.close(stream.fd, () => {}) } this[ONERROR](er, entry) fullyDone() return } if (--actions === 0) { fs.close(stream.fd, er => { if (er) { this[ONERROR](er, entry) } else { this[UNPEND]() } fullyDone() }) } } stream.on('finish', _ => { // if futimes fails, try utimes // if utimes fails, fail with the original error // same for fchown/chown const abs = entry.absolute const fd = stream.fd if (entry.mtime && !this.noMtime) { actions++ const atime = entry.atime || new Date() const mtime = entry.mtime fs.futimes(fd, atime, mtime, er => er ? fs.utimes(abs, atime, mtime, er2 => done(er2 && er)) : done()) } if (this[DOCHOWN](entry)) { actions++ const uid = this[UID](entry) const gid = this[GID](entry) fs.fchown(fd, uid, gid, er => er ? fs.chown(abs, uid, gid, er2 => done(er2 && er)) : done()) } done() }) const tx = this.transform ? this.transform(entry) || entry : entry if (tx !== entry) { tx.on('error', er => { this[ONERROR](er, entry) fullyDone() }) entry.pipe(tx) } tx.pipe(stream) } [DIRECTORY] (entry, fullyDone) { const mode = entry.mode & 0o7777 || this.dmode this[MKDIR](entry.absolute, mode, er => { if (er) { this[ONERROR](er, entry) fullyDone() return } let actions = 1 const done = _ => { if (--actions === 0) { fullyDone() this[UNPEND]() entry.resume() } } if (entry.mtime && !this.noMtime) { actions++ fs.utimes(entry.absolute, entry.atime || new Date(), entry.mtime, done) } if (this[DOCHOWN](entry)) { actions++ fs.chown(entry.absolute, this[UID](entry), this[GID](entry), done) } done() }) } [UNSUPPORTED] (entry) { entry.unsupported = true this.warn('TAR_ENTRY_UNSUPPORTED', `unsupported entry type: ${entry.type}`, { entry }) entry.resume() } [SYMLINK] (entry, done) { this[LINK](entry, entry.linkpath, 'symlink', done) } [HARDLINK] (entry, done) { const linkpath = normPath(path.resolve(this.cwd, entry.linkpath)) this[LINK](entry, linkpath, 'link', done) } [PEND] () { this[PENDING]++ } [UNPEND] () { this[PENDING]-- this[MAYBECLOSE]() } [SKIP] (entry) { this[UNPEND]() entry.resume() } // Check if we can reuse an existing filesystem entry safely and // overwrite it, rather than unlinking and recreating // Windows doesn't report a useful nlink, so we just never reuse entries [ISREUSABLE] (entry, st) { return entry.type === 'File' && !this.unlink && st.isFile() && st.nlink <= 1 && !isWindows } // check if a thing is there, and if so, try to clobber it [CHECKFS] (entry) { this[PEND]() const paths = [entry.path] if (entry.linkpath) { paths.push(entry.linkpath) } this.reservations.reserve(paths, done => this[CHECKFS2](entry, done)) } [PRUNECACHE] (entry) { // if we are not creating a directory, and the path is in the dirCache, // then that means we are about to delete the directory we created // previously, and it is no longer going to be a directory, and neither // is any of its children. // If a symbolic link is encountered, all bets are off. There is no // reasonable way to sanitize the cache in such a way we will be able to // avoid having filesystem collisions. If this happens with a non-symlink // entry, it'll just fail to unpack, but a symlink to a directory, using an // 8.3 shortname or certain unicode attacks, can evade detection and lead // to arbitrary writes to anywhere on the system. if (entry.type === 'SymbolicLink') { dropCache(this.dirCache) } else if (entry.type !== 'Directory') { pruneCache(this.dirCache, entry.absolute) } } [CHECKFS2] (entry, fullyDone) { this[PRUNECACHE](entry) const done = er => { this[PRUNECACHE](entry) fullyDone(er) } const checkCwd = () => { this[MKDIR](this.cwd, this.dmode, er => { if (er) { this[ONERROR](er, entry) done() return } this[CHECKED_CWD] = true start() }) } const start = () => { if (entry.absolute !== this.cwd) { const parent = normPath(path.dirname(entry.absolute)) if (parent !== this.cwd) { return this[MKDIR](parent, this.dmode, er => { if (er) { this[ONERROR](er, entry) done() return } afterMakeParent() }) } } afterMakeParent() } const afterMakeParent = () => { fs.lstat(entry.absolute, (lstatEr, st) => { if (st && (this.keep || this.newer && st.mtime > entry.mtime)) { this[SKIP](entry) done() return } if (lstatEr || this[ISREUSABLE](entry, st)) { return this[MAKEFS](null, entry, done) } if (st.isDirectory()) { if (entry.type === 'Directory') { const needChmod = !this.noChmod && entry.mode && (st.mode & 0o7777) !== entry.mode const afterChmod = er => this[MAKEFS](er, entry, done) if (!needChmod) { return afterChmod() } return fs.chmod(entry.absolute, entry.mode, afterChmod) } // Not a dir entry, have to remove it. // NB: the only way to end up with an entry that is the cwd // itself, in such a way that == does not detect, is a // tricky windows absolute path with UNC or 8.3 parts (and // preservePaths:true, or else it will have been stripped). // In that case, the user has opted out of path protections // explicitly, so if they blow away the cwd, c'est la vie. if (entry.absolute !== this.cwd) { return fs.rmdir(entry.absolute, er => this[MAKEFS](er, entry, done)) } } // not a dir, and not reusable // don't remove if the cwd, we want that error if (entry.absolute === this.cwd) { return this[MAKEFS](null, entry, done) } unlinkFile(entry.absolute, er => this[MAKEFS](er, entry, done)) }) } if (this[CHECKED_CWD]) { start() } else { checkCwd() } } [MAKEFS] (er, entry, done) { if (er) { this[ONERROR](er, entry) done() return } switch (entry.type) { case 'File': case 'OldFile': case 'ContiguousFile': return this[FILE](entry, done) case 'Link': return this[HARDLINK](entry, done) case 'SymbolicLink': return this[SYMLINK](entry, done) case 'Directory': case 'GNUDumpDir': return this[DIRECTORY](entry, done) } } [LINK] (entry, linkpath, link, done) { // XXX: get the type ('symlink' or 'junction') for windows fs[link](linkpath, entry.absolute, er => { if (er) { this[ONERROR](er, entry) } else { this[UNPEND]() entry.resume() } done() }) } } const callSync = fn => { try { return [null, fn()] } catch (er) { return [er, null] } } class UnpackSync extends Unpack { [MAKEFS] (er, entry) { return super[MAKEFS](er, entry, () => {}) } [CHECKFS] (entry) { this[PRUNECACHE](entry) if (!this[CHECKED_CWD]) { const er = this[MKDIR](this.cwd, this.dmode) if (er) { return this[ONERROR](er, entry) } this[CHECKED_CWD] = true } // don't bother to make the parent if the current entry is the cwd, // we've already checked it. if (entry.absolute !== this.cwd) { const parent = normPath(path.dirname(entry.absolute)) if (parent !== this.cwd) { const mkParent = this[MKDIR](parent, this.dmode) if (mkParent) { return this[ONERROR](mkParent, entry) } } } const [lstatEr, st] = callSync(() => fs.lstatSync(entry.absolute)) if (st && (this.keep || this.newer && st.mtime > entry.mtime)) { return this[SKIP](entry) } if (lstatEr || this[ISREUSABLE](entry, st)) { return this[MAKEFS](null, entry) } if (st.isDirectory()) { if (entry.type === 'Directory') { const needChmod = !this.noChmod && entry.mode && (st.mode & 0o7777) !== entry.mode const [er] = needChmod ? callSync(() => { fs.chmodSync(entry.absolute, entry.mode) }) : [] return this[MAKEFS](er, entry) } // not a dir entry, have to remove it const [er] = callSync(() => fs.rmdirSync(entry.absolute)) this[MAKEFS](er, entry) } // not a dir, and not reusable. // don't remove if it's the cwd, since we want that error. const [er] = entry.absolute === this.cwd ? [] : callSync(() => unlinkFileSync(entry.absolute)) this[MAKEFS](er, entry) } [FILE] (entry, done) { const mode = entry.mode & 0o7777 || this.fmode const oner = er => { let closeError try { fs.closeSync(fd) } catch (e) { closeError = e } if (er || closeError) { this[ONERROR](er || closeError, entry) } done() } let fd try { fd = fs.openSync(entry.absolute, getFlag(entry.size), mode) } catch (er) { return oner(er) } const tx = this.transform ? this.transform(entry) || entry : entry if (tx !== entry) { tx.on('error', er => this[ONERROR](er, entry)) entry.pipe(tx) } tx.on('data', chunk => { try { fs.writeSync(fd, chunk, 0, chunk.length) } catch (er) { oner(er) } }) tx.on('end', _ => { let er = null // try both, falling futimes back to utimes // if either fails, handle the first error if (entry.mtime && !this.noMtime) { const atime = entry.atime || new Date() const mtime = entry.mtime try { fs.futimesSync(fd, atime, mtime) } catch (futimeser) { try { fs.utimesSync(entry.absolute, atime, mtime) } catch (utimeser) { er = futimeser } } } if (this[DOCHOWN](entry)) { const uid = this[UID](entry) const gid = this[GID](entry) try { fs.fchownSync(fd, uid, gid) } catch (fchowner) { try { fs.chownSync(entry.absolute, uid, gid) } catch (chowner) { er = er || fchowner } } } oner(er) }) } [DIRECTORY] (entry, done) { const mode = entry.mode & 0o7777 || this.dmode const er = this[MKDIR](entry.absolute, mode) if (er) { this[ONERROR](er, entry) done() return } if (entry.mtime && !this.noMtime) { try { fs.utimesSync(entry.absolute, entry.atime || new Date(), entry.mtime) } catch (er) {} } if (this[DOCHOWN](entry)) { try { fs.chownSync(entry.absolute, this[UID](entry), this[GID](entry)) } catch (er) {} } done() entry.resume() } [MKDIR] (dir, mode) { try { return mkdir.sync(normPath(dir), { uid: this.uid, gid: this.gid, processUid: this.processUid, processGid: this.processGid, umask: this.processUmask, preserve: this.preservePaths, unlink: this.unlink, cache: this.dirCache, cwd: this.cwd, mode: mode, }) } catch (er) { return er } } [LINK] (entry, linkpath, link, done) { try { fs[link + 'Sync'](linkpath, entry.absolute) done() entry.resume() } catch (er) { return this[ONERROR](er, entry) } } } Unpack.Sync = UnpackSync module.exports = Unpack /***/ }), /***/ 94404: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // tar -u const hlo = __nccwpck_require__(95274) const r = __nccwpck_require__(45923) // just call tar.r with the filter and mtimeCache module.exports = (opt_, files, cb) => { const opt = hlo(opt_) if (!opt.file) { throw new TypeError('file is required') } if (opt.gzip) { throw new TypeError('cannot append to compressed archives') } if (!files || !Array.isArray(files) || !files.length) { throw new TypeError('no files or directories specified') } files = Array.from(files) mtimeFilter(opt) return r(opt, files, cb) } const mtimeFilter = opt => { const filter = opt.filter if (!opt.mtimeCache) { opt.mtimeCache = new Map() } opt.filter = filter ? (path, stat) => filter(path, stat) && !(opt.mtimeCache.get(path) > stat.mtime) : (path, stat) => !(opt.mtimeCache.get(path) > stat.mtime) } /***/ }), /***/ 85899: /***/ ((module) => { "use strict"; module.exports = Base => class extends Base { warn (code, message, data = {}) { if (this.file) { data.file = this.file } if (this.cwd) { data.cwd = this.cwd } data.code = message instanceof Error && message.code || code data.tarCode = code if (!this.strict && data.recoverable !== false) { if (message instanceof Error) { data = Object.assign(message, data) message = message.message } this.emit('warn', data.tarCode, message, data) } else if (message instanceof Error) { this.emit('error', Object.assign(message, data)) } else { this.emit('error', Object.assign(new Error(`${code}: ${message}`), data)) } } } /***/ }), /***/ 44808: /***/ ((module) => { "use strict"; // When writing files on Windows, translate the characters to their // 0xf000 higher-encoded versions. const raw = [ '|', '<', '>', '?', ':', ] const win = raw.map(char => String.fromCharCode(0xf000 + char.charCodeAt(0))) const toWin = new Map(raw.map((char, i) => [char, win[i]])) const toRaw = new Map(win.map((char, i) => [char, raw[i]])) module.exports = { encode: s => raw.reduce((s, c) => s.split(c).join(toWin.get(c)), s), decode: s => win.reduce((s, c) => s.split(c).join(toRaw.get(c)), s), } /***/ }), /***/ 55450: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { Minipass } = __nccwpck_require__(96684) const Pax = __nccwpck_require__(77996) const Header = __nccwpck_require__(66043) const fs = __nccwpck_require__(57147) const path = __nccwpck_require__(71017) const normPath = __nccwpck_require__(56843) const stripSlash = __nccwpck_require__(88886) const prefixPath = (path, prefix) => { if (!prefix) { return normPath(path) } path = normPath(path).replace(/^\.(\/|$)/, '') return stripSlash(prefix) + '/' + path } const maxReadSize = 16 * 1024 * 1024 const PROCESS = Symbol('process') const FILE = Symbol('file') const DIRECTORY = Symbol('directory') const SYMLINK = Symbol('symlink') const HARDLINK = Symbol('hardlink') const HEADER = Symbol('header') const READ = Symbol('read') const LSTAT = Symbol('lstat') const ONLSTAT = Symbol('onlstat') const ONREAD = Symbol('onread') const ONREADLINK = Symbol('onreadlink') const OPENFILE = Symbol('openfile') const ONOPENFILE = Symbol('onopenfile') const CLOSE = Symbol('close') const MODE = Symbol('mode') const AWAITDRAIN = Symbol('awaitDrain') const ONDRAIN = Symbol('ondrain') const PREFIX = Symbol('prefix') const HAD_ERROR = Symbol('hadError') const warner = __nccwpck_require__(85899) const winchars = __nccwpck_require__(44808) const stripAbsolutePath = __nccwpck_require__(37111) const modeFix = __nccwpck_require__(88371) const WriteEntry = warner(class WriteEntry extends Minipass { constructor (p, opt) { opt = opt || {} super(opt) if (typeof p !== 'string') { throw new TypeError('path is required') } this.path = normPath(p) // suppress atime, ctime, uid, gid, uname, gname this.portable = !!opt.portable // until node has builtin pwnam functions, this'll have to do this.myuid = process.getuid && process.getuid() || 0 this.myuser = process.env.USER || '' this.maxReadSize = opt.maxReadSize || maxReadSize this.linkCache = opt.linkCache || new Map() this.statCache = opt.statCache || new Map() this.preservePaths = !!opt.preservePaths this.cwd = normPath(opt.cwd || process.cwd()) this.strict = !!opt.strict this.noPax = !!opt.noPax this.noMtime = !!opt.noMtime this.mtime = opt.mtime || null this.prefix = opt.prefix ? normPath(opt.prefix) : null this.fd = null this.blockLen = null this.blockRemain = null this.buf = null this.offset = null this.length = null this.pos = null this.remain = null if (typeof opt.onwarn === 'function') { this.on('warn', opt.onwarn) } let pathWarn = false if (!this.preservePaths) { const [root, stripped] = stripAbsolutePath(this.path) if (root) { this.path = stripped pathWarn = root } } this.win32 = !!opt.win32 || process.platform === 'win32' if (this.win32) { // force the \ to / normalization, since we might not *actually* // be on windows, but want \ to be considered a path separator. this.path = winchars.decode(this.path.replace(/\\/g, '/')) p = p.replace(/\\/g, '/') } this.absolute = normPath(opt.absolute || path.resolve(this.cwd, p)) if (this.path === '') { this.path = './' } if (pathWarn) { this.warn('TAR_ENTRY_INFO', `stripping ${pathWarn} from absolute path`, { entry: this, path: pathWarn + this.path, }) } if (this.statCache.has(this.absolute)) { this[ONLSTAT](this.statCache.get(this.absolute)) } else { this[LSTAT]() } } emit (ev, ...data) { if (ev === 'error') { this[HAD_ERROR] = true } return super.emit(ev, ...data) } [LSTAT] () { fs.lstat(this.absolute, (er, stat) => { if (er) { return this.emit('error', er) } this[ONLSTAT](stat) }) } [ONLSTAT] (stat) { this.statCache.set(this.absolute, stat) this.stat = stat if (!stat.isFile()) { stat.size = 0 } this.type = getType(stat) this.emit('stat', stat) this[PROCESS]() } [PROCESS] () { switch (this.type) { case 'File': return this[FILE]() case 'Directory': return this[DIRECTORY]() case 'SymbolicLink': return this[SYMLINK]() // unsupported types are ignored. default: return this.end() } } [MODE] (mode) { return modeFix(mode, this.type === 'Directory', this.portable) } [PREFIX] (path) { return prefixPath(path, this.prefix) } [HEADER] () { if (this.type === 'Directory' && this.portable) { this.noMtime = true } this.header = new Header({ path: this[PREFIX](this.path), // only apply the prefix to hard links. linkpath: this.type === 'Link' ? this[PREFIX](this.linkpath) : this.linkpath, // only the permissions and setuid/setgid/sticky bitflags // not the higher-order bits that specify file type mode: this[MODE](this.stat.mode), uid: this.portable ? null : this.stat.uid, gid: this.portable ? null : this.stat.gid, size: this.stat.size, mtime: this.noMtime ? null : this.mtime || this.stat.mtime, type: this.type, uname: this.portable ? null : this.stat.uid === this.myuid ? this.myuser : '', atime: this.portable ? null : this.stat.atime, ctime: this.portable ? null : this.stat.ctime, }) if (this.header.encode() && !this.noPax) { super.write(new Pax({ atime: this.portable ? null : this.header.atime, ctime: this.portable ? null : this.header.ctime, gid: this.portable ? null : this.header.gid, mtime: this.noMtime ? null : this.mtime || this.header.mtime, path: this[PREFIX](this.path), linkpath: this.type === 'Link' ? this[PREFIX](this.linkpath) : this.linkpath, size: this.header.size, uid: this.portable ? null : this.header.uid, uname: this.portable ? null : this.header.uname, dev: this.portable ? null : this.stat.dev, ino: this.portable ? null : this.stat.ino, nlink: this.portable ? null : this.stat.nlink, }).encode()) } super.write(this.header.block) } [DIRECTORY] () { if (this.path.slice(-1) !== '/') { this.path += '/' } this.stat.size = 0 this[HEADER]() this.end() } [SYMLINK] () { fs.readlink(this.absolute, (er, linkpath) => { if (er) { return this.emit('error', er) } this[ONREADLINK](linkpath) }) } [ONREADLINK] (linkpath) { this.linkpath = normPath(linkpath) this[HEADER]() this.end() } [HARDLINK] (linkpath) { this.type = 'Link' this.linkpath = normPath(path.relative(this.cwd, linkpath)) this.stat.size = 0 this[HEADER]() this.end() } [FILE] () { if (this.stat.nlink > 1) { const linkKey = this.stat.dev + ':' + this.stat.ino if (this.linkCache.has(linkKey)) { const linkpath = this.linkCache.get(linkKey) if (linkpath.indexOf(this.cwd) === 0) { return this[HARDLINK](linkpath) } } this.linkCache.set(linkKey, this.absolute) } this[HEADER]() if (this.stat.size === 0) { return this.end() } this[OPENFILE]() } [OPENFILE] () { fs.open(this.absolute, 'r', (er, fd) => { if (er) { return this.emit('error', er) } this[ONOPENFILE](fd) }) } [ONOPENFILE] (fd) { this.fd = fd if (this[HAD_ERROR]) { return this[CLOSE]() } this.blockLen = 512 * Math.ceil(this.stat.size / 512) this.blockRemain = this.blockLen const bufLen = Math.min(this.blockLen, this.maxReadSize) this.buf = Buffer.allocUnsafe(bufLen) this.offset = 0 this.pos = 0 this.remain = this.stat.size this.length = this.buf.length this[READ]() } [READ] () { const { fd, buf, offset, length, pos } = this fs.read(fd, buf, offset, length, pos, (er, bytesRead) => { if (er) { // ignoring the error from close(2) is a bad practice, but at // this point we already have an error, don't need another one return this[CLOSE](() => this.emit('error', er)) } this[ONREAD](bytesRead) }) } [CLOSE] (cb) { fs.close(this.fd, cb) } [ONREAD] (bytesRead) { if (bytesRead <= 0 && this.remain > 0) { const er = new Error('encountered unexpected EOF') er.path = this.absolute er.syscall = 'read' er.code = 'EOF' return this[CLOSE](() => this.emit('error', er)) } if (bytesRead > this.remain) { const er = new Error('did not encounter expected EOF') er.path = this.absolute er.syscall = 'read' er.code = 'EOF' return this[CLOSE](() => this.emit('error', er)) } // null out the rest of the buffer, if we could fit the block padding // at the end of this loop, we've incremented bytesRead and this.remain // to be incremented up to the blockRemain level, as if we had expected // to get a null-padded file, and read it until the end. then we will // decrement both remain and blockRemain by bytesRead, and know that we // reached the expected EOF, without any null buffer to append. if (bytesRead === this.remain) { for (let i = bytesRead; i < this.length && bytesRead < this.blockRemain; i++) { this.buf[i + this.offset] = 0 bytesRead++ this.remain++ } } const writeBuf = this.offset === 0 && bytesRead === this.buf.length ? this.buf : this.buf.slice(this.offset, this.offset + bytesRead) const flushed = this.write(writeBuf) if (!flushed) { this[AWAITDRAIN](() => this[ONDRAIN]()) } else { this[ONDRAIN]() } } [AWAITDRAIN] (cb) { this.once('drain', cb) } write (writeBuf) { if (this.blockRemain < writeBuf.length) { const er = new Error('writing more data than expected') er.path = this.absolute return this.emit('error', er) } this.remain -= writeBuf.length this.blockRemain -= writeBuf.length this.pos += writeBuf.length this.offset += writeBuf.length return super.write(writeBuf) } [ONDRAIN] () { if (!this.remain) { if (this.blockRemain) { super.write(Buffer.alloc(this.blockRemain)) } return this[CLOSE](er => er ? this.emit('error', er) : this.end()) } if (this.offset >= this.length) { // if we only have a smaller bit left to read, alloc a smaller buffer // otherwise, keep it the same length it was before. this.buf = Buffer.allocUnsafe(Math.min(this.blockRemain, this.buf.length)) this.offset = 0 } this.length = this.buf.length - this.offset this[READ]() } }) class WriteEntrySync extends WriteEntry { [LSTAT] () { this[ONLSTAT](fs.lstatSync(this.absolute)) } [SYMLINK] () { this[ONREADLINK](fs.readlinkSync(this.absolute)) } [OPENFILE] () { this[ONOPENFILE](fs.openSync(this.absolute, 'r')) } [READ] () { let threw = true try { const { fd, buf, offset, length, pos } = this const bytesRead = fs.readSync(fd, buf, offset, length, pos) this[ONREAD](bytesRead) threw = false } finally { // ignoring the error from close(2) is a bad practice, but at // this point we already have an error, don't need another one if (threw) { try { this[CLOSE](() => {}) } catch (er) {} } } } [AWAITDRAIN] (cb) { cb() } [CLOSE] (cb) { fs.closeSync(this.fd) cb() } } const WriteEntryTar = warner(class WriteEntryTar extends Minipass { constructor (readEntry, opt) { opt = opt || {} super(opt) this.preservePaths = !!opt.preservePaths this.portable = !!opt.portable this.strict = !!opt.strict this.noPax = !!opt.noPax this.noMtime = !!opt.noMtime this.readEntry = readEntry this.type = readEntry.type if (this.type === 'Directory' && this.portable) { this.noMtime = true } this.prefix = opt.prefix || null this.path = normPath(readEntry.path) this.mode = this[MODE](readEntry.mode) this.uid = this.portable ? null : readEntry.uid this.gid = this.portable ? null : readEntry.gid this.uname = this.portable ? null : readEntry.uname this.gname = this.portable ? null : readEntry.gname this.size = readEntry.size this.mtime = this.noMtime ? null : opt.mtime || readEntry.mtime this.atime = this.portable ? null : readEntry.atime this.ctime = this.portable ? null : readEntry.ctime this.linkpath = normPath(readEntry.linkpath) if (typeof opt.onwarn === 'function') { this.on('warn', opt.onwarn) } let pathWarn = false if (!this.preservePaths) { const [root, stripped] = stripAbsolutePath(this.path) if (root) { this.path = stripped pathWarn = root } } this.remain = readEntry.size this.blockRemain = readEntry.startBlockSize this.header = new Header({ path: this[PREFIX](this.path), linkpath: this.type === 'Link' ? this[PREFIX](this.linkpath) : this.linkpath, // only the permissions and setuid/setgid/sticky bitflags // not the higher-order bits that specify file type mode: this.mode, uid: this.portable ? null : this.uid, gid: this.portable ? null : this.gid, size: this.size, mtime: this.noMtime ? null : this.mtime, type: this.type, uname: this.portable ? null : this.uname, atime: this.portable ? null : this.atime, ctime: this.portable ? null : this.ctime, }) if (pathWarn) { this.warn('TAR_ENTRY_INFO', `stripping ${pathWarn} from absolute path`, { entry: this, path: pathWarn + this.path, }) } if (this.header.encode() && !this.noPax) { super.write(new Pax({ atime: this.portable ? null : this.atime, ctime: this.portable ? null : this.ctime, gid: this.portable ? null : this.gid, mtime: this.noMtime ? null : this.mtime, path: this[PREFIX](this.path), linkpath: this.type === 'Link' ? this[PREFIX](this.linkpath) : this.linkpath, size: this.size, uid: this.portable ? null : this.uid, uname: this.portable ? null : this.uname, dev: this.portable ? null : this.readEntry.dev, ino: this.portable ? null : this.readEntry.ino, nlink: this.portable ? null : this.readEntry.nlink, }).encode()) } super.write(this.header.block) readEntry.pipe(this) } [PREFIX] (path) { return prefixPath(path, this.prefix) } [MODE] (mode) { return modeFix(mode, this.type === 'Directory', this.portable) } write (data) { const writeLen = data.length if (writeLen > this.blockRemain) { throw new Error('writing more to entry than is appropriate') } this.blockRemain -= writeLen return super.write(data) } end () { if (this.blockRemain) { super.write(Buffer.alloc(this.blockRemain)) } return super.end() } }) WriteEntry.Sync = WriteEntrySync WriteEntry.Tar = WriteEntryTar const getType = stat => stat.isFile() ? 'File' : stat.isDirectory() ? 'Directory' : stat.isSymbolicLink() ? 'SymbolicLink' : 'Unsupported' module.exports = WriteEntry /***/ }), /***/ 96684: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; const proc = typeof process === 'object' && process ? process : { stdout: null, stderr: null, } const EE = __nccwpck_require__(82361) const Stream = __nccwpck_require__(12781) const stringdecoder = __nccwpck_require__(71576) const SD = stringdecoder.StringDecoder const EOF = Symbol('EOF') const MAYBE_EMIT_END = Symbol('maybeEmitEnd') const EMITTED_END = Symbol('emittedEnd') const EMITTING_END = Symbol('emittingEnd') const EMITTED_ERROR = Symbol('emittedError') const CLOSED = Symbol('closed') const READ = Symbol('read') const FLUSH = Symbol('flush') const FLUSHCHUNK = Symbol('flushChunk') const ENCODING = Symbol('encoding') const DECODER = Symbol('decoder') const FLOWING = Symbol('flowing') const PAUSED = Symbol('paused') const RESUME = Symbol('resume') const BUFFER = Symbol('buffer') const PIPES = Symbol('pipes') const BUFFERLENGTH = Symbol('bufferLength') const BUFFERPUSH = Symbol('bufferPush') const BUFFERSHIFT = Symbol('bufferShift') const OBJECTMODE = Symbol('objectMode') // internal event when stream is destroyed const DESTROYED = Symbol('destroyed') // internal event when stream has an error const ERROR = Symbol('error') const EMITDATA = Symbol('emitData') const EMITEND = Symbol('emitEnd') const EMITEND2 = Symbol('emitEnd2') const ASYNC = Symbol('async') const ABORT = Symbol('abort') const ABORTED = Symbol('aborted') const SIGNAL = Symbol('signal') const defer = fn => Promise.resolve().then(fn) // TODO remove when Node v8 support drops const doIter = global._MP_NO_ITERATOR_SYMBOLS_ !== '1' const ASYNCITERATOR = (doIter && Symbol.asyncIterator) || Symbol('asyncIterator not implemented') const ITERATOR = (doIter && Symbol.iterator) || Symbol('iterator not implemented') // events that mean 'the stream is over' // these are treated specially, and re-emitted // if they are listened for after emitting. const isEndish = ev => ev === 'end' || ev === 'finish' || ev === 'prefinish' const isArrayBuffer = b => b instanceof ArrayBuffer || (typeof b === 'object' && b.constructor && b.constructor.name === 'ArrayBuffer' && b.byteLength >= 0) const isArrayBufferView = b => !Buffer.isBuffer(b) && ArrayBuffer.isView(b) class Pipe { constructor(src, dest, opts) { this.src = src this.dest = dest this.opts = opts this.ondrain = () => src[RESUME]() dest.on('drain', this.ondrain) } unpipe() { this.dest.removeListener('drain', this.ondrain) } // istanbul ignore next - only here for the prototype proxyErrors() {} end() { this.unpipe() if (this.opts.end) this.dest.end() } } class PipeProxyErrors extends Pipe { unpipe() { this.src.removeListener('error', this.proxyErrors) super.unpipe() } constructor(src, dest, opts) { super(src, dest, opts) this.proxyErrors = er => dest.emit('error', er) src.on('error', this.proxyErrors) } } class Minipass extends Stream { constructor(options) { super() this[FLOWING] = false // whether we're explicitly paused this[PAUSED] = false this[PIPES] = [] this[BUFFER] = [] this[OBJECTMODE] = (options && options.objectMode) || false if (this[OBJECTMODE]) this[ENCODING] = null else this[ENCODING] = (options && options.encoding) || null if (this[ENCODING] === 'buffer') this[ENCODING] = null this[ASYNC] = (options && !!options.async) || false this[DECODER] = this[ENCODING] ? new SD(this[ENCODING]) : null this[EOF] = false this[EMITTED_END] = false this[EMITTING_END] = false this[CLOSED] = false this[EMITTED_ERROR] = null this.writable = true this.readable = true this[BUFFERLENGTH] = 0 this[DESTROYED] = false if (options && options.debugExposeBuffer === true) { Object.defineProperty(this, 'buffer', { get: () => this[BUFFER] }) } if (options && options.debugExposePipes === true) { Object.defineProperty(this, 'pipes', { get: () => this[PIPES] }) } this[SIGNAL] = options && options.signal this[ABORTED] = false if (this[SIGNAL]) { this[SIGNAL].addEventListener('abort', () => this[ABORT]()) if (this[SIGNAL].aborted) { this[ABORT]() } } } get bufferLength() { return this[BUFFERLENGTH] } get encoding() { return this[ENCODING] } set encoding(enc) { if (this[OBJECTMODE]) throw new Error('cannot set encoding in objectMode') if ( this[ENCODING] && enc !== this[ENCODING] && ((this[DECODER] && this[DECODER].lastNeed) || this[BUFFERLENGTH]) ) throw new Error('cannot change encoding') if (this[ENCODING] !== enc) { this[DECODER] = enc ? new SD(enc) : null if (this[BUFFER].length) this[BUFFER] = this[BUFFER].map(chunk => this[DECODER].write(chunk)) } this[ENCODING] = enc } setEncoding(enc) { this.encoding = enc } get objectMode() { return this[OBJECTMODE] } set objectMode(om) { this[OBJECTMODE] = this[OBJECTMODE] || !!om } get ['async']() { return this[ASYNC] } set ['async'](a) { this[ASYNC] = this[ASYNC] || !!a } // drop everything and get out of the flow completely [ABORT]() { this[ABORTED] = true this.emit('abort', this[SIGNAL].reason) this.destroy(this[SIGNAL].reason) } get aborted() { return this[ABORTED] } set aborted(_) {} write(chunk, encoding, cb) { if (this[ABORTED]) return false if (this[EOF]) throw new Error('write after end') if (this[DESTROYED]) { this.emit( 'error', Object.assign( new Error('Cannot call write after a stream was destroyed'), { code: 'ERR_STREAM_DESTROYED' } ) ) return true } if (typeof encoding === 'function') (cb = encoding), (encoding = 'utf8') if (!encoding) encoding = 'utf8' const fn = this[ASYNC] ? defer : f => f() // convert array buffers and typed array views into buffers // at some point in the future, we may want to do the opposite! // leave strings and buffers as-is // anything else switches us into object mode if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) { if (isArrayBufferView(chunk)) chunk = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength) else if (isArrayBuffer(chunk)) chunk = Buffer.from(chunk) else if (typeof chunk !== 'string') // use the setter so we throw if we have encoding set this.objectMode = true } // handle object mode up front, since it's simpler // this yields better performance, fewer checks later. if (this[OBJECTMODE]) { /* istanbul ignore if - maybe impossible? */ if (this.flowing && this[BUFFERLENGTH] !== 0) this[FLUSH](true) if (this.flowing) this.emit('data', chunk) else this[BUFFERPUSH](chunk) if (this[BUFFERLENGTH] !== 0) this.emit('readable') if (cb) fn(cb) return this.flowing } // at this point the chunk is a buffer or string // don't buffer it up or send it to the decoder if (!chunk.length) { if (this[BUFFERLENGTH] !== 0) this.emit('readable') if (cb) fn(cb) return this.flowing } // fast-path writing strings of same encoding to a stream with // an empty buffer, skipping the buffer/decoder dance if ( typeof chunk === 'string' && // unless it is a string already ready for us to use !(encoding === this[ENCODING] && !this[DECODER].lastNeed) ) { chunk = Buffer.from(chunk, encoding) } if (Buffer.isBuffer(chunk) && this[ENCODING]) chunk = this[DECODER].write(chunk) // Note: flushing CAN potentially switch us into not-flowing mode if (this.flowing && this[BUFFERLENGTH] !== 0) this[FLUSH](true) if (this.flowing) this.emit('data', chunk) else this[BUFFERPUSH](chunk) if (this[BUFFERLENGTH] !== 0) this.emit('readable') if (cb) fn(cb) return this.flowing } read(n) { if (this[DESTROYED]) return null if (this[BUFFERLENGTH] === 0 || n === 0 || n > this[BUFFERLENGTH]) { this[MAYBE_EMIT_END]() return null } if (this[OBJECTMODE]) n = null if (this[BUFFER].length > 1 && !this[OBJECTMODE]) { if (this.encoding) this[BUFFER] = [this[BUFFER].join('')] else this[BUFFER] = [Buffer.concat(this[BUFFER], this[BUFFERLENGTH])] } const ret = this[READ](n || null, this[BUFFER][0]) this[MAYBE_EMIT_END]() return ret } [READ](n, chunk) { if (n === chunk.length || n === null) this[BUFFERSHIFT]() else { this[BUFFER][0] = chunk.slice(n) chunk = chunk.slice(0, n) this[BUFFERLENGTH] -= n } this.emit('data', chunk) if (!this[BUFFER].length && !this[EOF]) this.emit('drain') return chunk } end(chunk, encoding, cb) { if (typeof chunk === 'function') (cb = chunk), (chunk = null) if (typeof encoding === 'function') (cb = encoding), (encoding = 'utf8') if (chunk) this.write(chunk, encoding) if (cb) this.once('end', cb) this[EOF] = true this.writable = false // if we haven't written anything, then go ahead and emit, // even if we're not reading. // we'll re-emit if a new 'end' listener is added anyway. // This makes MP more suitable to write-only use cases. if (this.flowing || !this[PAUSED]) this[MAYBE_EMIT_END]() return this } // don't let the internal resume be overwritten [RESUME]() { if (this[DESTROYED]) return this[PAUSED] = false this[FLOWING] = true this.emit('resume') if (this[BUFFER].length) this[FLUSH]() else if (this[EOF]) this[MAYBE_EMIT_END]() else this.emit('drain') } resume() { return this[RESUME]() } pause() { this[FLOWING] = false this[PAUSED] = true } get destroyed() { return this[DESTROYED] } get flowing() { return this[FLOWING] } get paused() { return this[PAUSED] } [BUFFERPUSH](chunk) { if (this[OBJECTMODE]) this[BUFFERLENGTH] += 1 else this[BUFFERLENGTH] += chunk.length this[BUFFER].push(chunk) } [BUFFERSHIFT]() { if (this[OBJECTMODE]) this[BUFFERLENGTH] -= 1 else this[BUFFERLENGTH] -= this[BUFFER][0].length return this[BUFFER].shift() } [FLUSH](noDrain) { do {} while (this[FLUSHCHUNK](this[BUFFERSHIFT]()) && this[BUFFER].length) if (!noDrain && !this[BUFFER].length && !this[EOF]) this.emit('drain') } [FLUSHCHUNK](chunk) { this.emit('data', chunk) return this.flowing } pipe(dest, opts) { if (this[DESTROYED]) return const ended = this[EMITTED_END] opts = opts || {} if (dest === proc.stdout || dest === proc.stderr) opts.end = false else opts.end = opts.end !== false opts.proxyErrors = !!opts.proxyErrors // piping an ended stream ends immediately if (ended) { if (opts.end) dest.end() } else { this[PIPES].push( !opts.proxyErrors ? new Pipe(this, dest, opts) : new PipeProxyErrors(this, dest, opts) ) if (this[ASYNC]) defer(() => this[RESUME]()) else this[RESUME]() } return dest } unpipe(dest) { const p = this[PIPES].find(p => p.dest === dest) if (p) { this[PIPES].splice(this[PIPES].indexOf(p), 1) p.unpipe() } } addListener(ev, fn) { return this.on(ev, fn) } on(ev, fn) { const ret = super.on(ev, fn) if (ev === 'data' && !this[PIPES].length && !this.flowing) this[RESUME]() else if (ev === 'readable' && this[BUFFERLENGTH] !== 0) super.emit('readable') else if (isEndish(ev) && this[EMITTED_END]) { super.emit(ev) this.removeAllListeners(ev) } else if (ev === 'error' && this[EMITTED_ERROR]) { if (this[ASYNC]) defer(() => fn.call(this, this[EMITTED_ERROR])) else fn.call(this, this[EMITTED_ERROR]) } return ret } get emittedEnd() { return this[EMITTED_END] } [MAYBE_EMIT_END]() { if ( !this[EMITTING_END] && !this[EMITTED_END] && !this[DESTROYED] && this[BUFFER].length === 0 && this[EOF] ) { this[EMITTING_END] = true this.emit('end') this.emit('prefinish') this.emit('finish') if (this[CLOSED]) this.emit('close') this[EMITTING_END] = false } } emit(ev, data, ...extra) { // error and close are only events allowed after calling destroy() if (ev !== 'error' && ev !== 'close' && ev !== DESTROYED && this[DESTROYED]) return else if (ev === 'data') { return !this[OBJECTMODE] && !data ? false : this[ASYNC] ? defer(() => this[EMITDATA](data)) : this[EMITDATA](data) } else if (ev === 'end') { return this[EMITEND]() } else if (ev === 'close') { this[CLOSED] = true // don't emit close before 'end' and 'finish' if (!this[EMITTED_END] && !this[DESTROYED]) return const ret = super.emit('close') this.removeAllListeners('close') return ret } else if (ev === 'error') { this[EMITTED_ERROR] = data super.emit(ERROR, data) const ret = !this[SIGNAL] || this.listeners('error').length ? super.emit('error', data) : false this[MAYBE_EMIT_END]() return ret } else if (ev === 'resume') { const ret = super.emit('resume') this[MAYBE_EMIT_END]() return ret } else if (ev === 'finish' || ev === 'prefinish') { const ret = super.emit(ev) this.removeAllListeners(ev) return ret } // Some other unknown event const ret = super.emit(ev, data, ...extra) this[MAYBE_EMIT_END]() return ret } [EMITDATA](data) { for (const p of this[PIPES]) { if (p.dest.write(data) === false) this.pause() } const ret = super.emit('data', data) this[MAYBE_EMIT_END]() return ret } [EMITEND]() { if (this[EMITTED_END]) return this[EMITTED_END] = true this.readable = false if (this[ASYNC]) defer(() => this[EMITEND2]()) else this[EMITEND2]() } [EMITEND2]() { if (this[DECODER]) { const data = this[DECODER].end() if (data) { for (const p of this[PIPES]) { p.dest.write(data) } super.emit('data', data) } } for (const p of this[PIPES]) { p.end() } const ret = super.emit('end') this.removeAllListeners('end') return ret } // const all = await stream.collect() collect() { const buf = [] if (!this[OBJECTMODE]) buf.dataLength = 0 // set the promise first, in case an error is raised // by triggering the flow here. const p = this.promise() this.on('data', c => { buf.push(c) if (!this[OBJECTMODE]) buf.dataLength += c.length }) return p.then(() => buf) } // const data = await stream.concat() concat() { return this[OBJECTMODE] ? Promise.reject(new Error('cannot concat in objectMode')) : this.collect().then(buf => this[OBJECTMODE] ? Promise.reject(new Error('cannot concat in objectMode')) : this[ENCODING] ? buf.join('') : Buffer.concat(buf, buf.dataLength) ) } // stream.promise().then(() => done, er => emitted error) promise() { return new Promise((resolve, reject) => { this.on(DESTROYED, () => reject(new Error('stream destroyed'))) this.on('error', er => reject(er)) this.on('end', () => resolve()) }) } // for await (let chunk of stream) [ASYNCITERATOR]() { let stopped = false const stop = () => { this.pause() stopped = true return Promise.resolve({ done: true }) } const next = () => { if (stopped) return stop() const res = this.read() if (res !== null) return Promise.resolve({ done: false, value: res }) if (this[EOF]) return stop() let resolve = null let reject = null const onerr = er => { this.removeListener('data', ondata) this.removeListener('end', onend) this.removeListener(DESTROYED, ondestroy) stop() reject(er) } const ondata = value => { this.removeListener('error', onerr) this.removeListener('end', onend) this.removeListener(DESTROYED, ondestroy) this.pause() resolve({ value: value, done: !!this[EOF] }) } const onend = () => { this.removeListener('error', onerr) this.removeListener('data', ondata) this.removeListener(DESTROYED, ondestroy) stop() resolve({ done: true }) } const ondestroy = () => onerr(new Error('stream destroyed')) return new Promise((res, rej) => { reject = rej resolve = res this.once(DESTROYED, ondestroy) this.once('error', onerr) this.once('end', onend) this.once('data', ondata) }) } return { next, throw: stop, return: stop, [ASYNCITERATOR]() { return this }, } } // for (let chunk of stream) [ITERATOR]() { let stopped = false const stop = () => { this.pause() this.removeListener(ERROR, stop) this.removeListener(DESTROYED, stop) this.removeListener('end', stop) stopped = true return { done: true } } const next = () => { if (stopped) return stop() const value = this.read() return value === null ? stop() : { value } } this.once('end', stop) this.once(ERROR, stop) this.once(DESTROYED, stop) return { next, throw: stop, return: stop, [ITERATOR]() { return this }, } } destroy(er) { if (this[DESTROYED]) { if (er) this.emit('error', er) else this.emit(DESTROYED) return this } this[DESTROYED] = true // throw away all buffered data, it's never coming out this[BUFFER].length = 0 this[BUFFERLENGTH] = 0 if (typeof this.close === 'function' && !this[CLOSED]) this.close() if (er) this.emit('error', er) // if no error to emit, still reject pending promises else this.emit(DESTROYED) return this } static isStream(s) { return ( !!s && (s instanceof Minipass || s instanceof Stream || (s instanceof EE && // readable (typeof s.pipe === 'function' || // writable (typeof s.write === 'function' && typeof s.end === 'function')))) ) } } exports.Minipass = Minipass /***/ }), /***/ 68065: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { promisify } = __nccwpck_require__(73837); const tmp = __nccwpck_require__(8517); // file module.exports.fileSync = tmp.fileSync; const fileWithOptions = promisify((options, cb) => tmp.file(options, (err, path, fd, cleanup) => err ? cb(err) : cb(undefined, { path, fd, cleanup: promisify(cleanup) }) ) ); module.exports.file = async (options) => fileWithOptions(options); module.exports.withFile = async function withFile(fn, options) { const { path, fd, cleanup } = await module.exports.file(options); try { return await fn({ path, fd }); } finally { await cleanup(); } }; // directory module.exports.dirSync = tmp.dirSync; const dirWithOptions = promisify((options, cb) => tmp.dir(options, (err, path, cleanup) => err ? cb(err) : cb(undefined, { path, cleanup: promisify(cleanup) }) ) ); module.exports.dir = async (options) => dirWithOptions(options); module.exports.withDir = async function withDir(fn, options) { const { path, cleanup } = await module.exports.dir(options); try { return await fn({ path }); } finally { await cleanup(); } }; // name generation module.exports.tmpNameSync = tmp.tmpNameSync; module.exports.tmpName = promisify(tmp.tmpName); module.exports.tmpdir = tmp.tmpdir; module.exports.setGracefulCleanup = tmp.setGracefulCleanup; /***/ }), /***/ 8517: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /*! * Tmp * * Copyright (c) 2011-2017 KARASZI Istvan * * MIT Licensed */ /* * Module dependencies. */ const fs = __nccwpck_require__(57147); const os = __nccwpck_require__(22037); const path = __nccwpck_require__(71017); const crypto = __nccwpck_require__(6113); const _c = { fs: fs.constants, os: os.constants }; const rimraf = __nccwpck_require__(14959); /* * The working inner variables. */ const // the random characters to choose from RANDOM_CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', TEMPLATE_PATTERN = /XXXXXX/, DEFAULT_TRIES = 3, CREATE_FLAGS = (_c.O_CREAT || _c.fs.O_CREAT) | (_c.O_EXCL || _c.fs.O_EXCL) | (_c.O_RDWR || _c.fs.O_RDWR), // constants are off on the windows platform and will not match the actual errno codes IS_WIN32 = os.platform() === 'win32', EBADF = _c.EBADF || _c.os.errno.EBADF, ENOENT = _c.ENOENT || _c.os.errno.ENOENT, DIR_MODE = 0o700 /* 448 */, FILE_MODE = 0o600 /* 384 */, EXIT = 'exit', // this will hold the objects need to be removed on exit _removeObjects = [], // API change in fs.rmdirSync leads to error when passing in a second parameter, e.g. the callback FN_RMDIR_SYNC = fs.rmdirSync.bind(fs), FN_RIMRAF_SYNC = rimraf.sync; let _gracefulCleanup = false; /** * Gets a temporary file name. * * @param {(Options|tmpNameCallback)} options options or callback * @param {?tmpNameCallback} callback the callback function */ function tmpName(options, callback) { const args = _parseArguments(options, callback), opts = args[0], cb = args[1]; try { _assertAndSanitizeOptions(opts); } catch (err) { return cb(err); } let tries = opts.tries; (function _getUniqueName() { try { const name = _generateTmpName(opts); // check whether the path exists then retry if needed fs.stat(name, function (err) { /* istanbul ignore else */ if (!err) { /* istanbul ignore else */ if (tries-- > 0) return _getUniqueName(); return cb(new Error('Could not get a unique tmp filename, max tries reached ' + name)); } cb(null, name); }); } catch (err) { cb(err); } }()); } /** * Synchronous version of tmpName. * * @param {Object} options * @returns {string} the generated random name * @throws {Error} if the options are invalid or could not generate a filename */ function tmpNameSync(options) { const args = _parseArguments(options), opts = args[0]; _assertAndSanitizeOptions(opts); let tries = opts.tries; do { const name = _generateTmpName(opts); try { fs.statSync(name); } catch (e) { return name; } } while (tries-- > 0); throw new Error('Could not get a unique tmp filename, max tries reached'); } /** * Creates and opens a temporary file. * * @param {(Options|null|undefined|fileCallback)} options the config options or the callback function or null or undefined * @param {?fileCallback} callback */ function file(options, callback) { const args = _parseArguments(options, callback), opts = args[0], cb = args[1]; // gets a temporary filename tmpName(opts, function _tmpNameCreated(err, name) { /* istanbul ignore else */ if (err) return cb(err); // create and open the file fs.open(name, CREATE_FLAGS, opts.mode || FILE_MODE, function _fileCreated(err, fd) { /* istanbu ignore else */ if (err) return cb(err); if (opts.discardDescriptor) { return fs.close(fd, function _discardCallback(possibleErr) { // the chance of getting an error on close here is rather low and might occur in the most edgiest cases only return cb(possibleErr, name, undefined, _prepareTmpFileRemoveCallback(name, -1, opts, false)); }); } else { // detachDescriptor passes the descriptor whereas discardDescriptor closes it, either way, we no longer care // about the descriptor const discardOrDetachDescriptor = opts.discardDescriptor || opts.detachDescriptor; cb(null, name, fd, _prepareTmpFileRemoveCallback(name, discardOrDetachDescriptor ? -1 : fd, opts, false)); } }); }); } /** * Synchronous version of file. * * @param {Options} options * @returns {FileSyncObject} object consists of name, fd and removeCallback * @throws {Error} if cannot create a file */ function fileSync(options) { const args = _parseArguments(options), opts = args[0]; const discardOrDetachDescriptor = opts.discardDescriptor || opts.detachDescriptor; const name = tmpNameSync(opts); var fd = fs.openSync(name, CREATE_FLAGS, opts.mode || FILE_MODE); /* istanbul ignore else */ if (opts.discardDescriptor) { fs.closeSync(fd); fd = undefined; } return { name: name, fd: fd, removeCallback: _prepareTmpFileRemoveCallback(name, discardOrDetachDescriptor ? -1 : fd, opts, true) }; } /** * Creates a temporary directory. * * @param {(Options|dirCallback)} options the options or the callback function * @param {?dirCallback} callback */ function dir(options, callback) { const args = _parseArguments(options, callback), opts = args[0], cb = args[1]; // gets a temporary filename tmpName(opts, function _tmpNameCreated(err, name) { /* istanbul ignore else */ if (err) return cb(err); // create the directory fs.mkdir(name, opts.mode || DIR_MODE, function _dirCreated(err) { /* istanbul ignore else */ if (err) return cb(err); cb(null, name, _prepareTmpDirRemoveCallback(name, opts, false)); }); }); } /** * Synchronous version of dir. * * @param {Options} options * @returns {DirSyncObject} object consists of name and removeCallback * @throws {Error} if it cannot create a directory */ function dirSync(options) { const args = _parseArguments(options), opts = args[0]; const name = tmpNameSync(opts); fs.mkdirSync(name, opts.mode || DIR_MODE); return { name: name, removeCallback: _prepareTmpDirRemoveCallback(name, opts, true) }; } /** * Removes files asynchronously. * * @param {Object} fdPath * @param {Function} next * @private */ function _removeFileAsync(fdPath, next) { const _handler = function (err) { if (err && !_isENOENT(err)) { // reraise any unanticipated error return next(err); } next(); }; if (0 <= fdPath[0]) fs.close(fdPath[0], function () { fs.unlink(fdPath[1], _handler); }); else fs.unlink(fdPath[1], _handler); } /** * Removes files synchronously. * * @param {Object} fdPath * @private */ function _removeFileSync(fdPath) { let rethrownException = null; try { if (0 <= fdPath[0]) fs.closeSync(fdPath[0]); } catch (e) { // reraise any unanticipated error if (!_isEBADF(e) && !_isENOENT(e)) throw e; } finally { try { fs.unlinkSync(fdPath[1]); } catch (e) { // reraise any unanticipated error if (!_isENOENT(e)) rethrownException = e; } } if (rethrownException !== null) { throw rethrownException; } } /** * Prepares the callback for removal of the temporary file. * * Returns either a sync callback or a async callback depending on whether * fileSync or file was called, which is expressed by the sync parameter. * * @param {string} name the path of the file * @param {number} fd file descriptor * @param {Object} opts * @param {boolean} sync * @returns {fileCallback | fileCallbackSync} * @private */ function _prepareTmpFileRemoveCallback(name, fd, opts, sync) { const removeCallbackSync = _prepareRemoveCallback(_removeFileSync, [fd, name], sync); const removeCallback = _prepareRemoveCallback(_removeFileAsync, [fd, name], sync, removeCallbackSync); if (!opts.keep) _removeObjects.unshift(removeCallbackSync); return sync ? removeCallbackSync : removeCallback; } /** * Prepares the callback for removal of the temporary directory. * * Returns either a sync callback or a async callback depending on whether * tmpFileSync or tmpFile was called, which is expressed by the sync parameter. * * @param {string} name * @param {Object} opts * @param {boolean} sync * @returns {Function} the callback * @private */ function _prepareTmpDirRemoveCallback(name, opts, sync) { const removeFunction = opts.unsafeCleanup ? rimraf : fs.rmdir.bind(fs); const removeFunctionSync = opts.unsafeCleanup ? FN_RIMRAF_SYNC : FN_RMDIR_SYNC; const removeCallbackSync = _prepareRemoveCallback(removeFunctionSync, name, sync); const removeCallback = _prepareRemoveCallback(removeFunction, name, sync, removeCallbackSync); if (!opts.keep) _removeObjects.unshift(removeCallbackSync); return sync ? removeCallbackSync : removeCallback; } /** * Creates a guarded function wrapping the removeFunction call. * * The cleanup callback is save to be called multiple times. * Subsequent invocations will be ignored. * * @param {Function} removeFunction * @param {string} fileOrDirName * @param {boolean} sync * @param {cleanupCallbackSync?} cleanupCallbackSync * @returns {cleanupCallback | cleanupCallbackSync} * @private */ function _prepareRemoveCallback(removeFunction, fileOrDirName, sync, cleanupCallbackSync) { let called = false; // if sync is true, the next parameter will be ignored return function _cleanupCallback(next) { /* istanbul ignore else */ if (!called) { // remove cleanupCallback from cache const toRemove = cleanupCallbackSync || _cleanupCallback; const index = _removeObjects.indexOf(toRemove); /* istanbul ignore else */ if (index >= 0) _removeObjects.splice(index, 1); called = true; if (sync || removeFunction === FN_RMDIR_SYNC || removeFunction === FN_RIMRAF_SYNC) { return removeFunction(fileOrDirName); } else { return removeFunction(fileOrDirName, next || function() {}); } } }; } /** * The garbage collector. * * @private */ function _garbageCollector() { /* istanbul ignore else */ if (!_gracefulCleanup) return; // the function being called removes itself from _removeObjects, // loop until _removeObjects is empty while (_removeObjects.length) { try { _removeObjects[0](); } catch (e) { // already removed? } } } /** * Random name generator based on crypto. * Adapted from http://blog.tompawlak.org/how-to-generate-random-values-nodejs-javascript * * @param {number} howMany * @returns {string} the generated random name * @private */ function _randomChars(howMany) { let value = [], rnd = null; // make sure that we do not fail because we ran out of entropy try { rnd = crypto.randomBytes(howMany); } catch (e) { rnd = crypto.pseudoRandomBytes(howMany); } for (var i = 0; i < howMany; i++) { value.push(RANDOM_CHARS[rnd[i] % RANDOM_CHARS.length]); } return value.join(''); } /** * Helper which determines whether a string s is blank, that is undefined, or empty or null. * * @private * @param {string} s * @returns {Boolean} true whether the string s is blank, false otherwise */ function _isBlank(s) { return s === null || _isUndefined(s) || !s.trim(); } /** * Checks whether the `obj` parameter is defined or not. * * @param {Object} obj * @returns {boolean} true if the object is undefined * @private */ function _isUndefined(obj) { return typeof obj === 'undefined'; } /** * Parses the function arguments. * * This function helps to have optional arguments. * * @param {(Options|null|undefined|Function)} options * @param {?Function} callback * @returns {Array} parsed arguments * @private */ function _parseArguments(options, callback) { /* istanbul ignore else */ if (typeof options === 'function') { return [{}, options]; } /* istanbul ignore else */ if (_isUndefined(options)) { return [{}, callback]; } // copy options so we do not leak the changes we make internally const actualOptions = {}; for (const key of Object.getOwnPropertyNames(options)) { actualOptions[key] = options[key]; } return [actualOptions, callback]; } /** * Generates a new temporary name. * * @param {Object} opts * @returns {string} the new random name according to opts * @private */ function _generateTmpName(opts) { const tmpDir = opts.tmpdir; /* istanbul ignore else */ if (!_isUndefined(opts.name)) return path.join(tmpDir, opts.dir, opts.name); /* istanbul ignore else */ if (!_isUndefined(opts.template)) return path.join(tmpDir, opts.dir, opts.template).replace(TEMPLATE_PATTERN, _randomChars(6)); // prefix and postfix const name = [ opts.prefix ? opts.prefix : 'tmp', '-', process.pid, '-', _randomChars(12), opts.postfix ? '-' + opts.postfix : '' ].join(''); return path.join(tmpDir, opts.dir, name); } /** * Asserts whether the specified options are valid, also sanitizes options and provides sane defaults for missing * options. * * @param {Options} options * @private */ function _assertAndSanitizeOptions(options) { options.tmpdir = _getTmpDir(options); const tmpDir = options.tmpdir; /* istanbul ignore else */ if (!_isUndefined(options.name)) _assertIsRelative(options.name, 'name', tmpDir); /* istanbul ignore else */ if (!_isUndefined(options.dir)) _assertIsRelative(options.dir, 'dir', tmpDir); /* istanbul ignore else */ if (!_isUndefined(options.template)) { _assertIsRelative(options.template, 'template', tmpDir); if (!options.template.match(TEMPLATE_PATTERN)) throw new Error(`Invalid template, found "${options.template}".`); } /* istanbul ignore else */ if (!_isUndefined(options.tries) && isNaN(options.tries) || options.tries < 0) throw new Error(`Invalid tries, found "${options.tries}".`); // if a name was specified we will try once options.tries = _isUndefined(options.name) ? options.tries || DEFAULT_TRIES : 1; options.keep = !!options.keep; options.detachDescriptor = !!options.detachDescriptor; options.discardDescriptor = !!options.discardDescriptor; options.unsafeCleanup = !!options.unsafeCleanup; // sanitize dir, also keep (multiple) blanks if the user, purportedly sane, requests us to options.dir = _isUndefined(options.dir) ? '' : path.relative(tmpDir, _resolvePath(options.dir, tmpDir)); options.template = _isUndefined(options.template) ? undefined : path.relative(tmpDir, _resolvePath(options.template, tmpDir)); // sanitize further if template is relative to options.dir options.template = _isBlank(options.template) ? undefined : path.relative(options.dir, options.template); // for completeness' sake only, also keep (multiple) blanks if the user, purportedly sane, requests us to options.name = _isUndefined(options.name) ? undefined : _sanitizeName(options.name); options.prefix = _isUndefined(options.prefix) ? '' : options.prefix; options.postfix = _isUndefined(options.postfix) ? '' : options.postfix; } /** * Resolve the specified path name in respect to tmpDir. * * The specified name might include relative path components, e.g. ../ * so we need to resolve in order to be sure that is is located inside tmpDir * * @param name * @param tmpDir * @returns {string} * @private */ function _resolvePath(name, tmpDir) { const sanitizedName = _sanitizeName(name); if (sanitizedName.startsWith(tmpDir)) { return path.resolve(sanitizedName); } else { return path.resolve(path.join(tmpDir, sanitizedName)); } } /** * Sanitize the specified path name by removing all quote characters. * * @param name * @returns {string} * @private */ function _sanitizeName(name) { if (_isBlank(name)) { return name; } return name.replace(/["']/g, ''); } /** * Asserts whether specified name is relative to the specified tmpDir. * * @param {string} name * @param {string} option * @param {string} tmpDir * @throws {Error} * @private */ function _assertIsRelative(name, option, tmpDir) { if (option === 'name') { // assert that name is not absolute and does not contain a path if (path.isAbsolute(name)) throw new Error(`${option} option must not contain an absolute path, found "${name}".`); // must not fail on valid . or .. or similar such constructs let basename = path.basename(name); if (basename === '..' || basename === '.' || basename !== name) throw new Error(`${option} option must not contain a path, found "${name}".`); } else { // if (option === 'dir' || option === 'template') { // assert that dir or template are relative to tmpDir if (path.isAbsolute(name) && !name.startsWith(tmpDir)) { throw new Error(`${option} option must be relative to "${tmpDir}", found "${name}".`); } let resolvedPath = _resolvePath(name, tmpDir); if (!resolvedPath.startsWith(tmpDir)) throw new Error(`${option} option must be relative to "${tmpDir}", found "${resolvedPath}".`); } } /** * Helper for testing against EBADF to compensate changes made to Node 7.x under Windows. * * @private */ function _isEBADF(error) { return _isExpectedError(error, -EBADF, 'EBADF'); } /** * Helper for testing against ENOENT to compensate changes made to Node 7.x under Windows. * * @private */ function _isENOENT(error) { return _isExpectedError(error, -ENOENT, 'ENOENT'); } /** * Helper to determine whether the expected error code matches the actual code and errno, * which will differ between the supported node versions. * * - Node >= 7.0: * error.code {string} * error.errno {number} any numerical value will be negated * * CAVEAT * * On windows, the errno for EBADF is -4083 but os.constants.errno.EBADF is different and we must assume that ENOENT * is no different here. * * @param {SystemError} error * @param {number} errno * @param {string} code * @private */ function _isExpectedError(error, errno, code) { return IS_WIN32 ? error.code === code : error.code === code && error.errno === errno; } /** * Sets the graceful cleanup. * * If graceful cleanup is set, tmp will remove all controlled temporary objects on process exit, otherwise the * temporary objects will remain in place, waiting to be cleaned up on system restart or otherwise scheduled temporary * object removals. */ function setGracefulCleanup() { _gracefulCleanup = true; } /** * Returns the currently configured tmp dir from os.tmpdir(). * * @private * @param {?Options} options * @returns {string} the currently configured tmp dir */ function _getTmpDir(options) { return path.resolve(_sanitizeName(options && options.tmpdir || os.tmpdir())); } // Install process exit listener process.addListener(EXIT, _garbageCollector); /** * Configuration options. * * @typedef {Object} Options * @property {?boolean} keep the temporary object (file or dir) will not be garbage collected * @property {?number} tries the number of tries before give up the name generation * @property (?int) mode the access mode, defaults are 0o700 for directories and 0o600 for files * @property {?string} template the "mkstemp" like filename template * @property {?string} name fixed name relative to tmpdir or the specified dir option * @property {?string} dir tmp directory relative to the root tmp directory in use * @property {?string} prefix prefix for the generated name * @property {?string} postfix postfix for the generated name * @property {?string} tmpdir the root tmp directory which overrides the os tmpdir * @property {?boolean} unsafeCleanup recursively removes the created temporary directory, even when it's not empty * @property {?boolean} detachDescriptor detaches the file descriptor, caller is responsible for closing the file, tmp will no longer try closing the file during garbage collection * @property {?boolean} discardDescriptor discards the file descriptor (closes file, fd is -1), tmp will no longer try closing the file during garbage collection */ /** * @typedef {Object} FileSyncObject * @property {string} name the name of the file * @property {string} fd the file descriptor or -1 if the fd has been discarded * @property {fileCallback} removeCallback the callback function to remove the file */ /** * @typedef {Object} DirSyncObject * @property {string} name the name of the directory * @property {fileCallback} removeCallback the callback function to remove the directory */ /** * @callback tmpNameCallback * @param {?Error} err the error object if anything goes wrong * @param {string} name the temporary file name */ /** * @callback fileCallback * @param {?Error} err the error object if anything goes wrong * @param {string} name the temporary file name * @param {number} fd the file descriptor or -1 if the fd had been discarded * @param {cleanupCallback} fn the cleanup callback function */ /** * @callback fileCallbackSync * @param {?Error} err the error object if anything goes wrong * @param {string} name the temporary file name * @param {number} fd the file descriptor or -1 if the fd had been discarded * @param {cleanupCallbackSync} fn the cleanup callback function */ /** * @callback dirCallback * @param {?Error} err the error object if anything goes wrong * @param {string} name the temporary file name * @param {cleanupCallback} fn the cleanup callback function */ /** * @callback dirCallbackSync * @param {?Error} err the error object if anything goes wrong * @param {string} name the temporary file name * @param {cleanupCallbackSync} fn the cleanup callback function */ /** * Removes the temporary created file or directory. * * @callback cleanupCallback * @param {simpleCallback} [next] function to call whenever the tmp object needs to be removed */ /** * Removes the temporary created file or directory. * * @callback cleanupCallbackSync */ /** * Callback function for function composition. * @see {@link https://github.com/raszi/node-tmp/issues/57|raszi/node-tmp#57} * * @callback simpleCallback */ // exporting all the needed methods // evaluate _getTmpDir() lazily, mainly for simplifying testing but it also will // allow users to reconfigure the temporary directory Object.defineProperty(module.exports, "tmpdir", ({ enumerable: true, configurable: false, get: function () { return _getTmpDir(); } })); module.exports.dir = dir; module.exports.dirSync = dirSync; module.exports.file = file; module.exports.fileSync = fileSync; module.exports.tmpName = tmpName; module.exports.tmpNameSync = tmpNameSync; module.exports.setGracefulCleanup = setGracefulCleanup; /***/ }), /***/ 47372: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /*! * Copyright (c) 2015, Salesforce.com, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of Salesforce.com nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ var net = __nccwpck_require__(41808); var urlParse = (__nccwpck_require__(57310).parse); var util = __nccwpck_require__(73837); var pubsuffix = __nccwpck_require__(94401); var Store = (__nccwpck_require__(460)/* .Store */ .y); var MemoryCookieStore = (__nccwpck_require__(52640)/* .MemoryCookieStore */ .m); var pathMatch = (__nccwpck_require__(54336)/* .pathMatch */ .U); var VERSION = __nccwpck_require__(93199); var punycode; try { punycode = __nccwpck_require__(85477); } catch(e) { console.warn("tough-cookie: can't load punycode; won't use punycode for domain normalization"); } // From RFC6265 S4.1.1 // note that it excludes \x3B ";" var COOKIE_OCTETS = /^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]+$/; var CONTROL_CHARS = /[\x00-\x1F]/; // From Chromium // '\r', '\n' and '\0' should be treated as a terminator in // the "relaxed" mode, see: // https://github.com/ChromiumWebApps/chromium/blob/b3d3b4da8bb94c1b2e061600df106d590fda3620/net/cookies/parsed_cookie.cc#L60 var TERMINATORS = ['\n', '\r', '\0']; // RFC6265 S4.1.1 defines path value as 'any CHAR except CTLs or ";"' // Note ';' is \x3B var PATH_VALUE = /[\x20-\x3A\x3C-\x7E]+/; // date-time parsing constants (RFC6265 S5.1.1) var DATE_DELIM = /[\x09\x20-\x2F\x3B-\x40\x5B-\x60\x7B-\x7E]/; var MONTH_TO_NUM = { jan:0, feb:1, mar:2, apr:3, may:4, jun:5, jul:6, aug:7, sep:8, oct:9, nov:10, dec:11 }; var NUM_TO_MONTH = [ 'Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec' ]; var NUM_TO_DAY = [ 'Sun','Mon','Tue','Wed','Thu','Fri','Sat' ]; var MAX_TIME = 2147483647000; // 31-bit max var MIN_TIME = 0; // 31-bit min /* * Parses a Natural number (i.e., non-negative integer) with either the * *DIGIT ( non-digit *OCTET ) * or * *DIGIT * grammar (RFC6265 S5.1.1). * * The "trailingOK" boolean controls if the grammar accepts a * "( non-digit *OCTET )" trailer. */ function parseDigits(token, minDigits, maxDigits, trailingOK) { var count = 0; while (count < token.length) { var c = token.charCodeAt(count); // "non-digit = %x00-2F / %x3A-FF" if (c <= 0x2F || c >= 0x3A) { break; } count++; } // constrain to a minimum and maximum number of digits. if (count < minDigits || count > maxDigits) { return null; } if (!trailingOK && count != token.length) { return null; } return parseInt(token.substr(0,count), 10); } function parseTime(token) { var parts = token.split(':'); var result = [0,0,0]; /* RF6256 S5.1.1: * time = hms-time ( non-digit *OCTET ) * hms-time = time-field ":" time-field ":" time-field * time-field = 1*2DIGIT */ if (parts.length !== 3) { return null; } for (var i = 0; i < 3; i++) { // "time-field" must be strictly "1*2DIGIT", HOWEVER, "hms-time" can be // followed by "( non-digit *OCTET )" so therefore the last time-field can // have a trailer var trailingOK = (i == 2); var num = parseDigits(parts[i], 1, 2, trailingOK); if (num === null) { return null; } result[i] = num; } return result; } function parseMonth(token) { token = String(token).substr(0,3).toLowerCase(); var num = MONTH_TO_NUM[token]; return num >= 0 ? num : null; } /* * RFC6265 S5.1.1 date parser (see RFC for full grammar) */ function parseDate(str) { if (!str) { return; } /* RFC6265 S5.1.1: * 2. Process each date-token sequentially in the order the date-tokens * appear in the cookie-date */ var tokens = str.split(DATE_DELIM); if (!tokens) { return; } var hour = null; var minute = null; var second = null; var dayOfMonth = null; var month = null; var year = null; for (var i=0; i= 70 && year <= 99) { year += 1900; } else if (year >= 0 && year <= 69) { year += 2000; } } } } /* RFC 6265 S5.1.1 * "5. Abort these steps and fail to parse the cookie-date if: * * at least one of the found-day-of-month, found-month, found- * year, or found-time flags is not set, * * the day-of-month-value is less than 1 or greater than 31, * * the year-value is less than 1601, * * the hour-value is greater than 23, * * the minute-value is greater than 59, or * * the second-value is greater than 59. * (Note that leap seconds cannot be represented in this syntax.)" * * So, in order as above: */ if ( dayOfMonth === null || month === null || year === null || second === null || dayOfMonth < 1 || dayOfMonth > 31 || year < 1601 || hour > 23 || minute > 59 || second > 59 ) { return; } return new Date(Date.UTC(year, month, dayOfMonth, hour, minute, second)); } function formatDate(date) { var d = date.getUTCDate(); d = d >= 10 ? d : '0'+d; var h = date.getUTCHours(); h = h >= 10 ? h : '0'+h; var m = date.getUTCMinutes(); m = m >= 10 ? m : '0'+m; var s = date.getUTCSeconds(); s = s >= 10 ? s : '0'+s; return NUM_TO_DAY[date.getUTCDay()] + ', ' + d+' '+ NUM_TO_MONTH[date.getUTCMonth()] +' '+ date.getUTCFullYear() +' '+ h+':'+m+':'+s+' GMT'; } // S5.1.2 Canonicalized Host Names function canonicalDomain(str) { if (str == null) { return null; } str = str.trim().replace(/^\./,''); // S4.1.2.3 & S5.2.3: ignore leading . // convert to IDN if any non-ASCII characters if (punycode && /[^\u0001-\u007f]/.test(str)) { str = punycode.toASCII(str); } return str.toLowerCase(); } // S5.1.3 Domain Matching function domainMatch(str, domStr, canonicalize) { if (str == null || domStr == null) { return null; } if (canonicalize !== false) { str = canonicalDomain(str); domStr = canonicalDomain(domStr); } /* * "The domain string and the string are identical. (Note that both the * domain string and the string will have been canonicalized to lower case at * this point)" */ if (str == domStr) { return true; } /* "All of the following [three] conditions hold:" (order adjusted from the RFC) */ /* "* The string is a host name (i.e., not an IP address)." */ if (net.isIP(str)) { return false; } /* "* The domain string is a suffix of the string" */ var idx = str.indexOf(domStr); if (idx <= 0) { return false; // it's a non-match (-1) or prefix (0) } // e.g "a.b.c".indexOf("b.c") === 2 // 5 === 3+2 if (str.length !== domStr.length + idx) { // it's not a suffix return false; } /* "* The last character of the string that is not included in the domain * string is a %x2E (".") character." */ if (str.substr(idx-1,1) !== '.') { return false; } return true; } // RFC6265 S5.1.4 Paths and Path-Match /* * "The user agent MUST use an algorithm equivalent to the following algorithm * to compute the default-path of a cookie:" * * Assumption: the path (and not query part or absolute uri) is passed in. */ function defaultPath(path) { // "2. If the uri-path is empty or if the first character of the uri-path is not // a %x2F ("/") character, output %x2F ("/") and skip the remaining steps. if (!path || path.substr(0,1) !== "/") { return "/"; } // "3. If the uri-path contains no more than one %x2F ("/") character, output // %x2F ("/") and skip the remaining step." if (path === "/") { return path; } var rightSlash = path.lastIndexOf("/"); if (rightSlash === 0) { return "/"; } // "4. Output the characters of the uri-path from the first character up to, // but not including, the right-most %x2F ("/")." return path.slice(0, rightSlash); } function trimTerminator(str) { for (var t = 0; t < TERMINATORS.length; t++) { var terminatorIdx = str.indexOf(TERMINATORS[t]); if (terminatorIdx !== -1) { str = str.substr(0,terminatorIdx); } } return str; } function parseCookiePair(cookiePair, looseMode) { cookiePair = trimTerminator(cookiePair); var firstEq = cookiePair.indexOf('='); if (looseMode) { if (firstEq === 0) { // '=' is immediately at start cookiePair = cookiePair.substr(1); firstEq = cookiePair.indexOf('='); // might still need to split on '=' } } else { // non-loose mode if (firstEq <= 0) { // no '=' or is at start return; // needs to have non-empty "cookie-name" } } var cookieName, cookieValue; if (firstEq <= 0) { cookieName = ""; cookieValue = cookiePair.trim(); } else { cookieName = cookiePair.substr(0, firstEq).trim(); cookieValue = cookiePair.substr(firstEq+1).trim(); } if (CONTROL_CHARS.test(cookieName) || CONTROL_CHARS.test(cookieValue)) { return; } var c = new Cookie(); c.key = cookieName; c.value = cookieValue; return c; } function parse(str, options) { if (!options || typeof options !== 'object') { options = {}; } str = str.trim(); // We use a regex to parse the "name-value-pair" part of S5.2 var firstSemi = str.indexOf(';'); // S5.2 step 1 var cookiePair = (firstSemi === -1) ? str : str.substr(0, firstSemi); var c = parseCookiePair(cookiePair, !!options.loose); if (!c) { return; } if (firstSemi === -1) { return c; } // S5.2.3 "unparsed-attributes consist of the remainder of the set-cookie-string // (including the %x3B (";") in question)." plus later on in the same section // "discard the first ";" and trim". var unparsed = str.slice(firstSemi + 1).trim(); // "If the unparsed-attributes string is empty, skip the rest of these // steps." if (unparsed.length === 0) { return c; } /* * S5.2 says that when looping over the items "[p]rocess the attribute-name * and attribute-value according to the requirements in the following * subsections" for every item. Plus, for many of the individual attributes * in S5.3 it says to use the "attribute-value of the last attribute in the * cookie-attribute-list". Therefore, in this implementation, we overwrite * the previous value. */ var cookie_avs = unparsed.split(';'); while (cookie_avs.length) { var av = cookie_avs.shift().trim(); if (av.length === 0) { // happens if ";;" appears continue; } var av_sep = av.indexOf('='); var av_key, av_value; if (av_sep === -1) { av_key = av; av_value = null; } else { av_key = av.substr(0,av_sep); av_value = av.substr(av_sep+1); } av_key = av_key.trim().toLowerCase(); if (av_value) { av_value = av_value.trim(); } switch(av_key) { case 'expires': // S5.2.1 if (av_value) { var exp = parseDate(av_value); // "If the attribute-value failed to parse as a cookie date, ignore the // cookie-av." if (exp) { // over and underflow not realistically a concern: V8's getTime() seems to // store something larger than a 32-bit time_t (even with 32-bit node) c.expires = exp; } } break; case 'max-age': // S5.2.2 if (av_value) { // "If the first character of the attribute-value is not a DIGIT or a "-" // character ...[or]... If the remainder of attribute-value contains a // non-DIGIT character, ignore the cookie-av." if (/^-?[0-9]+$/.test(av_value)) { var delta = parseInt(av_value, 10); // "If delta-seconds is less than or equal to zero (0), let expiry-time // be the earliest representable date and time." c.setMaxAge(delta); } } break; case 'domain': // S5.2.3 // "If the attribute-value is empty, the behavior is undefined. However, // the user agent SHOULD ignore the cookie-av entirely." if (av_value) { // S5.2.3 "Let cookie-domain be the attribute-value without the leading %x2E // (".") character." var domain = av_value.trim().replace(/^\./, ''); if (domain) { // "Convert the cookie-domain to lower case." c.domain = domain.toLowerCase(); } } break; case 'path': // S5.2.4 /* * "If the attribute-value is empty or if the first character of the * attribute-value is not %x2F ("/"): * Let cookie-path be the default-path. * Otherwise: * Let cookie-path be the attribute-value." * * We'll represent the default-path as null since it depends on the * context of the parsing. */ c.path = av_value && av_value[0] === "/" ? av_value : null; break; case 'secure': // S5.2.5 /* * "If the attribute-name case-insensitively matches the string "Secure", * the user agent MUST append an attribute to the cookie-attribute-list * with an attribute-name of Secure and an empty attribute-value." */ c.secure = true; break; case 'httponly': // S5.2.6 -- effectively the same as 'secure' c.httpOnly = true; break; default: c.extensions = c.extensions || []; c.extensions.push(av); break; } } return c; } // avoid the V8 deoptimization monster! function jsonParse(str) { var obj; try { obj = JSON.parse(str); } catch (e) { return e; } return obj; } function fromJSON(str) { if (!str) { return null; } var obj; if (typeof str === 'string') { obj = jsonParse(str); if (obj instanceof Error) { return null; } } else { // assume it's an Object obj = str; } var c = new Cookie(); for (var i=0; i 1) { var lindex = path.lastIndexOf('/'); if (lindex === 0) { break; } path = path.substr(0,lindex); permutations.push(path); } permutations.push('/'); return permutations; } function getCookieContext(url) { if (url instanceof Object) { return url; } // NOTE: decodeURI will throw on malformed URIs (see GH-32). // Therefore, we will just skip decoding for such URIs. try { url = decodeURI(url); } catch(err) { // Silently swallow error } return urlParse(url); } function Cookie(options) { options = options || {}; Object.keys(options).forEach(function(prop) { if (Cookie.prototype.hasOwnProperty(prop) && Cookie.prototype[prop] !== options[prop] && prop.substr(0,1) !== '_') { this[prop] = options[prop]; } }, this); this.creation = this.creation || new Date(); // used to break creation ties in cookieCompare(): Object.defineProperty(this, 'creationIndex', { configurable: false, enumerable: false, // important for assert.deepEqual checks writable: true, value: ++Cookie.cookiesCreated }); } Cookie.cookiesCreated = 0; // incremented each time a cookie is created Cookie.parse = parse; Cookie.fromJSON = fromJSON; Cookie.prototype.key = ""; Cookie.prototype.value = ""; // the order in which the RFC has them: Cookie.prototype.expires = "Infinity"; // coerces to literal Infinity Cookie.prototype.maxAge = null; // takes precedence over expires for TTL Cookie.prototype.domain = null; Cookie.prototype.path = null; Cookie.prototype.secure = false; Cookie.prototype.httpOnly = false; Cookie.prototype.extensions = null; // set by the CookieJar: Cookie.prototype.hostOnly = null; // boolean when set Cookie.prototype.pathIsDefault = null; // boolean when set Cookie.prototype.creation = null; // Date when set; defaulted by Cookie.parse Cookie.prototype.lastAccessed = null; // Date when set Object.defineProperty(Cookie.prototype, 'creationIndex', { configurable: true, enumerable: false, writable: true, value: 0 }); Cookie.serializableProperties = Object.keys(Cookie.prototype) .filter(function(prop) { return !( Cookie.prototype[prop] instanceof Function || prop === 'creationIndex' || prop.substr(0,1) === '_' ); }); Cookie.prototype.inspect = function inspect() { var now = Date.now(); return 'Cookie="'+this.toString() + '; hostOnly='+(this.hostOnly != null ? this.hostOnly : '?') + '; aAge='+(this.lastAccessed ? (now-this.lastAccessed.getTime())+'ms' : '?') + '; cAge='+(this.creation ? (now-this.creation.getTime())+'ms' : '?') + '"'; }; // Use the new custom inspection symbol to add the custom inspect function if // available. if (util.inspect.custom) { Cookie.prototype[util.inspect.custom] = Cookie.prototype.inspect; } Cookie.prototype.toJSON = function() { var obj = {}; var props = Cookie.serializableProperties; for (var i=0; i { "use strict"; /*! * Copyright (c) 2015, Salesforce.com, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of Salesforce.com nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ var Store = (__nccwpck_require__(460)/* .Store */ .y); var permuteDomain = (__nccwpck_require__(55986).permuteDomain); var pathMatch = (__nccwpck_require__(54336)/* .pathMatch */ .U); var util = __nccwpck_require__(73837); function MemoryCookieStore() { Store.call(this); this.idx = {}; } util.inherits(MemoryCookieStore, Store); exports.m = MemoryCookieStore; MemoryCookieStore.prototype.idx = null; // Since it's just a struct in RAM, this Store is synchronous MemoryCookieStore.prototype.synchronous = true; // force a default depth: MemoryCookieStore.prototype.inspect = function() { return "{ idx: "+util.inspect(this.idx, false, 2)+' }'; }; // Use the new custom inspection symbol to add the custom inspect function if // available. if (util.inspect.custom) { MemoryCookieStore.prototype[util.inspect.custom] = MemoryCookieStore.prototype.inspect; } MemoryCookieStore.prototype.findCookie = function(domain, path, key, cb) { if (!this.idx[domain]) { return cb(null,undefined); } if (!this.idx[domain][path]) { return cb(null,undefined); } return cb(null,this.idx[domain][path][key]||null); }; MemoryCookieStore.prototype.findCookies = function(domain, path, cb) { var results = []; if (!domain) { return cb(null,[]); } var pathMatcher; if (!path) { // null means "all paths" pathMatcher = function matchAll(domainIndex) { for (var curPath in domainIndex) { var pathIndex = domainIndex[curPath]; for (var key in pathIndex) { results.push(pathIndex[key]); } } }; } else { pathMatcher = function matchRFC(domainIndex) { //NOTE: we should use path-match algorithm from S5.1.4 here //(see : https://github.com/ChromiumWebApps/chromium/blob/b3d3b4da8bb94c1b2e061600df106d590fda3620/net/cookies/canonical_cookie.cc#L299) Object.keys(domainIndex).forEach(function (cookiePath) { if (pathMatch(path, cookiePath)) { var pathIndex = domainIndex[cookiePath]; for (var key in pathIndex) { results.push(pathIndex[key]); } } }); }; } var domains = permuteDomain(domain) || [domain]; var idx = this.idx; domains.forEach(function(curDomain) { var domainIndex = idx[curDomain]; if (!domainIndex) { return; } pathMatcher(domainIndex); }); cb(null,results); }; MemoryCookieStore.prototype.putCookie = function(cookie, cb) { if (!this.idx[cookie.domain]) { this.idx[cookie.domain] = {}; } if (!this.idx[cookie.domain][cookie.path]) { this.idx[cookie.domain][cookie.path] = {}; } this.idx[cookie.domain][cookie.path][cookie.key] = cookie; cb(null); }; MemoryCookieStore.prototype.updateCookie = function(oldCookie, newCookie, cb) { // updateCookie() may avoid updating cookies that are identical. For example, // lastAccessed may not be important to some stores and an equality // comparison could exclude that field. this.putCookie(newCookie,cb); }; MemoryCookieStore.prototype.removeCookie = function(domain, path, key, cb) { if (this.idx[domain] && this.idx[domain][path] && this.idx[domain][path][key]) { delete this.idx[domain][path][key]; } cb(null); }; MemoryCookieStore.prototype.removeCookies = function(domain, path, cb) { if (this.idx[domain]) { if (path) { delete this.idx[domain][path]; } else { delete this.idx[domain]; } } return cb(null); }; MemoryCookieStore.prototype.removeAllCookies = function(cb) { this.idx = {}; return cb(null); } MemoryCookieStore.prototype.getAllCookies = function(cb) { var cookies = []; var idx = this.idx; var domains = Object.keys(idx); domains.forEach(function(domain) { var paths = Object.keys(idx[domain]); paths.forEach(function(path) { var keys = Object.keys(idx[domain][path]); keys.forEach(function(key) { if (key !== null) { cookies.push(idx[domain][path][key]); } }); }); }); // Sort by creationIndex so deserializing retains the creation order. // When implementing your own store, this SHOULD retain the order too cookies.sort(function(a,b) { return (a.creationIndex||0) - (b.creationIndex||0); }); cb(null, cookies); }; /***/ }), /***/ 54336: /***/ ((__unused_webpack_module, exports) => { "use strict"; /*! * Copyright (c) 2015, Salesforce.com, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of Salesforce.com nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * "A request-path path-matches a given cookie-path if at least one of the * following conditions holds:" */ function pathMatch (reqPath, cookiePath) { // "o The cookie-path and the request-path are identical." if (cookiePath === reqPath) { return true; } var idx = reqPath.indexOf(cookiePath); if (idx === 0) { // "o The cookie-path is a prefix of the request-path, and the last // character of the cookie-path is %x2F ("/")." if (cookiePath.substr(-1) === "/") { return true; } // " o The cookie-path is a prefix of the request-path, and the first // character of the request-path that is not included in the cookie- path // is a %x2F ("/") character." if (reqPath.substr(cookiePath.length, 1) === "/") { return true; } } return false; } exports.U = pathMatch; /***/ }), /***/ 55986: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /*! * Copyright (c) 2015, Salesforce.com, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of Salesforce.com nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ var pubsuffix = __nccwpck_require__(94401); // Gives the permutation of all possible domainMatch()es of a given domain. The // array is in shortest-to-longest order. Handy for indexing. function permuteDomain (domain) { var pubSuf = pubsuffix.getPublicSuffix(domain); if (!pubSuf) { return null; } if (pubSuf == domain) { return [domain]; } var prefix = domain.slice(0, -(pubSuf.length + 1)); // ".example.com" var parts = prefix.split('.').reverse(); var cur = pubSuf; var permutations = [cur]; while (parts.length) { cur = parts.shift() + '.' + cur; permutations.push(cur); } return permutations; } exports.permuteDomain = permuteDomain; /***/ }), /***/ 94401: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; /*! * Copyright (c) 2018, Salesforce.com, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of Salesforce.com nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ var psl = __nccwpck_require__(29975); function getPublicSuffix(domain) { return psl.get(domain); } exports.getPublicSuffix = getPublicSuffix; /***/ }), /***/ 460: /***/ ((__unused_webpack_module, exports) => { "use strict"; /*! * Copyright (c) 2015, Salesforce.com, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of Salesforce.com nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /*jshint unused:false */ function Store() { } exports.y = Store; // Stores may be synchronous, but are still required to use a // Continuation-Passing Style API. The CookieJar itself will expose a "*Sync" // API that converts from synchronous-callbacks to imperative style. Store.prototype.synchronous = false; Store.prototype.findCookie = function(domain, path, key, cb) { throw new Error('findCookie is not implemented'); }; Store.prototype.findCookies = function(domain, path, cb) { throw new Error('findCookies is not implemented'); }; Store.prototype.putCookie = function(cookie, cb) { throw new Error('putCookie is not implemented'); }; Store.prototype.updateCookie = function(oldCookie, newCookie, cb) { // recommended default implementation: // return this.putCookie(newCookie, cb); throw new Error('updateCookie is not implemented'); }; Store.prototype.removeCookie = function(domain, path, key, cb) { throw new Error('removeCookie is not implemented'); }; Store.prototype.removeCookies = function(domain, path, cb) { throw new Error('removeCookies is not implemented'); }; Store.prototype.removeAllCookies = function(cb) { throw new Error('removeAllCookies is not implemented'); } Store.prototype.getAllCookies = function(cb) { throw new Error('getAllCookies is not implemented (therefore jar cannot be serialized)'); }; /***/ }), /***/ 93199: /***/ ((module) => { // generated by genversion module.exports = '2.5.0' /***/ }), /***/ 4351: /***/ ((module) => { /****************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ /* global global, define, Symbol, Reflect, Promise, SuppressedError, Iterator */ var __extends; var __assign; var __rest; var __decorate; var __param; var __esDecorate; var __runInitializers; var __propKey; var __setFunctionName; var __metadata; var __awaiter; var __generator; var __exportStar; var __values; var __read; var __spread; var __spreadArrays; var __spreadArray; var __await; var __asyncGenerator; var __asyncDelegator; var __asyncValues; var __makeTemplateObject; var __importStar; var __importDefault; var __classPrivateFieldGet; var __classPrivateFieldSet; var __classPrivateFieldIn; var __createBinding; var __addDisposableResource; var __disposeResources; var __rewriteRelativeImportExtension; (function (factory) { var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {}; if (typeof define === "function" && define.amd) { define("tslib", ["exports"], function (exports) { factory(createExporter(root, createExporter(exports))); }); } else if ( true && typeof module.exports === "object") { factory(createExporter(root, createExporter(module.exports))); } else { factory(createExporter(root)); } function createExporter(exports, previous) { if (exports !== root) { if (typeof Object.create === "function") { Object.defineProperty(exports, "__esModule", { value: true }); } else { exports.__esModule = true; } } return function (id, v) { return exports[id] = previous ? previous(id, v) : v; }; } }) (function (exporter) { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; __extends = function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; __assign = Object.assign || function (t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; __rest = function (s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; __decorate = function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; __param = function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; __esDecorate = function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; } var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); var _, done = false; for (var i = decorators.length - 1; i >= 0; i--) { var context = {}; for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; for (var p in contextIn.access) context.access[p] = contextIn.access[p]; context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); }; var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context); if (kind === "accessor") { if (result === void 0) continue; if (result === null || typeof result !== "object") throw new TypeError("Object expected"); if (_ = accept(result.get)) descriptor.get = _; if (_ = accept(result.set)) descriptor.set = _; if (_ = accept(result.init)) initializers.unshift(_); } else if (_ = accept(result)) { if (kind === "field") initializers.unshift(_); else descriptor[key] = _; } } if (target) Object.defineProperty(target, contextIn.name, descriptor); done = true; }; __runInitializers = function (thisArg, initializers, value) { var useValue = arguments.length > 2; for (var i = 0; i < initializers.length; i++) { value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); } return useValue ? value : void 0; }; __propKey = function (x) { return typeof x === "symbol" ? x : "".concat(x); }; __setFunctionName = function (f, name, prefix) { if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); }; __metadata = function (metadataKey, metadataValue) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); }; __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()); }); }; __generator = function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; __exportStar = function(m, o) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); }; __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]; }); __values = function (o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); }; __read = function (o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; }; /** @deprecated */ __spread = function () { for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); return ar; }; /** @deprecated */ __spreadArrays = function () { for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j]; return r; }; __spreadArray = function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; __await = function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }; __asyncGenerator = function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var g = generator.apply(thisArg, _arguments || []), i, q = []; return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i; function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; } function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } } function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; __asyncDelegator = function (o) { var i, p; return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } }; __asyncValues = function (o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator], i; return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } }; __makeTemplateObject = function (cooked, raw) { if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } return cooked; }; var __setModuleDefault = Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }; var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; __importStar = function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; __importDefault = function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; __classPrivateFieldGet = function (receiver, state, kind, f) { if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); }; __classPrivateFieldSet = function (receiver, state, value, kind, f) { if (kind === "m") throw new TypeError("Private method is not writable"); if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; }; __classPrivateFieldIn = function (state, receiver) { if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object"); return typeof state === "function" ? receiver === state : state.has(receiver); }; __addDisposableResource = function (env, value, async) { if (value !== null && value !== void 0) { if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); var dispose, inner; if (async) { if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); dispose = value[Symbol.asyncDispose]; } if (dispose === void 0) { if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); dispose = value[Symbol.dispose]; if (async) inner = dispose; } if (typeof dispose !== "function") throw new TypeError("Object not disposable."); if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } }; env.stack.push({ value: value, dispose: dispose, async: async }); } else if (async) { env.stack.push({ async: true }); } return value; }; var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { var e = new Error(message); return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; }; __disposeResources = function (env) { function fail(e) { env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; env.hasError = true; } var r, s = 0; function next() { while (r = env.stack.pop()) { try { if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next); if (r.dispose) { var result = r.dispose.call(r.value); if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); } else s |= 1; } catch (e) { fail(e); } } if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve(); if (env.hasError) throw env.error; } return next(); }; __rewriteRelativeImportExtension = function (path, preserveJsx) { if (typeof path === "string" && /^\.\.?\//.test(path)) { return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) { return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js"); }); } return path; }; exporter("__extends", __extends); exporter("__assign", __assign); exporter("__rest", __rest); exporter("__decorate", __decorate); exporter("__param", __param); exporter("__esDecorate", __esDecorate); exporter("__runInitializers", __runInitializers); exporter("__propKey", __propKey); exporter("__setFunctionName", __setFunctionName); exporter("__metadata", __metadata); exporter("__awaiter", __awaiter); exporter("__generator", __generator); exporter("__exportStar", __exportStar); exporter("__createBinding", __createBinding); exporter("__values", __values); exporter("__read", __read); exporter("__spread", __spread); exporter("__spreadArrays", __spreadArrays); exporter("__spreadArray", __spreadArray); exporter("__await", __await); exporter("__asyncGenerator", __asyncGenerator); exporter("__asyncDelegator", __asyncDelegator); exporter("__asyncValues", __asyncValues); exporter("__makeTemplateObject", __makeTemplateObject); exporter("__importStar", __importStar); exporter("__importDefault", __importDefault); exporter("__classPrivateFieldGet", __classPrivateFieldGet); exporter("__classPrivateFieldSet", __classPrivateFieldSet); exporter("__classPrivateFieldIn", __classPrivateFieldIn); exporter("__addDisposableResource", __addDisposableResource); exporter("__disposeResources", __disposeResources); exporter("__rewriteRelativeImportExtension", __rewriteRelativeImportExtension); }); 0 && (0); /***/ }), /***/ 11137: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; var net = __nccwpck_require__(41808) , tls = __nccwpck_require__(24404) , http = __nccwpck_require__(13685) , https = __nccwpck_require__(95687) , events = __nccwpck_require__(82361) , assert = __nccwpck_require__(39491) , util = __nccwpck_require__(73837) , Buffer = (__nccwpck_require__(21867).Buffer) ; 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 = [] self.on('free', function onFree(socket, host, port) { for (var i = 0, len = self.requests.length; i < len; ++i) { var pending = self.requests[i] if (pending.host === host && pending.port === port) { // Detect the request to connect same origin server, // reuse the connection. self.requests.splice(i, 1) pending.request.onSocket(socket) return } } socket.destroy() self.removeSocket(socket) }) } util.inherits(TunnelingAgent, events.EventEmitter) TunnelingAgent.prototype.addRequest = function addRequest(req, options) { var self = this // Legacy API: addRequest(req, host, port, path) if (typeof options === 'string') { options = { host: options, port: arguments[2], path: arguments[3] }; } if (self.sockets.length >= this.maxSockets) { // We are over limit so we'll add it to the queue. self.requests.push({host: options.host, port: options.port, request: req}) return } // If we are under maxSockets create a new one. self.createConnection({host: options.host, port: options.port, request: req}) } TunnelingAgent.prototype.createConnection = function createConnection(pending) { var self = this self.createSocket(pending, function(socket) { socket.on('free', onFree) socket.on('close', onCloseOrRemove) socket.on('agentRemove', onCloseOrRemove) pending.request.onSocket(socket) function onFree() { self.emit('free', socket, pending.host, pending.port) } function onCloseOrRemove(err) { self.removeSocket(socket) socket.removeListener('free', onFree) socket.removeListener('close', onCloseOrRemove) socket.removeListener('agentRemove', onCloseOrRemove) } }) } 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 } ) if (connectOptions.proxyAuth) { connectOptions.headers = connectOptions.headers || {} connectOptions.headers['Proxy-Authorization'] = 'Basic ' + Buffer.from(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) { assert.equal(head.length, 0) debug('tunneling connection has established') self.sockets[self.sockets.indexOf(placeholder)] = socket cb(socket) } else { debug('tunneling socket could not be established, statusCode=%d', res.statusCode) var error = new Error('tunneling socket could not be established, ' + 'statusCode=' + res.statusCode) error.code = 'ECONNRESET' options.request.emit('error', error) self.removeSocket(placeholder) } } 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.createConnection(pending) } } function createSecureSocket(options, cb) { var self = this TunnelingAgent.prototype.createSocket.call(self, options, function(socket) { // 0 is dummy port for v0.6 var secureSocket = tls.connect(0, mergeOptions({}, self.options, { servername: options.host , socket: socket } )) self.sockets[self.sockets.indexOf(socket)] = secureSocket cb(secureSocket) }) } 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] } } } } 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:') } console.error.apply(console, args) } } else { debug = function() {} } exports.debug = debug // for test /***/ }), /***/ 74294: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { module.exports = __nccwpck_require__(54219); /***/ }), /***/ 54219: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; var net = __nccwpck_require__(41808); var tls = __nccwpck_require__(24404); var http = __nccwpck_require__(13685); var https = __nccwpck_require__(95687); var events = __nccwpck_require__(82361); var assert = __nccwpck_require__(39491); var util = __nccwpck_require__(73837); 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 = []; 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; } } 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); } function onCloseOrRemove(err) { self.removeSocket(socket); socket.removeListener('free', onFree); socket.removeListener('close', onCloseOrRemove); socket.removeListener('agentRemove', onCloseOrRemove); } }); }; 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 (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; } 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; } 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]; } } } } 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:'); } console.error.apply(console, args); } } else { debug = function() {}; } exports.debug = debug; // for test /***/ }), /***/ 68729: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { (function(nacl) { 'use strict'; // Ported in 2014 by Dmitry Chestnykh and Devi Mandiri. // Public domain. // // Implementation derived from TweetNaCl version 20140427. // See for details: http://tweetnacl.cr.yp.to/ var gf = function(init) { var i, r = new Float64Array(16); if (init) for (i = 0; i < init.length; i++) r[i] = init[i]; return r; }; // Pluggable, initialized in high-level API below. var randombytes = function(/* x, n */) { throw new Error('no PRNG'); }; var _0 = new Uint8Array(16); var _9 = new Uint8Array(32); _9[0] = 9; var gf0 = gf(), gf1 = gf([1]), _121665 = gf([0xdb41, 1]), D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]), D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]), X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]), Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]), I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]); function ts64(x, i, h, l) { x[i] = (h >> 24) & 0xff; x[i+1] = (h >> 16) & 0xff; x[i+2] = (h >> 8) & 0xff; x[i+3] = h & 0xff; x[i+4] = (l >> 24) & 0xff; x[i+5] = (l >> 16) & 0xff; x[i+6] = (l >> 8) & 0xff; x[i+7] = l & 0xff; } function vn(x, xi, y, yi, n) { var i,d = 0; for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i]; return (1 & ((d - 1) >>> 8)) - 1; } function crypto_verify_16(x, xi, y, yi) { return vn(x,xi,y,yi,16); } function crypto_verify_32(x, xi, y, yi) { return vn(x,xi,y,yi,32); } function core_salsa20(o, p, k, c) { var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24, j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24, j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24, j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24, j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24, j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24, j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24, j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24, j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24, j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24, j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24, j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24, j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24, j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24, j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24, j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24; var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7, x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, x15 = j15, u; for (var i = 0; i < 20; i += 2) { u = x0 + x12 | 0; x4 ^= u<<7 | u>>>(32-7); u = x4 + x0 | 0; x8 ^= u<<9 | u>>>(32-9); u = x8 + x4 | 0; x12 ^= u<<13 | u>>>(32-13); u = x12 + x8 | 0; x0 ^= u<<18 | u>>>(32-18); u = x5 + x1 | 0; x9 ^= u<<7 | u>>>(32-7); u = x9 + x5 | 0; x13 ^= u<<9 | u>>>(32-9); u = x13 + x9 | 0; x1 ^= u<<13 | u>>>(32-13); u = x1 + x13 | 0; x5 ^= u<<18 | u>>>(32-18); u = x10 + x6 | 0; x14 ^= u<<7 | u>>>(32-7); u = x14 + x10 | 0; x2 ^= u<<9 | u>>>(32-9); u = x2 + x14 | 0; x6 ^= u<<13 | u>>>(32-13); u = x6 + x2 | 0; x10 ^= u<<18 | u>>>(32-18); u = x15 + x11 | 0; x3 ^= u<<7 | u>>>(32-7); u = x3 + x15 | 0; x7 ^= u<<9 | u>>>(32-9); u = x7 + x3 | 0; x11 ^= u<<13 | u>>>(32-13); u = x11 + x7 | 0; x15 ^= u<<18 | u>>>(32-18); u = x0 + x3 | 0; x1 ^= u<<7 | u>>>(32-7); u = x1 + x0 | 0; x2 ^= u<<9 | u>>>(32-9); u = x2 + x1 | 0; x3 ^= u<<13 | u>>>(32-13); u = x3 + x2 | 0; x0 ^= u<<18 | u>>>(32-18); u = x5 + x4 | 0; x6 ^= u<<7 | u>>>(32-7); u = x6 + x5 | 0; x7 ^= u<<9 | u>>>(32-9); u = x7 + x6 | 0; x4 ^= u<<13 | u>>>(32-13); u = x4 + x7 | 0; x5 ^= u<<18 | u>>>(32-18); u = x10 + x9 | 0; x11 ^= u<<7 | u>>>(32-7); u = x11 + x10 | 0; x8 ^= u<<9 | u>>>(32-9); u = x8 + x11 | 0; x9 ^= u<<13 | u>>>(32-13); u = x9 + x8 | 0; x10 ^= u<<18 | u>>>(32-18); u = x15 + x14 | 0; x12 ^= u<<7 | u>>>(32-7); u = x12 + x15 | 0; x13 ^= u<<9 | u>>>(32-9); u = x13 + x12 | 0; x14 ^= u<<13 | u>>>(32-13); u = x14 + x13 | 0; x15 ^= u<<18 | u>>>(32-18); } x0 = x0 + j0 | 0; x1 = x1 + j1 | 0; x2 = x2 + j2 | 0; x3 = x3 + j3 | 0; x4 = x4 + j4 | 0; x5 = x5 + j5 | 0; x6 = x6 + j6 | 0; x7 = x7 + j7 | 0; x8 = x8 + j8 | 0; x9 = x9 + j9 | 0; x10 = x10 + j10 | 0; x11 = x11 + j11 | 0; x12 = x12 + j12 | 0; x13 = x13 + j13 | 0; x14 = x14 + j14 | 0; x15 = x15 + j15 | 0; o[ 0] = x0 >>> 0 & 0xff; o[ 1] = x0 >>> 8 & 0xff; o[ 2] = x0 >>> 16 & 0xff; o[ 3] = x0 >>> 24 & 0xff; o[ 4] = x1 >>> 0 & 0xff; o[ 5] = x1 >>> 8 & 0xff; o[ 6] = x1 >>> 16 & 0xff; o[ 7] = x1 >>> 24 & 0xff; o[ 8] = x2 >>> 0 & 0xff; o[ 9] = x2 >>> 8 & 0xff; o[10] = x2 >>> 16 & 0xff; o[11] = x2 >>> 24 & 0xff; o[12] = x3 >>> 0 & 0xff; o[13] = x3 >>> 8 & 0xff; o[14] = x3 >>> 16 & 0xff; o[15] = x3 >>> 24 & 0xff; o[16] = x4 >>> 0 & 0xff; o[17] = x4 >>> 8 & 0xff; o[18] = x4 >>> 16 & 0xff; o[19] = x4 >>> 24 & 0xff; o[20] = x5 >>> 0 & 0xff; o[21] = x5 >>> 8 & 0xff; o[22] = x5 >>> 16 & 0xff; o[23] = x5 >>> 24 & 0xff; o[24] = x6 >>> 0 & 0xff; o[25] = x6 >>> 8 & 0xff; o[26] = x6 >>> 16 & 0xff; o[27] = x6 >>> 24 & 0xff; o[28] = x7 >>> 0 & 0xff; o[29] = x7 >>> 8 & 0xff; o[30] = x7 >>> 16 & 0xff; o[31] = x7 >>> 24 & 0xff; o[32] = x8 >>> 0 & 0xff; o[33] = x8 >>> 8 & 0xff; o[34] = x8 >>> 16 & 0xff; o[35] = x8 >>> 24 & 0xff; o[36] = x9 >>> 0 & 0xff; o[37] = x9 >>> 8 & 0xff; o[38] = x9 >>> 16 & 0xff; o[39] = x9 >>> 24 & 0xff; o[40] = x10 >>> 0 & 0xff; o[41] = x10 >>> 8 & 0xff; o[42] = x10 >>> 16 & 0xff; o[43] = x10 >>> 24 & 0xff; o[44] = x11 >>> 0 & 0xff; o[45] = x11 >>> 8 & 0xff; o[46] = x11 >>> 16 & 0xff; o[47] = x11 >>> 24 & 0xff; o[48] = x12 >>> 0 & 0xff; o[49] = x12 >>> 8 & 0xff; o[50] = x12 >>> 16 & 0xff; o[51] = x12 >>> 24 & 0xff; o[52] = x13 >>> 0 & 0xff; o[53] = x13 >>> 8 & 0xff; o[54] = x13 >>> 16 & 0xff; o[55] = x13 >>> 24 & 0xff; o[56] = x14 >>> 0 & 0xff; o[57] = x14 >>> 8 & 0xff; o[58] = x14 >>> 16 & 0xff; o[59] = x14 >>> 24 & 0xff; o[60] = x15 >>> 0 & 0xff; o[61] = x15 >>> 8 & 0xff; o[62] = x15 >>> 16 & 0xff; o[63] = x15 >>> 24 & 0xff; } function core_hsalsa20(o,p,k,c) { var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24, j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24, j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24, j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24, j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24, j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24, j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24, j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24, j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24, j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24, j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24, j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24, j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24, j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24, j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24, j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24; var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7, x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, x15 = j15, u; for (var i = 0; i < 20; i += 2) { u = x0 + x12 | 0; x4 ^= u<<7 | u>>>(32-7); u = x4 + x0 | 0; x8 ^= u<<9 | u>>>(32-9); u = x8 + x4 | 0; x12 ^= u<<13 | u>>>(32-13); u = x12 + x8 | 0; x0 ^= u<<18 | u>>>(32-18); u = x5 + x1 | 0; x9 ^= u<<7 | u>>>(32-7); u = x9 + x5 | 0; x13 ^= u<<9 | u>>>(32-9); u = x13 + x9 | 0; x1 ^= u<<13 | u>>>(32-13); u = x1 + x13 | 0; x5 ^= u<<18 | u>>>(32-18); u = x10 + x6 | 0; x14 ^= u<<7 | u>>>(32-7); u = x14 + x10 | 0; x2 ^= u<<9 | u>>>(32-9); u = x2 + x14 | 0; x6 ^= u<<13 | u>>>(32-13); u = x6 + x2 | 0; x10 ^= u<<18 | u>>>(32-18); u = x15 + x11 | 0; x3 ^= u<<7 | u>>>(32-7); u = x3 + x15 | 0; x7 ^= u<<9 | u>>>(32-9); u = x7 + x3 | 0; x11 ^= u<<13 | u>>>(32-13); u = x11 + x7 | 0; x15 ^= u<<18 | u>>>(32-18); u = x0 + x3 | 0; x1 ^= u<<7 | u>>>(32-7); u = x1 + x0 | 0; x2 ^= u<<9 | u>>>(32-9); u = x2 + x1 | 0; x3 ^= u<<13 | u>>>(32-13); u = x3 + x2 | 0; x0 ^= u<<18 | u>>>(32-18); u = x5 + x4 | 0; x6 ^= u<<7 | u>>>(32-7); u = x6 + x5 | 0; x7 ^= u<<9 | u>>>(32-9); u = x7 + x6 | 0; x4 ^= u<<13 | u>>>(32-13); u = x4 + x7 | 0; x5 ^= u<<18 | u>>>(32-18); u = x10 + x9 | 0; x11 ^= u<<7 | u>>>(32-7); u = x11 + x10 | 0; x8 ^= u<<9 | u>>>(32-9); u = x8 + x11 | 0; x9 ^= u<<13 | u>>>(32-13); u = x9 + x8 | 0; x10 ^= u<<18 | u>>>(32-18); u = x15 + x14 | 0; x12 ^= u<<7 | u>>>(32-7); u = x12 + x15 | 0; x13 ^= u<<9 | u>>>(32-9); u = x13 + x12 | 0; x14 ^= u<<13 | u>>>(32-13); u = x14 + x13 | 0; x15 ^= u<<18 | u>>>(32-18); } o[ 0] = x0 >>> 0 & 0xff; o[ 1] = x0 >>> 8 & 0xff; o[ 2] = x0 >>> 16 & 0xff; o[ 3] = x0 >>> 24 & 0xff; o[ 4] = x5 >>> 0 & 0xff; o[ 5] = x5 >>> 8 & 0xff; o[ 6] = x5 >>> 16 & 0xff; o[ 7] = x5 >>> 24 & 0xff; o[ 8] = x10 >>> 0 & 0xff; o[ 9] = x10 >>> 8 & 0xff; o[10] = x10 >>> 16 & 0xff; o[11] = x10 >>> 24 & 0xff; o[12] = x15 >>> 0 & 0xff; o[13] = x15 >>> 8 & 0xff; o[14] = x15 >>> 16 & 0xff; o[15] = x15 >>> 24 & 0xff; o[16] = x6 >>> 0 & 0xff; o[17] = x6 >>> 8 & 0xff; o[18] = x6 >>> 16 & 0xff; o[19] = x6 >>> 24 & 0xff; o[20] = x7 >>> 0 & 0xff; o[21] = x7 >>> 8 & 0xff; o[22] = x7 >>> 16 & 0xff; o[23] = x7 >>> 24 & 0xff; o[24] = x8 >>> 0 & 0xff; o[25] = x8 >>> 8 & 0xff; o[26] = x8 >>> 16 & 0xff; o[27] = x8 >>> 24 & 0xff; o[28] = x9 >>> 0 & 0xff; o[29] = x9 >>> 8 & 0xff; o[30] = x9 >>> 16 & 0xff; o[31] = x9 >>> 24 & 0xff; } function crypto_core_salsa20(out,inp,k,c) { core_salsa20(out,inp,k,c); } function crypto_core_hsalsa20(out,inp,k,c) { core_hsalsa20(out,inp,k,c); } var sigma = new Uint8Array([101, 120, 112, 97, 110, 100, 32, 51, 50, 45, 98, 121, 116, 101, 32, 107]); // "expand 32-byte k" function crypto_stream_salsa20_xor(c,cpos,m,mpos,b,n,k) { var z = new Uint8Array(16), x = new Uint8Array(64); var u, i; for (i = 0; i < 16; i++) z[i] = 0; for (i = 0; i < 8; i++) z[i] = n[i]; while (b >= 64) { crypto_core_salsa20(x,z,k,sigma); for (i = 0; i < 64; i++) c[cpos+i] = m[mpos+i] ^ x[i]; u = 1; for (i = 8; i < 16; i++) { u = u + (z[i] & 0xff) | 0; z[i] = u & 0xff; u >>>= 8; } b -= 64; cpos += 64; mpos += 64; } if (b > 0) { crypto_core_salsa20(x,z,k,sigma); for (i = 0; i < b; i++) c[cpos+i] = m[mpos+i] ^ x[i]; } return 0; } function crypto_stream_salsa20(c,cpos,b,n,k) { var z = new Uint8Array(16), x = new Uint8Array(64); var u, i; for (i = 0; i < 16; i++) z[i] = 0; for (i = 0; i < 8; i++) z[i] = n[i]; while (b >= 64) { crypto_core_salsa20(x,z,k,sigma); for (i = 0; i < 64; i++) c[cpos+i] = x[i]; u = 1; for (i = 8; i < 16; i++) { u = u + (z[i] & 0xff) | 0; z[i] = u & 0xff; u >>>= 8; } b -= 64; cpos += 64; } if (b > 0) { crypto_core_salsa20(x,z,k,sigma); for (i = 0; i < b; i++) c[cpos+i] = x[i]; } return 0; } function crypto_stream(c,cpos,d,n,k) { var s = new Uint8Array(32); crypto_core_hsalsa20(s,n,k,sigma); var sn = new Uint8Array(8); for (var i = 0; i < 8; i++) sn[i] = n[i+16]; return crypto_stream_salsa20(c,cpos,d,sn,s); } function crypto_stream_xor(c,cpos,m,mpos,d,n,k) { var s = new Uint8Array(32); crypto_core_hsalsa20(s,n,k,sigma); var sn = new Uint8Array(8); for (var i = 0; i < 8; i++) sn[i] = n[i+16]; return crypto_stream_salsa20_xor(c,cpos,m,mpos,d,sn,s); } /* * Port of Andrew Moon's Poly1305-donna-16. Public domain. * https://github.com/floodyberry/poly1305-donna */ var poly1305 = function(key) { this.buffer = new Uint8Array(16); this.r = new Uint16Array(10); this.h = new Uint16Array(10); this.pad = new Uint16Array(8); this.leftover = 0; this.fin = 0; var t0, t1, t2, t3, t4, t5, t6, t7; t0 = key[ 0] & 0xff | (key[ 1] & 0xff) << 8; this.r[0] = ( t0 ) & 0x1fff; t1 = key[ 2] & 0xff | (key[ 3] & 0xff) << 8; this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff; t2 = key[ 4] & 0xff | (key[ 5] & 0xff) << 8; this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03; t3 = key[ 6] & 0xff | (key[ 7] & 0xff) << 8; this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff; t4 = key[ 8] & 0xff | (key[ 9] & 0xff) << 8; this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff; this.r[5] = ((t4 >>> 1)) & 0x1ffe; t5 = key[10] & 0xff | (key[11] & 0xff) << 8; this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff; t6 = key[12] & 0xff | (key[13] & 0xff) << 8; this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81; t7 = key[14] & 0xff | (key[15] & 0xff) << 8; this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff; this.r[9] = ((t7 >>> 5)) & 0x007f; this.pad[0] = key[16] & 0xff | (key[17] & 0xff) << 8; this.pad[1] = key[18] & 0xff | (key[19] & 0xff) << 8; this.pad[2] = key[20] & 0xff | (key[21] & 0xff) << 8; this.pad[3] = key[22] & 0xff | (key[23] & 0xff) << 8; this.pad[4] = key[24] & 0xff | (key[25] & 0xff) << 8; this.pad[5] = key[26] & 0xff | (key[27] & 0xff) << 8; this.pad[6] = key[28] & 0xff | (key[29] & 0xff) << 8; this.pad[7] = key[30] & 0xff | (key[31] & 0xff) << 8; }; poly1305.prototype.blocks = function(m, mpos, bytes) { var hibit = this.fin ? 0 : (1 << 11); var t0, t1, t2, t3, t4, t5, t6, t7, c; var d0, d1, d2, d3, d4, d5, d6, d7, d8, d9; var h0 = this.h[0], h1 = this.h[1], h2 = this.h[2], h3 = this.h[3], h4 = this.h[4], h5 = this.h[5], h6 = this.h[6], h7 = this.h[7], h8 = this.h[8], h9 = this.h[9]; var r0 = this.r[0], r1 = this.r[1], r2 = this.r[2], r3 = this.r[3], r4 = this.r[4], r5 = this.r[5], r6 = this.r[6], r7 = this.r[7], r8 = this.r[8], r9 = this.r[9]; while (bytes >= 16) { t0 = m[mpos+ 0] & 0xff | (m[mpos+ 1] & 0xff) << 8; h0 += ( t0 ) & 0x1fff; t1 = m[mpos+ 2] & 0xff | (m[mpos+ 3] & 0xff) << 8; h1 += ((t0 >>> 13) | (t1 << 3)) & 0x1fff; t2 = m[mpos+ 4] & 0xff | (m[mpos+ 5] & 0xff) << 8; h2 += ((t1 >>> 10) | (t2 << 6)) & 0x1fff; t3 = m[mpos+ 6] & 0xff | (m[mpos+ 7] & 0xff) << 8; h3 += ((t2 >>> 7) | (t3 << 9)) & 0x1fff; t4 = m[mpos+ 8] & 0xff | (m[mpos+ 9] & 0xff) << 8; h4 += ((t3 >>> 4) | (t4 << 12)) & 0x1fff; h5 += ((t4 >>> 1)) & 0x1fff; t5 = m[mpos+10] & 0xff | (m[mpos+11] & 0xff) << 8; h6 += ((t4 >>> 14) | (t5 << 2)) & 0x1fff; t6 = m[mpos+12] & 0xff | (m[mpos+13] & 0xff) << 8; h7 += ((t5 >>> 11) | (t6 << 5)) & 0x1fff; t7 = m[mpos+14] & 0xff | (m[mpos+15] & 0xff) << 8; h8 += ((t6 >>> 8) | (t7 << 8)) & 0x1fff; h9 += ((t7 >>> 5)) | hibit; c = 0; d0 = c; d0 += h0 * r0; d0 += h1 * (5 * r9); d0 += h2 * (5 * r8); d0 += h3 * (5 * r7); d0 += h4 * (5 * r6); c = (d0 >>> 13); d0 &= 0x1fff; d0 += h5 * (5 * r5); d0 += h6 * (5 * r4); d0 += h7 * (5 * r3); d0 += h8 * (5 * r2); d0 += h9 * (5 * r1); c += (d0 >>> 13); d0 &= 0x1fff; d1 = c; d1 += h0 * r1; d1 += h1 * r0; d1 += h2 * (5 * r9); d1 += h3 * (5 * r8); d1 += h4 * (5 * r7); c = (d1 >>> 13); d1 &= 0x1fff; d1 += h5 * (5 * r6); d1 += h6 * (5 * r5); d1 += h7 * (5 * r4); d1 += h8 * (5 * r3); d1 += h9 * (5 * r2); c += (d1 >>> 13); d1 &= 0x1fff; d2 = c; d2 += h0 * r2; d2 += h1 * r1; d2 += h2 * r0; d2 += h3 * (5 * r9); d2 += h4 * (5 * r8); c = (d2 >>> 13); d2 &= 0x1fff; d2 += h5 * (5 * r7); d2 += h6 * (5 * r6); d2 += h7 * (5 * r5); d2 += h8 * (5 * r4); d2 += h9 * (5 * r3); c += (d2 >>> 13); d2 &= 0x1fff; d3 = c; d3 += h0 * r3; d3 += h1 * r2; d3 += h2 * r1; d3 += h3 * r0; d3 += h4 * (5 * r9); c = (d3 >>> 13); d3 &= 0x1fff; d3 += h5 * (5 * r8); d3 += h6 * (5 * r7); d3 += h7 * (5 * r6); d3 += h8 * (5 * r5); d3 += h9 * (5 * r4); c += (d3 >>> 13); d3 &= 0x1fff; d4 = c; d4 += h0 * r4; d4 += h1 * r3; d4 += h2 * r2; d4 += h3 * r1; d4 += h4 * r0; c = (d4 >>> 13); d4 &= 0x1fff; d4 += h5 * (5 * r9); d4 += h6 * (5 * r8); d4 += h7 * (5 * r7); d4 += h8 * (5 * r6); d4 += h9 * (5 * r5); c += (d4 >>> 13); d4 &= 0x1fff; d5 = c; d5 += h0 * r5; d5 += h1 * r4; d5 += h2 * r3; d5 += h3 * r2; d5 += h4 * r1; c = (d5 >>> 13); d5 &= 0x1fff; d5 += h5 * r0; d5 += h6 * (5 * r9); d5 += h7 * (5 * r8); d5 += h8 * (5 * r7); d5 += h9 * (5 * r6); c += (d5 >>> 13); d5 &= 0x1fff; d6 = c; d6 += h0 * r6; d6 += h1 * r5; d6 += h2 * r4; d6 += h3 * r3; d6 += h4 * r2; c = (d6 >>> 13); d6 &= 0x1fff; d6 += h5 * r1; d6 += h6 * r0; d6 += h7 * (5 * r9); d6 += h8 * (5 * r8); d6 += h9 * (5 * r7); c += (d6 >>> 13); d6 &= 0x1fff; d7 = c; d7 += h0 * r7; d7 += h1 * r6; d7 += h2 * r5; d7 += h3 * r4; d7 += h4 * r3; c = (d7 >>> 13); d7 &= 0x1fff; d7 += h5 * r2; d7 += h6 * r1; d7 += h7 * r0; d7 += h8 * (5 * r9); d7 += h9 * (5 * r8); c += (d7 >>> 13); d7 &= 0x1fff; d8 = c; d8 += h0 * r8; d8 += h1 * r7; d8 += h2 * r6; d8 += h3 * r5; d8 += h4 * r4; c = (d8 >>> 13); d8 &= 0x1fff; d8 += h5 * r3; d8 += h6 * r2; d8 += h7 * r1; d8 += h8 * r0; d8 += h9 * (5 * r9); c += (d8 >>> 13); d8 &= 0x1fff; d9 = c; d9 += h0 * r9; d9 += h1 * r8; d9 += h2 * r7; d9 += h3 * r6; d9 += h4 * r5; c = (d9 >>> 13); d9 &= 0x1fff; d9 += h5 * r4; d9 += h6 * r3; d9 += h7 * r2; d9 += h8 * r1; d9 += h9 * r0; c += (d9 >>> 13); d9 &= 0x1fff; c = (((c << 2) + c)) | 0; c = (c + d0) | 0; d0 = c & 0x1fff; c = (c >>> 13); d1 += c; h0 = d0; h1 = d1; h2 = d2; h3 = d3; h4 = d4; h5 = d5; h6 = d6; h7 = d7; h8 = d8; h9 = d9; mpos += 16; bytes -= 16; } this.h[0] = h0; this.h[1] = h1; this.h[2] = h2; this.h[3] = h3; this.h[4] = h4; this.h[5] = h5; this.h[6] = h6; this.h[7] = h7; this.h[8] = h8; this.h[9] = h9; }; poly1305.prototype.finish = function(mac, macpos) { var g = new Uint16Array(10); var c, mask, f, i; if (this.leftover) { i = this.leftover; this.buffer[i++] = 1; for (; i < 16; i++) this.buffer[i] = 0; this.fin = 1; this.blocks(this.buffer, 0, 16); } c = this.h[1] >>> 13; this.h[1] &= 0x1fff; for (i = 2; i < 10; i++) { this.h[i] += c; c = this.h[i] >>> 13; this.h[i] &= 0x1fff; } this.h[0] += (c * 5); c = this.h[0] >>> 13; this.h[0] &= 0x1fff; this.h[1] += c; c = this.h[1] >>> 13; this.h[1] &= 0x1fff; this.h[2] += c; g[0] = this.h[0] + 5; c = g[0] >>> 13; g[0] &= 0x1fff; for (i = 1; i < 10; i++) { g[i] = this.h[i] + c; c = g[i] >>> 13; g[i] &= 0x1fff; } g[9] -= (1 << 13); mask = (c ^ 1) - 1; for (i = 0; i < 10; i++) g[i] &= mask; mask = ~mask; for (i = 0; i < 10; i++) this.h[i] = (this.h[i] & mask) | g[i]; this.h[0] = ((this.h[0] ) | (this.h[1] << 13) ) & 0xffff; this.h[1] = ((this.h[1] >>> 3) | (this.h[2] << 10) ) & 0xffff; this.h[2] = ((this.h[2] >>> 6) | (this.h[3] << 7) ) & 0xffff; this.h[3] = ((this.h[3] >>> 9) | (this.h[4] << 4) ) & 0xffff; this.h[4] = ((this.h[4] >>> 12) | (this.h[5] << 1) | (this.h[6] << 14)) & 0xffff; this.h[5] = ((this.h[6] >>> 2) | (this.h[7] << 11) ) & 0xffff; this.h[6] = ((this.h[7] >>> 5) | (this.h[8] << 8) ) & 0xffff; this.h[7] = ((this.h[8] >>> 8) | (this.h[9] << 5) ) & 0xffff; f = this.h[0] + this.pad[0]; this.h[0] = f & 0xffff; for (i = 1; i < 8; i++) { f = (((this.h[i] + this.pad[i]) | 0) + (f >>> 16)) | 0; this.h[i] = f & 0xffff; } mac[macpos+ 0] = (this.h[0] >>> 0) & 0xff; mac[macpos+ 1] = (this.h[0] >>> 8) & 0xff; mac[macpos+ 2] = (this.h[1] >>> 0) & 0xff; mac[macpos+ 3] = (this.h[1] >>> 8) & 0xff; mac[macpos+ 4] = (this.h[2] >>> 0) & 0xff; mac[macpos+ 5] = (this.h[2] >>> 8) & 0xff; mac[macpos+ 6] = (this.h[3] >>> 0) & 0xff; mac[macpos+ 7] = (this.h[3] >>> 8) & 0xff; mac[macpos+ 8] = (this.h[4] >>> 0) & 0xff; mac[macpos+ 9] = (this.h[4] >>> 8) & 0xff; mac[macpos+10] = (this.h[5] >>> 0) & 0xff; mac[macpos+11] = (this.h[5] >>> 8) & 0xff; mac[macpos+12] = (this.h[6] >>> 0) & 0xff; mac[macpos+13] = (this.h[6] >>> 8) & 0xff; mac[macpos+14] = (this.h[7] >>> 0) & 0xff; mac[macpos+15] = (this.h[7] >>> 8) & 0xff; }; poly1305.prototype.update = function(m, mpos, bytes) { var i, want; if (this.leftover) { want = (16 - this.leftover); if (want > bytes) want = bytes; for (i = 0; i < want; i++) this.buffer[this.leftover + i] = m[mpos+i]; bytes -= want; mpos += want; this.leftover += want; if (this.leftover < 16) return; this.blocks(this.buffer, 0, 16); this.leftover = 0; } if (bytes >= 16) { want = bytes - (bytes % 16); this.blocks(m, mpos, want); mpos += want; bytes -= want; } if (bytes) { for (i = 0; i < bytes; i++) this.buffer[this.leftover + i] = m[mpos+i]; this.leftover += bytes; } }; function crypto_onetimeauth(out, outpos, m, mpos, n, k) { var s = new poly1305(k); s.update(m, mpos, n); s.finish(out, outpos); return 0; } function crypto_onetimeauth_verify(h, hpos, m, mpos, n, k) { var x = new Uint8Array(16); crypto_onetimeauth(x,0,m,mpos,n,k); return crypto_verify_16(h,hpos,x,0); } function crypto_secretbox(c,m,d,n,k) { var i; if (d < 32) return -1; crypto_stream_xor(c,0,m,0,d,n,k); crypto_onetimeauth(c, 16, c, 32, d - 32, c); for (i = 0; i < 16; i++) c[i] = 0; return 0; } function crypto_secretbox_open(m,c,d,n,k) { var i; var x = new Uint8Array(32); if (d < 32) return -1; crypto_stream(x,0,32,n,k); if (crypto_onetimeauth_verify(c, 16,c, 32,d - 32,x) !== 0) return -1; crypto_stream_xor(m,0,c,0,d,n,k); for (i = 0; i < 32; i++) m[i] = 0; return 0; } function set25519(r, a) { var i; for (i = 0; i < 16; i++) r[i] = a[i]|0; } function car25519(o) { var i, v, c = 1; for (i = 0; i < 16; i++) { v = o[i] + c + 65535; c = Math.floor(v / 65536); o[i] = v - c * 65536; } o[0] += c-1 + 37 * (c-1); } function sel25519(p, q, b) { var t, c = ~(b-1); for (var i = 0; i < 16; i++) { t = c & (p[i] ^ q[i]); p[i] ^= t; q[i] ^= t; } } function pack25519(o, n) { var i, j, b; var m = gf(), t = gf(); for (i = 0; i < 16; i++) t[i] = n[i]; car25519(t); car25519(t); car25519(t); for (j = 0; j < 2; j++) { m[0] = t[0] - 0xffed; for (i = 1; i < 15; i++) { m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1); m[i-1] &= 0xffff; } m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1); b = (m[15]>>16) & 1; m[14] &= 0xffff; sel25519(t, m, 1-b); } for (i = 0; i < 16; i++) { o[2*i] = t[i] & 0xff; o[2*i+1] = t[i]>>8; } } function neq25519(a, b) { var c = new Uint8Array(32), d = new Uint8Array(32); pack25519(c, a); pack25519(d, b); return crypto_verify_32(c, 0, d, 0); } function par25519(a) { var d = new Uint8Array(32); pack25519(d, a); return d[0] & 1; } function unpack25519(o, n) { var i; for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8); o[15] &= 0x7fff; } function A(o, a, b) { for (var i = 0; i < 16; i++) o[i] = a[i] + b[i]; } function Z(o, a, b) { for (var i = 0; i < 16; i++) o[i] = a[i] - b[i]; } function M(o, a, b) { var v, c, t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3], b4 = b[4], b5 = b[5], b6 = b[6], b7 = b[7], b8 = b[8], b9 = b[9], b10 = b[10], b11 = b[11], b12 = b[12], b13 = b[13], b14 = b[14], b15 = b[15]; v = a[0]; t0 += v * b0; t1 += v * b1; t2 += v * b2; t3 += v * b3; t4 += v * b4; t5 += v * b5; t6 += v * b6; t7 += v * b7; t8 += v * b8; t9 += v * b9; t10 += v * b10; t11 += v * b11; t12 += v * b12; t13 += v * b13; t14 += v * b14; t15 += v * b15; v = a[1]; t1 += v * b0; t2 += v * b1; t3 += v * b2; t4 += v * b3; t5 += v * b4; t6 += v * b5; t7 += v * b6; t8 += v * b7; t9 += v * b8; t10 += v * b9; t11 += v * b10; t12 += v * b11; t13 += v * b12; t14 += v * b13; t15 += v * b14; t16 += v * b15; v = a[2]; t2 += v * b0; t3 += v * b1; t4 += v * b2; t5 += v * b3; t6 += v * b4; t7 += v * b5; t8 += v * b6; t9 += v * b7; t10 += v * b8; t11 += v * b9; t12 += v * b10; t13 += v * b11; t14 += v * b12; t15 += v * b13; t16 += v * b14; t17 += v * b15; v = a[3]; t3 += v * b0; t4 += v * b1; t5 += v * b2; t6 += v * b3; t7 += v * b4; t8 += v * b5; t9 += v * b6; t10 += v * b7; t11 += v * b8; t12 += v * b9; t13 += v * b10; t14 += v * b11; t15 += v * b12; t16 += v * b13; t17 += v * b14; t18 += v * b15; v = a[4]; t4 += v * b0; t5 += v * b1; t6 += v * b2; t7 += v * b3; t8 += v * b4; t9 += v * b5; t10 += v * b6; t11 += v * b7; t12 += v * b8; t13 += v * b9; t14 += v * b10; t15 += v * b11; t16 += v * b12; t17 += v * b13; t18 += v * b14; t19 += v * b15; v = a[5]; t5 += v * b0; t6 += v * b1; t7 += v * b2; t8 += v * b3; t9 += v * b4; t10 += v * b5; t11 += v * b6; t12 += v * b7; t13 += v * b8; t14 += v * b9; t15 += v * b10; t16 += v * b11; t17 += v * b12; t18 += v * b13; t19 += v * b14; t20 += v * b15; v = a[6]; t6 += v * b0; t7 += v * b1; t8 += v * b2; t9 += v * b3; t10 += v * b4; t11 += v * b5; t12 += v * b6; t13 += v * b7; t14 += v * b8; t15 += v * b9; t16 += v * b10; t17 += v * b11; t18 += v * b12; t19 += v * b13; t20 += v * b14; t21 += v * b15; v = a[7]; t7 += v * b0; t8 += v * b1; t9 += v * b2; t10 += v * b3; t11 += v * b4; t12 += v * b5; t13 += v * b6; t14 += v * b7; t15 += v * b8; t16 += v * b9; t17 += v * b10; t18 += v * b11; t19 += v * b12; t20 += v * b13; t21 += v * b14; t22 += v * b15; v = a[8]; t8 += v * b0; t9 += v * b1; t10 += v * b2; t11 += v * b3; t12 += v * b4; t13 += v * b5; t14 += v * b6; t15 += v * b7; t16 += v * b8; t17 += v * b9; t18 += v * b10; t19 += v * b11; t20 += v * b12; t21 += v * b13; t22 += v * b14; t23 += v * b15; v = a[9]; t9 += v * b0; t10 += v * b1; t11 += v * b2; t12 += v * b3; t13 += v * b4; t14 += v * b5; t15 += v * b6; t16 += v * b7; t17 += v * b8; t18 += v * b9; t19 += v * b10; t20 += v * b11; t21 += v * b12; t22 += v * b13; t23 += v * b14; t24 += v * b15; v = a[10]; t10 += v * b0; t11 += v * b1; t12 += v * b2; t13 += v * b3; t14 += v * b4; t15 += v * b5; t16 += v * b6; t17 += v * b7; t18 += v * b8; t19 += v * b9; t20 += v * b10; t21 += v * b11; t22 += v * b12; t23 += v * b13; t24 += v * b14; t25 += v * b15; v = a[11]; t11 += v * b0; t12 += v * b1; t13 += v * b2; t14 += v * b3; t15 += v * b4; t16 += v * b5; t17 += v * b6; t18 += v * b7; t19 += v * b8; t20 += v * b9; t21 += v * b10; t22 += v * b11; t23 += v * b12; t24 += v * b13; t25 += v * b14; t26 += v * b15; v = a[12]; t12 += v * b0; t13 += v * b1; t14 += v * b2; t15 += v * b3; t16 += v * b4; t17 += v * b5; t18 += v * b6; t19 += v * b7; t20 += v * b8; t21 += v * b9; t22 += v * b10; t23 += v * b11; t24 += v * b12; t25 += v * b13; t26 += v * b14; t27 += v * b15; v = a[13]; t13 += v * b0; t14 += v * b1; t15 += v * b2; t16 += v * b3; t17 += v * b4; t18 += v * b5; t19 += v * b6; t20 += v * b7; t21 += v * b8; t22 += v * b9; t23 += v * b10; t24 += v * b11; t25 += v * b12; t26 += v * b13; t27 += v * b14; t28 += v * b15; v = a[14]; t14 += v * b0; t15 += v * b1; t16 += v * b2; t17 += v * b3; t18 += v * b4; t19 += v * b5; t20 += v * b6; t21 += v * b7; t22 += v * b8; t23 += v * b9; t24 += v * b10; t25 += v * b11; t26 += v * b12; t27 += v * b13; t28 += v * b14; t29 += v * b15; v = a[15]; t15 += v * b0; t16 += v * b1; t17 += v * b2; t18 += v * b3; t19 += v * b4; t20 += v * b5; t21 += v * b6; t22 += v * b7; t23 += v * b8; t24 += v * b9; t25 += v * b10; t26 += v * b11; t27 += v * b12; t28 += v * b13; t29 += v * b14; t30 += v * b15; t0 += 38 * t16; t1 += 38 * t17; t2 += 38 * t18; t3 += 38 * t19; t4 += 38 * t20; t5 += 38 * t21; t6 += 38 * t22; t7 += 38 * t23; t8 += 38 * t24; t9 += 38 * t25; t10 += 38 * t26; t11 += 38 * t27; t12 += 38 * t28; t13 += 38 * t29; t14 += 38 * t30; // t15 left as is // first car c = 1; v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; t0 += c-1 + 37 * (c-1); // second car c = 1; v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; t0 += c-1 + 37 * (c-1); o[ 0] = t0; o[ 1] = t1; o[ 2] = t2; o[ 3] = t3; o[ 4] = t4; o[ 5] = t5; o[ 6] = t6; o[ 7] = t7; o[ 8] = t8; o[ 9] = t9; o[10] = t10; o[11] = t11; o[12] = t12; o[13] = t13; o[14] = t14; o[15] = t15; } function S(o, a) { M(o, a, a); } function inv25519(o, i) { var c = gf(); var a; for (a = 0; a < 16; a++) c[a] = i[a]; for (a = 253; a >= 0; a--) { S(c, c); if(a !== 2 && a !== 4) M(c, c, i); } for (a = 0; a < 16; a++) o[a] = c[a]; } function pow2523(o, i) { var c = gf(); var a; for (a = 0; a < 16; a++) c[a] = i[a]; for (a = 250; a >= 0; a--) { S(c, c); if(a !== 1) M(c, c, i); } for (a = 0; a < 16; a++) o[a] = c[a]; } function crypto_scalarmult(q, n, p) { var z = new Uint8Array(32); var x = new Float64Array(80), r, i; var a = gf(), b = gf(), c = gf(), d = gf(), e = gf(), f = gf(); for (i = 0; i < 31; i++) z[i] = n[i]; z[31]=(n[31]&127)|64; z[0]&=248; unpack25519(x,p); for (i = 0; i < 16; i++) { b[i]=x[i]; d[i]=a[i]=c[i]=0; } a[0]=d[0]=1; for (i=254; i>=0; --i) { r=(z[i>>>3]>>>(i&7))&1; sel25519(a,b,r); sel25519(c,d,r); A(e,a,c); Z(a,a,c); A(c,b,d); Z(b,b,d); S(d,e); S(f,a); M(a,c,a); M(c,b,e); A(e,a,c); Z(a,a,c); S(b,a); Z(c,d,f); M(a,c,_121665); A(a,a,d); M(c,c,a); M(a,d,f); M(d,b,x); S(b,e); sel25519(a,b,r); sel25519(c,d,r); } for (i = 0; i < 16; i++) { x[i+16]=a[i]; x[i+32]=c[i]; x[i+48]=b[i]; x[i+64]=d[i]; } var x32 = x.subarray(32); var x16 = x.subarray(16); inv25519(x32,x32); M(x16,x16,x32); pack25519(q,x16); return 0; } function crypto_scalarmult_base(q, n) { return crypto_scalarmult(q, n, _9); } function crypto_box_keypair(y, x) { randombytes(x, 32); return crypto_scalarmult_base(y, x); } function crypto_box_beforenm(k, y, x) { var s = new Uint8Array(32); crypto_scalarmult(s, x, y); return crypto_core_hsalsa20(k, _0, s, sigma); } var crypto_box_afternm = crypto_secretbox; var crypto_box_open_afternm = crypto_secretbox_open; function crypto_box(c, m, d, n, y, x) { var k = new Uint8Array(32); crypto_box_beforenm(k, y, x); return crypto_box_afternm(c, m, d, n, k); } function crypto_box_open(m, c, d, n, y, x) { var k = new Uint8Array(32); crypto_box_beforenm(k, y, x); return crypto_box_open_afternm(m, c, d, n, k); } var K = [ 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 ]; function crypto_hashblocks_hl(hh, hl, m, n) { var wh = new Int32Array(16), wl = new Int32Array(16), bh0, bh1, bh2, bh3, bh4, bh5, bh6, bh7, bl0, bl1, bl2, bl3, bl4, bl5, bl6, bl7, th, tl, i, j, h, l, a, b, c, d; var ah0 = hh[0], ah1 = hh[1], ah2 = hh[2], ah3 = hh[3], ah4 = hh[4], ah5 = hh[5], ah6 = hh[6], ah7 = hh[7], al0 = hl[0], al1 = hl[1], al2 = hl[2], al3 = hl[3], al4 = hl[4], al5 = hl[5], al6 = hl[6], al7 = hl[7]; var pos = 0; while (n >= 128) { for (i = 0; i < 16; i++) { j = 8 * i + pos; wh[i] = (m[j+0] << 24) | (m[j+1] << 16) | (m[j+2] << 8) | m[j+3]; wl[i] = (m[j+4] << 24) | (m[j+5] << 16) | (m[j+6] << 8) | m[j+7]; } for (i = 0; i < 80; i++) { bh0 = ah0; bh1 = ah1; bh2 = ah2; bh3 = ah3; bh4 = ah4; bh5 = ah5; bh6 = ah6; bh7 = ah7; bl0 = al0; bl1 = al1; bl2 = al2; bl3 = al3; bl4 = al4; bl5 = al5; bl6 = al6; bl7 = al7; // add h = ah7; l = al7; a = l & 0xffff; b = l >>> 16; c = h & 0xffff; d = h >>> 16; // Sigma1 h = ((ah4 >>> 14) | (al4 << (32-14))) ^ ((ah4 >>> 18) | (al4 << (32-18))) ^ ((al4 >>> (41-32)) | (ah4 << (32-(41-32)))); l = ((al4 >>> 14) | (ah4 << (32-14))) ^ ((al4 >>> 18) | (ah4 << (32-18))) ^ ((ah4 >>> (41-32)) | (al4 << (32-(41-32)))); a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; // Ch h = (ah4 & ah5) ^ (~ah4 & ah6); l = (al4 & al5) ^ (~al4 & al6); a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; // K h = K[i*2]; l = K[i*2+1]; a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; // w h = wh[i%16]; l = wl[i%16]; a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; th = c & 0xffff | d << 16; tl = a & 0xffff | b << 16; // add h = th; l = tl; a = l & 0xffff; b = l >>> 16; c = h & 0xffff; d = h >>> 16; // Sigma0 h = ((ah0 >>> 28) | (al0 << (32-28))) ^ ((al0 >>> (34-32)) | (ah0 << (32-(34-32)))) ^ ((al0 >>> (39-32)) | (ah0 << (32-(39-32)))); l = ((al0 >>> 28) | (ah0 << (32-28))) ^ ((ah0 >>> (34-32)) | (al0 << (32-(34-32)))) ^ ((ah0 >>> (39-32)) | (al0 << (32-(39-32)))); a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; // Maj h = (ah0 & ah1) ^ (ah0 & ah2) ^ (ah1 & ah2); l = (al0 & al1) ^ (al0 & al2) ^ (al1 & al2); a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; bh7 = (c & 0xffff) | (d << 16); bl7 = (a & 0xffff) | (b << 16); // add h = bh3; l = bl3; a = l & 0xffff; b = l >>> 16; c = h & 0xffff; d = h >>> 16; h = th; l = tl; a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; bh3 = (c & 0xffff) | (d << 16); bl3 = (a & 0xffff) | (b << 16); ah1 = bh0; ah2 = bh1; ah3 = bh2; ah4 = bh3; ah5 = bh4; ah6 = bh5; ah7 = bh6; ah0 = bh7; al1 = bl0; al2 = bl1; al3 = bl2; al4 = bl3; al5 = bl4; al6 = bl5; al7 = bl6; al0 = bl7; if (i%16 === 15) { for (j = 0; j < 16; j++) { // add h = wh[j]; l = wl[j]; a = l & 0xffff; b = l >>> 16; c = h & 0xffff; d = h >>> 16; h = wh[(j+9)%16]; l = wl[(j+9)%16]; a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; // sigma0 th = wh[(j+1)%16]; tl = wl[(j+1)%16]; h = ((th >>> 1) | (tl << (32-1))) ^ ((th >>> 8) | (tl << (32-8))) ^ (th >>> 7); l = ((tl >>> 1) | (th << (32-1))) ^ ((tl >>> 8) | (th << (32-8))) ^ ((tl >>> 7) | (th << (32-7))); a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; // sigma1 th = wh[(j+14)%16]; tl = wl[(j+14)%16]; h = ((th >>> 19) | (tl << (32-19))) ^ ((tl >>> (61-32)) | (th << (32-(61-32)))) ^ (th >>> 6); l = ((tl >>> 19) | (th << (32-19))) ^ ((th >>> (61-32)) | (tl << (32-(61-32)))) ^ ((tl >>> 6) | (th << (32-6))); a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; wh[j] = (c & 0xffff) | (d << 16); wl[j] = (a & 0xffff) | (b << 16); } } } // add h = ah0; l = al0; a = l & 0xffff; b = l >>> 16; c = h & 0xffff; d = h >>> 16; h = hh[0]; l = hl[0]; a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; hh[0] = ah0 = (c & 0xffff) | (d << 16); hl[0] = al0 = (a & 0xffff) | (b << 16); h = ah1; l = al1; a = l & 0xffff; b = l >>> 16; c = h & 0xffff; d = h >>> 16; h = hh[1]; l = hl[1]; a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; hh[1] = ah1 = (c & 0xffff) | (d << 16); hl[1] = al1 = (a & 0xffff) | (b << 16); h = ah2; l = al2; a = l & 0xffff; b = l >>> 16; c = h & 0xffff; d = h >>> 16; h = hh[2]; l = hl[2]; a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; hh[2] = ah2 = (c & 0xffff) | (d << 16); hl[2] = al2 = (a & 0xffff) | (b << 16); h = ah3; l = al3; a = l & 0xffff; b = l >>> 16; c = h & 0xffff; d = h >>> 16; h = hh[3]; l = hl[3]; a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; hh[3] = ah3 = (c & 0xffff) | (d << 16); hl[3] = al3 = (a & 0xffff) | (b << 16); h = ah4; l = al4; a = l & 0xffff; b = l >>> 16; c = h & 0xffff; d = h >>> 16; h = hh[4]; l = hl[4]; a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; hh[4] = ah4 = (c & 0xffff) | (d << 16); hl[4] = al4 = (a & 0xffff) | (b << 16); h = ah5; l = al5; a = l & 0xffff; b = l >>> 16; c = h & 0xffff; d = h >>> 16; h = hh[5]; l = hl[5]; a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; hh[5] = ah5 = (c & 0xffff) | (d << 16); hl[5] = al5 = (a & 0xffff) | (b << 16); h = ah6; l = al6; a = l & 0xffff; b = l >>> 16; c = h & 0xffff; d = h >>> 16; h = hh[6]; l = hl[6]; a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; hh[6] = ah6 = (c & 0xffff) | (d << 16); hl[6] = al6 = (a & 0xffff) | (b << 16); h = ah7; l = al7; a = l & 0xffff; b = l >>> 16; c = h & 0xffff; d = h >>> 16; h = hh[7]; l = hl[7]; a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; hh[7] = ah7 = (c & 0xffff) | (d << 16); hl[7] = al7 = (a & 0xffff) | (b << 16); pos += 128; n -= 128; } return n; } function crypto_hash(out, m, n) { var hh = new Int32Array(8), hl = new Int32Array(8), x = new Uint8Array(256), i, b = n; hh[0] = 0x6a09e667; hh[1] = 0xbb67ae85; hh[2] = 0x3c6ef372; hh[3] = 0xa54ff53a; hh[4] = 0x510e527f; hh[5] = 0x9b05688c; hh[6] = 0x1f83d9ab; hh[7] = 0x5be0cd19; hl[0] = 0xf3bcc908; hl[1] = 0x84caa73b; hl[2] = 0xfe94f82b; hl[3] = 0x5f1d36f1; hl[4] = 0xade682d1; hl[5] = 0x2b3e6c1f; hl[6] = 0xfb41bd6b; hl[7] = 0x137e2179; crypto_hashblocks_hl(hh, hl, m, n); n %= 128; for (i = 0; i < n; i++) x[i] = m[b-n+i]; x[n] = 128; n = 256-128*(n<112?1:0); x[n-9] = 0; ts64(x, n-8, (b / 0x20000000) | 0, b << 3); crypto_hashblocks_hl(hh, hl, x, n); for (i = 0; i < 8; i++) ts64(out, 8*i, hh[i], hl[i]); return 0; } function add(p, q) { var a = gf(), b = gf(), c = gf(), d = gf(), e = gf(), f = gf(), g = gf(), h = gf(), t = gf(); Z(a, p[1], p[0]); Z(t, q[1], q[0]); M(a, a, t); A(b, p[0], p[1]); A(t, q[0], q[1]); M(b, b, t); M(c, p[3], q[3]); M(c, c, D2); M(d, p[2], q[2]); A(d, d, d); Z(e, b, a); Z(f, d, c); A(g, d, c); A(h, b, a); M(p[0], e, f); M(p[1], h, g); M(p[2], g, f); M(p[3], e, h); } function cswap(p, q, b) { var i; for (i = 0; i < 4; i++) { sel25519(p[i], q[i], b); } } function pack(r, p) { var tx = gf(), ty = gf(), zi = gf(); inv25519(zi, p[2]); M(tx, p[0], zi); M(ty, p[1], zi); pack25519(r, ty); r[31] ^= par25519(tx) << 7; } function scalarmult(p, q, s) { var b, i; set25519(p[0], gf0); set25519(p[1], gf1); set25519(p[2], gf1); set25519(p[3], gf0); for (i = 255; i >= 0; --i) { b = (s[(i/8)|0] >> (i&7)) & 1; cswap(p, q, b); add(q, p); add(p, p); cswap(p, q, b); } } function scalarbase(p, s) { var q = [gf(), gf(), gf(), gf()]; set25519(q[0], X); set25519(q[1], Y); set25519(q[2], gf1); M(q[3], X, Y); scalarmult(p, q, s); } function crypto_sign_keypair(pk, sk, seeded) { var d = new Uint8Array(64); var p = [gf(), gf(), gf(), gf()]; var i; if (!seeded) randombytes(sk, 32); crypto_hash(d, sk, 32); d[0] &= 248; d[31] &= 127; d[31] |= 64; scalarbase(p, d); pack(pk, p); for (i = 0; i < 32; i++) sk[i+32] = pk[i]; return 0; } var L = new Float64Array([0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]); function modL(r, x) { var carry, i, j, k; for (i = 63; i >= 32; --i) { carry = 0; for (j = i - 32, k = i - 12; j < k; ++j) { x[j] += carry - 16 * x[i] * L[j - (i - 32)]; carry = (x[j] + 128) >> 8; x[j] -= carry * 256; } x[j] += carry; x[i] = 0; } carry = 0; for (j = 0; j < 32; j++) { x[j] += carry - (x[31] >> 4) * L[j]; carry = x[j] >> 8; x[j] &= 255; } for (j = 0; j < 32; j++) x[j] -= carry * L[j]; for (i = 0; i < 32; i++) { x[i+1] += x[i] >> 8; r[i] = x[i] & 255; } } function reduce(r) { var x = new Float64Array(64), i; for (i = 0; i < 64; i++) x[i] = r[i]; for (i = 0; i < 64; i++) r[i] = 0; modL(r, x); } // Note: difference from C - smlen returned, not passed as argument. function crypto_sign(sm, m, n, sk) { var d = new Uint8Array(64), h = new Uint8Array(64), r = new Uint8Array(64); var i, j, x = new Float64Array(64); var p = [gf(), gf(), gf(), gf()]; crypto_hash(d, sk, 32); d[0] &= 248; d[31] &= 127; d[31] |= 64; var smlen = n + 64; for (i = 0; i < n; i++) sm[64 + i] = m[i]; for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i]; crypto_hash(r, sm.subarray(32), n+32); reduce(r); scalarbase(p, r); pack(sm, p); for (i = 32; i < 64; i++) sm[i] = sk[i]; crypto_hash(h, sm, n + 64); reduce(h); for (i = 0; i < 64; i++) x[i] = 0; for (i = 0; i < 32; i++) x[i] = r[i]; for (i = 0; i < 32; i++) { for (j = 0; j < 32; j++) { x[i+j] += h[i] * d[j]; } } modL(sm.subarray(32), x); return smlen; } function unpackneg(r, p) { var t = gf(), chk = gf(), num = gf(), den = gf(), den2 = gf(), den4 = gf(), den6 = gf(); set25519(r[2], gf1); unpack25519(r[1], p); S(num, r[1]); M(den, num, D); Z(num, num, r[2]); A(den, r[2], den); S(den2, den); S(den4, den2); M(den6, den4, den2); M(t, den6, num); M(t, t, den); pow2523(t, t); M(t, t, num); M(t, t, den); M(t, t, den); M(r[0], t, den); S(chk, r[0]); M(chk, chk, den); if (neq25519(chk, num)) M(r[0], r[0], I); S(chk, r[0]); M(chk, chk, den); if (neq25519(chk, num)) return -1; if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]); M(r[3], r[0], r[1]); return 0; } function crypto_sign_open(m, sm, n, pk) { var i, mlen; var t = new Uint8Array(32), h = new Uint8Array(64); var p = [gf(), gf(), gf(), gf()], q = [gf(), gf(), gf(), gf()]; mlen = -1; if (n < 64) return -1; if (unpackneg(q, pk)) return -1; for (i = 0; i < n; i++) m[i] = sm[i]; for (i = 0; i < 32; i++) m[i+32] = pk[i]; crypto_hash(h, m, n); reduce(h); scalarmult(p, q, h); scalarbase(q, sm.subarray(32)); add(p, q); pack(t, p); n -= 64; if (crypto_verify_32(sm, 0, t, 0)) { for (i = 0; i < n; i++) m[i] = 0; return -1; } for (i = 0; i < n; i++) m[i] = sm[i + 64]; mlen = n; return mlen; } var crypto_secretbox_KEYBYTES = 32, crypto_secretbox_NONCEBYTES = 24, crypto_secretbox_ZEROBYTES = 32, crypto_secretbox_BOXZEROBYTES = 16, crypto_scalarmult_BYTES = 32, crypto_scalarmult_SCALARBYTES = 32, crypto_box_PUBLICKEYBYTES = 32, crypto_box_SECRETKEYBYTES = 32, crypto_box_BEFORENMBYTES = 32, crypto_box_NONCEBYTES = crypto_secretbox_NONCEBYTES, crypto_box_ZEROBYTES = crypto_secretbox_ZEROBYTES, crypto_box_BOXZEROBYTES = crypto_secretbox_BOXZEROBYTES, crypto_sign_BYTES = 64, crypto_sign_PUBLICKEYBYTES = 32, crypto_sign_SECRETKEYBYTES = 64, crypto_sign_SEEDBYTES = 32, crypto_hash_BYTES = 64; nacl.lowlevel = { crypto_core_hsalsa20: crypto_core_hsalsa20, crypto_stream_xor: crypto_stream_xor, crypto_stream: crypto_stream, crypto_stream_salsa20_xor: crypto_stream_salsa20_xor, crypto_stream_salsa20: crypto_stream_salsa20, crypto_onetimeauth: crypto_onetimeauth, crypto_onetimeauth_verify: crypto_onetimeauth_verify, crypto_verify_16: crypto_verify_16, crypto_verify_32: crypto_verify_32, crypto_secretbox: crypto_secretbox, crypto_secretbox_open: crypto_secretbox_open, crypto_scalarmult: crypto_scalarmult, crypto_scalarmult_base: crypto_scalarmult_base, crypto_box_beforenm: crypto_box_beforenm, crypto_box_afternm: crypto_box_afternm, crypto_box: crypto_box, crypto_box_open: crypto_box_open, crypto_box_keypair: crypto_box_keypair, crypto_hash: crypto_hash, crypto_sign: crypto_sign, crypto_sign_keypair: crypto_sign_keypair, crypto_sign_open: crypto_sign_open, crypto_secretbox_KEYBYTES: crypto_secretbox_KEYBYTES, crypto_secretbox_NONCEBYTES: crypto_secretbox_NONCEBYTES, crypto_secretbox_ZEROBYTES: crypto_secretbox_ZEROBYTES, crypto_secretbox_BOXZEROBYTES: crypto_secretbox_BOXZEROBYTES, crypto_scalarmult_BYTES: crypto_scalarmult_BYTES, crypto_scalarmult_SCALARBYTES: crypto_scalarmult_SCALARBYTES, crypto_box_PUBLICKEYBYTES: crypto_box_PUBLICKEYBYTES, crypto_box_SECRETKEYBYTES: crypto_box_SECRETKEYBYTES, crypto_box_BEFORENMBYTES: crypto_box_BEFORENMBYTES, crypto_box_NONCEBYTES: crypto_box_NONCEBYTES, crypto_box_ZEROBYTES: crypto_box_ZEROBYTES, crypto_box_BOXZEROBYTES: crypto_box_BOXZEROBYTES, crypto_sign_BYTES: crypto_sign_BYTES, crypto_sign_PUBLICKEYBYTES: crypto_sign_PUBLICKEYBYTES, crypto_sign_SECRETKEYBYTES: crypto_sign_SECRETKEYBYTES, crypto_sign_SEEDBYTES: crypto_sign_SEEDBYTES, crypto_hash_BYTES: crypto_hash_BYTES }; /* High-level API */ function checkLengths(k, n) { if (k.length !== crypto_secretbox_KEYBYTES) throw new Error('bad key size'); if (n.length !== crypto_secretbox_NONCEBYTES) throw new Error('bad nonce size'); } function checkBoxLengths(pk, sk) { if (pk.length !== crypto_box_PUBLICKEYBYTES) throw new Error('bad public key size'); if (sk.length !== crypto_box_SECRETKEYBYTES) throw new Error('bad secret key size'); } function checkArrayTypes() { var t, i; for (i = 0; i < arguments.length; i++) { if ((t = Object.prototype.toString.call(arguments[i])) !== '[object Uint8Array]') throw new TypeError('unexpected type ' + t + ', use Uint8Array'); } } function cleanup(arr) { for (var i = 0; i < arr.length; i++) arr[i] = 0; } // TODO: Completely remove this in v0.15. if (!nacl.util) { nacl.util = {}; nacl.util.decodeUTF8 = nacl.util.encodeUTF8 = nacl.util.encodeBase64 = nacl.util.decodeBase64 = function() { throw new Error('nacl.util moved into separate package: https://github.com/dchest/tweetnacl-util-js'); }; } nacl.randomBytes = function(n) { var b = new Uint8Array(n); randombytes(b, n); return b; }; nacl.secretbox = function(msg, nonce, key) { checkArrayTypes(msg, nonce, key); checkLengths(key, nonce); var m = new Uint8Array(crypto_secretbox_ZEROBYTES + msg.length); var c = new Uint8Array(m.length); for (var i = 0; i < msg.length; i++) m[i+crypto_secretbox_ZEROBYTES] = msg[i]; crypto_secretbox(c, m, m.length, nonce, key); return c.subarray(crypto_secretbox_BOXZEROBYTES); }; nacl.secretbox.open = function(box, nonce, key) { checkArrayTypes(box, nonce, key); checkLengths(key, nonce); var c = new Uint8Array(crypto_secretbox_BOXZEROBYTES + box.length); var m = new Uint8Array(c.length); for (var i = 0; i < box.length; i++) c[i+crypto_secretbox_BOXZEROBYTES] = box[i]; if (c.length < 32) return false; if (crypto_secretbox_open(m, c, c.length, nonce, key) !== 0) return false; return m.subarray(crypto_secretbox_ZEROBYTES); }; nacl.secretbox.keyLength = crypto_secretbox_KEYBYTES; nacl.secretbox.nonceLength = crypto_secretbox_NONCEBYTES; nacl.secretbox.overheadLength = crypto_secretbox_BOXZEROBYTES; nacl.scalarMult = function(n, p) { checkArrayTypes(n, p); if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size'); var q = new Uint8Array(crypto_scalarmult_BYTES); crypto_scalarmult(q, n, p); return q; }; nacl.scalarMult.base = function(n) { checkArrayTypes(n); if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); var q = new Uint8Array(crypto_scalarmult_BYTES); crypto_scalarmult_base(q, n); return q; }; nacl.scalarMult.scalarLength = crypto_scalarmult_SCALARBYTES; nacl.scalarMult.groupElementLength = crypto_scalarmult_BYTES; nacl.box = function(msg, nonce, publicKey, secretKey) { var k = nacl.box.before(publicKey, secretKey); return nacl.secretbox(msg, nonce, k); }; nacl.box.before = function(publicKey, secretKey) { checkArrayTypes(publicKey, secretKey); checkBoxLengths(publicKey, secretKey); var k = new Uint8Array(crypto_box_BEFORENMBYTES); crypto_box_beforenm(k, publicKey, secretKey); return k; }; nacl.box.after = nacl.secretbox; nacl.box.open = function(msg, nonce, publicKey, secretKey) { var k = nacl.box.before(publicKey, secretKey); return nacl.secretbox.open(msg, nonce, k); }; nacl.box.open.after = nacl.secretbox.open; nacl.box.keyPair = function() { var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); var sk = new Uint8Array(crypto_box_SECRETKEYBYTES); crypto_box_keypair(pk, sk); return {publicKey: pk, secretKey: sk}; }; nacl.box.keyPair.fromSecretKey = function(secretKey) { checkArrayTypes(secretKey); if (secretKey.length !== crypto_box_SECRETKEYBYTES) throw new Error('bad secret key size'); var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); crypto_scalarmult_base(pk, secretKey); return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; }; nacl.box.publicKeyLength = crypto_box_PUBLICKEYBYTES; nacl.box.secretKeyLength = crypto_box_SECRETKEYBYTES; nacl.box.sharedKeyLength = crypto_box_BEFORENMBYTES; nacl.box.nonceLength = crypto_box_NONCEBYTES; nacl.box.overheadLength = nacl.secretbox.overheadLength; nacl.sign = function(msg, secretKey) { checkArrayTypes(msg, secretKey); if (secretKey.length !== crypto_sign_SECRETKEYBYTES) throw new Error('bad secret key size'); var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length); crypto_sign(signedMsg, msg, msg.length, secretKey); return signedMsg; }; nacl.sign.open = function(signedMsg, publicKey) { if (arguments.length !== 2) throw new Error('nacl.sign.open accepts 2 arguments; did you mean to use nacl.sign.detached.verify?'); checkArrayTypes(signedMsg, publicKey); if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) throw new Error('bad public key size'); var tmp = new Uint8Array(signedMsg.length); var mlen = crypto_sign_open(tmp, signedMsg, signedMsg.length, publicKey); if (mlen < 0) return null; var m = new Uint8Array(mlen); for (var i = 0; i < m.length; i++) m[i] = tmp[i]; return m; }; nacl.sign.detached = function(msg, secretKey) { var signedMsg = nacl.sign(msg, secretKey); var sig = new Uint8Array(crypto_sign_BYTES); for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i]; return sig; }; nacl.sign.detached.verify = function(msg, sig, publicKey) { checkArrayTypes(msg, sig, publicKey); if (sig.length !== crypto_sign_BYTES) throw new Error('bad signature size'); if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) throw new Error('bad public key size'); var sm = new Uint8Array(crypto_sign_BYTES + msg.length); var m = new Uint8Array(crypto_sign_BYTES + msg.length); var i; for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i]; for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i]; return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0); }; nacl.sign.keyPair = function() { var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); crypto_sign_keypair(pk, sk); return {publicKey: pk, secretKey: sk}; }; nacl.sign.keyPair.fromSecretKey = function(secretKey) { checkArrayTypes(secretKey); if (secretKey.length !== crypto_sign_SECRETKEYBYTES) throw new Error('bad secret key size'); var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i]; return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; }; nacl.sign.keyPair.fromSeed = function(seed) { checkArrayTypes(seed); if (seed.length !== crypto_sign_SEEDBYTES) throw new Error('bad seed size'); var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); for (var i = 0; i < 32; i++) sk[i] = seed[i]; crypto_sign_keypair(pk, sk, true); return {publicKey: pk, secretKey: sk}; }; nacl.sign.publicKeyLength = crypto_sign_PUBLICKEYBYTES; nacl.sign.secretKeyLength = crypto_sign_SECRETKEYBYTES; nacl.sign.seedLength = crypto_sign_SEEDBYTES; nacl.sign.signatureLength = crypto_sign_BYTES; nacl.hash = function(msg) { checkArrayTypes(msg); var h = new Uint8Array(crypto_hash_BYTES); crypto_hash(h, msg, msg.length); return h; }; nacl.hash.hashLength = crypto_hash_BYTES; nacl.verify = function(x, y) { checkArrayTypes(x, y); // Zero length arguments are considered not equal. if (x.length === 0 || y.length === 0) return false; if (x.length !== y.length) return false; return (vn(x, 0, y, 0, x.length) === 0) ? true : false; }; nacl.setPRNG = function(fn) { randombytes = fn; }; (function() { // Initialize PRNG if environment provides CSPRNG. // If not, methods calling randombytes will throw. var crypto = typeof self !== 'undefined' ? (self.crypto || self.msCrypto) : null; if (crypto && crypto.getRandomValues) { // Browsers. var QUOTA = 65536; nacl.setPRNG(function(x, n) { var i, v = new Uint8Array(n); for (i = 0; i < n; i += QUOTA) { crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA))); } for (i = 0; i < n; i++) x[i] = v[i]; cleanup(v); }); } else if (true) { // Node.js. crypto = __nccwpck_require__(6113); if (crypto && crypto.randomBytes) { nacl.setPRNG(function(x, n) { var i, v = crypto.randomBytes(n); for (i = 0; i < n; i++) x[i] = v[i]; cleanup(v); }); } } })(); })( true && module.exports ? module.exports : (self.nacl = self.nacl || {})); /***/ }), /***/ 31524: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 66647: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isValidErrorCode = exports.httpStatusFromErrorCode = exports.TwirpErrorCode = exports.BadRouteError = exports.InternalServerErrorWith = exports.InternalServerError = exports.RequiredArgumentError = exports.InvalidArgumentError = exports.NotFoundError = exports.TwirpError = void 0; /** * Represents a twirp error */ class TwirpError extends Error { constructor(code, msg) { super(msg); this.code = TwirpErrorCode.Internal; this.meta = {}; this.code = code; this.msg = msg; Object.setPrototypeOf(this, TwirpError.prototype); } /** * Adds a metadata kv to the error * @param key * @param value */ withMeta(key, value) { this.meta[key] = value; return this; } /** * Returns a single metadata value * return "" if not found * @param key */ getMeta(key) { return this.meta[key] || ""; } /** * Add the original error cause * @param err * @param addMeta */ withCause(err, addMeta = false) { this._originalCause = err; if (addMeta) { this.withMeta("cause", err.message); } return this; } cause() { return this._originalCause; } /** * Returns the error representation to JSON */ toJSON() { try { return JSON.stringify({ code: this.code, msg: this.msg, meta: this.meta, }); } catch (e) { return `{"code": "internal", "msg": "There was an error but it could not be serialized into JSON"}`; } } /** * Create a twirp error from an object * @param obj */ static fromObject(obj) { const code = obj["code"] || TwirpErrorCode.Unknown; const msg = obj["msg"] || "unknown"; const error = new TwirpError(code, msg); if (obj["meta"]) { Object.keys(obj["meta"]).forEach((key) => { error.withMeta(key, obj["meta"][key]); }); } return error; } } exports.TwirpError = TwirpError; /** * NotFoundError constructor for the common NotFound error. */ class NotFoundError extends TwirpError { constructor(msg) { super(TwirpErrorCode.NotFound, msg); } } exports.NotFoundError = NotFoundError; /** * InvalidArgumentError constructor for the common InvalidArgument error. Can be * used when an argument has invalid format, is a number out of range, is a bad * option, etc). */ class InvalidArgumentError extends TwirpError { constructor(argument, validationMsg) { super(TwirpErrorCode.InvalidArgument, argument + " " + validationMsg); this.withMeta("argument", argument); } } exports.InvalidArgumentError = InvalidArgumentError; /** * RequiredArgumentError is a more specific constructor for InvalidArgument * error. Should be used when the argument is required (expected to have a * non-zero value). */ class RequiredArgumentError extends InvalidArgumentError { constructor(argument) { super(argument, "is required"); } } exports.RequiredArgumentError = RequiredArgumentError; /** * InternalError constructor for the common Internal error. Should be used to * specify that something bad or unexpected happened. */ class InternalServerError extends TwirpError { constructor(msg) { super(TwirpErrorCode.Internal, msg); } } exports.InternalServerError = InternalServerError; /** * InternalErrorWith makes an internal error, wrapping the original error and using it * for the error message, and with metadata "cause" with the original error type. * This function is used by Twirp services to wrap non-Twirp errors as internal errors. * The wrapped error can be extracted later with err.cause() */ class InternalServerErrorWith extends InternalServerError { constructor(err) { super(err.message); this.withMeta("cause", err.name); this.withCause(err); } } exports.InternalServerErrorWith = InternalServerErrorWith; /** * A standard BadRoute Error */ class BadRouteError extends TwirpError { constructor(msg, method, url) { super(TwirpErrorCode.BadRoute, msg); this.withMeta("twirp_invalid_route", method + " " + url); } } exports.BadRouteError = BadRouteError; var TwirpErrorCode; (function (TwirpErrorCode) { // Canceled indicates the operation was cancelled (typically by the caller). TwirpErrorCode["Canceled"] = "canceled"; // Unknown error. For example when handling errors raised by APIs that do not // return enough error information. TwirpErrorCode["Unknown"] = "unknown"; // InvalidArgument indicates client specified an invalid argument. It // indicates arguments that are problematic regardless of the state of the // system (i.e. a malformed file name, required argument, number out of range, // etc.). TwirpErrorCode["InvalidArgument"] = "invalid_argument"; // Malformed indicates an error occurred while decoding the client's request. // This may mean that the message was encoded improperly, or that there is a // disagreement in message format between the client and server. TwirpErrorCode["Malformed"] = "malformed"; // DeadlineExceeded means operation expired before completion. For operations // that change the state of the system, this error may be returned even if the // operation has completed successfully (timeout). TwirpErrorCode["DeadlineExceeded"] = "deadline_exceeded"; // NotFound means some requested entity was not found. TwirpErrorCode["NotFound"] = "not_found"; // BadRoute means that the requested URL path wasn't routable to a Twirp // service and method. This is returned by the generated server, and usually // shouldn't be returned by applications. Instead, applications should use // NotFound or Unimplemented. TwirpErrorCode["BadRoute"] = "bad_route"; // AlreadyExists means an attempt to create an entity failed because one // already exists. TwirpErrorCode["AlreadyExists"] = "already_exists"; // PermissionDenied indicates the caller does not have permission to execute // the specified operation. It must not be used if the caller cannot be // identified (Unauthenticated). TwirpErrorCode["PermissionDenied"] = "permission_denied"; // Unauthenticated indicates the request does not have valid authentication // credentials for the operation. TwirpErrorCode["Unauthenticated"] = "unauthenticated"; // ResourceExhausted indicates some resource has been exhausted, perhaps a // per-user quota, or perhaps the entire file system is out of space. TwirpErrorCode["ResourceExhausted"] = "resource_exhausted"; // FailedPrecondition indicates operation was rejected because the system is // not in a state required for the operation's execution. For example, doing // an rmdir operation on a directory that is non-empty, or on a non-directory // object, or when having conflicting read-modify-write on the same resource. TwirpErrorCode["FailedPrecondition"] = "failed_precondition"; // Aborted indicates the operation was aborted, typically due to a concurrency // issue like sequencer check failures, transaction aborts, etc. TwirpErrorCode["Aborted"] = "aborted"; // OutOfRange means operation was attempted past the valid range. For example, // seeking or reading past end of a paginated collection. // // Unlike InvalidArgument, this error indicates a problem that may be fixed if // the system state changes (i.e. adding more items to the collection). // // There is a fair bit of overlap between FailedPrecondition and OutOfRange. // We recommend using OutOfRange (the more specific error) when it applies so // that callers who are iterating through a space can easily look for an // OutOfRange error to detect when they are done. TwirpErrorCode["OutOfRange"] = "out_of_range"; // Unimplemented indicates operation is not implemented or not // supported/enabled in this service. TwirpErrorCode["Unimplemented"] = "unimplemented"; // Internal errors. When some invariants expected by the underlying system // have been broken. In other words, something bad happened in the library or // backend service. Do not confuse with HTTP Internal Server Error; an // Internal error could also happen on the client code, i.e. when parsing a // server response. TwirpErrorCode["Internal"] = "internal"; // Unavailable indicates the service is currently unavailable. This is a most // likely a transient condition and may be corrected by retrying with a // backoff. TwirpErrorCode["Unavailable"] = "unavailable"; // DataLoss indicates unrecoverable data loss or corruption. TwirpErrorCode["DataLoss"] = "data_loss"; })(TwirpErrorCode = exports.TwirpErrorCode || (exports.TwirpErrorCode = {})); // ServerHTTPStatusFromErrorCode maps a Twirp error type into a similar HTTP // response status. It is used by the Twirp server handler to set the HTTP // response status code. Returns 0 if the ErrorCode is invalid. function httpStatusFromErrorCode(code) { switch (code) { case TwirpErrorCode.Canceled: return 408; // RequestTimeout case TwirpErrorCode.Unknown: return 500; // Internal Server Error case TwirpErrorCode.InvalidArgument: return 400; // BadRequest case TwirpErrorCode.Malformed: return 400; // BadRequest case TwirpErrorCode.DeadlineExceeded: return 408; // RequestTimeout case TwirpErrorCode.NotFound: return 404; // Not Found case TwirpErrorCode.BadRoute: return 404; // Not Found case TwirpErrorCode.AlreadyExists: return 409; // Conflict case TwirpErrorCode.PermissionDenied: return 403; // Forbidden case TwirpErrorCode.Unauthenticated: return 401; // Unauthorized case TwirpErrorCode.ResourceExhausted: return 429; // Too Many Requests case TwirpErrorCode.FailedPrecondition: return 412; // Precondition Failed case TwirpErrorCode.Aborted: return 409; // Conflict case TwirpErrorCode.OutOfRange: return 400; // Bad Request case TwirpErrorCode.Unimplemented: return 501; // Not Implemented case TwirpErrorCode.Internal: return 500; // Internal Server Error case TwirpErrorCode.Unavailable: return 503; // Service Unavailable case TwirpErrorCode.DataLoss: return 500; // Internal Server Error default: return 0; // Invalid! } } exports.httpStatusFromErrorCode = httpStatusFromErrorCode; // IsValidErrorCode returns true if is one of the valid predefined constants. function isValidErrorCode(code) { return httpStatusFromErrorCode(code) != 0; } exports.isValidErrorCode = isValidErrorCode; /***/ }), /***/ 56748: /***/ (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; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __rest = (this && this.__rest) || function (s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Gateway = exports.Pattern = void 0; const querystring_1 = __nccwpck_require__(63477); const dotObject = __importStar(__nccwpck_require__(13598)); const request_1 = __nccwpck_require__(8347); const errors_1 = __nccwpck_require__(66647); const http_client_1 = __nccwpck_require__(94091); const server_1 = __nccwpck_require__(26604); var Pattern; (function (Pattern) { Pattern["POST"] = "post"; Pattern["GET"] = "get"; Pattern["PATCH"] = "patch"; Pattern["PUT"] = "put"; Pattern["DELETE"] = "delete"; })(Pattern = exports.Pattern || (exports.Pattern = {})); /** * The Gateway proxies http requests to Twirp Compliant * handlers */ class Gateway { constructor(routes) { this.routes = routes; } /** * Middleware that rewrite the current request * to a Twirp compliant request */ twirpRewrite(prefix = "/twirp") { return (req, resp, next) => { this.rewrite(req, resp, prefix) .then(() => next()) .catch((e) => { if (e instanceof errors_1.TwirpError) { if (e.code !== errors_1.TwirpErrorCode.NotFound) { server_1.writeError(resp, e); } else { next(); } } }); }; } /** * Rewrite an incoming request to a Twirp compliant request * @param req * @param resp * @param prefix */ rewrite(req, resp, prefix = "/twirp") { return __awaiter(this, void 0, void 0, function* () { const [match, route] = this.matchRoute(req); const body = yield this.prepareTwirpBody(req, match, route); const twirpUrl = `${prefix}/${route.packageName}.${route.serviceName}/${route.methodName}`; req.url = twirpUrl; req.originalUrl = twirpUrl; req.method = "POST"; req.headers["content-type"] = "application/json"; req.rawBody = Buffer.from(JSON.stringify(body)); if (route.responseBodyKey) { const endFn = resp.end.bind(resp); resp.end = function (chunk) { if (resp.statusCode === 200) { endFn(`{ "${route.responseBodyKey}": ${chunk} }`); } else { endFn(chunk); } }; } }); } /** * Create a reverse proxy handler to * proxy http requests to Twirp Compliant handlers * @param httpClientOption */ reverseProxy(httpClientOption) { const client = http_client_1.NodeHttpRPC(httpClientOption); return (req, res) => __awaiter(this, void 0, void 0, function* () { try { const [match, route] = this.matchRoute(req); const body = yield this.prepareTwirpBody(req, match, route); const response = yield client.request(`${route.packageName}.${route.serviceName}`, route.methodName, "application/json", body); res.statusCode = 200; res.setHeader("content-type", "application/json"); let jsonResponse; if (route.responseBodyKey) { jsonResponse = JSON.stringify({ [route.responseBodyKey]: response }); } else { jsonResponse = JSON.stringify(response); } res.end(jsonResponse); } catch (e) { server_1.writeError(res, e); } }); } /** * Prepares twirp body requests using http.google.annotions * compliant spec * * @param req * @param match * @param route * @protected */ prepareTwirpBody(req, match, route) { return __awaiter(this, void 0, void 0, function* () { const _a = match.params, { query_string } = _a, params = __rest(_a, ["query_string"]); let requestBody = Object.assign({}, params); if (query_string && route.bodyKey !== "*") { const queryParams = this.parseQueryString(query_string); requestBody = Object.assign(Object.assign({}, queryParams), requestBody); } let body = {}; if (route.bodyKey) { const data = yield request_1.getRequestData(req); try { const jsonBody = JSON.parse(data.toString() || "{}"); if (route.bodyKey === "*") { body = jsonBody; } else { body[route.bodyKey] = jsonBody; } } catch (e) { const msg = "the json request could not be decoded"; throw new errors_1.TwirpError(errors_1.TwirpErrorCode.Malformed, msg).withCause(e, true); } } return Object.assign(Object.assign({}, body), requestBody); }); } /** * Matches a route * @param req */ matchRoute(req) { var _a; const httpMethod = (_a = req.method) === null || _a === void 0 ? void 0 : _a.toLowerCase(); if (!httpMethod) { throw new errors_1.BadRouteError(`method not allowed`, req.method || "", req.url || ""); } const routes = this.routes[httpMethod]; for (const route of routes) { const match = route.matcher(req.url || "/"); if (match) { return [match, route]; } } throw new errors_1.NotFoundError(`url ${req.url} not found`); } /** * Parse query string * @param queryString */ parseQueryString(queryString) { const queryParams = querystring_1.parse(queryString.replace("?", "")); return dotObject.object(queryParams); } } exports.Gateway = Gateway; /***/ }), /***/ 4263: /***/ (function(__unused_webpack_module, exports) { "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.isHook = exports.chainHooks = void 0; // ChainHooks creates a new ServerHook which chains the callbacks in // each of the constituent hooks passed in. Each hook function will be // called in the order of the ServerHooks values passed in. // // For the erroring hooks, RequestReceived and RequestRouted, any returned // errors prevent processing by later hooks. function chainHooks(...hooks) { if (hooks.length === 0) { return null; } if (hooks.length === 1) { return hooks[0]; } const serverHook = { requestReceived(ctx) { return __awaiter(this, void 0, void 0, function* () { for (const hook of hooks) { if (!hook.requestReceived) { continue; } yield hook.requestReceived(ctx); } }); }, requestPrepared(ctx) { return __awaiter(this, void 0, void 0, function* () { for (const hook of hooks) { if (!hook.requestPrepared) { continue; } console.warn("hook requestPrepared is deprecated and will be removed in the next release. " + "Please use responsePrepared instead."); yield hook.requestPrepared(ctx); } }); }, responsePrepared(ctx) { return __awaiter(this, void 0, void 0, function* () { for (const hook of hooks) { if (!hook.responsePrepared) { continue; } yield hook.responsePrepared(ctx); } }); }, requestSent(ctx) { return __awaiter(this, void 0, void 0, function* () { for (const hook of hooks) { if (!hook.requestSent) { continue; } console.warn("hook requestSent is deprecated and will be removed in the next release. " + "Please use responseSent instead."); yield hook.requestSent(ctx); } }); }, responseSent(ctx) { return __awaiter(this, void 0, void 0, function* () { for (const hook of hooks) { if (!hook.responseSent) { continue; } yield hook.responseSent(ctx); } }); }, requestRouted(ctx) { return __awaiter(this, void 0, void 0, function* () { for (const hook of hooks) { if (!hook.requestRouted) { continue; } yield hook.requestRouted(ctx); } }); }, error(ctx, err) { return __awaiter(this, void 0, void 0, function* () { for (const hook of hooks) { if (!hook.error) { continue; } yield hook.error(ctx, err); } }); }, }; return serverHook; } exports.chainHooks = chainHooks; function isHook(object) { return ("requestReceived" in object || "requestPrepared" in object || "requestSent" in object || "requestRouted" in object || "responsePrepared" in object || "responseSent" in object || "error" in object); } exports.isHook = isHook; /***/ }), /***/ 94091: /***/ (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; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.FetchRPC = exports.wrapErrorResponseToTwirpError = exports.NodeHttpRPC = void 0; const http = __importStar(__nccwpck_require__(13685)); const https = __importStar(__nccwpck_require__(95687)); const url_1 = __nccwpck_require__(57310); const errors_1 = __nccwpck_require__(66647); /** * a node HTTP RPC implementation * @param options * @constructor */ const NodeHttpRPC = (options) => ({ request(service, method, contentType, data) { let client; return new Promise((resolve, rejected) => { const responseChunks = []; const requestData = contentType === "application/protobuf" ? Buffer.from(data) : JSON.stringify(data); const url = new url_1.URL(options.baseUrl); const isHttps = url.protocol === "https:"; if (isHttps) { client = https; } else { client = http; } const prefix = url.pathname !== "/" ? url.pathname : ""; const req = client .request(Object.assign(Object.assign({}, (options ? options : {})), { method: "POST", protocol: url.protocol, host: url.hostname, port: url.port ? url.port : isHttps ? 443 : 80, path: `${prefix}/${service}/${method}`, headers: Object.assign(Object.assign({}, (options.headers ? options.headers : {})), { "Content-Type": contentType, "Content-Length": contentType === "application/protobuf" ? Buffer.byteLength(requestData) : Buffer.from(requestData).byteLength }) }), (res) => { res.on("data", (chunk) => responseChunks.push(chunk)); res.on("end", () => { const data = Buffer.concat(responseChunks); if (res.statusCode != 200) { rejected(wrapErrorResponseToTwirpError(data.toString())); } else { if (contentType === "application/json") { resolve(JSON.parse(data.toString())); } else { resolve(data); } } }); res.on("error", (err) => { rejected(err); }); }) .on("error", (err) => { rejected(err); }); req.end(requestData); }); }, }); exports.NodeHttpRPC = NodeHttpRPC; function wrapErrorResponseToTwirpError(errorResponse) { return errors_1.TwirpError.fromObject(JSON.parse(errorResponse)); } exports.wrapErrorResponseToTwirpError = wrapErrorResponseToTwirpError; /** * a browser fetch RPC implementation */ const FetchRPC = (options) => ({ request(service, method, contentType, data) { return __awaiter(this, void 0, void 0, function* () { const headers = new Headers(options.headers); headers.set("content-type", contentType); const response = yield fetch(`${options.baseUrl}/${service}/${method}`, Object.assign(Object.assign({}, options), { method: "POST", headers, body: data instanceof Uint8Array ? data : JSON.stringify(data) })); if (response.status === 200) { if (contentType === "application/json") { return yield response.json(); } return new Uint8Array(yield response.arrayBuffer()); } throw errors_1.TwirpError.fromObject(yield response.json()); }); }, }); exports.FetchRPC = FetchRPC; /***/ }), /***/ 66465: /***/ (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; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __exportStar = (this && this.__exportStar) || function(m, exports) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.TwirpContentType = void 0; __exportStar(__nccwpck_require__(31524), exports); __exportStar(__nccwpck_require__(26604), exports); __exportStar(__nccwpck_require__(48913), exports); __exportStar(__nccwpck_require__(4263), exports); __exportStar(__nccwpck_require__(66647), exports); __exportStar(__nccwpck_require__(56748), exports); __exportStar(__nccwpck_require__(94091), exports); var request_1 = __nccwpck_require__(8347); Object.defineProperty(exports, "TwirpContentType", ({ enumerable: true, get: function () { return request_1.TwirpContentType; } })); /***/ }), /***/ 48913: /***/ (function(__unused_webpack_module, exports) { "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.chainInterceptors = void 0; // chains multiple Interceptors into a single Interceptor. // The first interceptor wraps the second one, and so on. // Returns null if interceptors is empty. function chainInterceptors(...interceptors) { if (interceptors.length === 0) { return; } if (interceptors.length === 1) { return interceptors[0]; } const first = interceptors[0]; return (ctx, request, handler) => __awaiter(this, void 0, void 0, function* () { let next = handler; for (let i = interceptors.length - 1; i > 0; i--) { next = ((next) => (ctx, typedRequest) => { return interceptors[i](ctx, typedRequest, next); })(next); } return first(ctx, request, next); }); } exports.chainInterceptors = chainInterceptors; /***/ }), /***/ 8347: /***/ (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.parseTwirpPath = exports.getRequestData = exports.validateRequest = exports.getContentType = exports.TwirpContentType = void 0; const errors_1 = __nccwpck_require__(66647); /** * Supported Twirp Content-Type */ var TwirpContentType; (function (TwirpContentType) { TwirpContentType[TwirpContentType["Protobuf"] = 0] = "Protobuf"; TwirpContentType[TwirpContentType["JSON"] = 1] = "JSON"; TwirpContentType[TwirpContentType["Unknown"] = 2] = "Unknown"; })(TwirpContentType = exports.TwirpContentType || (exports.TwirpContentType = {})); /** * Get supported content-type * @param mimeType */ function getContentType(mimeType) { switch (mimeType) { case "application/protobuf": return TwirpContentType.Protobuf; case "application/json": return TwirpContentType.JSON; default: return TwirpContentType.Unknown; } } exports.getContentType = getContentType; /** * Validate a twirp request * @param ctx * @param request * @param pathPrefix */ function validateRequest(ctx, request, pathPrefix) { if (request.method !== "POST") { const msg = `unsupported method ${request.method} (only POST is allowed)`; throw new errors_1.BadRouteError(msg, request.method || "", request.url || ""); } const path = parseTwirpPath(request.url || ""); if (path.pkgService !== (ctx.packageName ? ctx.packageName + "." : "") + ctx.serviceName) { const msg = `no handler for path ${request.url}`; throw new errors_1.BadRouteError(msg, request.method || "", request.url || ""); } if (path.prefix !== pathPrefix) { const msg = `invalid path prefix ${path.prefix}, expected ${pathPrefix}, on path ${request.url}`; throw new errors_1.BadRouteError(msg, request.method || "", request.url || ""); } const mimeContentType = request.headers["content-type"] || ""; if (ctx.contentType === TwirpContentType.Unknown) { const msg = `unexpected Content-Type: ${request.headers["content-type"]}`; throw new errors_1.BadRouteError(msg, request.method || "", request.url || ""); } return Object.assign(Object.assign({}, path), { mimeContentType, contentType: ctx.contentType }); } exports.validateRequest = validateRequest; /** * Get request data from the body * @param req */ function getRequestData(req) { return new Promise((resolve, reject) => { const reqWithRawBody = req; if (reqWithRawBody.rawBody instanceof Buffer) { resolve(reqWithRawBody.rawBody); return; } const chunks = []; req.on("data", (chunk) => chunks.push(chunk)); req.on("end", () => __awaiter(this, void 0, void 0, function* () { const data = Buffer.concat(chunks); resolve(data); })); req.on("error", (err) => { if (req.aborted) { reject(new errors_1.TwirpError(errors_1.TwirpErrorCode.DeadlineExceeded, "failed to read request: deadline exceeded")); } else { reject(new errors_1.TwirpError(errors_1.TwirpErrorCode.Malformed, err.message).withCause(err)); } }); req.on("close", () => { reject(new errors_1.TwirpError(errors_1.TwirpErrorCode.Canceled, "failed to read request: context canceled")); }); }); } exports.getRequestData = getRequestData; /** * Parses twirp url path * @param path */ function parseTwirpPath(path) { const parts = path.split("/"); if (parts.length < 2) { return { pkgService: "", method: "", prefix: "", }; } return { method: parts[parts.length - 1], pkgService: parts[parts.length - 2], prefix: parts.slice(0, parts.length - 2).join("/"), }; } exports.parseTwirpPath = parseTwirpPath; /***/ }), /***/ 26604: /***/ (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.writeError = exports.TwirpServer = void 0; const hooks_1 = __nccwpck_require__(4263); const request_1 = __nccwpck_require__(8347); const errors_1 = __nccwpck_require__(66647); /** * Runtime server implementation of a TwirpServer */ class TwirpServer { constructor(options) { this.pathPrefix = "/twirp"; this.hooks = []; this.interceptors = []; this.packageName = options.packageName; this.serviceName = options.serviceName; this.methodList = options.methodList; this.matchRoute = options.matchRoute; this.service = options.service; } /** * Returns the prefix for this server */ get prefix() { return this.pathPrefix; } /** * The http handler for twirp complaint endpoints * @param options */ httpHandler(options) { return (req, resp) => { // setup prefix if ((options === null || options === void 0 ? void 0 : options.prefix) !== undefined) { this.withPrefix(options.prefix); } return this._httpHandler(req, resp); }; } /** * Adds interceptors or hooks to the request stack * @param middlewares */ use(...middlewares) { middlewares.forEach((middleware) => { if (hooks_1.isHook(middleware)) { this.hooks.push(middleware); return this; } this.interceptors.push(middleware); }); return this; } /** * Adds a prefix to the service url path * @param prefix */ withPrefix(prefix) { if (prefix === false) { this.pathPrefix = ""; } else { this.pathPrefix = prefix; } return this; } /** * Returns the regex matching path for this twirp server */ matchingPath() { const baseRegex = this.baseURI().replace(/\./g, "\\."); return new RegExp(`${baseRegex}\/(${this.methodList.join("|")})`); } /** * Returns the base URI for this twirp server */ baseURI() { return `${this.pathPrefix}/${this.packageName ? this.packageName + "." : ""}${this.serviceName}`; } /** * Create a twirp context * @param req * @param res * @private */ createContext(req, res) { return { packageName: this.packageName, serviceName: this.serviceName, methodName: "", contentType: request_1.getContentType(req.headers["content-type"]), req: req, res: res, }; } /** * Twrip server http handler implementation * @param req * @param resp * @private */ _httpHandler(req, resp) { return __awaiter(this, void 0, void 0, function* () { const ctx = this.createContext(req, resp); try { yield this.invokeHook("requestReceived", ctx); const { method, mimeContentType } = request_1.validateRequest(ctx, req, this.pathPrefix || ""); const handler = this.matchRoute(method, { onMatch: (ctx) => { return this.invokeHook("requestRouted", ctx); }, onNotFound: () => { const msg = `no handler for path ${req.url}`; throw new errors_1.BadRouteError(msg, req.method || "", req.url || ""); }, }); const body = yield request_1.getRequestData(req); const response = yield handler(ctx, this.service, body, this.interceptors); yield Promise.all([ this.invokeHook("responsePrepared", ctx), // keep backwards compatibility till next release this.invokeHook("requestPrepared", ctx), ]); resp.statusCode = 200; resp.setHeader("Content-Type", mimeContentType); resp.end(response); } catch (e) { yield this.invokeHook("error", ctx, mustBeTwirpError(e)); if (!resp.headersSent) { writeError(resp, e); } } finally { yield Promise.all([ this.invokeHook("responseSent", ctx), // keep backwards compatibility till next release this.invokeHook("requestSent", ctx), ]); } }); } /** * Invoke a hook * @param hookName * @param ctx * @param err * @protected */ invokeHook(hookName, ctx, err) { return __awaiter(this, void 0, void 0, function* () { if (this.hooks.length === 0) { return; } const chainedHooks = hooks_1.chainHooks(...this.hooks); const hook = chainedHooks === null || chainedHooks === void 0 ? void 0 : chainedHooks[hookName]; if (hook) { yield hook(ctx, err || new errors_1.InternalServerError("internal server error")); } }); } } exports.TwirpServer = TwirpServer; /** * Write http error response * @param res * @param error */ function writeError(res, error) { const twirpError = mustBeTwirpError(error); res.setHeader("Content-Type", "application/json"); res.statusCode = errors_1.httpStatusFromErrorCode(twirpError.code); res.end(twirpError.toJSON()); } exports.writeError = writeError; /** * Make sure that the error passed is a TwirpError * otherwise it will wrap it into an InternalError * @param err */ function mustBeTwirpError(err) { if (err instanceof errors_1.TwirpError) { return err; } return new errors_1.InternalServerErrorWith(err); } /***/ }), /***/ 41773: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const Client = __nccwpck_require__(33598) const Dispatcher = __nccwpck_require__(60412) const errors = __nccwpck_require__(48045) const Pool = __nccwpck_require__(4634) const BalancedPool = __nccwpck_require__(37931) const Agent = __nccwpck_require__(7890) const util = __nccwpck_require__(83983) const { InvalidArgumentError } = errors const api = __nccwpck_require__(44059) const buildConnector = __nccwpck_require__(82067) const MockClient = __nccwpck_require__(58687) const MockAgent = __nccwpck_require__(66771) const MockPool = __nccwpck_require__(26193) const mockErrors = __nccwpck_require__(50888) const ProxyAgent = __nccwpck_require__(97858) const RetryHandler = __nccwpck_require__(82286) const { getGlobalDispatcher, setGlobalDispatcher } = __nccwpck_require__(21892) const DecoratorHandler = __nccwpck_require__(46930) const RedirectHandler = __nccwpck_require__(72860) const createRedirectInterceptor = __nccwpck_require__(38861) let hasCrypto try { __nccwpck_require__(6113) hasCrypto = true } catch { hasCrypto = false } Object.assign(Dispatcher.prototype, api) module.exports.Dispatcher = Dispatcher module.exports.Client = Client module.exports.Pool = Pool module.exports.BalancedPool = BalancedPool module.exports.Agent = Agent module.exports.ProxyAgent = ProxyAgent module.exports.RetryHandler = RetryHandler module.exports.DecoratorHandler = DecoratorHandler module.exports.RedirectHandler = RedirectHandler module.exports.createRedirectInterceptor = createRedirectInterceptor module.exports.buildConnector = buildConnector module.exports.errors = errors function makeDispatcher (fn) { return (url, opts, handler) => { if (typeof opts === 'function') { handler = opts opts = null } if (!url || (typeof url !== 'string' && typeof url !== 'object' && !(url instanceof URL))) { throw new InvalidArgumentError('invalid url') } if (opts != null && typeof opts !== 'object') { throw new InvalidArgumentError('invalid opts') } 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) } const { agent, dispatcher = getGlobalDispatcher() } = opts if (agent) { throw new InvalidArgumentError('unsupported opts.agent. Did you mean opts.client?') } return fn.call(dispatcher, { ...opts, origin: url.origin, path: url.search ? `${url.pathname}${url.search}` : url.pathname, method: opts.method || (opts.body ? 'PUT' : 'GET') }, handler) } } module.exports.setGlobalDispatcher = setGlobalDispatcher module.exports.getGlobalDispatcher = getGlobalDispatcher if (util.nodeMajor > 16 || (util.nodeMajor === 16 && util.nodeMinor >= 8)) { let fetchImpl = null module.exports.fetch = async function fetch (resource) { if (!fetchImpl) { fetchImpl = (__nccwpck_require__(74881).fetch) } try { return await fetchImpl(...arguments) } catch (err) { if (typeof err === 'object') { Error.captureStackTrace(err, this) } throw err } } module.exports.Headers = __nccwpck_require__(10554).Headers module.exports.Response = __nccwpck_require__(27823).Response module.exports.Request = __nccwpck_require__(48359).Request module.exports.FormData = __nccwpck_require__(72015).FormData module.exports.File = __nccwpck_require__(78511).File module.exports.FileReader = __nccwpck_require__(1446).FileReader const { setGlobalOrigin, getGlobalOrigin } = __nccwpck_require__(71246) module.exports.setGlobalOrigin = setGlobalOrigin module.exports.getGlobalOrigin = getGlobalOrigin const { CacheStorage } = __nccwpck_require__(37907) const { kConstruct } = __nccwpck_require__(29174) // Cache & CacheStorage are tightly coupled with fetch. Even if it may run // in an older version of Node, it doesn't have any use without fetch. module.exports.caches = new CacheStorage(kConstruct) } if (util.nodeMajor >= 16) { const { deleteCookie, getCookies, getSetCookies, setCookie } = __nccwpck_require__(41724) module.exports.deleteCookie = deleteCookie module.exports.getCookies = getCookies module.exports.getSetCookies = getSetCookies module.exports.setCookie = setCookie const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(685) module.exports.parseMIMEType = parseMIMEType module.exports.serializeAMimeType = serializeAMimeType } if (util.nodeMajor >= 18 && hasCrypto) { const { WebSocket } = __nccwpck_require__(54284) module.exports.WebSocket = WebSocket } 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.MockPool = MockPool module.exports.MockAgent = MockAgent module.exports.mockErrors = mockErrors /***/ }), /***/ 7890: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { InvalidArgumentError } = __nccwpck_require__(48045) const { kClients, kRunning, kClose, kDestroy, kDispatch, kInterceptors } = __nccwpck_require__(72785) const DispatcherBase = __nccwpck_require__(74839) const Pool = __nccwpck_require__(4634) const Client = __nccwpck_require__(33598) const util = __nccwpck_require__(83983) const createRedirectInterceptor = __nccwpck_require__(38861) const { WeakRef, FinalizationRegistry } = __nccwpck_require__(56436)() const kOnConnect = Symbol('onConnect') const kOnDisconnect = Symbol('onDisconnect') const kOnConnectionError = Symbol('onConnectionError') const kMaxRedirections = Symbol('maxRedirections') const kOnDrain = Symbol('onDrain') const kFactory = Symbol('factory') const kFinalizer = Symbol('finalizer') const kOptions = Symbol('options') function defaultFactory (origin, opts) { return opts && opts.connections === 1 ? new Client(origin, opts) : new Pool(origin, opts) } class Agent extends DispatcherBase { constructor ({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { super() 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 (!Number.isInteger(maxRedirections) || maxRedirections < 0) { throw new InvalidArgumentError('maxRedirections must be a positive number') } if (connect && typeof connect !== 'function') { connect = { ...connect } } this[kInterceptors] = options.interceptors && options.interceptors.Agent && Array.isArray(options.interceptors.Agent) ? options.interceptors.Agent : [createRedirectInterceptor({ maxRedirections })] this[kOptions] = { ...util.deepClone(options), connect } this[kOptions].interceptors = options.interceptors ? { ...options.interceptors } : undefined this[kMaxRedirections] = maxRedirections this[kFactory] = factory this[kClients] = new Map() this[kFinalizer] = new FinalizationRegistry(/* istanbul ignore next: gc is undeterministic */ key => { const ref = this[kClients].get(key) if (ref !== undefined && ref.deref() === undefined) { this[kClients].delete(key) } }) const agent = this this[kOnDrain] = (origin, targets) => { agent.emit('drain', origin, [agent, ...targets]) } this[kOnConnect] = (origin, targets) => { agent.emit('connect', origin, [agent, ...targets]) } this[kOnDisconnect] = (origin, targets, err) => { agent.emit('disconnect', origin, [agent, ...targets], err) } this[kOnConnectionError] = (origin, targets, err) => { agent.emit('connectionError', origin, [agent, ...targets], err) } } get [kRunning] () { let ret = 0 for (const ref of this[kClients].values()) { const client = ref.deref() /* istanbul ignore next: gc is undeterministic */ if (client) { ret += client[kRunning] } } return ret } [kDispatch] (opts, handler) { let key if (opts.origin && (typeof opts.origin === 'string' || opts.origin instanceof URL)) { key = String(opts.origin) } else { throw new InvalidArgumentError('opts.origin must be a non-empty string or URL.') } const ref = this[kClients].get(key) let dispatcher = ref ? ref.deref() : null if (!dispatcher) { dispatcher = this[kFactory](opts.origin, this[kOptions]) .on('drain', this[kOnDrain]) .on('connect', this[kOnConnect]) .on('disconnect', this[kOnDisconnect]) .on('connectionError', this[kOnConnectionError]) this[kClients].set(key, new WeakRef(dispatcher)) this[kFinalizer].register(dispatcher, key) } return dispatcher.dispatch(opts, handler) } async [kClose] () { const closePromises = [] for (const ref of this[kClients].values()) { const client = ref.deref() /* istanbul ignore else: gc is undeterministic */ if (client) { closePromises.push(client.close()) } } await Promise.all(closePromises) } async [kDestroy] (err) { const destroyPromises = [] for (const ref of this[kClients].values()) { const client = ref.deref() /* istanbul ignore else: gc is undeterministic */ if (client) { destroyPromises.push(client.destroy(err)) } } await Promise.all(destroyPromises) } } module.exports = Agent /***/ }), /***/ 7032: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { addAbortListener } = __nccwpck_require__(83983) const { RequestAbortedError } = __nccwpck_require__(48045) const kListener = Symbol('kListener') const kSignal = Symbol('kSignal') function abort (self) { if (self.abort) { self.abort() } else { self.onError(new RequestAbortedError()) } } function addSignal (self, signal) { 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 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 } module.exports = { addSignal, removeSignal } /***/ }), /***/ 29744: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { AsyncResource } = __nccwpck_require__(50852) const { InvalidArgumentError, RequestAbortedError, SocketError } = __nccwpck_require__(48045) const util = __nccwpck_require__(83983) const { addSignal, removeSignal } = __nccwpck_require__(7032) class ConnectHandler extends AsyncResource { constructor (opts, callback) { if (!opts || typeof opts !== 'object') { throw new InvalidArgumentError('invalid opts') } if (typeof callback !== 'function') { throw new InvalidArgumentError('invalid callback') } 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') } super('UNDICI_CONNECT') this.opaque = opaque || null this.responseHeaders = responseHeaders || null this.callback = callback this.abort = null addSignal(this, signal) } onConnect (abort, context) { if (!this.callback) { throw new RequestAbortedError() } this.abort = abort this.context = context } onHeaders () { throw new SocketError('bad connect', null) } onUpgrade (statusCode, rawHeaders, socket) { const { callback, opaque, context } = this removeSignal(this) this.callback = null let headers = rawHeaders // Indicates is an HTTP2Session if (headers != null) { headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) } this.runInAsyncScope(callback, null, null, { statusCode, headers, socket, opaque, context }) } onError (err) { const { callback, opaque } = this removeSignal(this) if (callback) { this.callback = null queueMicrotask(() => { this.runInAsyncScope(callback, null, err, { opaque }) }) } } } 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) this.dispatch({ ...opts, method: 'CONNECT' }, connectHandler) } catch (err) { if (typeof callback !== 'function') { throw err } const opaque = opts && opts.opaque queueMicrotask(() => callback(err, { opaque })) } } module.exports = connect /***/ }), /***/ 28752: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { Readable, Duplex, PassThrough } = __nccwpck_require__(12781) const { InvalidArgumentError, InvalidReturnValueError, RequestAbortedError } = __nccwpck_require__(48045) const util = __nccwpck_require__(83983) const { AsyncResource } = __nccwpck_require__(50852) const { addSignal, removeSignal } = __nccwpck_require__(7032) const assert = __nccwpck_require__(39491) const kResume = Symbol('resume') class PipelineRequest extends Readable { constructor () { super({ autoDestroy: true }) this[kResume] = null } _read () { const { [kResume]: resume } = this if (resume) { this[kResume] = null resume() } } _destroy (err, callback) { this._read() callback(err) } } 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) } } class PipelineHandler extends AsyncResource { constructor (opts, handler) { if (!opts || typeof opts !== 'object') { throw new InvalidArgumentError('invalid opts') } if (typeof handler !== 'function') { throw new InvalidArgumentError('invalid handler') } 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') } if (method === 'CONNECT') { throw new InvalidArgumentError('invalid method') } if (onInfo && typeof onInfo !== 'function') { throw new InvalidArgumentError('invalid onInfo callback') } 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', util.nop) this.ret = new Duplex({ readableObjectMode: opts.objectMode, autoDestroy: true, read: () => { const { body } = this if (body && 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) } onConnect (abort, context) { const { ret, res } = this assert(!res, 'pipeline cannot be retried') if (ret.destroyed) { throw new RequestAbortedError() } this.abort = abort this.context = context } onHeaders (statusCode, rawHeaders, resume) { const { opaque, handler, context } = this if (statusCode < 200) { if (this.onInfo) { const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) this.onInfo({ statusCode, headers }) } return } this.res = new PipelineResponse(resume) let body try { this.handler = null const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) body = this.runInAsyncScope(handler, null, { statusCode, headers, opaque, body: this.res, context }) } catch (err) { this.res.on('error', util.nop) throw err } if (!body || typeof body.on !== 'function') { throw new InvalidReturnValueError('expected Readable') } 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 } onData (chunk) { const { res } = this return res.push(chunk) } onComplete (trailers) { const { res } = this res.push(null) } onError (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 /***/ }), /***/ 55448: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const Readable = __nccwpck_require__(73858) const { InvalidArgumentError, RequestAbortedError } = __nccwpck_require__(48045) const util = __nccwpck_require__(83983) const { getResolveErrorBodyCallback } = __nccwpck_require__(77474) const { AsyncResource } = __nccwpck_require__(50852) const { addSignal, removeSignal } = __nccwpck_require__(7032) class RequestHandler extends AsyncResource { constructor (opts, callback) { if (!opts || typeof opts !== 'object') { throw new InvalidArgumentError('invalid opts') } const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError, highWaterMark } = opts try { if (typeof callback !== 'function') { throw new InvalidArgumentError('invalid callback') } if (highWaterMark && (typeof highWaterMark !== 'number' || 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', util.nop), err) } throw err } 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.onInfo = onInfo || null this.throwOnError = throwOnError this.highWaterMark = highWaterMark if (util.isStream(body)) { body.on('error', (err) => { this.onError(err) }) } addSignal(this, signal) } onConnect (abort, context) { if (!this.callback) { throw new RequestAbortedError() } this.abort = abort this.context = context } onHeaders (statusCode, rawHeaders, resume, statusMessage) { const { callback, opaque, abort, context, responseHeaders, highWaterMark } = this const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) if (statusCode < 200) { if (this.onInfo) { this.onInfo({ statusCode, headers }) } return } const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers const contentType = parsedHeaders['content-type'] const body = new Readable({ resume, abort, contentType, highWaterMark }) this.callback = null this.res = body if (callback !== null) { if (this.throwOnError && statusCode >= 400) { this.runInAsyncScope(getResolveErrorBodyCallback, null, { callback, body, contentType, statusCode, statusMessage, headers } ) } else { this.runInAsyncScope(callback, null, null, { statusCode, headers, trailers: this.trailers, opaque, body, context }) } } } onData (chunk) { const { res } = this return res.push(chunk) } onComplete (trailers) { const { res } = this removeSignal(this) util.parseHeaders(trailers, this.trailers) res.push(null) } onError (err) { const { res, callback, body, opaque } = this removeSignal(this) if (callback) { // TODO: Does this need queueMicrotask? this.callback = null queueMicrotask(() => { this.runInAsyncScope(callback, null, err, { opaque }) }) } if (res) { this.res = null // Ensure all queued handlers are invoked before destroying res. queueMicrotask(() => { util.destroy(res, err) }) } if (body) { this.body = null util.destroy(body, err) } } } 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 { this.dispatch(opts, new RequestHandler(opts, callback)) } catch (err) { if (typeof callback !== 'function') { throw err } const opaque = opts && opts.opaque queueMicrotask(() => callback(err, { opaque })) } } module.exports = request module.exports.RequestHandler = RequestHandler /***/ }), /***/ 75395: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { finished, PassThrough } = __nccwpck_require__(12781) const { InvalidArgumentError, InvalidReturnValueError, RequestAbortedError } = __nccwpck_require__(48045) const util = __nccwpck_require__(83983) const { getResolveErrorBodyCallback } = __nccwpck_require__(77474) const { AsyncResource } = __nccwpck_require__(50852) const { addSignal, removeSignal } = __nccwpck_require__(7032) class StreamHandler extends AsyncResource { constructor (opts, factory, callback) { if (!opts || typeof opts !== 'object') { throw new InvalidArgumentError('invalid opts') } const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError } = 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', util.nop), 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.trailers = null this.body = body this.onInfo = onInfo || null this.throwOnError = throwOnError || false if (util.isStream(body)) { body.on('error', (err) => { this.onError(err) }) } addSignal(this, signal) } onConnect (abort, context) { if (!this.callback) { throw new RequestAbortedError() } this.abort = abort this.context = context } onHeaders (statusCode, rawHeaders, resume, statusMessage) { const { factory, opaque, context, callback, responseHeaders } = this const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) if (statusCode < 200) { if (this.onInfo) { this.onInfo({ statusCode, headers }) } return } this.factory = null let res if (this.throwOnError && statusCode >= 400) { const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers const contentType = parsedHeaders['content-type'] res = new PassThrough() this.callback = null this.runInAsyncScope(getResolveErrorBodyCallback, null, { callback, body: res, contentType, statusCode, statusMessage, headers } ) } else { if (factory === null) { return } res = this.runInAsyncScope(factory, null, { statusCode, headers, opaque, context }) if ( !res || typeof res.write !== 'function' || typeof res.end !== 'function' || typeof res.on !== 'function' ) { throw new InvalidReturnValueError('expected Writable') } // TODO: Avoid finished. It registers an unnecessary amount of listeners. finished(res, { readable: false }, (err) => { const { callback, res, opaque, trailers, abort } = this this.res = null if (err || !res.readable) { util.destroy(res, err) } this.callback = null this.runInAsyncScope(callback, null, err || null, { opaque, trailers }) if (err) { abort() } }) } res.on('drain', resume) this.res = res const needDrain = res.writableNeedDrain !== undefined ? res.writableNeedDrain : res._writableState && res._writableState.needDrain return needDrain !== true } onData (chunk) { const { res } = this return res ? res.write(chunk) : true } onComplete (trailers) { const { res } = this removeSignal(this) if (!res) { return } this.trailers = util.parseHeaders(trailers) res.end() } onError (err) { const { res, callback, opaque, body } = this removeSignal(this) 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 }) }) } if (body) { this.body = null util.destroy(body, err) } } } 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) }) }) } try { this.dispatch(opts, new StreamHandler(opts, factory, callback)) } catch (err) { if (typeof callback !== 'function') { throw err } const opaque = opts && opts.opaque queueMicrotask(() => callback(err, { opaque })) } } module.exports = stream /***/ }), /***/ 36923: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { InvalidArgumentError, RequestAbortedError, SocketError } = __nccwpck_require__(48045) const { AsyncResource } = __nccwpck_require__(50852) const util = __nccwpck_require__(83983) const { addSignal, removeSignal } = __nccwpck_require__(7032) const assert = __nccwpck_require__(39491) class UpgradeHandler extends AsyncResource { constructor (opts, callback) { if (!opts || typeof opts !== 'object') { throw new InvalidArgumentError('invalid opts') } if (typeof callback !== 'function') { throw new InvalidArgumentError('invalid callback') } 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') } super('UNDICI_UPGRADE') this.responseHeaders = responseHeaders || null this.opaque = opaque || null this.callback = callback this.abort = null this.context = null addSignal(this, signal) } onConnect (abort, context) { if (!this.callback) { throw new RequestAbortedError() } this.abort = abort this.context = null } onHeaders () { throw new SocketError('bad upgrade', null) } onUpgrade (statusCode, rawHeaders, socket) { const { callback, opaque, context } = this assert.strictEqual(statusCode, 101) removeSignal(this) this.callback = null const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) this.runInAsyncScope(callback, null, null, { headers, socket, opaque, context }) } onError (err) { const { callback, opaque } = this removeSignal(this) if (callback) { this.callback = null queueMicrotask(() => { this.runInAsyncScope(callback, null, err, { opaque }) }) } } } function upgrade (opts, callback) { if (callback === undefined) { return new Promise((resolve, reject) => { upgrade.call(this, opts, (err, data) => { return err ? reject(err) : resolve(data) }) }) } try { const upgradeHandler = new UpgradeHandler(opts, callback) this.dispatch({ ...opts, method: opts.method || 'GET', upgrade: opts.protocol || 'Websocket' }, upgradeHandler) } catch (err) { if (typeof callback !== 'function') { throw err } const opaque = opts && opts.opaque queueMicrotask(() => callback(err, { opaque })) } } module.exports = upgrade /***/ }), /***/ 44059: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; module.exports.request = __nccwpck_require__(55448) module.exports.stream = __nccwpck_require__(75395) module.exports.pipeline = __nccwpck_require__(28752) module.exports.upgrade = __nccwpck_require__(36923) module.exports.connect = __nccwpck_require__(29744) /***/ }), /***/ 73858: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // Ported from https://github.com/nodejs/undici/pull/907 const assert = __nccwpck_require__(39491) const { Readable } = __nccwpck_require__(12781) const { RequestAbortedError, NotSupportedError, InvalidArgumentError } = __nccwpck_require__(48045) const util = __nccwpck_require__(83983) const { ReadableStreamFrom, toUSVString } = __nccwpck_require__(83983) let Blob const kConsume = Symbol('kConsume') const kReading = Symbol('kReading') const kBody = Symbol('kBody') const kAbort = Symbol('abort') const kContentType = Symbol('kContentType') const noop = () => {} module.exports = class BodyReadable extends Readable { constructor ({ resume, abort, contentType = '', highWaterMark = 64 * 1024 // Same as nodejs fs streams. }) { super({ autoDestroy: true, read: resume, highWaterMark }) this._readableState.dataEmitted = false this[kAbort] = abort this[kConsume] = null this[kBody] = null this[kContentType] = contentType // 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(). this[kReading] = false } destroy (err) { if (this.destroyed) { // Node < 16 return this } if (!err && !this._readableState.endEmitted) { err = new RequestAbortedError() } if (err) { this[kAbort]() } return super.destroy(err) } emit (ev, ...args) { if (ev === 'data') { // Node < 16.7 this._readableState.dataEmitted = true } else if (ev === 'error') { // Node < 16 this._readableState.errorEmitted = true } return super.emit(ev, ...args) } on (ev, ...args) { if (ev === 'data' || ev === 'readable') { this[kReading] = true } return super.on(ev, ...args) } addListener (ev, ...args) { return this.on(ev, ...args) } off (ev, ...args) { const ret = super.off(ev, ...args) if (ev === 'data' || ev === 'readable') { this[kReading] = ( this.listenerCount('data') > 0 || this.listenerCount('readable') > 0 ) } return ret } removeListener (ev, ...args) { return this.off(ev, ...args) } push (chunk) { if (this[kConsume] && chunk !== null && this.readableLength === 0) { consumePush(this[kConsume], chunk) return this[kReading] ? super.push(chunk) : true } return super.push(chunk) } // https://fetch.spec.whatwg.org/#dom-body-text async text () { return consume(this, 'text') } // https://fetch.spec.whatwg.org/#dom-body-json async json () { return consume(this, 'json') } // https://fetch.spec.whatwg.org/#dom-body-blob async blob () { return consume(this, 'blob') } // https://fetch.spec.whatwg.org/#dom-body-arraybuffer async arrayBuffer () { return consume(this, 'arrayBuffer') } // https://fetch.spec.whatwg.org/#dom-body-formdata async formData () { // TODO: Implement. throw new NotSupportedError() } // https://fetch.spec.whatwg.org/#dom-body-bodyused get bodyUsed () { return util.isDisturbed(this) } // https://fetch.spec.whatwg.org/#dom-body-body get body () { if (!this[kBody]) { this[kBody] = ReadableStreamFrom(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) } } return this[kBody] } dump (opts) { let limit = opts && Number.isFinite(opts.limit) ? opts.limit : 262144 const signal = opts && opts.signal if (signal) { try { if (typeof signal !== 'object' || !('aborted' in signal)) { throw new InvalidArgumentError('signal must be an AbortSignal') } util.throwIfAborted(signal) } catch (err) { return Promise.reject(err) } } if (this.closed) { return Promise.resolve(null) } return new Promise((resolve, reject) => { const signalListenerCleanup = signal ? util.addAbortListener(signal, () => { this.destroy() }) : noop this .on('close', function () { signalListenerCleanup() if (signal && signal.aborted) { reject(signal.reason || Object.assign(new Error('The operation was aborted'), { name: 'AbortError' })) } else { resolve(null) } }) .on('error', noop) .on('data', function (chunk) { limit -= chunk.length if (limit <= 0) { this.destroy() } }) .resume() }) } } // https://streams.spec.whatwg.org/#readablestream-locked function isLocked (self) { // Consume is an implicit lock. return (self[kBody] && self[kBody].locked === true) || self[kConsume] } // https://fetch.spec.whatwg.org/#body-unusable function isUnusable (self) { return util.isDisturbed(self) || isLocked(self) } async function consume (stream, type) { if (isUnusable(stream)) { throw new TypeError('unusable') } assert(!stream[kConsume]) return new Promise((resolve, reject) => { 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()) } }) process.nextTick(consumeStart, stream[kConsume]) }) } function consumeStart (consume) { if (consume.body === null) { return } const { _readableState: state } = consume.stream for (const chunk of state.buffer) { consumePush(consume, chunk) } if (state.endEmitted) { consumeEnd(this[kConsume]) } else { consume.stream.on('end', function () { consumeEnd(this[kConsume]) }) } consume.stream.resume() while (consume.stream.read() != null) { // Loop } } function consumeEnd (consume) { const { type, body, resolve, stream, length } = consume try { if (type === 'text') { resolve(toUSVString(Buffer.concat(body))) } else if (type === 'json') { resolve(JSON.parse(Buffer.concat(body))) } else if (type === 'arrayBuffer') { const dst = new Uint8Array(length) let pos = 0 for (const buf of body) { dst.set(buf, pos) pos += buf.byteLength } resolve(dst.buffer) } else if (type === 'blob') { if (!Blob) { Blob = (__nccwpck_require__(14300).Blob) } resolve(new Blob(body, { type: stream[kContentType] })) } consumeFinish(consume) } catch (err) { stream.destroy(err) } } function consumePush (consume, chunk) { consume.length += chunk.length consume.body.push(chunk) } function consumeFinish (consume, err) { if (consume.body === null) { return } if (err) { consume.reject(err) } else { consume.resolve() } consume.type = null consume.stream = null consume.resolve = null consume.reject = null consume.length = 0 consume.body = null } /***/ }), /***/ 77474: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const assert = __nccwpck_require__(39491) const { ResponseStatusCodeError } = __nccwpck_require__(48045) const { toUSVString } = __nccwpck_require__(83983) async function getResolveErrorBodyCallback ({ callback, body, contentType, statusCode, statusMessage, headers }) { assert(body) let chunks = [] let limit = 0 for await (const chunk of body) { chunks.push(chunk) limit += chunk.length if (limit > 128 * 1024) { chunks = null break } } if (statusCode === 204 || !contentType || !chunks) { process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers)) return } try { if (contentType.startsWith('application/json')) { const payload = JSON.parse(toUSVString(Buffer.concat(chunks))) process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers, payload)) return } if (contentType.startsWith('text/')) { const payload = toUSVString(Buffer.concat(chunks)) process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers, payload)) return } } catch (err) { // Process in a fallback if error } process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers)) } module.exports = { getResolveErrorBodyCallback } /***/ }), /***/ 37931: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { BalancedPoolMissingUpstreamError, InvalidArgumentError } = __nccwpck_require__(48045) const { PoolBase, kClients, kNeedDrain, kAddClient, kRemoveClient, kGetDispatcher } = __nccwpck_require__(73198) const Pool = __nccwpck_require__(4634) const { kUrl, kInterceptors } = __nccwpck_require__(72785) const { parseOrigin } = __nccwpck_require__(83983) 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') function getGreatestCommonDivisor (a, b) { if (b === 0) return a return getGreatestCommonDivisor(b, a % b) } function defaultFactory (origin, opts) { return new Pool(origin, opts) } class BalancedPool extends PoolBase { constructor (upstreams = [], { factory = defaultFactory, ...opts } = {}) { super() this[kOptions] = opts this[kIndex] = -1 this[kCurrentWeight] = 0 this[kMaxWeightPerServer] = this[kOptions].maxWeightPerServer || 100 this[kErrorPenalty] = this[kOptions].errorPenalty || 15 if (!Array.isArray(upstreams)) { upstreams = [upstreams] } if (typeof factory !== 'function') { throw new InvalidArgumentError('factory must be a function.') } this[kInterceptors] = opts.interceptors && opts.interceptors.BalancedPool && Array.isArray(opts.interceptors.BalancedPool) ? opts.interceptors.BalancedPool : [] this[kFactory] = factory for (const upstream of upstreams) { this.addUpstream(upstream) } this._updateBalancedPoolStats() } addUpstream (upstream) { const upstreamOrigin = 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, Object.assign({}, 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 () { this[kGreatestCommonDivisor] = this[kClients].map(p => p[kWeight]).reduce(getGreatestCommonDivisor, 0) } removeUpstream (upstream) { const upstreamOrigin = 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 } 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() } const dispatcher = this[kClients].find(dispatcher => ( !dispatcher[kNeedDrain] && dispatcher.closed !== true && dispatcher.destroyed !== true )) if (!dispatcher) { return } const allClientsBusy = this[kClients].map(pool => pool[kNeedDrain]).reduce((a, b) => a && b, true) if (allClientsBusy) { return } let counter = 0 let maxWeightIndex = this[kClients].findIndex(pool => !pool[kNeedDrain]) while (counter++ < this[kClients].length) { this[kIndex] = (this[kIndex] + 1) % this[kClients].length const pool = this[kClients][this[kIndex]] // find pool index with the largest weight if (pool[kWeight] > this[kClients][maxWeightIndex][kWeight] && !pool[kNeedDrain]) { maxWeightIndex = 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] } } if (pool[kWeight] >= this[kCurrentWeight] && (!pool[kNeedDrain])) { return pool } } this[kCurrentWeight] = this[kClients][maxWeightIndex][kWeight] this[kIndex] = maxWeightIndex return this[kClients][maxWeightIndex] } } module.exports = BalancedPool /***/ }), /***/ 66101: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { kConstruct } = __nccwpck_require__(29174) const { urlEquals, fieldValues: getFieldValues } = __nccwpck_require__(82396) const { kEnumerableProperty, isDisturbed } = __nccwpck_require__(83983) const { kHeadersList } = __nccwpck_require__(72785) const { webidl } = __nccwpck_require__(21744) const { Response, cloneResponse } = __nccwpck_require__(27823) const { Request } = __nccwpck_require__(48359) const { kState, kHeaders, kGuard, kRealm } = __nccwpck_require__(15861) const { fetching } = __nccwpck_require__(74881) const { urlIsHttpHttpsScheme, createDeferredPromise, readAllBytes } = __nccwpck_require__(52538) const assert = __nccwpck_require__(39491) const { getGlobalDispatcher } = __nccwpck_require__(21892) /** * @see https://w3c.github.io/ServiceWorker/#dfn-cache-batch-operation * @typedef {Object} CacheBatchOperation * @property {'delete' | 'put'} type * @property {any} request * @property {any} response * @property {import('../../types/cache').CacheQueryOptions} options */ /** * @see https://w3c.github.io/ServiceWorker/#dfn-request-response-list * @typedef {[any, any][]} requestResponseList */ class Cache { /** * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-request-response-list * @type {requestResponseList} */ #relevantRequestResponseList constructor () { if (arguments[0] !== kConstruct) { webidl.illegalConstructor() } this.#relevantRequestResponseList = arguments[1] } async match (request, options = {}) { webidl.brandCheck(this, Cache) webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.match' }) request = webidl.converters.RequestInfo(request) options = webidl.converters.CacheQueryOptions(options) const p = await this.matchAll(request, options) if (p.length === 0) { return } return p[0] } async matchAll (request = undefined, options = {}) { webidl.brandCheck(this, Cache) if (request !== undefined) request = webidl.converters.RequestInfo(request) options = webidl.converters.CacheQueryOptions(options) // 1. let r = null // 2. if (request !== undefined) { if (request instanceof Request) { // 2.1.1 r = request[kState] // 2.1.2 if (r.method !== 'GET' && !options.ignoreMethod) { return [] } } else if (typeof request === 'string') { // 2.2.1 r = new Request(request)[kState] } } // 5. // 5.1 const responses = [] // 5.2 if (request === undefined) { // 5.2.1 for (const requestResponse of this.#relevantRequestResponseList) { responses.push(requestResponse[1]) } } else { // 5.3 // 5.3.1 const requestResponses = this.#queryCache(r, options) // 5.3.2 for (const requestResponse of requestResponses) { responses.push(requestResponse[1]) } } // 5.4 // We don't implement CORs so we don't need to loop over the responses, yay! // 5.5.1 const responseList = [] // 5.5.2 for (const response of responses) { // 5.5.2.1 const responseObject = new Response(response.body?.source ?? null) const body = responseObject[kState].body responseObject[kState] = response responseObject[kState].body = body responseObject[kHeaders][kHeadersList] = response.headersList responseObject[kHeaders][kGuard] = 'immutable' responseList.push(responseObject) } // 6. return Object.freeze(responseList) } async add (request) { webidl.brandCheck(this, Cache) webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.add' }) request = webidl.converters.RequestInfo(request) // 1. const requests = [request] // 2. const responseArrayPromise = this.addAll(requests) // 3. return await responseArrayPromise } async addAll (requests) { webidl.brandCheck(this, Cache) webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.addAll' }) requests = webidl.converters['sequence'](requests) // 1. const responsePromises = [] // 2. const requestList = [] // 3. for (const request of requests) { if (typeof request === 'string') { continue } // 3.1 const r = request[kState] // 3.2 if (!urlIsHttpHttpsScheme(r.url) || r.method !== 'GET') { throw webidl.errors.exception({ header: 'Cache.addAll', message: 'Expected http/s scheme when method is not GET.' }) } } // 4. /** @type {ReturnType[]} */ const fetchControllers = [] // 5. for (const request of requests) { // 5.1 const r = new Request(request)[kState] // 5.2 if (!urlIsHttpHttpsScheme(r.url)) { throw webidl.errors.exception({ header: 'Cache.addAll', message: 'Expected http/s scheme.' }) } // 5.4 r.initiator = 'fetch' r.destination = 'subresource' // 5.5 requestList.push(r) // 5.6 const responsePromise = createDeferredPromise() // 5.7 fetchControllers.push(fetching({ request: r, dispatcher: getGlobalDispatcher(), processResponse (response) { // 1. if (response.type === 'error' || response.status === 206 || response.status < 200 || response.status > 299) { responsePromise.reject(webidl.errors.exception({ header: 'Cache.addAll', message: 'Received an invalid status code or the request failed.' })) } else if (response.headersList.contains('vary')) { // 2. // 2.1 const fieldValues = getFieldValues(response.headersList.get('vary')) // 2.2 for (const fieldValue of fieldValues) { // 2.2.1 if (fieldValue === '*') { responsePromise.reject(webidl.errors.exception({ header: 'Cache.addAll', message: 'invalid vary field value' })) for (const controller of fetchControllers) { controller.abort() } return } } } }, processResponseEndOfBody (response) { // 1. if (response.aborted) { responsePromise.reject(new DOMException('aborted', 'AbortError')) return } // 2. responsePromise.resolve(response) } })) // 5.8 responsePromises.push(responsePromise.promise) } // 6. const p = Promise.all(responsePromises) // 7. const responses = await p // 7.1 const operations = [] // 7.2 let index = 0 // 7.3 for (const response of responses) { // 7.3.1 /** @type {CacheBatchOperation} */ const operation = { type: 'put', // 7.3.2 request: requestList[index], // 7.3.3 response // 7.3.4 } operations.push(operation) // 7.3.5 index++ // 7.3.6 } // 7.5 const cacheJobPromise = createDeferredPromise() // 7.6.1 let errorData = null // 7.6.2 try { this.#batchCacheOperations(operations) } catch (e) { errorData = e } // 7.6.3 queueMicrotask(() => { // 7.6.3.1 if (errorData === null) { cacheJobPromise.resolve(undefined) } else { // 7.6.3.2 cacheJobPromise.reject(errorData) } }) // 7.7 return cacheJobPromise.promise } async put (request, response) { webidl.brandCheck(this, Cache) webidl.argumentLengthCheck(arguments, 2, { header: 'Cache.put' }) request = webidl.converters.RequestInfo(request) response = webidl.converters.Response(response) // 1. let innerRequest = null // 2. if (request instanceof Request) { innerRequest = request[kState] } else { // 3. innerRequest = new Request(request)[kState] } // 4. if (!urlIsHttpHttpsScheme(innerRequest.url) || innerRequest.method !== 'GET') { throw webidl.errors.exception({ header: 'Cache.put', message: 'Expected an http/s scheme when method is not GET' }) } // 5. const innerResponse = response[kState] // 6. if (innerResponse.status === 206) { throw webidl.errors.exception({ header: 'Cache.put', message: 'Got 206 status' }) } // 7. if (innerResponse.headersList.contains('vary')) { // 7.1. const fieldValues = getFieldValues(innerResponse.headersList.get('vary')) // 7.2. for (const fieldValue of fieldValues) { // 7.2.1 if (fieldValue === '*') { throw webidl.errors.exception({ header: 'Cache.put', message: 'Got * vary field value' }) } } } // 8. if (innerResponse.body && (isDisturbed(innerResponse.body.stream) || innerResponse.body.stream.locked)) { throw webidl.errors.exception({ header: 'Cache.put', message: 'Response body is locked or disturbed' }) } // 9. const clonedResponse = cloneResponse(innerResponse) // 10. const bodyReadPromise = createDeferredPromise() // 11. if (innerResponse.body != null) { // 11.1 const stream = innerResponse.body.stream // 11.2 const reader = stream.getReader() // 11.3 readAllBytes(reader).then(bodyReadPromise.resolve, bodyReadPromise.reject) } else { bodyReadPromise.resolve(undefined) } // 12. /** @type {CacheBatchOperation[]} */ const operations = [] // 13. /** @type {CacheBatchOperation} */ const operation = { type: 'put', // 14. request: innerRequest, // 15. response: clonedResponse // 16. } // 17. operations.push(operation) // 19. const bytes = await bodyReadPromise.promise if (clonedResponse.body != null) { clonedResponse.body.source = bytes } // 19.1 const cacheJobPromise = createDeferredPromise() // 19.2.1 let errorData = null // 19.2.2 try { this.#batchCacheOperations(operations) } catch (e) { errorData = e } // 19.2.3 queueMicrotask(() => { // 19.2.3.1 if (errorData === null) { cacheJobPromise.resolve() } else { // 19.2.3.2 cacheJobPromise.reject(errorData) } }) return cacheJobPromise.promise } async delete (request, options = {}) { webidl.brandCheck(this, Cache) webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.delete' }) request = webidl.converters.RequestInfo(request) options = webidl.converters.CacheQueryOptions(options) /** * @type {Request} */ let r = null if (request instanceof Request) { r = request[kState] if (r.method !== 'GET' && !options.ignoreMethod) { return false } } else { assert(typeof request === 'string') r = new Request(request)[kState] } /** @type {CacheBatchOperation[]} */ const operations = [] /** @type {CacheBatchOperation} */ const operation = { type: 'delete', request: r, options } operations.push(operation) const cacheJobPromise = createDeferredPromise() let errorData = null let requestResponses try { requestResponses = this.#batchCacheOperations(operations) } catch (e) { errorData = e } queueMicrotask(() => { if (errorData === null) { cacheJobPromise.resolve(!!requestResponses?.length) } else { cacheJobPromise.reject(errorData) } }) return cacheJobPromise.promise } /** * @see https://w3c.github.io/ServiceWorker/#dom-cache-keys * @param {any} request * @param {import('../../types/cache').CacheQueryOptions} options * @returns {readonly Request[]} */ async keys (request = undefined, options = {}) { webidl.brandCheck(this, Cache) if (request !== undefined) request = webidl.converters.RequestInfo(request) options = webidl.converters.CacheQueryOptions(options) // 1. let r = null // 2. if (request !== undefined) { // 2.1 if (request instanceof Request) { // 2.1.1 r = request[kState] // 2.1.2 if (r.method !== 'GET' && !options.ignoreMethod) { return [] } } else if (typeof request === 'string') { // 2.2 r = new Request(request)[kState] } } // 4. const promise = createDeferredPromise() // 5. // 5.1 const requests = [] // 5.2 if (request === undefined) { // 5.2.1 for (const requestResponse of this.#relevantRequestResponseList) { // 5.2.1.1 requests.push(requestResponse[0]) } } else { // 5.3 // 5.3.1 const requestResponses = this.#queryCache(r, options) // 5.3.2 for (const requestResponse of requestResponses) { // 5.3.2.1 requests.push(requestResponse[0]) } } // 5.4 queueMicrotask(() => { // 5.4.1 const requestList = [] // 5.4.2 for (const request of requests) { const requestObject = new Request('https://a') requestObject[kState] = request requestObject[kHeaders][kHeadersList] = request.headersList requestObject[kHeaders][kGuard] = 'immutable' requestObject[kRealm] = request.client // 5.4.2.1 requestList.push(requestObject) } // 5.4.3 promise.resolve(Object.freeze(requestList)) }) return promise.promise } /** * @see https://w3c.github.io/ServiceWorker/#batch-cache-operations-algorithm * @param {CacheBatchOperation[]} operations * @returns {requestResponseList} */ #batchCacheOperations (operations) { // 1. const cache = this.#relevantRequestResponseList // 2. const backupCache = [...cache] // 3. const addedItems = [] // 4.1 const resultList = [] try { // 4.2 for (const operation of operations) { // 4.2.1 if (operation.type !== 'delete' && operation.type !== 'put') { throw webidl.errors.exception({ header: 'Cache.#batchCacheOperations', message: 'operation type does not match "delete" or "put"' }) } // 4.2.2 if (operation.type === 'delete' && operation.response != null) { throw webidl.errors.exception({ header: 'Cache.#batchCacheOperations', message: 'delete operation should not have an associated response' }) } // 4.2.3 if (this.#queryCache(operation.request, operation.options, addedItems).length) { throw new DOMException('???', 'InvalidStateError') } // 4.2.4 let requestResponses // 4.2.5 if (operation.type === 'delete') { // 4.2.5.1 requestResponses = this.#queryCache(operation.request, operation.options) // TODO: the spec is wrong, this is needed to pass WPTs if (requestResponses.length === 0) { return [] } // 4.2.5.2 for (const requestResponse of requestResponses) { const idx = cache.indexOf(requestResponse) assert(idx !== -1) // 4.2.5.2.1 cache.splice(idx, 1) } } else if (operation.type === 'put') { // 4.2.6 // 4.2.6.1 if (operation.response == null) { throw webidl.errors.exception({ header: 'Cache.#batchCacheOperations', message: 'put operation should have an associated response' }) } // 4.2.6.2 const r = operation.request // 4.2.6.3 if (!urlIsHttpHttpsScheme(r.url)) { throw webidl.errors.exception({ header: 'Cache.#batchCacheOperations', message: 'expected http or https scheme' }) } // 4.2.6.4 if (r.method !== 'GET') { throw webidl.errors.exception({ header: 'Cache.#batchCacheOperations', message: 'not get method' }) } // 4.2.6.5 if (operation.options != null) { throw webidl.errors.exception({ header: 'Cache.#batchCacheOperations', message: 'options must not be defined' }) } // 4.2.6.6 requestResponses = this.#queryCache(operation.request) // 4.2.6.7 for (const requestResponse of requestResponses) { const idx = cache.indexOf(requestResponse) assert(idx !== -1) // 4.2.6.7.1 cache.splice(idx, 1) } // 4.2.6.8 cache.push([operation.request, operation.response]) // 4.2.6.10 addedItems.push([operation.request, operation.response]) } // 4.2.7 resultList.push([operation.request, operation.response]) } // 4.3 return resultList } catch (e) { // 5. // 5.1 this.#relevantRequestResponseList.length = 0 // 5.2 this.#relevantRequestResponseList = backupCache // 5.3 throw e } } /** * @see https://w3c.github.io/ServiceWorker/#query-cache * @param {any} requestQuery * @param {import('../../types/cache').CacheQueryOptions} options * @param {requestResponseList} targetStorage * @returns {requestResponseList} */ #queryCache (requestQuery, options, targetStorage) { /** @type {requestResponseList} */ const resultList = [] const storage = targetStorage ?? this.#relevantRequestResponseList for (const requestResponse of storage) { const [cachedRequest, cachedResponse] = requestResponse if (this.#requestMatchesCachedItem(requestQuery, cachedRequest, cachedResponse, options)) { resultList.push(requestResponse) } } return resultList } /** * @see https://w3c.github.io/ServiceWorker/#request-matches-cached-item-algorithm * @param {any} requestQuery * @param {any} request * @param {any | null} response * @param {import('../../types/cache').CacheQueryOptions | undefined} options * @returns {boolean} */ #requestMatchesCachedItem (requestQuery, request, response = null, options) { // if (options?.ignoreMethod === false && request.method === 'GET') { // return false // } const queryURL = new URL(requestQuery.url) const cachedURL = new URL(request.url) if (options?.ignoreSearch) { cachedURL.search = '' queryURL.search = '' } if (!urlEquals(queryURL, cachedURL, true)) { return false } if ( response == null || options?.ignoreVary || !response.headersList.contains('vary') ) { return true } const fieldValues = getFieldValues(response.headersList.get('vary')) for (const fieldValue of fieldValues) { if (fieldValue === '*') { return false } const requestValue = request.headersList.get(fieldValue) const queryValue = requestQuery.headersList.get(fieldValue) // If one has the header and the other doesn't, or one has // a different value than the other, return false if (requestValue !== queryValue) { return false } } return true } } Object.defineProperties(Cache.prototype, { [Symbol.toStringTag]: { value: 'Cache', configurable: true }, match: kEnumerableProperty, matchAll: kEnumerableProperty, add: kEnumerableProperty, addAll: kEnumerableProperty, put: kEnumerableProperty, delete: kEnumerableProperty, keys: kEnumerableProperty }) const cacheQueryOptionConverters = [ { key: 'ignoreSearch', converter: webidl.converters.boolean, defaultValue: false }, { key: 'ignoreMethod', converter: webidl.converters.boolean, defaultValue: false }, { key: 'ignoreVary', converter: webidl.converters.boolean, defaultValue: false } ] webidl.converters.CacheQueryOptions = webidl.dictionaryConverter(cacheQueryOptionConverters) webidl.converters.MultiCacheQueryOptions = webidl.dictionaryConverter([ ...cacheQueryOptionConverters, { key: 'cacheName', converter: webidl.converters.DOMString } ]) webidl.converters.Response = webidl.interfaceConverter(Response) webidl.converters['sequence'] = webidl.sequenceConverter( webidl.converters.RequestInfo ) module.exports = { Cache } /***/ }), /***/ 37907: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { kConstruct } = __nccwpck_require__(29174) const { Cache } = __nccwpck_require__(66101) const { webidl } = __nccwpck_require__(21744) const { kEnumerableProperty } = __nccwpck_require__(83983) class CacheStorage { /** * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-name-to-cache-map * @type {Map} */ async has (cacheName) { webidl.brandCheck(this, CacheStorage) webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.has' }) cacheName = webidl.converters.DOMString(cacheName) // 2.1.1 // 2.2 return this.#caches.has(cacheName) } /** * @see https://w3c.github.io/ServiceWorker/#dom-cachestorage-open * @param {string} cacheName * @returns {Promise} */ async open (cacheName) { webidl.brandCheck(this, CacheStorage) webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.open' }) cacheName = webidl.converters.DOMString(cacheName) // 2.1 if (this.#caches.has(cacheName)) { // await caches.open('v1') !== await caches.open('v1') // 2.1.1 const cache = this.#caches.get(cacheName) // 2.1.1.1 return new Cache(kConstruct, cache) } // 2.2 const cache = [] // 2.3 this.#caches.set(cacheName, cache) // 2.4 return new Cache(kConstruct, cache) } /** * @see https://w3c.github.io/ServiceWorker/#cache-storage-delete * @param {string} cacheName * @returns {Promise} */ async delete (cacheName) { webidl.brandCheck(this, CacheStorage) webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.delete' }) cacheName = webidl.converters.DOMString(cacheName) return this.#caches.delete(cacheName) } /** * @see https://w3c.github.io/ServiceWorker/#cache-storage-keys * @returns {string[]} */ async keys () { webidl.brandCheck(this, CacheStorage) // 2.1 const keys = this.#caches.keys() // 2.2 return [...keys] } } Object.defineProperties(CacheStorage.prototype, { [Symbol.toStringTag]: { value: 'CacheStorage', configurable: true }, match: kEnumerableProperty, has: kEnumerableProperty, open: kEnumerableProperty, delete: kEnumerableProperty, keys: kEnumerableProperty }) module.exports = { CacheStorage } /***/ }), /***/ 29174: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; module.exports = { kConstruct: (__nccwpck_require__(72785).kConstruct) } /***/ }), /***/ 82396: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const assert = __nccwpck_require__(39491) const { URLSerializer } = __nccwpck_require__(685) const { isValidHeaderName } = __nccwpck_require__(52538) /** * @see https://url.spec.whatwg.org/#concept-url-equals * @param {URL} A * @param {URL} B * @param {boolean | undefined} excludeFragment * @returns {boolean} */ function urlEquals (A, B, excludeFragment = false) { const serializedA = URLSerializer(A, excludeFragment) const serializedB = URLSerializer(B, excludeFragment) return serializedA === serializedB } /** * @see https://github.com/chromium/chromium/blob/694d20d134cb553d8d89e5500b9148012b1ba299/content/browser/cache_storage/cache_storage_cache.cc#L260-L262 * @param {string} header */ function fieldValues (header) { assert(header !== null) const values = [] for (let value of header.split(',')) { value = value.trim() if (!value.length) { continue } else if (!isValidHeaderName(value)) { continue } values.push(value) } return values } module.exports = { urlEquals, fieldValues } /***/ }), /***/ 33598: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // @ts-check /* global WebAssembly */ const assert = __nccwpck_require__(39491) const net = __nccwpck_require__(41808) const http = __nccwpck_require__(13685) const { pipeline } = __nccwpck_require__(12781) const util = __nccwpck_require__(83983) const timers = __nccwpck_require__(29459) const Request = __nccwpck_require__(62905) const DispatcherBase = __nccwpck_require__(74839) const { RequestContentLengthMismatchError, ResponseContentLengthMismatchError, InvalidArgumentError, RequestAbortedError, HeadersTimeoutError, HeadersOverflowError, SocketError, InformationalError, BodyTimeoutError, HTTPParserError, ResponseExceededMaxSizeError, ClientDestroyedError } = __nccwpck_require__(48045) const buildConnector = __nccwpck_require__(82067) const { kUrl, kReset, kServerName, kClient, kBusy, kParser, kConnect, kBlocking, kResuming, kRunning, kPending, kSize, kWriting, kQueue, kConnected, kConnecting, kNeedDrain, kNoRef, kKeepAliveDefaultTimeout, kHostHeader, kPendingIdx, kRunningIdx, kError, kPipelining, kSocket, kKeepAliveTimeoutValue, kMaxHeadersSize, kKeepAliveMaxTimeout, kKeepAliveTimeoutThreshold, kHeadersTimeout, kBodyTimeout, kStrictContentLength, kConnector, kMaxRedirections, kMaxRequests, kCounter, kClose, kDestroy, kDispatch, kInterceptors, kLocalAddress, kMaxResponseSize, kHTTPConnVersion, // HTTP2 kHost, kHTTP2Session, kHTTP2SessionState, kHTTP2BuildRequest, kHTTP2CopyHeaders, kHTTP1BuildRequest } = __nccwpck_require__(72785) /** @type {import('http2')} */ let http2 try { http2 = __nccwpck_require__(85158) } catch { // @ts-ignore http2 = { constants: {} } } const { constants: { HTTP2_HEADER_AUTHORITY, HTTP2_HEADER_METHOD, HTTP2_HEADER_PATH, HTTP2_HEADER_SCHEME, HTTP2_HEADER_CONTENT_LENGTH, HTTP2_HEADER_EXPECT, HTTP2_HEADER_STATUS } } = http2 // Experimental let h2ExperimentalWarned = false const FastBuffer = Buffer[Symbol.species] const kClosedResolve = Symbol('kClosedResolve') const channels = {} try { const diagnosticsChannel = __nccwpck_require__(67643) channels.sendHeaders = diagnosticsChannel.channel('undici:client:sendHeaders') channels.beforeConnect = diagnosticsChannel.channel('undici:client:beforeConnect') channels.connectError = diagnosticsChannel.channel('undici:client:connectError') channels.connected = diagnosticsChannel.channel('undici:client:connected') } catch { channels.sendHeaders = { hasSubscribers: false } channels.beforeConnect = { hasSubscribers: false } channels.connectError = { hasSubscribers: false } channels.connected = { hasSubscribers: false } } /** * @type {import('../types/client').default} */ class Client extends DispatcherBase { /** * * @param {string|URL} url * @param {import('../types/client').Client.Options} options */ constructor (url, { interceptors, maxHeaderSize, headersTimeout, socketTimeout, requestTimeout, connectTimeout, bodyTimeout, idleTimeout, keepAlive, keepAliveTimeout, maxKeepAliveTimeout, keepAliveMaxTimeout, keepAliveTimeoutThreshold, socketPath, pipelining, tls, strictContentLength, maxCachedSessions, maxRedirections, connect, maxRequestsPerClient, localAddress, maxResponseSize, autoSelectFamily, autoSelectFamilyAttemptTimeout, // h2 allowH2, maxConcurrentStreams } = {}) { super() if (keepAlive !== undefined) { throw new InvalidArgumentError('unsupported keepAlive, use pipelining=0 instead') } if (socketTimeout !== undefined) { throw new InvalidArgumentError('unsupported socketTimeout, use headersTimeout & bodyTimeout instead') } if (requestTimeout !== undefined) { throw new InvalidArgumentError('unsupported requestTimeout, use headersTimeout & bodyTimeout instead') } if (idleTimeout !== undefined) { throw new InvalidArgumentError('unsupported idleTimeout, use keepAliveTimeout instead') } if (maxKeepAliveTimeout !== undefined) { throw new InvalidArgumentError('unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead') } if (maxHeaderSize != null && !Number.isFinite(maxHeaderSize)) { throw new InvalidArgumentError('invalid maxHeaderSize') } if (socketPath != null && typeof socketPath !== 'string') { throw new InvalidArgumentError('invalid socketPath') } if (connectTimeout != null && (!Number.isFinite(connectTimeout) || connectTimeout < 0)) { throw new InvalidArgumentError('invalid connectTimeout') } if (keepAliveTimeout != null && (!Number.isFinite(keepAliveTimeout) || keepAliveTimeout <= 0)) { throw new InvalidArgumentError('invalid keepAliveTimeout') } if (keepAliveMaxTimeout != null && (!Number.isFinite(keepAliveMaxTimeout) || keepAliveMaxTimeout <= 0)) { throw new InvalidArgumentError('invalid keepAliveMaxTimeout') } if (keepAliveTimeoutThreshold != null && !Number.isFinite(keepAliveTimeoutThreshold)) { throw new InvalidArgumentError('invalid keepAliveTimeoutThreshold') } if (headersTimeout != null && (!Number.isInteger(headersTimeout) || headersTimeout < 0)) { throw new InvalidArgumentError('headersTimeout must be a positive integer or zero') } if (bodyTimeout != null && (!Number.isInteger(bodyTimeout) || bodyTimeout < 0)) { throw new InvalidArgumentError('bodyTimeout must be a positive integer or zero') } if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { throw new InvalidArgumentError('connect must be a function or an object') } if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) { throw new InvalidArgumentError('maxRedirections must be a positive number') } if (maxRequestsPerClient != null && (!Number.isInteger(maxRequestsPerClient) || maxRequestsPerClient < 0)) { throw new InvalidArgumentError('maxRequestsPerClient must be a positive number') } if (localAddress != null && (typeof localAddress !== 'string' || net.isIP(localAddress) === 0)) { throw new InvalidArgumentError('localAddress must be valid string IP address') } if (maxResponseSize != null && (!Number.isInteger(maxResponseSize) || maxResponseSize < -1)) { throw new InvalidArgumentError('maxResponseSize must be a positive number') } if ( autoSelectFamilyAttemptTimeout != null && (!Number.isInteger(autoSelectFamilyAttemptTimeout) || autoSelectFamilyAttemptTimeout < -1) ) { throw new InvalidArgumentError('autoSelectFamilyAttemptTimeout must be a positive number') } // h2 if (allowH2 != null && typeof allowH2 !== 'boolean') { throw new InvalidArgumentError('allowH2 must be a valid boolean value') } if (maxConcurrentStreams != null && (typeof maxConcurrentStreams !== 'number' || maxConcurrentStreams < 1)) { throw new InvalidArgumentError('maxConcurrentStreams must be a possitive integer, greater than 0') } if (typeof connect !== 'function') { connect = buildConnector({ ...tls, maxCachedSessions, allowH2, socketPath, timeout: connectTimeout, ...(util.nodeHasAutoSelectFamily && autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined), ...connect }) } this[kInterceptors] = interceptors && interceptors.Client && Array.isArray(interceptors.Client) ? interceptors.Client : [createRedirectInterceptor({ maxRedirections })] this[kUrl] = util.parseOrigin(url) this[kConnector] = connect this[kSocket] = null this[kPipelining] = pipelining != null ? pipelining : 1 this[kMaxHeadersSize] = maxHeaderSize || http.maxHeaderSize this[kKeepAliveDefaultTimeout] = keepAliveTimeout == null ? 4e3 : keepAliveTimeout this[kKeepAliveMaxTimeout] = keepAliveMaxTimeout == null ? 600e3 : keepAliveMaxTimeout this[kKeepAliveTimeoutThreshold] = keepAliveTimeoutThreshold == null ? 1e3 : keepAliveTimeoutThreshold this[kKeepAliveTimeoutValue] = this[kKeepAliveDefaultTimeout] this[kServerName] = null this[kLocalAddress] = localAddress != null ? localAddress : null this[kResuming] = 0 // 0, idle, 1, scheduled, 2 resuming this[kNeedDrain] = 0 // 0, idle, 1, scheduled, 2 resuming this[kHostHeader] = `host: ${this[kUrl].hostname}${this[kUrl].port ? `:${this[kUrl].port}` : ''}\r\n` this[kBodyTimeout] = bodyTimeout != null ? bodyTimeout : 300e3 this[kHeadersTimeout] = headersTimeout != null ? headersTimeout : 300e3 this[kStrictContentLength] = strictContentLength == null ? true : strictContentLength this[kMaxRedirections] = maxRedirections this[kMaxRequests] = maxRequestsPerClient this[kClosedResolve] = null this[kMaxResponseSize] = maxResponseSize > -1 ? maxResponseSize : -1 this[kHTTPConnVersion] = 'h1' // HTTP/2 this[kHTTP2Session] = null this[kHTTP2SessionState] = !allowH2 ? null : { // streams: null, // Fixed queue of streams - For future support of `push` openStreams: 0, // Keep track of them to decide wether or not unref the session maxConcurrentStreams: maxConcurrentStreams != null ? maxConcurrentStreams : 100 // Max peerConcurrentStreams for a Node h2 server } this[kHost] = `${this[kUrl].hostname}${this[kUrl].port ? `:${this[kUrl].port}` : ''}` // kQueue is built up of 3 sections separated by // the kRunningIdx and kPendingIdx indices. // | complete | running | pending | // ^ kRunningIdx ^ kPendingIdx ^ kQueue.length // kRunningIdx points to the first running element. // kPendingIdx points to the first pending element. // This implements a fast queue with an amortized // time of O(1). this[kQueue] = [] this[kRunningIdx] = 0 this[kPendingIdx] = 0 } get pipelining () { return this[kPipelining] } set pipelining (value) { this[kPipelining] = value resume(this, true) } get [kPending] () { return this[kQueue].length - this[kPendingIdx] } get [kRunning] () { return this[kPendingIdx] - this[kRunningIdx] } get [kSize] () { return this[kQueue].length - this[kRunningIdx] } get [kConnected] () { return !!this[kSocket] && !this[kConnecting] && !this[kSocket].destroyed } get [kBusy] () { const socket = this[kSocket] return ( (socket && (socket[kReset] || socket[kWriting] || socket[kBlocking])) || (this[kSize] >= (this[kPipelining] || 1)) || this[kPending] > 0 ) } /* istanbul ignore: only used for test */ [kConnect] (cb) { connect(this) this.once('connect', cb) } [kDispatch] (opts, handler) { const origin = opts.origin || this[kUrl].origin const request = this[kHTTPConnVersion] === 'h2' ? Request[kHTTP2BuildRequest](origin, opts, handler) : Request[kHTTP1BuildRequest](origin, opts, handler) this[kQueue].push(request) if (this[kResuming]) { // Do nothing. } else if (util.bodyLength(request.body) == null && util.isIterable(request.body)) { // Wait a tick in case stream/iterator is ended in the same tick. this[kResuming] = 1 process.nextTick(resume, this) } else { resume(this, true) } if (this[kResuming] && this[kNeedDrain] !== 2 && this[kBusy]) { this[kNeedDrain] = 2 } return this[kNeedDrain] < 2 } async [kClose] () { // TODO: for H2 we need to gracefully flush the remaining enqueued // request and close each stream. return new Promise((resolve) => { if (!this[kSize]) { resolve(null) } else { this[kClosedResolve] = resolve } }) } async [kDestroy] (err) { return new Promise((resolve) => { const requests = this[kQueue].splice(this[kPendingIdx]) for (let i = 0; i < requests.length; i++) { const request = requests[i] errorRequest(this, request, err) } const callback = () => { if (this[kClosedResolve]) { // TODO (fix): Should we error here with ClientDestroyedError? this[kClosedResolve]() this[kClosedResolve] = null } resolve() } if (this[kHTTP2Session] != null) { util.destroy(this[kHTTP2Session], err) this[kHTTP2Session] = null this[kHTTP2SessionState] = null } if (!this[kSocket]) { queueMicrotask(callback) } else { util.destroy(this[kSocket].on('close', callback), err) } resume(this) }) } } function onHttp2SessionError (err) { assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID') this[kSocket][kError] = err onError(this[kClient], err) } function onHttp2FrameError (type, code, id) { const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`) if (id === 0) { this[kSocket][kError] = err onError(this[kClient], err) } } function onHttp2SessionEnd () { util.destroy(this, new SocketError('other side closed')) util.destroy(this[kSocket], new SocketError('other side closed')) } function onHTTP2GoAway (code) { const client = this[kClient] const err = new InformationalError(`HTTP/2: "GOAWAY" frame received with code ${code}`) client[kSocket] = null client[kHTTP2Session] = null if (client.destroyed) { assert(this[kPending] === 0) // Fail entire queue. const requests = client[kQueue].splice(client[kRunningIdx]) for (let i = 0; i < requests.length; i++) { const request = requests[i] errorRequest(this, request, err) } } else if (client[kRunning] > 0) { // Fail head of pipeline. const request = client[kQueue][client[kRunningIdx]] client[kQueue][client[kRunningIdx]++] = null errorRequest(client, request, err) } client[kPendingIdx] = client[kRunningIdx] assert(client[kRunning] === 0) client.emit('disconnect', client[kUrl], [client], err ) resume(client) } const constants = __nccwpck_require__(30953) const createRedirectInterceptor = __nccwpck_require__(38861) const EMPTY_BUF = Buffer.alloc(0) async function lazyllhttp () { const llhttpWasmData = process.env.JEST_WORKER_ID ? __nccwpck_require__(61145) : undefined let mod try { mod = await WebAssembly.compile(Buffer.from(__nccwpck_require__(95627), 'base64')) } catch (e) { /* istanbul ignore next */ // We could check if the error was caused by the simd option not // 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 = await WebAssembly.compile(Buffer.from(llhttpWasmData || __nccwpck_require__(61145), 'base64')) } return await WebAssembly.instantiate(mod, { env: { /* eslint-disable camelcase */ wasm_on_url: (p, at, len) => { /* istanbul ignore next */ return 0 }, wasm_on_status: (p, at, len) => { assert.strictEqual(currentParser.ptr, p) const start = at - currentBufferPtr + currentBufferRef.byteOffset return currentParser.onStatus(new FastBuffer(currentBufferRef.buffer, start, len)) || 0 }, wasm_on_message_begin: (p) => { assert.strictEqual(currentParser.ptr, p) return currentParser.onMessageBegin() || 0 }, wasm_on_header_field: (p, at, len) => { assert.strictEqual(currentParser.ptr, p) const start = at - currentBufferPtr + currentBufferRef.byteOffset return currentParser.onHeaderField(new FastBuffer(currentBufferRef.buffer, start, len)) || 0 }, wasm_on_header_value: (p, at, len) => { assert.strictEqual(currentParser.ptr, p) const start = at - currentBufferPtr + currentBufferRef.byteOffset return currentParser.onHeaderValue(new FastBuffer(currentBufferRef.buffer, start, len)) || 0 }, wasm_on_headers_complete: (p, statusCode, upgrade, shouldKeepAlive) => { assert.strictEqual(currentParser.ptr, p) return currentParser.onHeadersComplete(statusCode, Boolean(upgrade), Boolean(shouldKeepAlive)) || 0 }, wasm_on_body: (p, at, len) => { assert.strictEqual(currentParser.ptr, p) const start = at - currentBufferPtr + currentBufferRef.byteOffset return currentParser.onBody(new FastBuffer(currentBufferRef.buffer, start, len)) || 0 }, wasm_on_message_complete: (p) => { assert.strictEqual(currentParser.ptr, p) return currentParser.onMessageComplete() || 0 } /* eslint-enable camelcase */ } }) } let llhttpInstance = null let llhttpPromise = lazyllhttp() llhttpPromise.catch() let currentParser = null let currentBufferRef = null let currentBufferSize = 0 let currentBufferPtr = null const TIMEOUT_HEADERS = 1 const TIMEOUT_BODY = 2 const TIMEOUT_IDLE = 3 class Parser { constructor (client, socket, { exports }) { assert(Number.isFinite(client[kMaxHeadersSize]) && client[kMaxHeadersSize] > 0) this.llhttp = exports this.ptr = this.llhttp.llhttp_alloc(constants.TYPE.RESPONSE) this.client = client this.socket = socket this.timeout = null this.timeoutValue = null this.timeoutType = null this.statusCode = null this.statusText = '' this.upgrade = false this.headers = [] this.headersSize = 0 this.headersMaxSize = client[kMaxHeadersSize] this.shouldKeepAlive = false this.paused = false this.resume = this.resume.bind(this) this.bytesRead = 0 this.keepAlive = '' this.contentLength = '' this.connection = '' this.maxResponseSize = client[kMaxResponseSize] } setTimeout (value, type) { this.timeoutType = type if (value !== this.timeoutValue) { timers.clearTimeout(this.timeout) if (value) { this.timeout = timers.setTimeout(onParserTimeout, value, this) // istanbul ignore else: only for jest if (this.timeout.unref) { this.timeout.unref() } } else { this.timeout = null } this.timeoutValue = value } else if (this.timeout) { // istanbul ignore else: only for jest if (this.timeout.refresh) { this.timeout.refresh() } } } resume () { if (this.socket.destroyed || !this.paused) { return } assert(this.ptr != null) assert(currentParser == null) this.llhttp.llhttp_resume(this.ptr) assert(this.timeoutType === TIMEOUT_BODY) if (this.timeout) { // istanbul ignore else: only for jest if (this.timeout.refresh) { this.timeout.refresh() } } this.paused = false this.execute(this.socket.read() || EMPTY_BUF) // Flush parser. this.readMore() } readMore () { while (!this.paused && this.ptr) { const chunk = this.socket.read() if (chunk === null) { break } this.execute(chunk) } } execute (data) { assert(this.ptr != null) assert(currentParser == null) assert(!this.paused) const { socket, llhttp } = this if (data.length > currentBufferSize) { if (currentBufferPtr) { llhttp.free(currentBufferPtr) } currentBufferSize = Math.ceil(data.length / 4096) * 4096 currentBufferPtr = llhttp.malloc(currentBufferSize) } new Uint8Array(llhttp.memory.buffer, currentBufferPtr, currentBufferSize).set(data) // Call `execute` on the wasm parser. // We pass the `llhttp_parser` pointer address, the pointer address of buffer view data, // and finally the length of bytes to parse. // The return value is an error code or `constants.ERROR.OK`. try { let ret try { currentBufferRef = data currentParser = this ret = llhttp.llhttp_execute(this.ptr, currentBufferPtr, data.length) /* eslint-disable-next-line no-useless-catch */ } catch (err) { /* istanbul ignore next: difficult to make a test case for */ throw err } finally { currentParser = null currentBufferRef = null } const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr if (ret === constants.ERROR.PAUSED_UPGRADE) { this.onUpgrade(data.slice(offset)) } else if (ret === constants.ERROR.PAUSED) { this.paused = true socket.unshift(data.slice(offset)) } else if (ret !== constants.ERROR.OK) { const ptr = llhttp.llhttp_get_error_reason(this.ptr) let message = '' /* istanbul ignore else: difficult to make a test case for */ if (ptr) { const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0) message = 'Response does not match the HTTP/1.1 protocol (' + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ')' } throw new HTTPParserError(message, constants.ERROR[ret], data.slice(offset)) } } catch (err) { util.destroy(socket, err) } } destroy () { assert(this.ptr != null) assert(currentParser == null) this.llhttp.llhttp_free(this.ptr) this.ptr = null timers.clearTimeout(this.timeout) this.timeout = null this.timeoutValue = null this.timeoutType = null this.paused = false } onStatus (buf) { this.statusText = buf.toString() } onMessageBegin () { const { socket, client } = this /* istanbul ignore next: difficult to make a test case for */ if (socket.destroyed) { return -1 } const request = client[kQueue][client[kRunningIdx]] if (!request) { return -1 } } onHeaderField (buf) { const len = this.headers.length if ((len & 1) === 0) { this.headers.push(buf) } else { this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf]) } this.trackHeader(buf.length) } onHeaderValue (buf) { let len = this.headers.length if ((len & 1) === 1) { this.headers.push(buf) len += 1 } else { this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf]) } const key = this.headers[len - 2] if (key.length === 10 && key.toString().toLowerCase() === 'keep-alive') { this.keepAlive += buf.toString() } else if (key.length === 10 && key.toString().toLowerCase() === 'connection') { this.connection += buf.toString() } else if (key.length === 14 && key.toString().toLowerCase() === 'content-length') { this.contentLength += buf.toString() } this.trackHeader(buf.length) } trackHeader (len) { this.headersSize += len if (this.headersSize >= this.headersMaxSize) { util.destroy(this.socket, new HeadersOverflowError()) } } onUpgrade (head) { const { upgrade, client, socket, headers, statusCode } = this assert(upgrade) const request = client[kQueue][client[kRunningIdx]] assert(request) assert(!socket.destroyed) assert(socket === client[kSocket]) assert(!this.paused) assert(request.upgrade || request.method === 'CONNECT') this.statusCode = null this.statusText = '' this.shouldKeepAlive = null assert(this.headers.length % 2 === 0) this.headers = [] this.headersSize = 0 socket.unshift(head) socket[kParser].destroy() socket[kParser] = null socket[kClient] = null socket[kError] = null socket .removeListener('error', onSocketError) .removeListener('readable', onSocketReadable) .removeListener('end', onSocketEnd) .removeListener('close', onSocketClose) client[kSocket] = null client[kQueue][client[kRunningIdx]++] = null client.emit('disconnect', client[kUrl], [client], new InformationalError('upgrade')) try { request.onUpgrade(statusCode, headers, socket) } catch (err) { util.destroy(socket, err) } resume(client) } onHeadersComplete (statusCode, upgrade, shouldKeepAlive) { const { client, socket, headers, statusText } = this /* istanbul ignore next: difficult to make a test case for */ if (socket.destroyed) { return -1 } const request = client[kQueue][client[kRunningIdx]] /* istanbul ignore next: difficult to make a test case for */ if (!request) { return -1 } assert(!this.upgrade) assert(this.statusCode < 200) if (statusCode === 100) { util.destroy(socket, new SocketError('bad response', util.getSocketInfo(socket))) return -1 } /* this can only happen if server is misbehaving */ if (upgrade && !request.upgrade) { util.destroy(socket, new SocketError('bad upgrade', util.getSocketInfo(socket))) return -1 } assert.strictEqual(this.timeoutType, TIMEOUT_HEADERS) this.statusCode = statusCode this.shouldKeepAlive = ( shouldKeepAlive || // Override llhttp value which does not allow keepAlive for HEAD. (request.method === 'HEAD' && !socket[kReset] && this.connection.toLowerCase() === 'keep-alive') ) if (this.statusCode >= 200) { const bodyTimeout = request.bodyTimeout != null ? request.bodyTimeout : client[kBodyTimeout] this.setTimeout(bodyTimeout, TIMEOUT_BODY) } else if (this.timeout) { // istanbul ignore else: only for jest if (this.timeout.refresh) { this.timeout.refresh() } } if (request.method === 'CONNECT') { assert(client[kRunning] === 1) this.upgrade = true return 2 } if (upgrade) { assert(client[kRunning] === 1) this.upgrade = true return 2 } assert(this.headers.length % 2 === 0) this.headers = [] this.headersSize = 0 if (this.shouldKeepAlive && client[kPipelining]) { const keepAliveTimeout = this.keepAlive ? util.parseKeepAliveTimeout(this.keepAlive) : null if (keepAliveTimeout != null) { const timeout = Math.min( keepAliveTimeout - client[kKeepAliveTimeoutThreshold], client[kKeepAliveMaxTimeout] ) if (timeout <= 0) { socket[kReset] = true } else { client[kKeepAliveTimeoutValue] = timeout } } else { client[kKeepAliveTimeoutValue] = client[kKeepAliveDefaultTimeout] } } else { // Stop more requests from being dispatched. socket[kReset] = true } const pause = request.onHeaders(statusCode, headers, this.resume, statusText) === false if (request.aborted) { return -1 } if (request.method === 'HEAD') { return 1 } if (statusCode < 200) { return 1 } if (socket[kBlocking]) { socket[kBlocking] = false resume(client) } return pause ? constants.ERROR.PAUSED : 0 } onBody (buf) { const { client, socket, statusCode, maxResponseSize } = this if (socket.destroyed) { return -1 } const request = client[kQueue][client[kRunningIdx]] assert(request) assert.strictEqual(this.timeoutType, TIMEOUT_BODY) if (this.timeout) { // istanbul ignore else: only for jest if (this.timeout.refresh) { this.timeout.refresh() } } assert(statusCode >= 200) if (maxResponseSize > -1 && this.bytesRead + buf.length > maxResponseSize) { util.destroy(socket, new ResponseExceededMaxSizeError()) return -1 } this.bytesRead += buf.length if (request.onData(buf) === false) { return constants.ERROR.PAUSED } } onMessageComplete () { const { client, socket, statusCode, upgrade, headers, contentLength, bytesRead, shouldKeepAlive } = this if (socket.destroyed && (!statusCode || shouldKeepAlive)) { return -1 } if (upgrade) { return } const request = client[kQueue][client[kRunningIdx]] assert(request) assert(statusCode >= 100) this.statusCode = null this.statusText = '' this.bytesRead = 0 this.contentLength = '' this.keepAlive = '' this.connection = '' assert(this.headers.length % 2 === 0) this.headers = [] this.headersSize = 0 if (statusCode < 200) { return } /* istanbul ignore next: should be handled by llhttp? */ if (request.method !== 'HEAD' && contentLength && bytesRead !== parseInt(contentLength, 10)) { util.destroy(socket, new ResponseContentLengthMismatchError()) return -1 } request.onComplete(headers) client[kQueue][client[kRunningIdx]++] = null if (socket[kWriting]) { assert.strictEqual(client[kRunning], 0) // Response completed before request. util.destroy(socket, new InformationalError('reset')) return constants.ERROR.PAUSED } else if (!shouldKeepAlive) { util.destroy(socket, new InformationalError('reset')) return constants.ERROR.PAUSED } else if (socket[kReset] && client[kRunning] === 0) { // Destroy socket once all requests have completed. // The request at the tail of the pipeline is the one // that requested reset and no further requests should // have been queued since then. util.destroy(socket, new InformationalError('reset')) return constants.ERROR.PAUSED } else if (client[kPipelining] === 1) { // We must wait a full event loop cycle to reuse this socket to make sure // that non-spec compliant servers are not closing the connection even if they // said they won't. setImmediate(resume, client) } else { resume(client) } } } function onParserTimeout (parser) { const { socket, timeoutType, client } = parser /* istanbul ignore else */ if (timeoutType === TIMEOUT_HEADERS) { if (!socket[kWriting] || socket.writableNeedDrain || client[kRunning] > 1) { assert(!parser.paused, 'cannot be paused while waiting for headers') util.destroy(socket, new HeadersTimeoutError()) } } else if (timeoutType === TIMEOUT_BODY) { if (!parser.paused) { util.destroy(socket, new BodyTimeoutError()) } } else if (timeoutType === TIMEOUT_IDLE) { assert(client[kRunning] === 0 && client[kKeepAliveTimeoutValue]) util.destroy(socket, new InformationalError('socket idle timeout')) } } function onSocketReadable () { const { [kParser]: parser } = this if (parser) { parser.readMore() } } function onSocketError (err) { const { [kClient]: client, [kParser]: parser } = this assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID') if (client[kHTTPConnVersion] !== 'h2') { // On Mac OS, we get an ECONNRESET even if there is a full body to be forwarded // to the user. if (err.code === 'ECONNRESET' && parser.statusCode && !parser.shouldKeepAlive) { // We treat all incoming data so for as a valid response. parser.onMessageComplete() return } } this[kError] = err onError(this[kClient], err) } function onError (client, err) { if ( client[kRunning] === 0 && err.code !== 'UND_ERR_INFO' && err.code !== 'UND_ERR_SOCKET' ) { // Error is not caused by running request and not a recoverable // socket error. assert(client[kPendingIdx] === client[kRunningIdx]) const requests = client[kQueue].splice(client[kRunningIdx]) for (let i = 0; i < requests.length; i++) { const request = requests[i] errorRequest(client, request, err) } assert(client[kSize] === 0) } } function onSocketEnd () { const { [kParser]: parser, [kClient]: client } = this if (client[kHTTPConnVersion] !== 'h2') { if (parser.statusCode && !parser.shouldKeepAlive) { // We treat all incoming data so far as a valid response. parser.onMessageComplete() return } } util.destroy(this, new SocketError('other side closed', util.getSocketInfo(this))) } function onSocketClose () { const { [kClient]: client, [kParser]: parser } = this if (client[kHTTPConnVersion] === 'h1' && parser) { if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { // We treat all incoming data so far as a valid response. parser.onMessageComplete() } this[kParser].destroy() this[kParser] = null } const err = this[kError] || new SocketError('closed', util.getSocketInfo(this)) client[kSocket] = null if (client.destroyed) { assert(client[kPending] === 0) // Fail entire queue. const requests = client[kQueue].splice(client[kRunningIdx]) for (let i = 0; i < requests.length; i++) { const request = requests[i] errorRequest(client, request, err) } } else if (client[kRunning] > 0 && err.code !== 'UND_ERR_INFO') { // Fail head of pipeline. const request = client[kQueue][client[kRunningIdx]] client[kQueue][client[kRunningIdx]++] = null errorRequest(client, request, err) } client[kPendingIdx] = client[kRunningIdx] assert(client[kRunning] === 0) client.emit('disconnect', client[kUrl], [client], err) resume(client) } async function connect (client) { assert(!client[kConnecting]) assert(!client[kSocket]) let { host, hostname, protocol, port } = client[kUrl] // Resolve ipv6 if (hostname[0] === '[') { const idx = hostname.indexOf(']') assert(idx !== -1) const ip = hostname.substring(1, idx) assert(net.isIP(ip)) hostname = ip } client[kConnecting] = true if (channels.beforeConnect.hasSubscribers) { channels.beforeConnect.publish({ connectParams: { host, hostname, protocol, port, servername: client[kServerName], localAddress: client[kLocalAddress] }, connector: client[kConnector] }) } try { const socket = await new Promise((resolve, reject) => { client[kConnector]({ host, hostname, protocol, port, servername: client[kServerName], localAddress: client[kLocalAddress] }, (err, socket) => { if (err) { reject(err) } else { resolve(socket) } }) }) if (client.destroyed) { util.destroy(socket.on('error', () => {}), new ClientDestroyedError()) return } client[kConnecting] = false assert(socket) const isH2 = socket.alpnProtocol === 'h2' if (isH2) { if (!h2ExperimentalWarned) { h2ExperimentalWarned = true process.emitWarning('H2 support is experimental, expect them to change at any time.', { code: 'UNDICI-H2' }) } const session = http2.connect(client[kUrl], { createConnection: () => socket, peerMaxConcurrentStreams: client[kHTTP2SessionState].maxConcurrentStreams }) client[kHTTPConnVersion] = 'h2' session[kClient] = client session[kSocket] = socket session.on('error', onHttp2SessionError) session.on('frameError', onHttp2FrameError) session.on('end', onHttp2SessionEnd) session.on('goaway', onHTTP2GoAway) session.on('close', onSocketClose) session.unref() client[kHTTP2Session] = session socket[kHTTP2Session] = session } else { if (!llhttpInstance) { llhttpInstance = await llhttpPromise llhttpPromise = null } socket[kNoRef] = false socket[kWriting] = false socket[kReset] = false socket[kBlocking] = false socket[kParser] = new Parser(client, socket, llhttpInstance) } socket[kCounter] = 0 socket[kMaxRequests] = client[kMaxRequests] socket[kClient] = client socket[kError] = null socket .on('error', onSocketError) .on('readable', onSocketReadable) .on('end', onSocketEnd) .on('close', onSocketClose) client[kSocket] = socket if (channels.connected.hasSubscribers) { channels.connected.publish({ connectParams: { host, hostname, protocol, port, servername: client[kServerName], localAddress: client[kLocalAddress] }, connector: client[kConnector], socket }) } client.emit('connect', client[kUrl], [client]) } catch (err) { if (client.destroyed) { return } client[kConnecting] = false if (channels.connectError.hasSubscribers) { channels.connectError.publish({ connectParams: { host, hostname, protocol, port, servername: client[kServerName], localAddress: client[kLocalAddress] }, connector: client[kConnector], error: err }) } if (err.code === 'ERR_TLS_CERT_ALTNAME_INVALID') { assert(client[kRunning] === 0) while (client[kPending] > 0 && client[kQueue][client[kPendingIdx]].servername === client[kServerName]) { const request = client[kQueue][client[kPendingIdx]++] errorRequest(client, request, err) } } else { onError(client, err) } client.emit('connectionError', client[kUrl], [client], err) } resume(client) } function emitDrain (client) { client[kNeedDrain] = 0 client.emit('drain', client[kUrl], [client]) } function resume (client, sync) { if (client[kResuming] === 2) { return } client[kResuming] = 2 _resume(client, sync) client[kResuming] = 0 if (client[kRunningIdx] > 256) { client[kQueue].splice(0, client[kRunningIdx]) client[kPendingIdx] -= client[kRunningIdx] client[kRunningIdx] = 0 } } function _resume (client, sync) { while (true) { if (client.destroyed) { assert(client[kPending] === 0) return } if (client[kClosedResolve] && !client[kSize]) { client[kClosedResolve]() client[kClosedResolve] = null return } const socket = client[kSocket] if (socket && !socket.destroyed && socket.alpnProtocol !== 'h2') { if (client[kSize] === 0) { if (!socket[kNoRef] && socket.unref) { socket.unref() socket[kNoRef] = true } } else if (socket[kNoRef] && socket.ref) { socket.ref() socket[kNoRef] = false } if (client[kSize] === 0) { if (socket[kParser].timeoutType !== TIMEOUT_IDLE) { socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_IDLE) } } else if (client[kRunning] > 0 && socket[kParser].statusCode < 200) { if (socket[kParser].timeoutType !== TIMEOUT_HEADERS) { const request = client[kQueue][client[kRunningIdx]] const headersTimeout = request.headersTimeout != null ? request.headersTimeout : client[kHeadersTimeout] socket[kParser].setTimeout(headersTimeout, TIMEOUT_HEADERS) } } } if (client[kBusy]) { client[kNeedDrain] = 2 } else if (client[kNeedDrain] === 2) { if (sync) { client[kNeedDrain] = 1 process.nextTick(emitDrain, client) } else { emitDrain(client) } continue } if (client[kPending] === 0) { return } if (client[kRunning] >= (client[kPipelining] || 1)) { return } const request = client[kQueue][client[kPendingIdx]] if (client[kUrl].protocol === 'https:' && client[kServerName] !== request.servername) { if (client[kRunning] > 0) { return } client[kServerName] = request.servername if (socket && socket.servername !== request.servername) { util.destroy(socket, new InformationalError('servername changed')) return } } if (client[kConnecting]) { return } if (!socket && !client[kHTTP2Session]) { connect(client) return } if (socket.destroyed || socket[kWriting] || socket[kReset] || socket[kBlocking]) { return } if (client[kRunning] > 0 && !request.idempotent) { // Non-idempotent request cannot be retried. // Ensure that no other requests are inflight and // could cause failure. return } if (client[kRunning] > 0 && (request.upgrade || request.method === 'CONNECT')) { // Don't dispatch an upgrade until all preceding requests have completed. // A misbehaving server might upgrade the connection before all pipelined // request has completed. return } if (client[kRunning] > 0 && util.bodyLength(request.body) !== 0 && (util.isStream(request.body) || util.isAsyncIterable(request.body))) { // Request with stream or iterator body can error while other requests // are inflight and indirectly error those as well. // Ensure this doesn't happen by waiting for inflight // to complete before dispatching. // Request with stream or iterator body cannot be retried. // Ensure that no other requests are inflight and // could cause failure. return } if (!request.aborted && write(client, request)) { client[kPendingIdx]++ } else { client[kQueue].splice(client[kPendingIdx], 1) } } } // https://www.rfc-editor.org/rfc/rfc7230#section-3.3.2 function shouldSendContentLength (method) { return method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS' && method !== 'TRACE' && method !== 'CONNECT' } function write (client, request) { if (client[kHTTPConnVersion] === 'h2') { writeH2(client, client[kHTTP2Session], request) return } const { body, method, path, host, upgrade, headers, blocking, reset } = request // https://tools.ietf.org/html/rfc7231#section-4.3.1 // https://tools.ietf.org/html/rfc7231#section-4.3.2 // https://tools.ietf.org/html/rfc7231#section-4.3.5 // Sending a payload body on a request that does not // expect it can cause undefined behavior on some // servers and corrupt connection state. Do not // re-use the connection for further requests. const expectsPayload = ( method === 'PUT' || method === 'POST' || method === 'PATCH' ) if (body && typeof body.read === 'function') { // Try to read EOF in order to get length. body.read(0) } const bodyLength = util.bodyLength(body) let contentLength = bodyLength if (contentLength === null) { contentLength = request.contentLength } if (contentLength === 0 && !expectsPayload) { // https://tools.ietf.org/html/rfc7230#section-3.3.2 // A user agent SHOULD NOT send a Content-Length header field when // the request message does not contain a payload body and the method // semantics do not anticipate such a body. contentLength = null } // https://github.com/nodejs/undici/issues/2046 // A user agent may send a Content-Length header with 0 value, this should be allowed. if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength !== null && request.contentLength !== contentLength) { if (client[kStrictContentLength]) { errorRequest(client, request, new RequestContentLengthMismatchError()) return false } process.emitWarning(new RequestContentLengthMismatchError()) } const socket = client[kSocket] try { request.onConnect((err) => { if (request.aborted || request.completed) { return } errorRequest(client, request, err || new RequestAbortedError()) util.destroy(socket, new InformationalError('aborted')) }) } catch (err) { errorRequest(client, request, err) } if (request.aborted) { return false } if (method === 'HEAD') { // https://github.com/mcollina/undici/issues/258 // Close after a HEAD request to interop with misbehaving servers // that may send a body in the response. socket[kReset] = true } if (upgrade || method === 'CONNECT') { // On CONNECT or upgrade, block pipeline from dispatching further // requests on this connection. socket[kReset] = true } if (reset != null) { socket[kReset] = reset } if (client[kMaxRequests] && socket[kCounter]++ >= client[kMaxRequests]) { socket[kReset] = true } if (blocking) { socket[kBlocking] = true } let header = `${method} ${path} HTTP/1.1\r\n` if (typeof host === 'string') { header += `host: ${host}\r\n` } else { header += client[kHostHeader] } if (upgrade) { header += `connection: upgrade\r\nupgrade: ${upgrade}\r\n` } else if (client[kPipelining] && !socket[kReset]) { header += 'connection: keep-alive\r\n' } else { header += 'connection: close\r\n' } if (headers) { header += headers } if (channels.sendHeaders.hasSubscribers) { channels.sendHeaders.publish({ request, headers: header, socket }) } /* istanbul ignore else: assertion */ if (!body || bodyLength === 0) { if (contentLength === 0) { socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1') } else { assert(contentLength === null, 'no body must not have content length') socket.write(`${header}\r\n`, 'latin1') } request.onRequestSent() } else if (util.isBuffer(body)) { assert(contentLength === body.byteLength, 'buffer body must have content length') socket.cork() socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1') socket.write(body) socket.uncork() request.onBodySent(body) request.onRequestSent() if (!expectsPayload) { socket[kReset] = true } } else if (util.isBlobLike(body)) { if (typeof body.stream === 'function') { writeIterable({ body: body.stream(), client, request, socket, contentLength, header, expectsPayload }) } else { writeBlob({ body, client, request, socket, contentLength, header, expectsPayload }) } } else if (util.isStream(body)) { writeStream({ body, client, request, socket, contentLength, header, expectsPayload }) } else if (util.isIterable(body)) { writeIterable({ body, client, request, socket, contentLength, header, expectsPayload }) } else { assert(false) } return true } function writeH2 (client, session, request) { const { body, method, path, host, upgrade, expectContinue, signal, headers: reqHeaders } = request let headers if (typeof reqHeaders === 'string') headers = Request[kHTTP2CopyHeaders](reqHeaders.trim()) else headers = reqHeaders if (upgrade) { errorRequest(client, request, new Error('Upgrade not supported for H2')) return false } try { // TODO(HTTP/2): Should we call onConnect immediately or on stream ready event? request.onConnect((err) => { if (request.aborted || request.completed) { return } errorRequest(client, request, err || new RequestAbortedError()) }) } catch (err) { errorRequest(client, request, err) } if (request.aborted) { return false } /** @type {import('node:http2').ClientHttp2Stream} */ let stream const h2State = client[kHTTP2SessionState] headers[HTTP2_HEADER_AUTHORITY] = host || client[kHost] headers[HTTP2_HEADER_METHOD] = method if (method === 'CONNECT') { session.ref() // we are already connected, streams are pending, first request // will create a new stream. We trigger a request to create the stream and wait until // `ready` event is triggered // We disabled endStream to allow the user to write to the stream stream = session.request(headers, { endStream: false, signal }) if (stream.id && !stream.pending) { request.onUpgrade(null, null, stream) ++h2State.openStreams } else { stream.once('ready', () => { request.onUpgrade(null, null, stream) ++h2State.openStreams }) } stream.once('close', () => { h2State.openStreams -= 1 // TODO(HTTP/2): unref only if current streams count is 0 if (h2State.openStreams === 0) session.unref() }) return true } // https://tools.ietf.org/html/rfc7540#section-8.3 // :path and :scheme headers must be omited when sending CONNECT headers[HTTP2_HEADER_PATH] = path headers[HTTP2_HEADER_SCHEME] = 'https' // https://tools.ietf.org/html/rfc7231#section-4.3.1 // https://tools.ietf.org/html/rfc7231#section-4.3.2 // https://tools.ietf.org/html/rfc7231#section-4.3.5 // Sending a payload body on a request that does not // expect it can cause undefined behavior on some // servers and corrupt connection state. Do not // re-use the connection for further requests. const expectsPayload = ( method === 'PUT' || method === 'POST' || method === 'PATCH' ) if (body && typeof body.read === 'function') { // Try to read EOF in order to get length. body.read(0) } let contentLength = util.bodyLength(body) if (contentLength == null) { contentLength = request.contentLength } if (contentLength === 0 || !expectsPayload) { // https://tools.ietf.org/html/rfc7230#section-3.3.2 // A user agent SHOULD NOT send a Content-Length header field when // the request message does not contain a payload body and the method // semantics do not anticipate such a body. contentLength = null } // https://github.com/nodejs/undici/issues/2046 // A user agent may send a Content-Length header with 0 value, this should be allowed. if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength != null && request.contentLength !== contentLength) { if (client[kStrictContentLength]) { errorRequest(client, request, new RequestContentLengthMismatchError()) return false } process.emitWarning(new RequestContentLengthMismatchError()) } if (contentLength != null) { assert(body, 'no body must not have content length') headers[HTTP2_HEADER_CONTENT_LENGTH] = `${contentLength}` } session.ref() const shouldEndStream = method === 'GET' || method === 'HEAD' if (expectContinue) { headers[HTTP2_HEADER_EXPECT] = '100-continue' stream = session.request(headers, { endStream: shouldEndStream, signal }) stream.once('continue', writeBodyH2) } else { stream = session.request(headers, { endStream: shouldEndStream, signal }) writeBodyH2() } // Increment counter as we have new several streams open ++h2State.openStreams stream.once('response', headers => { const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers if (request.onHeaders(Number(statusCode), realHeaders, stream.resume.bind(stream), '') === false) { stream.pause() } }) stream.once('end', () => { request.onComplete([]) }) stream.on('data', (chunk) => { if (request.onData(chunk) === false) { stream.pause() } }) stream.once('close', () => { h2State.openStreams -= 1 // TODO(HTTP/2): unref only if current streams count is 0 if (h2State.openStreams === 0) { session.unref() } }) stream.once('error', function (err) { if (client[kHTTP2Session] && !client[kHTTP2Session].destroyed && !this.closed && !this.destroyed) { h2State.streams -= 1 util.destroy(stream, err) } }) stream.once('frameError', (type, code) => { const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`) errorRequest(client, request, err) if (client[kHTTP2Session] && !client[kHTTP2Session].destroyed && !this.closed && !this.destroyed) { h2State.streams -= 1 util.destroy(stream, err) } }) // stream.on('aborted', () => { // // TODO(HTTP/2): Support aborted // }) // stream.on('timeout', () => { // // TODO(HTTP/2): Support timeout // }) // stream.on('push', headers => { // // TODO(HTTP/2): Suppor push // }) // stream.on('trailers', headers => { // // TODO(HTTP/2): Support trailers // }) return true function writeBodyH2 () { /* istanbul ignore else: assertion */ if (!body) { request.onRequestSent() } else if (util.isBuffer(body)) { assert(contentLength === body.byteLength, 'buffer body must have content length') stream.cork() stream.write(body) stream.uncork() stream.end() request.onBodySent(body) request.onRequestSent() } else if (util.isBlobLike(body)) { if (typeof body.stream === 'function') { writeIterable({ client, request, contentLength, h2stream: stream, expectsPayload, body: body.stream(), socket: client[kSocket], header: '' }) } else { writeBlob({ body, client, request, contentLength, expectsPayload, h2stream: stream, header: '', socket: client[kSocket] }) } } else if (util.isStream(body)) { writeStream({ body, client, request, contentLength, expectsPayload, socket: client[kSocket], h2stream: stream, header: '' }) } else if (util.isIterable(body)) { writeIterable({ body, client, request, contentLength, expectsPayload, header: '', h2stream: stream, socket: client[kSocket] }) } else { assert(false) } } } function writeStream ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) { assert(contentLength !== 0 || client[kRunning] === 0, 'stream body cannot be pipelined') if (client[kHTTPConnVersion] === 'h2') { // For HTTP/2, is enough to pipe the stream const pipe = pipeline( body, h2stream, (err) => { if (err) { util.destroy(body, err) util.destroy(h2stream, err) } else { request.onRequestSent() } } ) pipe.on('data', onPipeData) pipe.once('end', () => { pipe.removeListener('data', onPipeData) util.destroy(pipe) }) function onPipeData (chunk) { request.onBodySent(chunk) } return } let finished = false const writer = new AsyncWriter({ socket, request, contentLength, client, expectsPayload, header }) const onData = function (chunk) { if (finished) { return } try { if (!writer.write(chunk) && this.pause) { this.pause() } } catch (err) { util.destroy(this, err) } } const onDrain = function () { if (finished) { return } if (body.resume) { body.resume() } } const onAbort = function () { if (finished) { return } const err = new RequestAbortedError() queueMicrotask(() => onFinished(err)) } const onFinished = function (err) { if (finished) { return } finished = true assert(socket.destroyed || (socket[kWriting] && client[kRunning] <= 1)) socket .off('drain', onDrain) .off('error', onFinished) body .removeListener('data', onData) .removeListener('end', onFinished) .removeListener('error', onFinished) .removeListener('close', onAbort) if (!err) { try { writer.end() } catch (er) { err = er } } writer.destroy(err) if (err && (err.code !== 'UND_ERR_INFO' || err.message !== 'reset')) { util.destroy(body, err) } else { util.destroy(body) } } body .on('data', onData) .on('end', onFinished) .on('error', onFinished) .on('close', onAbort) if (body.resume) { body.resume() } socket .on('drain', onDrain) .on('error', onFinished) } async function writeBlob ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) { assert(contentLength === body.size, 'blob body must have content length') const isH2 = client[kHTTPConnVersion] === 'h2' try { if (contentLength != null && contentLength !== body.size) { throw new RequestContentLengthMismatchError() } const buffer = Buffer.from(await body.arrayBuffer()) if (isH2) { h2stream.cork() h2stream.write(buffer) h2stream.uncork() } else { socket.cork() socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1') socket.write(buffer) socket.uncork() } request.onBodySent(buffer) request.onRequestSent() if (!expectsPayload) { socket[kReset] = true } resume(client) } catch (err) { util.destroy(isH2 ? h2stream : socket, err) } } async function writeIterable ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) { assert(contentLength !== 0 || client[kRunning] === 0, 'iterator body cannot be pipelined') let callback = null function onDrain () { if (callback) { const cb = callback callback = null cb() } } const waitForDrain = () => new Promise((resolve, reject) => { assert(callback === null) if (socket[kError]) { reject(socket[kError]) } else { callback = resolve } }) if (client[kHTTPConnVersion] === 'h2') { h2stream .on('close', onDrain) .on('drain', onDrain) try { // It's up to the user to somehow abort the async iterable. for await (const chunk of body) { if (socket[kError]) { throw socket[kError] } const res = h2stream.write(chunk) request.onBodySent(chunk) if (!res) { await waitForDrain() } } } catch (err) { h2stream.destroy(err) } finally { request.onRequestSent() h2stream.end() h2stream .off('close', onDrain) .off('drain', onDrain) } return } socket .on('close', onDrain) .on('drain', onDrain) const writer = new AsyncWriter({ socket, request, contentLength, client, expectsPayload, header }) try { // It's up to the user to somehow abort the async iterable. for await (const chunk of body) { if (socket[kError]) { throw socket[kError] } if (!writer.write(chunk)) { await waitForDrain() } } writer.end() } catch (err) { writer.destroy(err) } finally { socket .off('close', onDrain) .off('drain', onDrain) } } class AsyncWriter { constructor ({ socket, request, contentLength, client, expectsPayload, header }) { this.socket = socket this.request = request this.contentLength = contentLength this.client = client this.bytesWritten = 0 this.expectsPayload = expectsPayload this.header = header socket[kWriting] = true } write (chunk) { const { socket, request, contentLength, client, bytesWritten, expectsPayload, header } = this if (socket[kError]) { throw socket[kError] } if (socket.destroyed) { return false } const len = Buffer.byteLength(chunk) if (!len) { return true } // We should defer writing chunks. if (contentLength !== null && bytesWritten + len > contentLength) { if (client[kStrictContentLength]) { throw new RequestContentLengthMismatchError() } process.emitWarning(new RequestContentLengthMismatchError()) } socket.cork() if (bytesWritten === 0) { if (!expectsPayload) { socket[kReset] = true } if (contentLength === null) { socket.write(`${header}transfer-encoding: chunked\r\n`, 'latin1') } else { socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1') } } if (contentLength === null) { socket.write(`\r\n${len.toString(16)}\r\n`, 'latin1') } this.bytesWritten += len const ret = socket.write(chunk) socket.uncork() request.onBodySent(chunk) if (!ret) { if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) { // istanbul ignore else: only for jest if (socket[kParser].timeout.refresh) { socket[kParser].timeout.refresh() } } } return ret } end () { const { socket, contentLength, client, bytesWritten, expectsPayload, header, request } = this request.onRequestSent() socket[kWriting] = false if (socket[kError]) { throw socket[kError] } if (socket.destroyed) { return } if (bytesWritten === 0) { if (expectsPayload) { // https://tools.ietf.org/html/rfc7230#section-3.3.2 // A user agent SHOULD send a Content-Length in a request message when // no Transfer-Encoding is sent and the request method defines a meaning // for an enclosed payload body. socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1') } else { socket.write(`${header}\r\n`, 'latin1') } } else if (contentLength === null) { socket.write('\r\n0\r\n\r\n', 'latin1') } if (contentLength !== null && bytesWritten !== contentLength) { if (client[kStrictContentLength]) { throw new RequestContentLengthMismatchError() } else { process.emitWarning(new RequestContentLengthMismatchError()) } } if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) { // istanbul ignore else: only for jest if (socket[kParser].timeout.refresh) { socket[kParser].timeout.refresh() } } resume(client) } destroy (err) { const { socket, client } = this socket[kWriting] = false if (err) { assert(client[kRunning] <= 1, 'pipeline should only contain this request') util.destroy(socket, err) } } } function errorRequest (client, request, err) { try { request.onError(err) assert(request.aborted) } catch (err) { client.emit('error', err) } } module.exports = Client /***/ }), /***/ 56436: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /* istanbul ignore file: only for Node 12 */ const { kConnected, kSize } = __nccwpck_require__(72785) class CompatWeakRef { constructor (value) { this.value = value } deref () { return this.value[kConnected] === 0 && this.value[kSize] === 0 ? undefined : this.value } } class CompatFinalizer { constructor (finalizer) { this.finalizer = finalizer } register (dispatcher, key) { if (dispatcher.on) { dispatcher.on('disconnect', () => { if (dispatcher[kConnected] === 0 && dispatcher[kSize] === 0) { this.finalizer(key) } }) } } } module.exports = function () { // FIXME: remove workaround when the Node bug is fixed // https://github.com/nodejs/node/issues/49344#issuecomment-1741776308 if (process.env.NODE_V8_COVERAGE) { return { WeakRef: CompatWeakRef, FinalizationRegistry: CompatFinalizer } } return { WeakRef: global.WeakRef || CompatWeakRef, FinalizationRegistry: global.FinalizationRegistry || CompatFinalizer } } /***/ }), /***/ 20663: /***/ ((module) => { "use strict"; // https://wicg.github.io/cookie-store/#cookie-maximum-attribute-value-size const maxAttributeValueSize = 1024 // https://wicg.github.io/cookie-store/#cookie-maximum-name-value-pair-size const maxNameValuePairSize = 4096 module.exports = { maxAttributeValueSize, maxNameValuePairSize } /***/ }), /***/ 41724: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { parseSetCookie } = __nccwpck_require__(24408) const { stringify, getHeadersList } = __nccwpck_require__(43121) const { webidl } = __nccwpck_require__(21744) const { Headers } = __nccwpck_require__(10554) /** * @typedef {Object} Cookie * @property {string} name * @property {string} value * @property {Date|number|undefined} expires * @property {number|undefined} maxAge * @property {string|undefined} domain * @property {string|undefined} path * @property {boolean|undefined} secure * @property {boolean|undefined} httpOnly * @property {'Strict'|'Lax'|'None'} sameSite * @property {string[]} unparsed */ /** * @param {Headers} headers * @returns {Record} */ function getCookies (headers) { webidl.argumentLengthCheck(arguments, 1, { header: 'getCookies' }) webidl.brandCheck(headers, Headers, { strict: false }) const cookie = headers.get('cookie') const out = {} if (!cookie) { return out } for (const piece of cookie.split(';')) { const [name, ...value] = piece.split('=') out[name.trim()] = value.join('=') } return out } /** * @param {Headers} headers * @param {string} name * @param {{ path?: string, domain?: string }|undefined} attributes * @returns {void} */ function deleteCookie (headers, name, attributes) { webidl.argumentLengthCheck(arguments, 2, { header: 'deleteCookie' }) webidl.brandCheck(headers, Headers, { strict: false }) name = webidl.converters.DOMString(name) attributes = webidl.converters.DeleteCookieAttributes(attributes) // Matches behavior of // https://github.com/denoland/deno_std/blob/63827b16330b82489a04614027c33b7904e08be5/http/cookie.ts#L278 setCookie(headers, { name, value: '', expires: new Date(0), ...attributes }) } /** * @param {Headers} headers * @returns {Cookie[]} */ function getSetCookies (headers) { webidl.argumentLengthCheck(arguments, 1, { header: 'getSetCookies' }) webidl.brandCheck(headers, Headers, { strict: false }) const cookies = getHeadersList(headers).cookies if (!cookies) { return [] } // In older versions of undici, cookies is a list of name:value. return cookies.map((pair) => parseSetCookie(Array.isArray(pair) ? pair[1] : pair)) } /** * @param {Headers} headers * @param {Cookie} cookie * @returns {void} */ function setCookie (headers, cookie) { webidl.argumentLengthCheck(arguments, 2, { header: 'setCookie' }) webidl.brandCheck(headers, Headers, { strict: false }) cookie = webidl.converters.Cookie(cookie) const str = stringify(cookie) if (str) { headers.append('Set-Cookie', stringify(cookie)) } } webidl.converters.DeleteCookieAttributes = webidl.dictionaryConverter([ { converter: webidl.nullableConverter(webidl.converters.DOMString), key: 'path', defaultValue: null }, { converter: webidl.nullableConverter(webidl.converters.DOMString), key: 'domain', defaultValue: null } ]) webidl.converters.Cookie = webidl.dictionaryConverter([ { converter: webidl.converters.DOMString, key: 'name' }, { converter: webidl.converters.DOMString, key: 'value' }, { converter: webidl.nullableConverter((value) => { if (typeof value === 'number') { return webidl.converters['unsigned long long'](value) } return new Date(value) }), key: 'expires', defaultValue: null }, { converter: webidl.nullableConverter(webidl.converters['long long']), key: 'maxAge', defaultValue: null }, { converter: webidl.nullableConverter(webidl.converters.DOMString), key: 'domain', defaultValue: null }, { converter: webidl.nullableConverter(webidl.converters.DOMString), key: 'path', defaultValue: null }, { converter: webidl.nullableConverter(webidl.converters.boolean), key: 'secure', defaultValue: null }, { converter: webidl.nullableConverter(webidl.converters.boolean), key: 'httpOnly', defaultValue: null }, { converter: webidl.converters.USVString, key: 'sameSite', allowedValues: ['Strict', 'Lax', 'None'] }, { converter: webidl.sequenceConverter(webidl.converters.DOMString), key: 'unparsed', defaultValue: [] } ]) module.exports = { getCookies, deleteCookie, getSetCookies, setCookie } /***/ }), /***/ 24408: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { maxNameValuePairSize, maxAttributeValueSize } = __nccwpck_require__(20663) const { isCTLExcludingHtab } = __nccwpck_require__(43121) const { collectASequenceOfCodePointsFast } = __nccwpck_require__(685) const assert = __nccwpck_require__(39491) /** * @description Parses the field-value attributes of a set-cookie header string. * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4 * @param {string} header * @returns if the header is invalid, null will be returned */ function parseSetCookie (header) { // 1. If the set-cookie-string contains a %x00-08 / %x0A-1F / %x7F // character (CTL characters excluding HTAB): Abort these steps and // ignore the set-cookie-string entirely. if (isCTLExcludingHtab(header)) { return null } let nameValuePair = '' let unparsedAttributes = '' let name = '' let value = '' // 2. If the set-cookie-string contains a %x3B (";") character: if (header.includes(';')) { // 1. The name-value-pair string consists of the characters up to, // but not including, the first %x3B (";"), and the unparsed- // attributes consist of the remainder of the set-cookie-string // (including the %x3B (";") in question). const position = { position: 0 } nameValuePair = collectASequenceOfCodePointsFast(';', header, position) unparsedAttributes = header.slice(position.position) } else { // Otherwise: // 1. The name-value-pair string consists of all the characters // contained in the set-cookie-string, and the unparsed- // attributes is the empty string. nameValuePair = header } // 3. If the name-value-pair string lacks a %x3D ("=") character, then // the name string is empty, and the value string is the value of // name-value-pair. if (!nameValuePair.includes('=')) { value = nameValuePair } else { // Otherwise, the name string consists of the characters up to, but // not including, the first %x3D ("=") character, and the (possibly // empty) value string consists of the characters after the first // %x3D ("=") character. const position = { position: 0 } name = collectASequenceOfCodePointsFast( '=', nameValuePair, position ) value = nameValuePair.slice(position.position + 1) } // 4. Remove any leading or trailing WSP characters from the name // string and the value string. name = name.trim() value = value.trim() // 5. If the sum of the lengths of the name string and the value string // is more than 4096 octets, abort these steps and ignore the set- // cookie-string entirely. if (name.length + value.length > maxNameValuePairSize) { return null } // 6. The cookie-name is the name string, and the cookie-value is the // value string. return { name, value, ...parseUnparsedAttributes(unparsedAttributes) } } /** * Parses the remaining attributes of a set-cookie header * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4 * @param {string} unparsedAttributes * @param {[Object.]={}} cookieAttributeList */ function parseUnparsedAttributes (unparsedAttributes, cookieAttributeList = {}) { // 1. If the unparsed-attributes string is empty, skip the rest of // these steps. if (unparsedAttributes.length === 0) { return cookieAttributeList } // 2. Discard the first character of the unparsed-attributes (which // will be a %x3B (";") character). assert(unparsedAttributes[0] === ';') unparsedAttributes = unparsedAttributes.slice(1) let cookieAv = '' // 3. If the remaining unparsed-attributes contains a %x3B (";") // character: if (unparsedAttributes.includes(';')) { // 1. Consume the characters of the unparsed-attributes up to, but // not including, the first %x3B (";") character. cookieAv = collectASequenceOfCodePointsFast( ';', unparsedAttributes, { position: 0 } ) unparsedAttributes = unparsedAttributes.slice(cookieAv.length) } else { // Otherwise: // 1. Consume the remainder of the unparsed-attributes. cookieAv = unparsedAttributes unparsedAttributes = '' } // Let the cookie-av string be the characters consumed in this step. let attributeName = '' let attributeValue = '' // 4. If the cookie-av string contains a %x3D ("=") character: if (cookieAv.includes('=')) { // 1. The (possibly empty) attribute-name string consists of the // characters up to, but not including, the first %x3D ("=") // character, and the (possibly empty) attribute-value string // consists of the characters after the first %x3D ("=") // character. const position = { position: 0 } attributeName = collectASequenceOfCodePointsFast( '=', cookieAv, position ) attributeValue = cookieAv.slice(position.position + 1) } else { // Otherwise: // 1. The attribute-name string consists of the entire cookie-av // string, and the attribute-value string is empty. attributeName = cookieAv } // 5. Remove any leading or trailing WSP characters from the attribute- // name string and the attribute-value string. attributeName = attributeName.trim() attributeValue = attributeValue.trim() // 6. If the attribute-value is longer than 1024 octets, ignore the // cookie-av string and return to Step 1 of this algorithm. if (attributeValue.length > maxAttributeValueSize) { return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) } // 7. Process the attribute-name and attribute-value according to the // requirements in the following subsections. (Notice that // attributes with unrecognized attribute-names are ignored.) const attributeNameLowercase = attributeName.toLowerCase() // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.1 // If the attribute-name case-insensitively matches the string // "Expires", the user agent MUST process the cookie-av as follows. if (attributeNameLowercase === 'expires') { // 1. Let the expiry-time be the result of parsing the attribute-value // as cookie-date (see Section 5.1.1). const expiryTime = new Date(attributeValue) // 2. If the attribute-value failed to parse as a cookie date, ignore // the cookie-av. cookieAttributeList.expires = expiryTime } else if (attributeNameLowercase === 'max-age') { // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.2 // If the attribute-name case-insensitively matches the string "Max- // Age", the user agent MUST process the cookie-av as follows. // 1. If the first character of the attribute-value is not a DIGIT or a // "-" character, ignore the cookie-av. const charCode = attributeValue.charCodeAt(0) if ((charCode < 48 || charCode > 57) && attributeValue[0] !== '-') { return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) } // 2. If the remainder of attribute-value contains a non-DIGIT // character, ignore the cookie-av. if (!/^\d+$/.test(attributeValue)) { return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) } // 3. Let delta-seconds be the attribute-value converted to an integer. const deltaSeconds = Number(attributeValue) // 4. Let cookie-age-limit be the maximum age of the cookie (which // SHOULD be 400 days or less, see Section 4.1.2.2). // 5. Set delta-seconds to the smaller of its present value and cookie- // age-limit. // deltaSeconds = Math.min(deltaSeconds * 1000, maxExpiresMs) // 6. If delta-seconds is less than or equal to zero (0), let expiry- // time be the earliest representable date and time. Otherwise, let // the expiry-time be the current date and time plus delta-seconds // seconds. // const expiryTime = deltaSeconds <= 0 ? Date.now() : Date.now() + deltaSeconds // 7. Append an attribute to the cookie-attribute-list with an // attribute-name of Max-Age and an attribute-value of expiry-time. cookieAttributeList.maxAge = deltaSeconds } else if (attributeNameLowercase === 'domain') { // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.3 // If the attribute-name case-insensitively matches the string "Domain", // the user agent MUST process the cookie-av as follows. // 1. Let cookie-domain be the attribute-value. let cookieDomain = attributeValue // 2. If cookie-domain starts with %x2E ("."), let cookie-domain be // cookie-domain without its leading %x2E ("."). if (cookieDomain[0] === '.') { cookieDomain = cookieDomain.slice(1) } // 3. Convert the cookie-domain to lower case. cookieDomain = cookieDomain.toLowerCase() // 4. Append an attribute to the cookie-attribute-list with an // attribute-name of Domain and an attribute-value of cookie-domain. cookieAttributeList.domain = cookieDomain } else if (attributeNameLowercase === 'path') { // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.4 // If the attribute-name case-insensitively matches the string "Path", // the user agent MUST process the cookie-av as follows. // 1. If the attribute-value is empty or if the first character of the // attribute-value is not %x2F ("/"): let cookiePath = '' if (attributeValue.length === 0 || attributeValue[0] !== '/') { // 1. Let cookie-path be the default-path. cookiePath = '/' } else { // Otherwise: // 1. Let cookie-path be the attribute-value. cookiePath = attributeValue } // 2. Append an attribute to the cookie-attribute-list with an // attribute-name of Path and an attribute-value of cookie-path. cookieAttributeList.path = cookiePath } else if (attributeNameLowercase === 'secure') { // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.5 // If the attribute-name case-insensitively matches the string "Secure", // the user agent MUST append an attribute to the cookie-attribute-list // with an attribute-name of Secure and an empty attribute-value. cookieAttributeList.secure = true } else if (attributeNameLowercase === 'httponly') { // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.6 // If the attribute-name case-insensitively matches the string // "HttpOnly", the user agent MUST append an attribute to the cookie- // attribute-list with an attribute-name of HttpOnly and an empty // attribute-value. cookieAttributeList.httpOnly = true } else if (attributeNameLowercase === 'samesite') { // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.7 // If the attribute-name case-insensitively matches the string // "SameSite", the user agent MUST process the cookie-av as follows: // 1. Let enforcement be "Default". let enforcement = 'Default' const attributeValueLowercase = attributeValue.toLowerCase() // 2. If cookie-av's attribute-value is a case-insensitive match for // "None", set enforcement to "None". if (attributeValueLowercase.includes('none')) { enforcement = 'None' } // 3. If cookie-av's attribute-value is a case-insensitive match for // "Strict", set enforcement to "Strict". if (attributeValueLowercase.includes('strict')) { enforcement = 'Strict' } // 4. If cookie-av's attribute-value is a case-insensitive match for // "Lax", set enforcement to "Lax". if (attributeValueLowercase.includes('lax')) { enforcement = 'Lax' } // 5. Append an attribute to the cookie-attribute-list with an // attribute-name of "SameSite" and an attribute-value of // enforcement. cookieAttributeList.sameSite = enforcement } else { cookieAttributeList.unparsed ??= [] cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`) } // 8. Return to Step 1 of this algorithm. return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) } module.exports = { parseSetCookie, parseUnparsedAttributes } /***/ }), /***/ 43121: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const assert = __nccwpck_require__(39491) const { kHeadersList } = __nccwpck_require__(72785) function isCTLExcludingHtab (value) { if (value.length === 0) { return false } for (const char of value) { const code = char.charCodeAt(0) if ( (code >= 0x00 || code <= 0x08) || (code >= 0x0A || code <= 0x1F) || code === 0x7F ) { return false } } } /** CHAR = token = 1* separators = "(" | ")" | "<" | ">" | "@" | "," | ";" | ":" | "\" | <"> | "/" | "[" | "]" | "?" | "=" | "{" | "}" | SP | HT * @param {string} name */ function validateCookieName (name) { for (const char of name) { const code = char.charCodeAt(0) if ( (code <= 0x20 || code > 0x7F) || char === '(' || char === ')' || char === '>' || char === '<' || char === '@' || char === ',' || char === ';' || char === ':' || char === '\\' || char === '"' || char === '/' || char === '[' || char === ']' || char === '?' || char === '=' || char === '{' || char === '}' ) { throw new Error('Invalid cookie name') } } } /** cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE ) cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E ; US-ASCII characters excluding CTLs, ; whitespace DQUOTE, comma, semicolon, ; and backslash * @param {string} value */ function validateCookieValue (value) { for (const char of value) { const code = char.charCodeAt(0) if ( code < 0x21 || // exclude CTLs (0-31) code === 0x22 || code === 0x2C || code === 0x3B || code === 0x5C || code > 0x7E // non-ascii ) { throw new Error('Invalid header value') } } } /** * path-value = * @param {string} path */ function validateCookiePath (path) { for (const char of path) { const code = char.charCodeAt(0) if (code < 0x21 || char === ';') { throw new Error('Invalid cookie path') } } } /** * I have no idea why these values aren't allowed to be honest, * but Deno tests these. - Khafra * @param {string} domain */ function validateCookieDomain (domain) { if ( domain.startsWith('-') || domain.endsWith('.') || domain.endsWith('-') ) { throw new Error('Invalid cookie domain') } } /** * @see https://www.rfc-editor.org/rfc/rfc7231#section-7.1.1.1 * @param {number|Date} date IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT ; fixed length/zone/capitalization subset of the format ; see Section 3.3 of [RFC5322] day-name = %x4D.6F.6E ; "Mon", case-sensitive / %x54.75.65 ; "Tue", case-sensitive / %x57.65.64 ; "Wed", case-sensitive / %x54.68.75 ; "Thu", case-sensitive / %x46.72.69 ; "Fri", case-sensitive / %x53.61.74 ; "Sat", case-sensitive / %x53.75.6E ; "Sun", case-sensitive date1 = day SP month SP year ; e.g., 02 Jun 1982 day = 2DIGIT month = %x4A.61.6E ; "Jan", case-sensitive / %x46.65.62 ; "Feb", case-sensitive / %x4D.61.72 ; "Mar", case-sensitive / %x41.70.72 ; "Apr", case-sensitive / %x4D.61.79 ; "May", case-sensitive / %x4A.75.6E ; "Jun", case-sensitive / %x4A.75.6C ; "Jul", case-sensitive / %x41.75.67 ; "Aug", case-sensitive / %x53.65.70 ; "Sep", case-sensitive / %x4F.63.74 ; "Oct", case-sensitive / %x4E.6F.76 ; "Nov", case-sensitive / %x44.65.63 ; "Dec", case-sensitive year = 4DIGIT GMT = %x47.4D.54 ; "GMT", case-sensitive time-of-day = hour ":" minute ":" second ; 00:00:00 - 23:59:60 (leap second) hour = 2DIGIT minute = 2DIGIT second = 2DIGIT */ function toIMFDate (date) { if (typeof date === 'number') { date = new Date(date) } const days = [ 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' ] const months = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ] const dayName = days[date.getUTCDay()] const day = date.getUTCDate().toString().padStart(2, '0') const month = months[date.getUTCMonth()] const year = date.getUTCFullYear() const hour = date.getUTCHours().toString().padStart(2, '0') const minute = date.getUTCMinutes().toString().padStart(2, '0') const second = date.getUTCSeconds().toString().padStart(2, '0') return `${dayName}, ${day} ${month} ${year} ${hour}:${minute}:${second} GMT` } /** max-age-av = "Max-Age=" non-zero-digit *DIGIT ; In practice, both expires-av and max-age-av ; are limited to dates representable by the ; user agent. * @param {number} maxAge */ function validateCookieMaxAge (maxAge) { if (maxAge < 0) { throw new Error('Invalid cookie max-age') } } /** * @see https://www.rfc-editor.org/rfc/rfc6265#section-4.1.1 * @param {import('./index').Cookie} cookie */ function stringify (cookie) { if (cookie.name.length === 0) { return null } validateCookieName(cookie.name) validateCookieValue(cookie.value) const out = [`${cookie.name}=${cookie.value}`] // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.1 // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.2 if (cookie.name.startsWith('__Secure-')) { cookie.secure = true } if (cookie.name.startsWith('__Host-')) { cookie.secure = true cookie.domain = null cookie.path = '/' } if (cookie.secure) { out.push('Secure') } if (cookie.httpOnly) { out.push('HttpOnly') } if (typeof cookie.maxAge === 'number') { validateCookieMaxAge(cookie.maxAge) out.push(`Max-Age=${cookie.maxAge}`) } if (cookie.domain) { validateCookieDomain(cookie.domain) out.push(`Domain=${cookie.domain}`) } if (cookie.path) { validateCookiePath(cookie.path) out.push(`Path=${cookie.path}`) } if (cookie.expires && cookie.expires.toString() !== 'Invalid Date') { out.push(`Expires=${toIMFDate(cookie.expires)}`) } if (cookie.sameSite) { out.push(`SameSite=${cookie.sameSite}`) } for (const part of cookie.unparsed) { if (!part.includes('=')) { throw new Error('Invalid unparsed') } const [key, ...value] = part.split('=') out.push(`${key.trim()}=${value.join('=')}`) } return out.join('; ') } let kHeadersListNode function getHeadersList (headers) { if (headers[kHeadersList]) { return headers[kHeadersList] } if (!kHeadersListNode) { kHeadersListNode = Object.getOwnPropertySymbols(headers).find( (symbol) => symbol.description === 'headers list' ) assert(kHeadersListNode, 'Headers cannot be parsed') } const headersList = headers[kHeadersListNode] assert(headersList) return headersList } module.exports = { isCTLExcludingHtab, stringify, getHeadersList } /***/ }), /***/ 82067: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const net = __nccwpck_require__(41808) const assert = __nccwpck_require__(39491) const util = __nccwpck_require__(83983) const { InvalidArgumentError, ConnectTimeoutError } = __nccwpck_require__(48045) 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. let SessionCache // FIXME: remove workaround when the Node bug is fixed // https://github.com/nodejs/node/issues/49344#issuecomment-1741776308 if (global.FinalizationRegistry && !process.env.NODE_V8_COVERAGE) { SessionCache = class WeakSessionCache { constructor (maxCachedSessions) { this._maxCachedSessions = maxCachedSessions this._sessionCache = new Map() this._sessionRegistry = new global.FinalizationRegistry((key) => { if (this._sessionCache.size < this._maxCachedSessions) { return } const ref = this._sessionCache.get(key) if (ref !== undefined && ref.deref() === undefined) { this._sessionCache.delete(key) } }) } get (sessionKey) { const ref = this._sessionCache.get(sessionKey) return ref ? ref.deref() : null } set (sessionKey, session) { if (this._maxCachedSessions === 0) { return } this._sessionCache.set(sessionKey, new WeakRef(session)) this._sessionRegistry.register(session, sessionKey) } } } else { SessionCache = class SimpleSessionCache { constructor (maxCachedSessions) { this._maxCachedSessions = maxCachedSessions this._sessionCache = new Map() } get (sessionKey) { return this._sessionCache.get(sessionKey) } set (sessionKey, session) { if (this._maxCachedSessions === 0) { return } if (this._sessionCache.size >= this._maxCachedSessions) { // remove the oldest session const { value: oldestKey } = this._sessionCache.keys().next() this._sessionCache.delete(oldestKey) } this._sessionCache.set(sessionKey, session) } } } function buildConnector ({ allowH2, maxCachedSessions, socketPath, timeout, ...opts }) { if (maxCachedSessions != null && (!Number.isInteger(maxCachedSessions) || maxCachedSessions < 0)) { throw new InvalidArgumentError('maxCachedSessions must be a positive integer or zero') } const options = { path: socketPath, ...opts } const sessionCache = new SessionCache(maxCachedSessions == null ? 100 : maxCachedSessions) timeout = timeout == null ? 10e3 : timeout allowH2 = allowH2 != null ? allowH2 : false return function connect ({ hostname, host, protocol, port, servername, localAddress, httpSocket }, callback) { let socket if (protocol === 'https:') { if (!tls) { tls = __nccwpck_require__(24404) } servername = servername || options.servername || util.getServerName(host) || null const sessionKey = servername || hostname const session = sessionCache.get(sessionKey) || null assert(sessionKey) socket = tls.connect({ highWaterMark: 16384, // TLS in node can't have bigger HWM anyway... ...options, servername, session, localAddress, // TODO(HTTP/2): Add support for h2c ALPNProtocols: allowH2 ? ['http/1.1', 'h2'] : ['http/1.1'], socket: httpSocket, // upgrade socket connection port: port || 443, host: hostname }) 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') socket = net.connect({ highWaterMark: 64 * 1024, // Same as nodejs fs streams. ...options, localAddress, port: port || 80, host: hostname }) } // 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) } const cancelTimeout = setupTimeout(() => onConnectTimeout(socket), timeout) socket .setNoDelay(true) .once(protocol === 'https:' ? 'secureConnect' : 'connect', function () { cancelTimeout() if (callback) { const cb = callback callback = null cb(null, this) } }) .on('error', function (err) { cancelTimeout() if (callback) { const cb = callback callback = null cb(err) } }) return socket } } function setupTimeout (onConnectTimeout, timeout) { if (!timeout) { return () => {} } let s1 = null let s2 = null const timeoutId = setTimeout(() => { // setImmediate is added to make sure that we priotorise socket error events over timeouts s1 = setImmediate(() => { if (process.platform === 'win32') { // Windows needs an extra setImmediate probably due to implementation differences in the socket logic s2 = setImmediate(() => onConnectTimeout()) } else { onConnectTimeout() } }) }, timeout) return () => { clearTimeout(timeoutId) clearImmediate(s1) clearImmediate(s2) } } function onConnectTimeout (socket) { util.destroy(socket, new ConnectTimeoutError()) } module.exports = buildConnector /***/ }), /***/ 48045: /***/ ((module) => { "use strict"; class UndiciError extends Error { constructor (message) { super(message) this.name = 'UndiciError' this.code = 'UND_ERR' } } class ConnectTimeoutError extends UndiciError { constructor (message) { super(message) Error.captureStackTrace(this, ConnectTimeoutError) this.name = 'ConnectTimeoutError' this.message = message || 'Connect Timeout Error' this.code = 'UND_ERR_CONNECT_TIMEOUT' } } class HeadersTimeoutError extends UndiciError { constructor (message) { super(message) Error.captureStackTrace(this, HeadersTimeoutError) this.name = 'HeadersTimeoutError' this.message = message || 'Headers Timeout Error' this.code = 'UND_ERR_HEADERS_TIMEOUT' } } class HeadersOverflowError extends UndiciError { constructor (message) { super(message) Error.captureStackTrace(this, HeadersOverflowError) this.name = 'HeadersOverflowError' this.message = message || 'Headers Overflow Error' this.code = 'UND_ERR_HEADERS_OVERFLOW' } } class BodyTimeoutError extends UndiciError { constructor (message) { super(message) Error.captureStackTrace(this, BodyTimeoutError) this.name = 'BodyTimeoutError' this.message = message || 'Body Timeout Error' this.code = 'UND_ERR_BODY_TIMEOUT' } } class ResponseStatusCodeError extends UndiciError { constructor (message, statusCode, headers, body) { super(message) Error.captureStackTrace(this, ResponseStatusCodeError) this.name = 'ResponseStatusCodeError' this.message = message || 'Response Status Code Error' this.code = 'UND_ERR_RESPONSE_STATUS_CODE' this.body = body this.status = statusCode this.statusCode = statusCode this.headers = headers } } class InvalidArgumentError extends UndiciError { constructor (message) { super(message) Error.captureStackTrace(this, InvalidArgumentError) this.name = 'InvalidArgumentError' this.message = message || 'Invalid Argument Error' this.code = 'UND_ERR_INVALID_ARG' } } class InvalidReturnValueError extends UndiciError { constructor (message) { super(message) Error.captureStackTrace(this, InvalidReturnValueError) this.name = 'InvalidReturnValueError' this.message = message || 'Invalid Return Value Error' this.code = 'UND_ERR_INVALID_RETURN_VALUE' } } class RequestAbortedError extends UndiciError { constructor (message) { super(message) Error.captureStackTrace(this, RequestAbortedError) this.name = 'AbortError' this.message = message || 'Request aborted' this.code = 'UND_ERR_ABORTED' } } class InformationalError extends UndiciError { constructor (message) { super(message) Error.captureStackTrace(this, InformationalError) this.name = 'InformationalError' this.message = message || 'Request information' this.code = 'UND_ERR_INFO' } } class RequestContentLengthMismatchError extends UndiciError { constructor (message) { super(message) Error.captureStackTrace(this, RequestContentLengthMismatchError) this.name = 'RequestContentLengthMismatchError' this.message = message || 'Request body length does not match content-length header' this.code = 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH' } } class ResponseContentLengthMismatchError extends UndiciError { constructor (message) { super(message) Error.captureStackTrace(this, ResponseContentLengthMismatchError) this.name = 'ResponseContentLengthMismatchError' this.message = message || 'Response body length does not match content-length header' this.code = 'UND_ERR_RES_CONTENT_LENGTH_MISMATCH' } } class ClientDestroyedError extends UndiciError { constructor (message) { super(message) Error.captureStackTrace(this, ClientDestroyedError) this.name = 'ClientDestroyedError' this.message = message || 'The client is destroyed' this.code = 'UND_ERR_DESTROYED' } } class ClientClosedError extends UndiciError { constructor (message) { super(message) Error.captureStackTrace(this, ClientClosedError) this.name = 'ClientClosedError' this.message = message || 'The client is closed' this.code = 'UND_ERR_CLOSED' } } class SocketError extends UndiciError { constructor (message, socket) { super(message) Error.captureStackTrace(this, SocketError) this.name = 'SocketError' this.message = message || 'Socket error' this.code = 'UND_ERR_SOCKET' this.socket = socket } } class NotSupportedError extends UndiciError { constructor (message) { super(message) Error.captureStackTrace(this, NotSupportedError) this.name = 'NotSupportedError' this.message = message || 'Not supported error' this.code = 'UND_ERR_NOT_SUPPORTED' } } class BalancedPoolMissingUpstreamError extends UndiciError { constructor (message) { super(message) Error.captureStackTrace(this, NotSupportedError) this.name = 'MissingUpstreamError' this.message = message || 'No upstream has been added to the BalancedPool' this.code = 'UND_ERR_BPL_MISSING_UPSTREAM' } } class HTTPParserError extends Error { constructor (message, code, data) { super(message) Error.captureStackTrace(this, HTTPParserError) this.name = 'HTTPParserError' this.code = code ? `HPE_${code}` : undefined this.data = data ? data.toString() : undefined } } class ResponseExceededMaxSizeError extends UndiciError { constructor (message) { super(message) Error.captureStackTrace(this, ResponseExceededMaxSizeError) this.name = 'ResponseExceededMaxSizeError' this.message = message || 'Response content exceeded max size' this.code = 'UND_ERR_RES_EXCEEDED_MAX_SIZE' } } class RequestRetryError extends UndiciError { constructor (message, code, { headers, data }) { super(message) Error.captureStackTrace(this, RequestRetryError) this.name = 'RequestRetryError' this.message = message || 'Request retry error' this.code = 'UND_ERR_REQ_RETRY' this.statusCode = code this.data = data this.headers = headers } } module.exports = { HTTPParserError, UndiciError, HeadersTimeoutError, HeadersOverflowError, BodyTimeoutError, RequestContentLengthMismatchError, ConnectTimeoutError, ResponseStatusCodeError, InvalidArgumentError, InvalidReturnValueError, RequestAbortedError, ClientDestroyedError, ClientClosedError, InformationalError, SocketError, NotSupportedError, ResponseContentLengthMismatchError, BalancedPoolMissingUpstreamError, ResponseExceededMaxSizeError, RequestRetryError } /***/ }), /***/ 62905: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { InvalidArgumentError, NotSupportedError } = __nccwpck_require__(48045) const assert = __nccwpck_require__(39491) const { kHTTP2BuildRequest, kHTTP2CopyHeaders, kHTTP1BuildRequest } = __nccwpck_require__(72785) const util = __nccwpck_require__(83983) // tokenRegExp and headerCharRegex have been lifted from // https://github.com/nodejs/node/blob/main/lib/_http_common.js /** * Verifies that the given val is a valid HTTP token * per the rules defined in RFC 7230 * See https://tools.ietf.org/html/rfc7230#section-3.2.6 */ const tokenRegExp = /^[\^_`a-zA-Z\-0-9!#$%&'*+.|~]+$/ /** * 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]/ // Verifies that a given path is valid does not contain control chars \x00 to \x20 const invalidPathRegex = /[^\u0021-\u00ff]/ const kHandler = Symbol('handler') const channels = {} let extractBody try { const diagnosticsChannel = __nccwpck_require__(67643) channels.create = diagnosticsChannel.channel('undici:request:create') channels.bodySent = diagnosticsChannel.channel('undici:request:bodySent') channels.headers = diagnosticsChannel.channel('undici:request:headers') channels.trailers = diagnosticsChannel.channel('undici:request:trailers') channels.error = diagnosticsChannel.channel('undici:request:error') } catch { channels.create = { hasSubscribers: false } channels.bodySent = { hasSubscribers: false } channels.headers = { hasSubscribers: false } channels.trailers = { hasSubscribers: false } channels.error = { hasSubscribers: false } } class Request { constructor (origin, { path, method, body, headers, query, idempotent, blocking, upgrade, headersTimeout, bodyTimeout, reset, throwOnError, expectContinue }, 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.exec(path) !== null) { throw new InvalidArgumentError('invalid request path') } if (typeof method !== 'string') { throw new InvalidArgumentError('method must be a string') } else if (tokenRegExp.exec(method) === null) { throw new InvalidArgumentError('invalid request method') } if (upgrade && typeof upgrade !== 'string') { throw new InvalidArgumentError('upgrade must be a string') } if (headersTimeout != null && (!Number.isFinite(headersTimeout) || headersTimeout < 0)) { throw new InvalidArgumentError('invalid headersTimeout') } if (bodyTimeout != null && (!Number.isFinite(bodyTimeout) || bodyTimeout < 0)) { throw new InvalidArgumentError('invalid bodyTimeout') } if (reset != null && typeof reset !== 'boolean') { throw new InvalidArgumentError('invalid reset') } if (expectContinue != null && typeof expectContinue !== 'boolean') { throw new InvalidArgumentError('invalid expectContinue') } this.headersTimeout = headersTimeout this.bodyTimeout = bodyTimeout this.throwOnError = throwOnError === true this.method = method this.abort = null if (body == null) { this.body = null } else if (util.isStream(body)) { this.body = body const rState = this.body._readableState if (!rState || !rState.autoDestroy) { this.endHandler = function autoDestroy () { util.destroy(this) } this.body.on('end', this.endHandler) } this.errorHandler = err => { if (this.abort) { this.abort(err) } else { this.error = err } } this.body.on('error', this.errorHandler) } else if (util.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 (util.isFormDataLike(body) || util.isIterable(body) || util.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 this.path = query ? util.buildURL(path, query) : path this.origin = origin this.idempotent = idempotent == null ? method === 'HEAD' || method === 'GET' : idempotent this.blocking = blocking == null ? false : blocking 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]) } } else if (headers && typeof headers === 'object') { const keys = Object.keys(headers) for (let i = 0; i < keys.length; i++) { const key = keys[i] processHeader(this, key, headers[key]) } } else if (headers != null) { throw new InvalidArgumentError('headers must be an object or an array') } if (util.isFormDataLike(this.body)) { if (util.nodeMajor < 16 || (util.nodeMajor === 16 && util.nodeMinor < 8)) { throw new InvalidArgumentError('Form-Data bodies are only supported in node v16.8 and newer.') } if (!extractBody) { extractBody = (__nccwpck_require__(41472).extractBody) } const [bodyStream, contentType] = extractBody(body) if (this.contentType == null) { this.contentType = contentType this.headers += `content-type: ${contentType}\r\n` } this.body = bodyStream.stream this.contentLength = bodyStream.length } else if (util.isBlobLike(body) && this.contentType == null && body.type) { this.contentType = body.type this.headers += `content-type: ${body.type}\r\n` } util.validateHandler(handler, method, upgrade) this.servername = util.getServerName(this.host) this[kHandler] = handler if (channels.create.hasSubscribers) { channels.create.publish({ request: this }) } } onBodySent (chunk) { if (this[kHandler].onBodySent) { try { return this[kHandler].onBodySent(chunk) } catch (err) { this.abort(err) } } } onRequestSent () { if (channels.bodySent.hasSubscribers) { channels.bodySent.publish({ request: this }) } if (this[kHandler].onRequestSent) { try { return this[kHandler].onRequestSent() } catch (err) { this.abort(err) } } } onConnect (abort) { assert(!this.aborted) assert(!this.completed) if (this.error) { abort(this.error) } else { this.abort = abort return this[kHandler].onConnect(abort) } } onHeaders (statusCode, headers, resume, statusText) { assert(!this.aborted) assert(!this.completed) if (channels.headers.hasSubscribers) { channels.headers.publish({ request: this, response: { statusCode, headers, statusText } }) } try { return this[kHandler].onHeaders(statusCode, headers, resume, statusText) } catch (err) { this.abort(err) } } onData (chunk) { assert(!this.aborted) assert(!this.completed) try { return this[kHandler].onData(chunk) } catch (err) { this.abort(err) return false } } onUpgrade (statusCode, headers, socket) { assert(!this.aborted) assert(!this.completed) return this[kHandler].onUpgrade(statusCode, headers, socket) } onComplete (trailers) { this.onFinally() assert(!this.aborted) this.completed = true if (channels.trailers.hasSubscribers) { channels.trailers.publish({ request: this, trailers }) } try { return this[kHandler].onComplete(trailers) } catch (err) { // TODO (fix): This might be a bad idea? this.onError(err) } } onError (error) { this.onFinally() if (channels.error.hasSubscribers) { channels.error.publish({ request: this, error }) } if (this.aborted) { return } this.aborted = true return this[kHandler].onError(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 } } // TODO: adjust to support H2 addHeader (key, value) { processHeader(this, key, value) return this } static [kHTTP1BuildRequest] (origin, opts, handler) { // TODO: Migrate header parsing here, to make Requests // HTTP agnostic return new Request(origin, opts, handler) } static [kHTTP2BuildRequest] (origin, opts, handler) { const headers = opts.headers opts = { ...opts, headers: null } const request = new Request(origin, opts, handler) request.headers = {} 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(request, headers[i], headers[i + 1], true) } } else if (headers && typeof headers === 'object') { const keys = Object.keys(headers) for (let i = 0; i < keys.length; i++) { const key = keys[i] processHeader(request, key, headers[key], true) } } else if (headers != null) { throw new InvalidArgumentError('headers must be an object or an array') } return request } static [kHTTP2CopyHeaders] (raw) { const rawHeaders = raw.split('\r\n') const headers = {} for (const header of rawHeaders) { const [key, value] = header.split(': ') if (value == null || value.length === 0) continue if (headers[key]) headers[key] += `,${value}` else headers[key] = value } return headers } } function processHeaderValue (key, val, skipAppend) { if (val && typeof val === 'object') { throw new InvalidArgumentError(`invalid ${key} header`) } val = val != null ? `${val}` : '' if (headerCharRegex.exec(val) !== null) { throw new InvalidArgumentError(`invalid ${key} header`) } return skipAppend ? val : `${key}: ${val}\r\n` } function processHeader (request, key, val, skipAppend = false) { if (val && (typeof val === 'object' && !Array.isArray(val))) { throw new InvalidArgumentError(`invalid ${key} header`) } else if (val === undefined) { return } if ( request.host === null && key.length === 4 && key.toLowerCase() === 'host' ) { if (headerCharRegex.exec(val) !== null) { throw new InvalidArgumentError(`invalid ${key} header`) } // Consumed by Client request.host = val } else if ( request.contentLength === null && key.length === 14 && key.toLowerCase() === 'content-length' ) { request.contentLength = parseInt(val, 10) if (!Number.isFinite(request.contentLength)) { throw new InvalidArgumentError('invalid content-length header') } } else if ( request.contentType === null && key.length === 12 && key.toLowerCase() === 'content-type' ) { request.contentType = val if (skipAppend) request.headers[key] = processHeaderValue(key, val, skipAppend) else request.headers += processHeaderValue(key, val) } else if ( key.length === 17 && key.toLowerCase() === 'transfer-encoding' ) { throw new InvalidArgumentError('invalid transfer-encoding header') } else if ( key.length === 10 && key.toLowerCase() === 'connection' ) { const value = typeof val === 'string' ? val.toLowerCase() : null if (value !== 'close' && value !== 'keep-alive') { throw new InvalidArgumentError('invalid connection header') } else if (value === 'close') { request.reset = true } } else if ( key.length === 10 && key.toLowerCase() === 'keep-alive' ) { throw new InvalidArgumentError('invalid keep-alive header') } else if ( key.length === 7 && key.toLowerCase() === 'upgrade' ) { throw new InvalidArgumentError('invalid upgrade header') } else if ( key.length === 6 && key.toLowerCase() === 'expect' ) { throw new NotSupportedError('expect header not supported') } else if (tokenRegExp.exec(key) === null) { throw new InvalidArgumentError('invalid header key') } else { if (Array.isArray(val)) { for (let i = 0; i < val.length; i++) { if (skipAppend) { if (request.headers[key]) request.headers[key] += `,${processHeaderValue(key, val[i], skipAppend)}` else request.headers[key] = processHeaderValue(key, val[i], skipAppend) } else { request.headers += processHeaderValue(key, val[i]) } } } else { if (skipAppend) request.headers[key] = processHeaderValue(key, val, skipAppend) else request.headers += processHeaderValue(key, val) } } } module.exports = Request /***/ }), /***/ 72785: /***/ ((module) => { module.exports = { kClose: Symbol('close'), kDestroy: Symbol('destroy'), kDispatch: Symbol('dispatch'), kUrl: Symbol('url'), kWriting: Symbol('writing'), kResuming: Symbol('resuming'), kQueue: Symbol('queue'), kConnect: Symbol('connect'), kConnecting: Symbol('connecting'), kHeadersList: Symbol('headers list'), 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'), 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'), 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'), kInterceptors: Symbol('dispatch interceptors'), kMaxResponseSize: Symbol('max response size'), kHTTP2Session: Symbol('http2Session'), kHTTP2SessionState: Symbol('http2Session state'), kHTTP2BuildRequest: Symbol('http2 build request'), kHTTP1BuildRequest: Symbol('http1 build request'), kHTTP2CopyHeaders: Symbol('http2 copy headers'), kHTTPConnVersion: Symbol('http connection version'), kRetryHandlerDefaultRetry: Symbol('retry agent default retry'), kConstruct: Symbol('constructable') } /***/ }), /***/ 83983: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const assert = __nccwpck_require__(39491) const { kDestroyed, kBodyUsed } = __nccwpck_require__(72785) const { IncomingMessage } = __nccwpck_require__(13685) const stream = __nccwpck_require__(12781) const net = __nccwpck_require__(41808) const { InvalidArgumentError } = __nccwpck_require__(48045) const { Blob } = __nccwpck_require__(14300) const nodeUtil = __nccwpck_require__(73837) const { stringify } = __nccwpck_require__(63477) const [nodeMajor, nodeMinor] = process.versions.node.split('.').map(v => Number(v)) function nop () {} function isStream (obj) { return obj && typeof obj === 'object' && typeof obj.pipe === 'function' && typeof obj.on === 'function' } // based on https://github.com/node-fetch/fetch-blob/blob/8ab587d34080de94140b54f07168451e7d0b655e/index.js#L229-L241 (MIT License) function isBlobLike (object) { return (Blob && object instanceof Blob) || ( object && typeof object === 'object' && (typeof object.stream === 'function' || typeof object.arrayBuffer === 'function') && /^(Blob|File)$/.test(object[Symbol.toStringTag]) ) } function buildURL (url, queryParams) { if (url.includes('?') || url.includes('#')) { throw new Error('Query params cannot be passed when url already contains "?" or "#".') } const stringified = stringify(queryParams) if (stringified) { url += '?' + stringified } return url } function parseURL (url) { if (typeof url === 'string') { url = new URL(url) if (!/^https?:/.test(url.origin || url.protocol)) { throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.') } return url } if (!url || typeof url !== 'object') { throw new InvalidArgumentError('Invalid URL: The URL argument must be a non-null object.') } if (!/^https?:/.test(url.origin || url.protocol)) { throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.') } if (!(url instanceof URL)) { if (url.port != null && url.port !== '' && !Number.isFinite(parseInt(url.port))) { throw new InvalidArgumentError('Invalid URL: port must be a valid integer or a string representation of an integer.') } if (url.path != null && typeof url.path !== 'string') { throw new InvalidArgumentError('Invalid URL path: the path must be a string or null/undefined.') } if (url.pathname != null && typeof url.pathname !== 'string') { throw new InvalidArgumentError('Invalid URL pathname: the pathname must be a string or null/undefined.') } if (url.hostname != null && typeof url.hostname !== 'string') { throw new InvalidArgumentError('Invalid URL hostname: the hostname must be a string or null/undefined.') } if (url.origin != null && typeof url.origin !== 'string') { throw new InvalidArgumentError('Invalid URL origin: the origin must be a string or null/undefined.') } 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 (origin.endsWith('/')) { origin = origin.substring(0, origin.length - 1) } if (path && !path.startsWith('/')) { path = `/${path}` } // 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. url = new URL(origin + path) } return url } function parseOrigin (url) { url = parseURL(url) if (url.pathname !== '/' || url.search || url.hash) { throw new InvalidArgumentError('invalid url') } return url } function getHostname (host) { if (host[0] === '[') { const idx = host.indexOf(']') assert(idx !== -1) return host.substring(1, idx) } const idx = host.indexOf(':') if (idx === -1) return host return host.substring(0, idx) } // IP addresses are not valid server names per RFC6066 // > Currently, the only server names supported are DNS hostnames function getServerName (host) { if (!host) { return null } assert.strictEqual(typeof host, 'string') const servername = getHostname(host) if (net.isIP(servername)) { return '' } return servername } function deepClone (obj) { return JSON.parse(JSON.stringify(obj)) } function isAsyncIterable (obj) { return !!(obj != null && typeof obj[Symbol.asyncIterator] === 'function') } function isIterable (obj) { return !!(obj != null && (typeof obj[Symbol.iterator] === 'function' || typeof obj[Symbol.asyncIterator] === 'function')) } 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 null } function isDestroyed (stream) { return !stream || !!(stream.destroyed || stream[kDestroyed]) } function isReadableAborted (stream) { const state = stream && stream._readableState return isDestroyed(stream) && state && !state.endEmitted } function destroy (stream, err) { if (stream == null || !isStream(stream) || isDestroyed(stream)) { return } if (typeof stream.destroy === 'function') { if (Object.getPrototypeOf(stream).constructor === IncomingMessage) { // See: https://github.com/nodejs/node/pull/38505/files stream.socket = null } stream.destroy(err) } else if (err) { process.nextTick((stream, err) => { stream.emit('error', err) }, stream, err) } if (stream.destroyed !== true) { stream[kDestroyed] = true } } const KEEPALIVE_TIMEOUT_EXPR = /timeout=(\d+)/ function parseKeepAliveTimeout (val) { const m = val.toString().match(KEEPALIVE_TIMEOUT_EXPR) return m ? parseInt(m[1], 10) * 1000 : null } function parseHeaders (headers, obj = {}) { // For H2 support if (!Array.isArray(headers)) return headers for (let i = 0; i < headers.length; i += 2) { const key = headers[i].toString().toLowerCase() let val = obj[key] if (!val) { if (Array.isArray(headers[i + 1])) { obj[key] = headers[i + 1].map(x => x.toString('utf8')) } else { obj[key] = headers[i + 1].toString('utf8') } } else { if (!Array.isArray(val)) { val = [val] obj[key] = val } val.push(headers[i + 1].toString('utf8')) } } // See https://github.com/nodejs/node/pull/46528 if ('content-length' in obj && 'content-disposition' in obj) { obj['content-disposition'] = Buffer.from(obj['content-disposition']).toString('latin1') } return obj } function parseRawHeaders (headers) { const ret = [] let hasContentLength = false let contentDispositionIdx = -1 for (let n = 0; n < headers.length; n += 2) { const key = headers[n + 0].toString() const val = headers[n + 1].toString('utf8') if (key.length === 14 && (key === 'content-length' || key.toLowerCase() === 'content-length')) { ret.push(key, val) hasContentLength = true } else if (key.length === 19 && (key === 'content-disposition' || key.toLowerCase() === 'content-disposition')) { contentDispositionIdx = ret.push(key, val) - 1 } else { ret.push(key, val) } } // See https://github.com/nodejs/node/pull/46528 if (hasContentLength && contentDispositionIdx !== -1) { ret[contentDispositionIdx] = Buffer.from(ret[contentDispositionIdx]).toString('latin1') } return ret } function isBuffer (buffer) { // See, https://github.com/mcollina/undici/pull/319 return buffer instanceof Uint8Array || Buffer.isBuffer(buffer) } function validateHandler (handler, method, upgrade) { if (!handler || typeof handler !== 'object') { throw new InvalidArgumentError('handler must be an object') } if (typeof handler.onConnect !== 'function') { throw new InvalidArgumentError('invalid onConnect method') } if (typeof handler.onError !== 'function') { throw new InvalidArgumentError('invalid onError method') } if (typeof handler.onBodySent !== 'function' && handler.onBodySent !== undefined) { throw new InvalidArgumentError('invalid onBodySent method') } if (upgrade || method === 'CONNECT') { if (typeof handler.onUpgrade !== 'function') { throw new InvalidArgumentError('invalid onUpgrade method') } } else { if (typeof handler.onHeaders !== 'function') { throw new InvalidArgumentError('invalid onHeaders method') } if (typeof handler.onData !== 'function') { throw new InvalidArgumentError('invalid onData method') } if (typeof handler.onComplete !== 'function') { throw new InvalidArgumentError('invalid onComplete method') } } } // A body is disturbed if it has been read from and it cannot // be re-used without losing state or data. function isDisturbed (body) { return !!(body && ( stream.isDisturbed ? stream.isDisturbed(body) || body[kBodyUsed] // TODO (fix): Why is body[kBodyUsed] needed? : body[kBodyUsed] || body.readableDidRead || (body._readableState && body._readableState.dataEmitted) || isReadableAborted(body) )) } function isErrored (body) { return !!(body && ( stream.isErrored ? stream.isErrored(body) : /state: 'errored'/.test(nodeUtil.inspect(body) ))) } function isReadable (body) { return !!(body && ( stream.isReadable ? stream.isReadable(body) : /state: 'readable'/.test(nodeUtil.inspect(body) ))) } 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 } } async function * convertIterableToBuffer (iterable) { for await (const chunk of iterable) { yield Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk) } } let ReadableStream function ReadableStreamFrom (iterable) { if (!ReadableStream) { ReadableStream = (__nccwpck_require__(35356).ReadableStream) } if (ReadableStream.from) { return ReadableStream.from(convertIterableToBuffer(iterable)) } let iterator return new ReadableStream( { async start () { iterator = iterable[Symbol.asyncIterator]() }, async pull (controller) { const { done, value } = await iterator.next() if (done) { queueMicrotask(() => { controller.close() }) } else { const buf = Buffer.isBuffer(value) ? value : Buffer.from(value) controller.enqueue(new Uint8Array(buf)) } return controller.desiredSize > 0 }, async cancel (reason) { await iterator.return() } }, 0 ) } // The chunk should be a FormData instance and contains // all the required methods. 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' ) } function throwIfAborted (signal) { if (!signal) { return } if (typeof signal.throwIfAborted === 'function') { signal.throwIfAborted() } else { if (signal.aborted) { // DOMException not available < v17.0.0 const err = new Error('The operation was aborted') err.name = 'AbortError' throw err } } } function addAbortListener (signal, listener) { if ('addEventListener' in signal) { signal.addEventListener('abort', listener, { once: true }) return () => signal.removeEventListener('abort', listener) } signal.addListener('abort', listener) return () => signal.removeListener('abort', listener) } const hasToWellFormed = !!String.prototype.toWellFormed /** * @param {string} val */ function toUSVString (val) { if (hasToWellFormed) { return `${val}`.toWellFormed() } else if (nodeUtil.toUSVString) { return nodeUtil.toUSVString(val) } return `${val}` } // Parsed accordingly to RFC 9110 // https://www.rfc-editor.org/rfc/rfc9110#field.content-range function parseRangeHeader (range) { if (range == null || range === '') return { start: 0, end: null, size: null } const m = range ? range.match(/^bytes (\d+)-(\d+)\/(\d+)?$/) : null return m ? { start: parseInt(m[1]), end: m[2] ? parseInt(m[2]) : null, size: m[3] ? parseInt(m[3]) : null } : null } const kEnumerableProperty = Object.create(null) kEnumerableProperty.enumerable = true module.exports = { kEnumerableProperty, nop, isDisturbed, isErrored, isReadable, toUSVString, isReadableAborted, isBlobLike, parseOrigin, parseURL, getServerName, isStream, isIterable, isAsyncIterable, isDestroyed, parseRawHeaders, parseHeaders, parseKeepAliveTimeout, destroy, bodyLength, deepClone, ReadableStreamFrom, isBuffer, validateHandler, getSocketInfo, isFormDataLike, buildURL, throwIfAborted, addAbortListener, parseRangeHeader, nodeMajor, nodeMinor, nodeHasAutoSelectFamily: nodeMajor > 18 || (nodeMajor === 18 && nodeMinor >= 13), safeHTTPMethods: ['GET', 'HEAD', 'OPTIONS', 'TRACE'] } /***/ }), /***/ 74839: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const Dispatcher = __nccwpck_require__(60412) const { ClientDestroyedError, ClientClosedError, InvalidArgumentError } = __nccwpck_require__(48045) const { kDestroy, kClose, kDispatch, kInterceptors } = __nccwpck_require__(72785) const kDestroyed = Symbol('destroyed') const kClosed = Symbol('closed') const kOnDestroyed = Symbol('onDestroyed') const kOnClosed = Symbol('onClosed') const kInterceptedDispatch = Symbol('Intercepted Dispatch') class DispatcherBase extends Dispatcher { constructor () { super() this[kDestroyed] = false this[kOnDestroyed] = null this[kClosed] = false this[kOnClosed] = [] } get destroyed () { return this[kDestroyed] } get closed () { return this[kClosed] } get interceptors () { return this[kInterceptors] } set interceptors (newInterceptors) { if (newInterceptors) { for (let i = newInterceptors.length - 1; i >= 0; i--) { const interceptor = this[kInterceptors][i] if (typeof interceptor !== 'function') { throw new InvalidArgumentError('interceptor must be an function') } } } this[kInterceptors] = newInterceptors } close (callback) { if (callback === undefined) { return new Promise((resolve, reject) => { this.close((err, data) => { return err ? reject(err) : resolve(data) }) }) } if (typeof callback !== 'function') { throw new InvalidArgumentError('invalid callback') } if (this[kDestroyed]) { queueMicrotask(() => callback(new ClientDestroyedError(), null)) return } if (this[kClosed]) { if (this[kOnClosed]) { this[kOnClosed].push(callback) } else { queueMicrotask(() => callback(null, null)) } return } this[kClosed] = true this[kOnClosed].push(callback) const onClosed = () => { const callbacks = this[kOnClosed] this[kOnClosed] = null for (let i = 0; i < callbacks.length; i++) { callbacks[i](null, null) } } // Should not error. this[kClose]() .then(() => this.destroy()) .then(() => { queueMicrotask(onClosed) }) } destroy (err, callback) { if (typeof err === 'function') { callback = err err = null } if (callback === undefined) { return new Promise((resolve, reject) => { this.destroy(err, (err, data) => { return err ? /* istanbul ignore next: should never error */ reject(err) : resolve(data) }) }) } if (typeof callback !== 'function') { throw new InvalidArgumentError('invalid callback') } if (this[kDestroyed]) { if (this[kOnDestroyed]) { this[kOnDestroyed].push(callback) } else { queueMicrotask(() => callback(null, null)) } return } if (!err) { err = new ClientDestroyedError() } this[kDestroyed] = true this[kOnDestroyed] = this[kOnDestroyed] || [] this[kOnDestroyed].push(callback) const onDestroyed = () => { const callbacks = this[kOnDestroyed] this[kOnDestroyed] = null for (let i = 0; i < callbacks.length; i++) { callbacks[i](null, null) } } // Should not error. this[kDestroy](err).then(() => { queueMicrotask(onDestroyed) }) } [kInterceptedDispatch] (opts, handler) { if (!this[kInterceptors] || this[kInterceptors].length === 0) { this[kInterceptedDispatch] = this[kDispatch] return this[kDispatch](opts, handler) } let dispatch = this[kDispatch].bind(this) for (let i = this[kInterceptors].length - 1; i >= 0; i--) { dispatch = this[kInterceptors][i](dispatch) } this[kInterceptedDispatch] = dispatch return dispatch(opts, handler) } dispatch (opts, handler) { if (!handler || typeof handler !== 'object') { throw new InvalidArgumentError('handler must be an object') } try { if (!opts || typeof opts !== 'object') { throw new InvalidArgumentError('opts must be an object.') } if (this[kDestroyed] || this[kOnDestroyed]) { throw new ClientDestroyedError() } if (this[kClosed]) { throw new ClientClosedError() } return this[kInterceptedDispatch](opts, handler) } catch (err) { if (typeof handler.onError !== 'function') { throw new InvalidArgumentError('invalid onError method') } handler.onError(err) return false } } } module.exports = DispatcherBase /***/ }), /***/ 60412: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const EventEmitter = __nccwpck_require__(82361) class Dispatcher extends EventEmitter { dispatch () { throw new Error('not implemented') } close () { throw new Error('not implemented') } destroy () { throw new Error('not implemented') } } module.exports = Dispatcher /***/ }), /***/ 41472: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const Busboy = __nccwpck_require__(33438) const util = __nccwpck_require__(83983) const { ReadableStreamFrom, isBlobLike, isReadableStreamLike, readableStreamClose, createDeferredPromise, fullyReadBody } = __nccwpck_require__(52538) const { FormData } = __nccwpck_require__(72015) const { kState } = __nccwpck_require__(15861) const { webidl } = __nccwpck_require__(21744) const { DOMException, structuredClone } = __nccwpck_require__(41037) const { Blob, File: NativeFile } = __nccwpck_require__(14300) const { kBodyUsed } = __nccwpck_require__(72785) const assert = __nccwpck_require__(39491) const { isErrored } = __nccwpck_require__(83983) const { isUint8Array, isArrayBuffer } = __nccwpck_require__(29830) const { File: UndiciFile } = __nccwpck_require__(78511) const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(685) let ReadableStream = globalThis.ReadableStream /** @type {globalThis['File']} */ const File = NativeFile ?? UndiciFile const textEncoder = new TextEncoder() const textDecoder = new TextDecoder() // https://fetch.spec.whatwg.org/#concept-bodyinit-extract function extractBody (object, keepalive = false) { if (!ReadableStream) { ReadableStream = (__nccwpck_require__(35356).ReadableStream) } // 1. Let stream be null. let stream = null // 2. If object is a ReadableStream object, then set stream to object. if (object instanceof ReadableStream) { stream = object } else if (isBlobLike(object)) { // 3. Otherwise, if object is a Blob object, set stream to the // result of running object’s get stream. stream = object.stream() } else { // 4. Otherwise, set stream to a new ReadableStream object, and set // up stream. stream = new ReadableStream({ async pull (controller) { controller.enqueue( typeof source === 'string' ? textEncoder.encode(source) : source ) queueMicrotask(() => readableStreamClose(controller)) }, start () {}, type: undefined }) } // 5. Assert: stream is a ReadableStream object. assert(isReadableStreamLike(stream)) // 6. Let action be null. let action = null // 7. Let source be null. let source = null // 8. Let length be null. let length = null // 9. Let type be null. let type = null // 10. Switch on object: if (typeof object === 'string') { // Set source to the UTF-8 encoding of object. // Note: setting source to a Uint8Array here breaks some mocking assumptions. source = object // Set type to `text/plain;charset=UTF-8`. type = 'text/plain;charset=UTF-8' } else if (object instanceof URLSearchParams) { // URLSearchParams // spec says to run application/x-www-form-urlencoded on body.list // this is implemented in Node.js as apart of an URLSearchParams instance toString method // See: https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L490 // and https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L1100 // Set source to the result of running the application/x-www-form-urlencoded serializer with object’s list. source = object.toString() // Set type to `application/x-www-form-urlencoded;charset=UTF-8`. type = 'application/x-www-form-urlencoded;charset=UTF-8' } else if (isArrayBuffer(object)) { // BufferSource/ArrayBuffer // Set source to a copy of the bytes held by object. source = new Uint8Array(object.slice()) } else if (ArrayBuffer.isView(object)) { // BufferSource/ArrayBufferView // Set source to a copy of the bytes held by object. source = new Uint8Array(object.buffer.slice(object.byteOffset, object.byteOffset + object.byteLength)) } else if (util.isFormDataLike(object)) { const boundary = `----formdata-undici-0${`${Math.floor(Math.random() * 1e11)}`.padStart(11, '0')}` const prefix = `--${boundary}\r\nContent-Disposition: form-data` /*! formdata-polyfill. MIT License. Jimmy Wärting */ const escape = (str) => str.replace(/\n/g, '%0A').replace(/\r/g, '%0D').replace(/"/g, '%22') const normalizeLinefeeds = (value) => value.replace(/\r?\n|\r/g, '\r\n') // Set action to this step: run the multipart/form-data // encoding algorithm, with object’s entry list and UTF-8. // - This ensures that the body is immutable and can't be changed afterwords // - That the content-length is calculated in advance. // - And that all parts are pre-encoded and ready to be sent. const blobParts = [] const rn = new Uint8Array([13, 10]) // '\r\n' length = 0 let hasUnknownSizeValue = false for (const [name, value] of object) { if (typeof value === 'string') { const chunk = textEncoder.encode(prefix + `; name="${escape(normalizeLinefeeds(name))}"` + `\r\n\r\n${normalizeLinefeeds(value)}\r\n`) blobParts.push(chunk) length += chunk.byteLength } else { const chunk = textEncoder.encode(`${prefix}; name="${escape(normalizeLinefeeds(name))}"` + (value.name ? `; filename="${escape(value.name)}"` : '') + '\r\n' + `Content-Type: ${ value.type || 'application/octet-stream' }\r\n\r\n`) blobParts.push(chunk, value, rn) if (typeof value.size === 'number') { length += chunk.byteLength + value.size + rn.byteLength } else { hasUnknownSizeValue = true } } } const chunk = textEncoder.encode(`--${boundary}--`) blobParts.push(chunk) length += chunk.byteLength if (hasUnknownSizeValue) { length = null } // Set source to object. source = object action = async function * () { for (const part of blobParts) { if (part.stream) { yield * part.stream() } else { yield part } } } // Set type to `multipart/form-data; boundary=`, // followed by the multipart/form-data boundary string generated // by the multipart/form-data encoding algorithm. type = 'multipart/form-data; boundary=' + boundary } else if (isBlobLike(object)) { // Blob // Set source to object. source = object // Set length to object’s size. length = object.size // If object’s type attribute is not the empty byte sequence, set // type to its value. if (object.type) { type = object.type } } else if (typeof object[Symbol.asyncIterator] === 'function') { // If keepalive is true, then throw a TypeError. if (keepalive) { throw new TypeError('keepalive') } // If object is disturbed or locked, then throw a TypeError. if (util.isDisturbed(object) || object.locked) { throw new TypeError( 'Response body object should not be disturbed or locked' ) } stream = object instanceof ReadableStream ? object : ReadableStreamFrom(object) } // 11. If source is a byte sequence, then set action to a // step that returns source and length to source’s length. if (typeof source === 'string' || util.isBuffer(source)) { length = Buffer.byteLength(source) } // 12. If action is non-null, then run these steps in in parallel: if (action != null) { // Run action. let iterator stream = new ReadableStream({ async start () { iterator = action(object)[Symbol.asyncIterator]() }, async pull (controller) { const { value, done } = await iterator.next() if (done) { // When running action is done, close stream. queueMicrotask(() => { controller.close() }) } else { // Whenever one or more bytes are available and stream is not errored, // enqueue a Uint8Array wrapping an ArrayBuffer containing the available // bytes into stream. if (!isErrored(stream)) { controller.enqueue(new Uint8Array(value)) } } return controller.desiredSize > 0 }, async cancel (reason) { await iterator.return() }, type: undefined }) } // 13. Let body be a body whose stream is stream, source is source, // and length is length. const body = { stream, source, length } // 14. Return (body, type). return [body, type] } // https://fetch.spec.whatwg.org/#bodyinit-safely-extract function safelyExtractBody (object, keepalive = false) { if (!ReadableStream) { // istanbul ignore next ReadableStream = (__nccwpck_require__(35356).ReadableStream) } // To safely extract a body and a `Content-Type` value from // a byte sequence or BodyInit object object, run these steps: // 1. If object is a ReadableStream object, then: if (object instanceof ReadableStream) { // Assert: object is neither disturbed nor locked. // istanbul ignore next assert(!util.isDisturbed(object), 'The body has already been consumed.') // istanbul ignore next assert(!object.locked, 'The stream is locked.') } // 2. Return the results of extracting object. return extractBody(object, keepalive) } function cloneBody (body) { // To clone a body body, run these steps: // https://fetch.spec.whatwg.org/#concept-body-clone // 1. Let « out1, out2 » be the result of teeing body’s stream. const [out1, out2] = body.stream.tee() const out2Clone = structuredClone(out2, { transfer: [out2] }) // This, for whatever reasons, unrefs out2Clone which allows // the process to exit by itself. const [, finalClone] = out2Clone.tee() // 2. Set body’s stream to out1. body.stream = out1 // 3. Return a body whose stream is out2 and other members are copied from body. return { stream: finalClone, length: body.length, source: body.source } } async function * consumeBody (body) { if (body) { if (isUint8Array(body)) { yield body } else { const stream = body.stream if (util.isDisturbed(stream)) { throw new TypeError('The body has already been consumed.') } if (stream.locked) { throw new TypeError('The stream is locked.') } // Compat. stream[kBodyUsed] = true yield * stream } } } function throwIfAborted (state) { if (state.aborted) { throw new DOMException('The operation was aborted.', 'AbortError') } } function bodyMixinMethods (instance) { const methods = { blob () { // The blob() method steps are to return the result of // running consume body with this and the following step // given a byte sequence bytes: return a Blob whose // contents are bytes and whose type attribute is this’s // MIME type. return specConsumeBody(this, (bytes) => { let mimeType = bodyMimeType(this) if (mimeType === 'failure') { mimeType = '' } else if (mimeType) { mimeType = serializeAMimeType(mimeType) } // Return a Blob whose contents are bytes and type attribute // is mimeType. return new Blob([bytes], { type: mimeType }) }, instance) }, arrayBuffer () { // The arrayBuffer() method steps are to return the result // of running consume body with this and the following step // given a byte sequence bytes: return a new ArrayBuffer // whose contents are bytes. return specConsumeBody(this, (bytes) => { return new Uint8Array(bytes).buffer }, instance) }, text () { // The text() method steps are to return the result of running // consume body with this and UTF-8 decode. return specConsumeBody(this, utf8DecodeBytes, instance) }, json () { // The json() method steps are to return the result of running // consume body with this and parse JSON from bytes. return specConsumeBody(this, parseJSONFromBytes, instance) }, async formData () { webidl.brandCheck(this, instance) throwIfAborted(this[kState]) const contentType = this.headers.get('Content-Type') // If mimeType’s essence is "multipart/form-data", then: if (/multipart\/form-data/.test(contentType)) { const headers = {} for (const [key, value] of this.headers) headers[key.toLowerCase()] = value const responseFormData = new FormData() let busboy try { busboy = new Busboy({ headers, preservePath: true }) } catch (err) { throw new DOMException(`${err}`, 'AbortError') } busboy.on('field', (name, value) => { responseFormData.append(name, value) }) busboy.on('file', (name, value, filename, encoding, mimeType) => { const chunks = [] if (encoding === 'base64' || encoding.toLowerCase() === 'base64') { let base64chunk = '' value.on('data', (chunk) => { base64chunk += chunk.toString().replace(/[\r\n]/gm, '') const end = base64chunk.length - base64chunk.length % 4 chunks.push(Buffer.from(base64chunk.slice(0, end), 'base64')) base64chunk = base64chunk.slice(end) }) value.on('end', () => { chunks.push(Buffer.from(base64chunk, 'base64')) responseFormData.append(name, new File(chunks, filename, { type: mimeType })) }) } else { value.on('data', (chunk) => { chunks.push(chunk) }) value.on('end', () => { responseFormData.append(name, new File(chunks, filename, { type: mimeType })) }) } }) const busboyResolve = new Promise((resolve, reject) => { busboy.on('finish', resolve) busboy.on('error', (err) => reject(new TypeError(err))) }) if (this.body !== null) for await (const chunk of consumeBody(this[kState].body)) busboy.write(chunk) busboy.end() await busboyResolve return responseFormData } else if (/application\/x-www-form-urlencoded/.test(contentType)) { // Otherwise, if mimeType’s essence is "application/x-www-form-urlencoded", then: // 1. Let entries be the result of parsing bytes. let entries try { let text = '' // application/x-www-form-urlencoded parser will keep the BOM. // https://url.spec.whatwg.org/#concept-urlencoded-parser // Note that streaming decoder is stateful and cannot be reused const streamingDecoder = new TextDecoder('utf-8', { ignoreBOM: true }) for await (const chunk of consumeBody(this[kState].body)) { if (!isUint8Array(chunk)) { throw new TypeError('Expected Uint8Array chunk') } text += streamingDecoder.decode(chunk, { stream: true }) } text += streamingDecoder.decode() entries = new URLSearchParams(text) } catch (err) { // istanbul ignore next: Unclear when new URLSearchParams can fail on a string. // 2. If entries is failure, then throw a TypeError. throw Object.assign(new TypeError(), { cause: err }) } // 3. Return a new FormData object whose entries are entries. const formData = new FormData() for (const [name, value] of entries) { formData.append(name, value) } return formData } else { // Wait a tick before checking if the request has been aborted. // Otherwise, a TypeError can be thrown when an AbortError should. await Promise.resolve() throwIfAborted(this[kState]) // Otherwise, throw a TypeError. throw webidl.errors.exception({ header: `${instance.name}.formData`, message: 'Could not parse content as FormData.' }) } } } return methods } function mixinBody (prototype) { Object.assign(prototype.prototype, bodyMixinMethods(prototype)) } /** * @see https://fetch.spec.whatwg.org/#concept-body-consume-body * @param {Response|Request} object * @param {(value: unknown) => unknown} convertBytesToJSValue * @param {Response|Request} instance */ async function specConsumeBody (object, convertBytesToJSValue, instance) { webidl.brandCheck(object, instance) throwIfAborted(object[kState]) // 1. If object is unusable, then return a promise rejected // with a TypeError. if (bodyUnusable(object[kState].body)) { throw new TypeError('Body is unusable') } // 2. Let promise be a new promise. const promise = createDeferredPromise() // 3. Let errorSteps given error be to reject promise with error. const errorSteps = (error) => promise.reject(error) // 4. Let successSteps given a byte sequence data be to resolve // promise with the result of running convertBytesToJSValue // with data. If that threw an exception, then run errorSteps // with that exception. const successSteps = (data) => { try { promise.resolve(convertBytesToJSValue(data)) } catch (e) { errorSteps(e) } } // 5. If object’s body is null, then run successSteps with an // empty byte sequence. if (object[kState].body == null) { successSteps(new Uint8Array()) return promise.promise } // 6. Otherwise, fully read object’s body given successSteps, // errorSteps, and object’s relevant global object. await fullyReadBody(object[kState].body, successSteps, errorSteps) // 7. Return promise. return promise.promise } // https://fetch.spec.whatwg.org/#body-unusable function bodyUnusable (body) { // An object including the Body interface mixin is // said to be unusable if its body is non-null and // its body’s stream is disturbed or locked. return body != null && (body.stream.locked || util.isDisturbed(body.stream)) } /** * @see https://encoding.spec.whatwg.org/#utf-8-decode * @param {Buffer} buffer */ function utf8DecodeBytes (buffer) { if (buffer.length === 0) { return '' } // 1. Let buffer be the result of peeking three bytes from // ioQueue, converted to a byte sequence. // 2. If buffer is 0xEF 0xBB 0xBF, then read three // bytes from ioQueue. (Do nothing with those bytes.) if (buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) { buffer = buffer.subarray(3) } // 3. Process a queue with an instance of UTF-8’s // decoder, ioQueue, output, and "replacement". const output = textDecoder.decode(buffer) // 4. Return output. return output } /** * @see https://infra.spec.whatwg.org/#parse-json-bytes-to-a-javascript-value * @param {Uint8Array} bytes */ function parseJSONFromBytes (bytes) { return JSON.parse(utf8DecodeBytes(bytes)) } /** * @see https://fetch.spec.whatwg.org/#concept-body-mime-type * @param {import('./response').Response|import('./request').Request} object */ function bodyMimeType (object) { const { headersList } = object[kState] const contentType = headersList.get('content-type') if (contentType === null) { return 'failure' } return parseMIMEType(contentType) } module.exports = { extractBody, safelyExtractBody, cloneBody, mixinBody } /***/ }), /***/ 41037: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { MessageChannel, receiveMessageOnPort } = __nccwpck_require__(71267) const corsSafeListedMethods = ['GET', 'HEAD', 'POST'] const corsSafeListedMethodsSet = new Set(corsSafeListedMethods) const nullBodyStatus = [101, 204, 205, 304] const redirectStatus = [301, 302, 303, 307, 308] const redirectStatusSet = new Set(redirectStatus) // https://fetch.spec.whatwg.org/#block-bad-port const badPorts = [ '1', '7', '9', '11', '13', '15', '17', '19', '20', '21', '22', '23', '25', '37', '42', '43', '53', '69', '77', '79', '87', '95', '101', '102', '103', '104', '109', '110', '111', '113', '115', '117', '119', '123', '135', '137', '139', '143', '161', '179', '389', '427', '465', '512', '513', '514', '515', '526', '530', '531', '532', '540', '548', '554', '556', '563', '587', '601', '636', '989', '990', '993', '995', '1719', '1720', '1723', '2049', '3659', '4045', '5060', '5061', '6000', '6566', '6665', '6666', '6667', '6668', '6669', '6697', '10080' ] const badPortsSet = new Set(badPorts) // https://w3c.github.io/webappsec-referrer-policy/#referrer-policies const referrerPolicy = [ '', 'no-referrer', 'no-referrer-when-downgrade', 'same-origin', 'origin', 'strict-origin', 'origin-when-cross-origin', 'strict-origin-when-cross-origin', 'unsafe-url' ] const referrerPolicySet = new Set(referrerPolicy) const requestRedirect = ['follow', 'manual', 'error'] const safeMethods = ['GET', 'HEAD', 'OPTIONS', 'TRACE'] const safeMethodsSet = new Set(safeMethods) const requestMode = ['navigate', 'same-origin', 'no-cors', 'cors'] const requestCredentials = ['omit', 'same-origin', 'include'] const requestCache = [ 'default', 'no-store', 'reload', 'no-cache', 'force-cache', 'only-if-cached' ] // https://fetch.spec.whatwg.org/#request-body-header-name const requestBodyHeader = [ 'content-encoding', 'content-language', 'content-location', 'content-type', // See https://github.com/nodejs/undici/issues/2021 // 'Content-Length' is a forbidden header name, which is typically // removed in the Headers implementation. However, undici doesn't // filter out headers, so we add it here. 'content-length' ] // https://fetch.spec.whatwg.org/#enumdef-requestduplex const requestDuplex = [ 'half' ] // http://fetch.spec.whatwg.org/#forbidden-method const forbiddenMethods = ['CONNECT', 'TRACE', 'TRACK'] const forbiddenMethodsSet = new Set(forbiddenMethods) const subresource = [ 'audio', 'audioworklet', 'font', 'image', 'manifest', 'paintworklet', 'script', 'style', 'track', 'video', 'xslt', '' ] const subresourceSet = new Set(subresource) /** @type {globalThis['DOMException']} */ const DOMException = globalThis.DOMException ?? (() => { // DOMException was only made a global in Node v17.0.0, // but fetch supports >= v16.8. try { atob('~') } catch (err) { return Object.getPrototypeOf(err).constructor } })() let channel /** @type {globalThis['structuredClone']} */ const structuredClone = globalThis.structuredClone ?? // https://github.com/nodejs/node/blob/b27ae24dcc4251bad726d9d84baf678d1f707fed/lib/internal/structured_clone.js // structuredClone was added in v17.0.0, but fetch supports v16.8 function structuredClone (value, options = undefined) { if (arguments.length === 0) { throw new TypeError('missing argument') } if (!channel) { channel = new MessageChannel() } channel.port1.unref() channel.port2.unref() channel.port1.postMessage(value, options?.transfer) return receiveMessageOnPort(channel.port2).message } module.exports = { DOMException, structuredClone, subresource, forbiddenMethods, requestBodyHeader, referrerPolicy, requestRedirect, requestMode, requestCredentials, requestCache, redirectStatus, corsSafeListedMethods, nullBodyStatus, safeMethods, badPorts, requestDuplex, subresourceSet, badPortsSet, redirectStatusSet, corsSafeListedMethodsSet, safeMethodsSet, forbiddenMethodsSet, referrerPolicySet } /***/ }), /***/ 685: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const assert = __nccwpck_require__(39491) const { atob } = __nccwpck_require__(14300) const { isomorphicDecode } = __nccwpck_require__(52538) const encoder = new TextEncoder() /** * @see https://mimesniff.spec.whatwg.org/#http-token-code-point */ const HTTP_TOKEN_CODEPOINTS = /^[!#$%&'*+-.^_|~A-Za-z0-9]+$/ const HTTP_WHITESPACE_REGEX = /(\u000A|\u000D|\u0009|\u0020)/ // eslint-disable-line /** * @see https://mimesniff.spec.whatwg.org/#http-quoted-string-token-code-point */ const HTTP_QUOTED_STRING_TOKENS = /[\u0009|\u0020-\u007E|\u0080-\u00FF]/ // eslint-disable-line // https://fetch.spec.whatwg.org/#data-url-processor /** @param {URL} dataURL */ function dataURLProcessor (dataURL) { // 1. Assert: dataURL’s scheme is "data". assert(dataURL.protocol === 'data:') // 2. Let input be the result of running the URL // serializer on dataURL with exclude fragment // set to true. let input = URLSerializer(dataURL, true) // 3. Remove the leading "data:" string from input. input = input.slice(5) // 4. Let position point at the start of input. const position = { position: 0 } // 5. Let mimeType be the result of collecting a // sequence of code points that are not equal // to U+002C (,), given position. let mimeType = collectASequenceOfCodePointsFast( ',', input, position ) // 6. Strip leading and trailing ASCII whitespace // from mimeType. // Undici implementation note: we need to store the // length because if the mimetype has spaces removed, // the wrong amount will be sliced from the input in // step #9 const mimeTypeLength = mimeType.length mimeType = removeASCIIWhitespace(mimeType, true, true) // 7. If position is past the end of input, then // return failure if (position.position >= input.length) { return 'failure' } // 8. Advance position by 1. position.position++ // 9. Let encodedBody be the remainder of input. const encodedBody = input.slice(mimeTypeLength + 1) // 10. Let body be the percent-decoding of encodedBody. let body = stringPercentDecode(encodedBody) // 11. If mimeType ends with U+003B (;), followed by // zero or more U+0020 SPACE, followed by an ASCII // case-insensitive match for "base64", then: if (/;(\u0020){0,}base64$/i.test(mimeType)) { // 1. Let stringBody be the isomorphic decode of body. const stringBody = isomorphicDecode(body) // 2. Set body to the forgiving-base64 decode of // stringBody. body = forgivingBase64(stringBody) // 3. If body is failure, then return failure. if (body === 'failure') { return 'failure' } // 4. Remove the last 6 code points from mimeType. mimeType = mimeType.slice(0, -6) // 5. Remove trailing U+0020 SPACE code points from mimeType, // if any. mimeType = mimeType.replace(/(\u0020)+$/, '') // 6. Remove the last U+003B (;) code point from mimeType. mimeType = mimeType.slice(0, -1) } // 12. If mimeType starts with U+003B (;), then prepend // "text/plain" to mimeType. if (mimeType.startsWith(';')) { mimeType = 'text/plain' + mimeType } // 13. Let mimeTypeRecord be the result of parsing // mimeType. let mimeTypeRecord = parseMIMEType(mimeType) // 14. If mimeTypeRecord is failure, then set // mimeTypeRecord to text/plain;charset=US-ASCII. if (mimeTypeRecord === 'failure') { mimeTypeRecord = parseMIMEType('text/plain;charset=US-ASCII') } // 15. Return a new data: URL struct whose MIME // type is mimeTypeRecord and body is body. // https://fetch.spec.whatwg.org/#data-url-struct return { mimeType: mimeTypeRecord, body } } // https://url.spec.whatwg.org/#concept-url-serializer /** * @param {URL} url * @param {boolean} excludeFragment */ function URLSerializer (url, excludeFragment = false) { if (!excludeFragment) { return url.href } const href = url.href const hashLength = url.hash.length return hashLength === 0 ? href : href.substring(0, href.length - hashLength) } // https://infra.spec.whatwg.org/#collect-a-sequence-of-code-points /** * @param {(char: string) => boolean} condition * @param {string} input * @param {{ position: number }} position */ function collectASequenceOfCodePoints (condition, input, position) { // 1. Let result be the empty string. let result = '' // 2. While position doesn’t point past the end of input and the // code point at position within input meets the condition condition: while (position.position < input.length && condition(input[position.position])) { // 1. Append that code point to the end of result. result += input[position.position] // 2. Advance position by 1. position.position++ } // 3. Return result. return result } /** * A faster collectASequenceOfCodePoints that only works when comparing a single character. * @param {string} char * @param {string} input * @param {{ position: number }} position */ function collectASequenceOfCodePointsFast (char, input, position) { const idx = input.indexOf(char, position.position) const start = position.position if (idx === -1) { position.position = input.length return input.slice(start) } position.position = idx return input.slice(start, position.position) } // https://url.spec.whatwg.org/#string-percent-decode /** @param {string} input */ function stringPercentDecode (input) { // 1. Let bytes be the UTF-8 encoding of input. const bytes = encoder.encode(input) // 2. Return the percent-decoding of bytes. return percentDecode(bytes) } // https://url.spec.whatwg.org/#percent-decode /** @param {Uint8Array} input */ function percentDecode (input) { // 1. Let output be an empty byte sequence. /** @type {number[]} */ const output = [] // 2. For each byte byte in input: for (let i = 0; i < input.length; i++) { const byte = input[i] // 1. If byte is not 0x25 (%), then append byte to output. if (byte !== 0x25) { output.push(byte) // 2. Otherwise, if byte is 0x25 (%) and the next two bytes // after byte in input are not in the ranges // 0x30 (0) to 0x39 (9), 0x41 (A) to 0x46 (F), // and 0x61 (a) to 0x66 (f), all inclusive, append byte // to output. } else if ( byte === 0x25 && !/^[0-9A-Fa-f]{2}$/i.test(String.fromCharCode(input[i + 1], input[i + 2])) ) { output.push(0x25) // 3. Otherwise: } else { // 1. Let bytePoint be the two bytes after byte in input, // decoded, and then interpreted as hexadecimal number. const nextTwoBytes = String.fromCharCode(input[i + 1], input[i + 2]) const bytePoint = Number.parseInt(nextTwoBytes, 16) // 2. Append a byte whose value is bytePoint to output. output.push(bytePoint) // 3. Skip the next two bytes in input. i += 2 } } // 3. Return output. return Uint8Array.from(output) } // https://mimesniff.spec.whatwg.org/#parse-a-mime-type /** @param {string} input */ function parseMIMEType (input) { // 1. Remove any leading and trailing HTTP whitespace // from input. input = removeHTTPWhitespace(input, true, true) // 2. Let position be a position variable for input, // initially pointing at the start of input. const position = { position: 0 } // 3. Let type be the result of collecting a sequence // of code points that are not U+002F (/) from // input, given position. const type = collectASequenceOfCodePointsFast( '/', input, position ) // 4. If type is the empty string or does not solely // contain HTTP token code points, then return failure. // https://mimesniff.spec.whatwg.org/#http-token-code-point if (type.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(type)) { return 'failure' } // 5. If position is past the end of input, then return // failure if (position.position > input.length) { return 'failure' } // 6. Advance position by 1. (This skips past U+002F (/).) position.position++ // 7. Let subtype be the result of collecting a sequence of // code points that are not U+003B (;) from input, given // position. let subtype = collectASequenceOfCodePointsFast( ';', input, position ) // 8. Remove any trailing HTTP whitespace from subtype. subtype = removeHTTPWhitespace(subtype, false, true) // 9. If subtype is the empty string or does not solely // contain HTTP token code points, then return failure. if (subtype.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(subtype)) { return 'failure' } const typeLowercase = type.toLowerCase() const subtypeLowercase = subtype.toLowerCase() // 10. Let mimeType be a new MIME type record whose type // is type, in ASCII lowercase, and subtype is subtype, // in ASCII lowercase. // https://mimesniff.spec.whatwg.org/#mime-type const mimeType = { type: typeLowercase, subtype: subtypeLowercase, /** @type {Map} */ parameters: new Map(), // https://mimesniff.spec.whatwg.org/#mime-type-essence essence: `${typeLowercase}/${subtypeLowercase}` } // 11. While position is not past the end of input: while (position.position < input.length) { // 1. Advance position by 1. (This skips past U+003B (;).) position.position++ // 2. Collect a sequence of code points that are HTTP // whitespace from input given position. collectASequenceOfCodePoints( // https://fetch.spec.whatwg.org/#http-whitespace char => HTTP_WHITESPACE_REGEX.test(char), input, position ) // 3. Let parameterName be the result of collecting a // sequence of code points that are not U+003B (;) // or U+003D (=) from input, given position. let parameterName = collectASequenceOfCodePoints( (char) => char !== ';' && char !== '=', input, position ) // 4. Set parameterName to parameterName, in ASCII // lowercase. parameterName = parameterName.toLowerCase() // 5. If position is not past the end of input, then: if (position.position < input.length) { // 1. If the code point at position within input is // U+003B (;), then continue. if (input[position.position] === ';') { continue } // 2. Advance position by 1. (This skips past U+003D (=).) position.position++ } // 6. If position is past the end of input, then break. if (position.position > input.length) { break } // 7. Let parameterValue be null. let parameterValue = null // 8. If the code point at position within input is // U+0022 ("), then: if (input[position.position] === '"') { // 1. Set parameterValue to the result of collecting // an HTTP quoted string from input, given position // and the extract-value flag. parameterValue = collectAnHTTPQuotedString(input, position, true) // 2. Collect a sequence of code points that are not // U+003B (;) from input, given position. collectASequenceOfCodePointsFast( ';', input, position ) // 9. Otherwise: } else { // 1. Set parameterValue to the result of collecting // a sequence of code points that are not U+003B (;) // from input, given position. parameterValue = collectASequenceOfCodePointsFast( ';', input, position ) // 2. Remove any trailing HTTP whitespace from parameterValue. parameterValue = removeHTTPWhitespace(parameterValue, false, true) // 3. If parameterValue is the empty string, then continue. if (parameterValue.length === 0) { continue } } // 10. If all of the following are true // - parameterName is not the empty string // - parameterName solely contains HTTP token code points // - parameterValue solely contains HTTP quoted-string token code points // - mimeType’s parameters[parameterName] does not exist // then set mimeType’s parameters[parameterName] to parameterValue. if ( parameterName.length !== 0 && HTTP_TOKEN_CODEPOINTS.test(parameterName) && (parameterValue.length === 0 || HTTP_QUOTED_STRING_TOKENS.test(parameterValue)) && !mimeType.parameters.has(parameterName) ) { mimeType.parameters.set(parameterName, parameterValue) } } // 12. Return mimeType. return mimeType } // https://infra.spec.whatwg.org/#forgiving-base64-decode /** @param {string} data */ function forgivingBase64 (data) { // 1. Remove all ASCII whitespace from data. data = data.replace(/[\u0009\u000A\u000C\u000D\u0020]/g, '') // eslint-disable-line // 2. If data’s code point length divides by 4 leaving // no remainder, then: if (data.length % 4 === 0) { // 1. If data ends with one or two U+003D (=) code points, // then remove them from data. data = data.replace(/=?=$/, '') } // 3. If data’s code point length divides by 4 leaving // a remainder of 1, then return failure. if (data.length % 4 === 1) { return 'failure' } // 4. If data contains a code point that is not one of // U+002B (+) // U+002F (/) // ASCII alphanumeric // then return failure. if (/[^+/0-9A-Za-z]/.test(data)) { return 'failure' } const binary = atob(data) const bytes = new Uint8Array(binary.length) for (let byte = 0; byte < binary.length; byte++) { bytes[byte] = binary.charCodeAt(byte) } return bytes } // https://fetch.spec.whatwg.org/#collect-an-http-quoted-string // tests: https://fetch.spec.whatwg.org/#example-http-quoted-string /** * @param {string} input * @param {{ position: number }} position * @param {boolean?} extractValue */ function collectAnHTTPQuotedString (input, position, extractValue) { // 1. Let positionStart be position. const positionStart = position.position // 2. Let value be the empty string. let value = '' // 3. Assert: the code point at position within input // is U+0022 ("). assert(input[position.position] === '"') // 4. Advance position by 1. position.position++ // 5. While true: while (true) { // 1. Append the result of collecting a sequence of code points // that are not U+0022 (") or U+005C (\) from input, given // position, to value. value += collectASequenceOfCodePoints( (char) => char !== '"' && char !== '\\', input, position ) // 2. If position is past the end of input, then break. if (position.position >= input.length) { break } // 3. Let quoteOrBackslash be the code point at position within // input. const quoteOrBackslash = input[position.position] // 4. Advance position by 1. position.position++ // 5. If quoteOrBackslash is U+005C (\), then: if (quoteOrBackslash === '\\') { // 1. If position is past the end of input, then append // U+005C (\) to value and break. if (position.position >= input.length) { value += '\\' break } // 2. Append the code point at position within input to value. value += input[position.position] // 3. Advance position by 1. position.position++ // 6. Otherwise: } else { // 1. Assert: quoteOrBackslash is U+0022 ("). assert(quoteOrBackslash === '"') // 2. Break. break } } // 6. If the extract-value flag is set, then return value. if (extractValue) { return value } // 7. Return the code points from positionStart to position, // inclusive, within input. return input.slice(positionStart, position.position) } /** * @see https://mimesniff.spec.whatwg.org/#serialize-a-mime-type */ function serializeAMimeType (mimeType) { assert(mimeType !== 'failure') const { parameters, essence } = mimeType // 1. Let serialization be the concatenation of mimeType’s // type, U+002F (/), and mimeType’s subtype. let serialization = essence // 2. For each name → value of mimeType’s parameters: for (let [name, value] of parameters.entries()) { // 1. Append U+003B (;) to serialization. serialization += ';' // 2. Append name to serialization. serialization += name // 3. Append U+003D (=) to serialization. serialization += '=' // 4. If value does not solely contain HTTP token code // points or value is the empty string, then: if (!HTTP_TOKEN_CODEPOINTS.test(value)) { // 1. Precede each occurence of U+0022 (") or // U+005C (\) in value with U+005C (\). value = value.replace(/(\\|")/g, '\\$1') // 2. Prepend U+0022 (") to value. value = '"' + value // 3. Append U+0022 (") to value. value += '"' } // 5. Append value to serialization. serialization += value } // 3. Return serialization. return serialization } /** * @see https://fetch.spec.whatwg.org/#http-whitespace * @param {string} char */ function isHTTPWhiteSpace (char) { return char === '\r' || char === '\n' || char === '\t' || char === ' ' } /** * @see https://fetch.spec.whatwg.org/#http-whitespace * @param {string} str */ function removeHTTPWhitespace (str, leading = true, trailing = true) { let lead = 0 let trail = str.length - 1 if (leading) { for (; lead < str.length && isHTTPWhiteSpace(str[lead]); lead++); } if (trailing) { for (; trail > 0 && isHTTPWhiteSpace(str[trail]); trail--); } return str.slice(lead, trail + 1) } /** * @see https://infra.spec.whatwg.org/#ascii-whitespace * @param {string} char */ function isASCIIWhitespace (char) { return char === '\r' || char === '\n' || char === '\t' || char === '\f' || char === ' ' } /** * @see https://infra.spec.whatwg.org/#strip-leading-and-trailing-ascii-whitespace */ function removeASCIIWhitespace (str, leading = true, trailing = true) { let lead = 0 let trail = str.length - 1 if (leading) { for (; lead < str.length && isASCIIWhitespace(str[lead]); lead++); } if (trailing) { for (; trail > 0 && isASCIIWhitespace(str[trail]); trail--); } return str.slice(lead, trail + 1) } module.exports = { dataURLProcessor, URLSerializer, collectASequenceOfCodePoints, collectASequenceOfCodePointsFast, stringPercentDecode, parseMIMEType, collectAnHTTPQuotedString, serializeAMimeType } /***/ }), /***/ 78511: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { Blob, File: NativeFile } = __nccwpck_require__(14300) const { types } = __nccwpck_require__(73837) const { kState } = __nccwpck_require__(15861) const { isBlobLike } = __nccwpck_require__(52538) const { webidl } = __nccwpck_require__(21744) const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(685) const { kEnumerableProperty } = __nccwpck_require__(83983) const encoder = new TextEncoder() class File extends Blob { constructor (fileBits, fileName, options = {}) { // The File constructor is invoked with two or three parameters, depending // on whether the optional dictionary parameter is used. When the File() // constructor is invoked, user agents must run the following steps: webidl.argumentLengthCheck(arguments, 2, { header: 'File constructor' }) fileBits = webidl.converters['sequence'](fileBits) fileName = webidl.converters.USVString(fileName) options = webidl.converters.FilePropertyBag(options) // 1. Let bytes be the result of processing blob parts given fileBits and // options. // Note: Blob handles this for us // 2. Let n be the fileName argument to the constructor. const n = fileName // 3. Process FilePropertyBag dictionary argument by running the following // substeps: // 1. If the type member is provided and is not the empty string, let t // be set to the type dictionary member. If t contains any characters // outside the range U+0020 to U+007E, then set t to the empty string // and return from these substeps. // 2. Convert every character in t to ASCII lowercase. let t = options.type let d // eslint-disable-next-line no-labels substep: { if (t) { t = parseMIMEType(t) if (t === 'failure') { t = '' // eslint-disable-next-line no-labels break substep } t = serializeAMimeType(t).toLowerCase() } // 3. If the lastModified member is provided, let d be set to the // lastModified dictionary member. If it is not provided, set d to the // current date and time represented as the number of milliseconds since // the Unix Epoch (which is the equivalent of Date.now() [ECMA-262]). d = options.lastModified } // 4. Return a new File object F such that: // F refers to the bytes byte sequence. // F.size is set to the number of total bytes in bytes. // F.name is set to n. // F.type is set to t. // F.lastModified is set to d. super(processBlobParts(fileBits, options), { type: t }) this[kState] = { name: n, lastModified: d, type: t } } get name () { webidl.brandCheck(this, File) return this[kState].name } get lastModified () { webidl.brandCheck(this, File) return this[kState].lastModified } get type () { webidl.brandCheck(this, File) return this[kState].type } } class FileLike { constructor (blobLike, fileName, options = {}) { // TODO: argument idl type check // The File constructor is invoked with two or three parameters, depending // on whether the optional dictionary parameter is used. When the File() // constructor is invoked, user agents must run the following steps: // 1. Let bytes be the result of processing blob parts given fileBits and // options. // 2. Let n be the fileName argument to the constructor. const n = fileName // 3. Process FilePropertyBag dictionary argument by running the following // substeps: // 1. If the type member is provided and is not the empty string, let t // be set to the type dictionary member. If t contains any characters // outside the range U+0020 to U+007E, then set t to the empty string // and return from these substeps. // TODO const t = options.type // 2. Convert every character in t to ASCII lowercase. // TODO // 3. If the lastModified member is provided, let d be set to the // lastModified dictionary member. If it is not provided, set d to the // current date and time represented as the number of milliseconds since // the Unix Epoch (which is the equivalent of Date.now() [ECMA-262]). const d = options.lastModified ?? Date.now() // 4. Return a new File object F such that: // F refers to the bytes byte sequence. // F.size is set to the number of total bytes in bytes. // F.name is set to n. // F.type is set to t. // F.lastModified is set to d. this[kState] = { blobLike, name: n, type: t, lastModified: d } } stream (...args) { webidl.brandCheck(this, FileLike) return this[kState].blobLike.stream(...args) } arrayBuffer (...args) { webidl.brandCheck(this, FileLike) return this[kState].blobLike.arrayBuffer(...args) } slice (...args) { webidl.brandCheck(this, FileLike) return this[kState].blobLike.slice(...args) } text (...args) { webidl.brandCheck(this, FileLike) return this[kState].blobLike.text(...args) } get size () { webidl.brandCheck(this, FileLike) return this[kState].blobLike.size } get type () { webidl.brandCheck(this, FileLike) return this[kState].blobLike.type } get name () { webidl.brandCheck(this, FileLike) return this[kState].name } get lastModified () { webidl.brandCheck(this, FileLike) return this[kState].lastModified } get [Symbol.toStringTag] () { return 'File' } } Object.defineProperties(File.prototype, { [Symbol.toStringTag]: { value: 'File', configurable: true }, name: kEnumerableProperty, lastModified: kEnumerableProperty }) webidl.converters.Blob = webidl.interfaceConverter(Blob) webidl.converters.BlobPart = function (V, opts) { if (webidl.util.Type(V) === 'Object') { if (isBlobLike(V)) { return webidl.converters.Blob(V, { strict: false }) } if ( ArrayBuffer.isView(V) || types.isAnyArrayBuffer(V) ) { return webidl.converters.BufferSource(V, opts) } } return webidl.converters.USVString(V, opts) } webidl.converters['sequence'] = webidl.sequenceConverter( webidl.converters.BlobPart ) // https://www.w3.org/TR/FileAPI/#dfn-FilePropertyBag webidl.converters.FilePropertyBag = webidl.dictionaryConverter([ { key: 'lastModified', converter: webidl.converters['long long'], get defaultValue () { return Date.now() } }, { key: 'type', converter: webidl.converters.DOMString, defaultValue: '' }, { key: 'endings', converter: (value) => { value = webidl.converters.DOMString(value) value = value.toLowerCase() if (value !== 'native') { value = 'transparent' } return value }, defaultValue: 'transparent' } ]) /** * @see https://www.w3.org/TR/FileAPI/#process-blob-parts * @param {(NodeJS.TypedArray|Blob|string)[]} parts * @param {{ type: string, endings: string }} options */ function processBlobParts (parts, options) { // 1. Let bytes be an empty sequence of bytes. /** @type {NodeJS.TypedArray[]} */ const bytes = [] // 2. For each element in parts: for (const element of parts) { // 1. If element is a USVString, run the following substeps: if (typeof element === 'string') { // 1. Let s be element. let s = element // 2. If the endings member of options is "native", set s // to the result of converting line endings to native // of element. if (options.endings === 'native') { s = convertLineEndingsNative(s) } // 3. Append the result of UTF-8 encoding s to bytes. bytes.push(encoder.encode(s)) } else if ( types.isAnyArrayBuffer(element) || types.isTypedArray(element) ) { // 2. If element is a BufferSource, get a copy of the // bytes held by the buffer source, and append those // bytes to bytes. if (!element.buffer) { // ArrayBuffer bytes.push(new Uint8Array(element)) } else { bytes.push( new Uint8Array(element.buffer, element.byteOffset, element.byteLength) ) } } else if (isBlobLike(element)) { // 3. If element is a Blob, append the bytes it represents // to bytes. bytes.push(element) } } // 3. Return bytes. return bytes } /** * @see https://www.w3.org/TR/FileAPI/#convert-line-endings-to-native * @param {string} s */ function convertLineEndingsNative (s) { // 1. Let native line ending be be the code point U+000A LF. let nativeLineEnding = '\n' // 2. If the underlying platform’s conventions are to // represent newlines as a carriage return and line feed // sequence, set native line ending to the code point // U+000D CR followed by the code point U+000A LF. if (process.platform === 'win32') { nativeLineEnding = '\r\n' } return s.replace(/\r?\n/g, nativeLineEnding) } // If this function is moved to ./util.js, some tools (such as // rollup) will warn about circular dependencies. See: // https://github.com/nodejs/undici/issues/1629 function isFileLike (object) { return ( (NativeFile && object instanceof NativeFile) || object instanceof File || ( object && (typeof object.stream === 'function' || typeof object.arrayBuffer === 'function') && object[Symbol.toStringTag] === 'File' ) ) } module.exports = { File, FileLike, isFileLike } /***/ }), /***/ 72015: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { isBlobLike, toUSVString, makeIterator } = __nccwpck_require__(52538) const { kState } = __nccwpck_require__(15861) const { File: UndiciFile, FileLike, isFileLike } = __nccwpck_require__(78511) const { webidl } = __nccwpck_require__(21744) const { Blob, File: NativeFile } = __nccwpck_require__(14300) /** @type {globalThis['File']} */ const File = NativeFile ?? UndiciFile // https://xhr.spec.whatwg.org/#formdata class FormData { constructor (form) { if (form !== undefined) { throw webidl.errors.conversionFailed({ prefix: 'FormData constructor', argument: 'Argument 1', types: ['undefined'] }) } this[kState] = [] } append (name, value, filename = undefined) { webidl.brandCheck(this, FormData) webidl.argumentLengthCheck(arguments, 2, { header: 'FormData.append' }) if (arguments.length === 3 && !isBlobLike(value)) { throw new TypeError( "Failed to execute 'append' on 'FormData': parameter 2 is not of type 'Blob'" ) } // 1. Let value be value if given; otherwise blobValue. name = webidl.converters.USVString(name) value = isBlobLike(value) ? webidl.converters.Blob(value, { strict: false }) : webidl.converters.USVString(value) filename = arguments.length === 3 ? webidl.converters.USVString(filename) : undefined // 2. Let entry be the result of creating an entry with // name, value, and filename if given. const entry = makeEntry(name, value, filename) // 3. Append entry to this’s entry list. this[kState].push(entry) } delete (name) { webidl.brandCheck(this, FormData) webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.delete' }) name = webidl.converters.USVString(name) // The delete(name) method steps are to remove all entries whose name // is name from this’s entry list. this[kState] = this[kState].filter(entry => entry.name !== name) } get (name) { webidl.brandCheck(this, FormData) webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.get' }) name = webidl.converters.USVString(name) // 1. If there is no entry whose name is name in this’s entry list, // then return null. const idx = this[kState].findIndex((entry) => entry.name === name) if (idx === -1) { return null } // 2. Return the value of the first entry whose name is name from // this’s entry list. return this[kState][idx].value } getAll (name) { webidl.brandCheck(this, FormData) webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.getAll' }) name = webidl.converters.USVString(name) // 1. If there is no entry whose name is name in this’s entry list, // then return the empty list. // 2. Return the values of all entries whose name is name, in order, // from this’s entry list. return this[kState] .filter((entry) => entry.name === name) .map((entry) => entry.value) } has (name) { webidl.brandCheck(this, FormData) webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.has' }) name = webidl.converters.USVString(name) // The has(name) method steps are to return true if there is an entry // whose name is name in this’s entry list; otherwise false. return this[kState].findIndex((entry) => entry.name === name) !== -1 } set (name, value, filename = undefined) { webidl.brandCheck(this, FormData) webidl.argumentLengthCheck(arguments, 2, { header: 'FormData.set' }) if (arguments.length === 3 && !isBlobLike(value)) { throw new TypeError( "Failed to execute 'set' on 'FormData': parameter 2 is not of type 'Blob'" ) } // The set(name, value) and set(name, blobValue, filename) method steps // are: // 1. Let value be value if given; otherwise blobValue. name = webidl.converters.USVString(name) value = isBlobLike(value) ? webidl.converters.Blob(value, { strict: false }) : webidl.converters.USVString(value) filename = arguments.length === 3 ? toUSVString(filename) : undefined // 2. Let entry be the result of creating an entry with name, value, and // filename if given. const entry = makeEntry(name, value, filename) // 3. If there are entries in this’s entry list whose name is name, then // replace the first such entry with entry and remove the others. const idx = this[kState].findIndex((entry) => entry.name === name) if (idx !== -1) { this[kState] = [ ...this[kState].slice(0, idx), entry, ...this[kState].slice(idx + 1).filter((entry) => entry.name !== name) ] } else { // 4. Otherwise, append entry to this’s entry list. this[kState].push(entry) } } entries () { webidl.brandCheck(this, FormData) return makeIterator( () => this[kState].map(pair => [pair.name, pair.value]), 'FormData', 'key+value' ) } keys () { webidl.brandCheck(this, FormData) return makeIterator( () => this[kState].map(pair => [pair.name, pair.value]), 'FormData', 'key' ) } values () { webidl.brandCheck(this, FormData) return makeIterator( () => this[kState].map(pair => [pair.name, pair.value]), 'FormData', 'value' ) } /** * @param {(value: string, key: string, self: FormData) => void} callbackFn * @param {unknown} thisArg */ forEach (callbackFn, thisArg = globalThis) { webidl.brandCheck(this, FormData) webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.forEach' }) if (typeof callbackFn !== 'function') { throw new TypeError( "Failed to execute 'forEach' on 'FormData': parameter 1 is not of type 'Function'." ) } for (const [key, value] of this) { callbackFn.apply(thisArg, [value, key, this]) } } } FormData.prototype[Symbol.iterator] = FormData.prototype.entries Object.defineProperties(FormData.prototype, { [Symbol.toStringTag]: { value: 'FormData', configurable: true } }) /** * @see https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#create-an-entry * @param {string} name * @param {string|Blob} value * @param {?string} filename * @returns */ function makeEntry (name, value, filename) { // 1. Set name to the result of converting name into a scalar value string. // "To convert a string into a scalar value string, replace any surrogates // with U+FFFD." // see: https://nodejs.org/dist/latest-v18.x/docs/api/buffer.html#buftostringencoding-start-end name = Buffer.from(name).toString('utf8') // 2. If value is a string, then set value to the result of converting // value into a scalar value string. if (typeof value === 'string') { value = Buffer.from(value).toString('utf8') } else { // 3. Otherwise: // 1. If value is not a File object, then set value to a new File object, // representing the same bytes, whose name attribute value is "blob" if (!isFileLike(value)) { value = value instanceof Blob ? new File([value], 'blob', { type: value.type }) : new FileLike(value, 'blob', { type: value.type }) } // 2. If filename is given, then set value to a new File object, // representing the same bytes, whose name attribute is filename. if (filename !== undefined) { /** @type {FilePropertyBag} */ const options = { type: value.type, lastModified: value.lastModified } value = (NativeFile && value instanceof NativeFile) || value instanceof UndiciFile ? new File([value], filename, options) : new FileLike(value, filename, options) } } // 4. Return an entry whose name is name and whose value is value. return { name, value } } module.exports = { FormData } /***/ }), /***/ 71246: /***/ ((module) => { "use strict"; // In case of breaking changes, increase the version // number to avoid conflicts. const globalOrigin = Symbol.for('undici.globalOrigin.1') function getGlobalOrigin () { return globalThis[globalOrigin] } function setGlobalOrigin (newOrigin) { if (newOrigin === undefined) { Object.defineProperty(globalThis, globalOrigin, { value: undefined, writable: true, enumerable: false, configurable: false }) return } const parsedURL = new URL(newOrigin) if (parsedURL.protocol !== 'http:' && parsedURL.protocol !== 'https:') { throw new TypeError(`Only http & https urls are allowed, received ${parsedURL.protocol}`) } Object.defineProperty(globalThis, globalOrigin, { value: parsedURL, writable: true, enumerable: false, configurable: false }) } module.exports = { getGlobalOrigin, setGlobalOrigin } /***/ }), /***/ 10554: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // https://github.com/Ethan-Arrowood/undici-fetch const { kHeadersList, kConstruct } = __nccwpck_require__(72785) const { kGuard } = __nccwpck_require__(15861) const { kEnumerableProperty } = __nccwpck_require__(83983) const { makeIterator, isValidHeaderName, isValidHeaderValue } = __nccwpck_require__(52538) const { webidl } = __nccwpck_require__(21744) const assert = __nccwpck_require__(39491) const kHeadersMap = Symbol('headers map') const kHeadersSortedMap = Symbol('headers map sorted') /** * @param {number} code */ function isHTTPWhiteSpaceCharCode (code) { return code === 0x00a || code === 0x00d || code === 0x009 || code === 0x020 } /** * @see https://fetch.spec.whatwg.org/#concept-header-value-normalize * @param {string} potentialValue */ function headerValueNormalize (potentialValue) { // To normalize a byte sequence potentialValue, remove // any leading and trailing HTTP whitespace bytes from // potentialValue. let i = 0; let j = potentialValue.length while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(j - 1))) --j while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(i))) ++i return i === 0 && j === potentialValue.length ? potentialValue : potentialValue.substring(i, j) } function fill (headers, object) { // To fill a Headers object headers with a given object object, run these steps: // 1. If object is a sequence, then for each header in object: // Note: webidl conversion to array has already been done. if (Array.isArray(object)) { for (let i = 0; i < object.length; ++i) { const header = object[i] // 1. If header does not contain exactly two items, then throw a TypeError. if (header.length !== 2) { throw webidl.errors.exception({ header: 'Headers constructor', message: `expected name/value pair to be length 2, found ${header.length}.` }) } // 2. Append (header’s first item, header’s second item) to headers. appendHeader(headers, header[0], header[1]) } } else if (typeof object === 'object' && object !== null) { // Note: null should throw // 2. Otherwise, object is a record, then for each key → value in object, // append (key, value) to headers const keys = Object.keys(object) for (let i = 0; i < keys.length; ++i) { appendHeader(headers, keys[i], object[keys[i]]) } } else { throw webidl.errors.conversionFailed({ prefix: 'Headers constructor', argument: 'Argument 1', types: ['sequence>', 'record'] }) } } /** * @see https://fetch.spec.whatwg.org/#concept-headers-append */ function appendHeader (headers, name, value) { // 1. Normalize value. value = headerValueNormalize(value) // 2. If name is not a header name or value is not a // header value, then throw a TypeError. if (!isValidHeaderName(name)) { throw webidl.errors.invalidArgument({ prefix: 'Headers.append', value: name, type: 'header name' }) } else if (!isValidHeaderValue(value)) { throw webidl.errors.invalidArgument({ prefix: 'Headers.append', value, type: 'header value' }) } // 3. If headers’s guard is "immutable", then throw a TypeError. // 4. Otherwise, if headers’s guard is "request" and name is a // forbidden header name, return. // Note: undici does not implement forbidden header names if (headers[kGuard] === 'immutable') { throw new TypeError('immutable') } else if (headers[kGuard] === 'request-no-cors') { // 5. Otherwise, if headers’s guard is "request-no-cors": // TODO } // 6. Otherwise, if headers’s guard is "response" and name is a // forbidden response-header name, return. // 7. Append (name, value) to headers’s header list. return headers[kHeadersList].append(name, value) // 8. If headers’s guard is "request-no-cors", then remove // privileged no-CORS request headers from headers } class HeadersList { /** @type {[string, string][]|null} */ cookies = null constructor (init) { if (init instanceof HeadersList) { this[kHeadersMap] = new Map(init[kHeadersMap]) this[kHeadersSortedMap] = init[kHeadersSortedMap] this.cookies = init.cookies === null ? null : [...init.cookies] } else { this[kHeadersMap] = new Map(init) this[kHeadersSortedMap] = null } } // https://fetch.spec.whatwg.org/#header-list-contains contains (name) { // A header list list contains a header name name if list // contains a header whose name is a byte-case-insensitive // match for name. name = name.toLowerCase() return this[kHeadersMap].has(name) } clear () { this[kHeadersMap].clear() this[kHeadersSortedMap] = null this.cookies = null } // https://fetch.spec.whatwg.org/#concept-header-list-append append (name, value) { this[kHeadersSortedMap] = null // 1. If list contains name, then set name to the first such // header’s name. const lowercaseName = name.toLowerCase() const exists = this[kHeadersMap].get(lowercaseName) // 2. Append (name, value) to list. if (exists) { const delimiter = lowercaseName === 'cookie' ? '; ' : ', ' this[kHeadersMap].set(lowercaseName, { name: exists.name, value: `${exists.value}${delimiter}${value}` }) } else { this[kHeadersMap].set(lowercaseName, { name, value }) } if (lowercaseName === 'set-cookie') { this.cookies ??= [] this.cookies.push(value) } } // https://fetch.spec.whatwg.org/#concept-header-list-set set (name, value) { this[kHeadersSortedMap] = null const lowercaseName = name.toLowerCase() if (lowercaseName === 'set-cookie') { this.cookies = [value] } // 1. If list contains name, then set the value of // the first such header to value and remove the // others. // 2. Otherwise, append header (name, value) to list. this[kHeadersMap].set(lowercaseName, { name, value }) } // https://fetch.spec.whatwg.org/#concept-header-list-delete delete (name) { this[kHeadersSortedMap] = null name = name.toLowerCase() if (name === 'set-cookie') { this.cookies = null } this[kHeadersMap].delete(name) } // https://fetch.spec.whatwg.org/#concept-header-list-get get (name) { const value = this[kHeadersMap].get(name.toLowerCase()) // 1. If list does not contain name, then return null. // 2. Return the values of all headers in list whose name // is a byte-case-insensitive match for name, // separated from each other by 0x2C 0x20, in order. return value === undefined ? null : value.value } * [Symbol.iterator] () { // use the lowercased name for (const [name, { value }] of this[kHeadersMap]) { yield [name, value] } } get entries () { const headers = {} if (this[kHeadersMap].size) { for (const { name, value } of this[kHeadersMap].values()) { headers[name] = value } } return headers } } // https://fetch.spec.whatwg.org/#headers-class class Headers { constructor (init = undefined) { if (init === kConstruct) { return } this[kHeadersList] = new HeadersList() // The new Headers(init) constructor steps are: // 1. Set this’s guard to "none". this[kGuard] = 'none' // 2. If init is given, then fill this with init. if (init !== undefined) { init = webidl.converters.HeadersInit(init) fill(this, init) } } // https://fetch.spec.whatwg.org/#dom-headers-append append (name, value) { webidl.brandCheck(this, Headers) webidl.argumentLengthCheck(arguments, 2, { header: 'Headers.append' }) name = webidl.converters.ByteString(name) value = webidl.converters.ByteString(value) return appendHeader(this, name, value) } // https://fetch.spec.whatwg.org/#dom-headers-delete delete (name) { webidl.brandCheck(this, Headers) webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.delete' }) name = webidl.converters.ByteString(name) // 1. If name is not a header name, then throw a TypeError. if (!isValidHeaderName(name)) { throw webidl.errors.invalidArgument({ prefix: 'Headers.delete', value: name, type: 'header name' }) } // 2. If this’s guard is "immutable", then throw a TypeError. // 3. Otherwise, if this’s guard is "request" and name is a // forbidden header name, return. // 4. Otherwise, if this’s guard is "request-no-cors", name // is not a no-CORS-safelisted request-header name, and // name is not a privileged no-CORS request-header name, // return. // 5. Otherwise, if this’s guard is "response" and name is // a forbidden response-header name, return. // Note: undici does not implement forbidden header names if (this[kGuard] === 'immutable') { throw new TypeError('immutable') } else if (this[kGuard] === 'request-no-cors') { // TODO } // 6. If this’s header list does not contain name, then // return. if (!this[kHeadersList].contains(name)) { return } // 7. Delete name from this’s header list. // 8. If this’s guard is "request-no-cors", then remove // privileged no-CORS request headers from this. this[kHeadersList].delete(name) } // https://fetch.spec.whatwg.org/#dom-headers-get get (name) { webidl.brandCheck(this, Headers) webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.get' }) name = webidl.converters.ByteString(name) // 1. If name is not a header name, then throw a TypeError. if (!isValidHeaderName(name)) { throw webidl.errors.invalidArgument({ prefix: 'Headers.get', value: name, type: 'header name' }) } // 2. Return the result of getting name from this’s header // list. return this[kHeadersList].get(name) } // https://fetch.spec.whatwg.org/#dom-headers-has has (name) { webidl.brandCheck(this, Headers) webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.has' }) name = webidl.converters.ByteString(name) // 1. If name is not a header name, then throw a TypeError. if (!isValidHeaderName(name)) { throw webidl.errors.invalidArgument({ prefix: 'Headers.has', value: name, type: 'header name' }) } // 2. Return true if this’s header list contains name; // otherwise false. return this[kHeadersList].contains(name) } // https://fetch.spec.whatwg.org/#dom-headers-set set (name, value) { webidl.brandCheck(this, Headers) webidl.argumentLengthCheck(arguments, 2, { header: 'Headers.set' }) name = webidl.converters.ByteString(name) value = webidl.converters.ByteString(value) // 1. Normalize value. value = headerValueNormalize(value) // 2. If name is not a header name or value is not a // header value, then throw a TypeError. if (!isValidHeaderName(name)) { throw webidl.errors.invalidArgument({ prefix: 'Headers.set', value: name, type: 'header name' }) } else if (!isValidHeaderValue(value)) { throw webidl.errors.invalidArgument({ prefix: 'Headers.set', value, type: 'header value' }) } // 3. If this’s guard is "immutable", then throw a TypeError. // 4. Otherwise, if this’s guard is "request" and name is a // forbidden header name, return. // 5. Otherwise, if this’s guard is "request-no-cors" and // name/value is not a no-CORS-safelisted request-header, // return. // 6. Otherwise, if this’s guard is "response" and name is a // forbidden response-header name, return. // Note: undici does not implement forbidden header names if (this[kGuard] === 'immutable') { throw new TypeError('immutable') } else if (this[kGuard] === 'request-no-cors') { // TODO } // 7. Set (name, value) in this’s header list. // 8. If this’s guard is "request-no-cors", then remove // privileged no-CORS request headers from this this[kHeadersList].set(name, value) } // https://fetch.spec.whatwg.org/#dom-headers-getsetcookie getSetCookie () { webidl.brandCheck(this, Headers) // 1. If this’s header list does not contain `Set-Cookie`, then return « ». // 2. Return the values of all headers in this’s header list whose name is // a byte-case-insensitive match for `Set-Cookie`, in order. const list = this[kHeadersList].cookies if (list) { return [...list] } return [] } // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine get [kHeadersSortedMap] () { if (this[kHeadersList][kHeadersSortedMap]) { return this[kHeadersList][kHeadersSortedMap] } // 1. Let headers be an empty list of headers with the key being the name // and value the value. const headers = [] // 2. Let names be the result of convert header names to a sorted-lowercase // set with all the names of the headers in list. const names = [...this[kHeadersList]].sort((a, b) => a[0] < b[0] ? -1 : 1) const cookies = this[kHeadersList].cookies // 3. For each name of names: for (let i = 0; i < names.length; ++i) { const [name, value] = names[i] // 1. If name is `set-cookie`, then: if (name === 'set-cookie') { // 1. Let values be a list of all values of headers in list whose name // is a byte-case-insensitive match for name, in order. // 2. For each value of values: // 1. Append (name, value) to headers. for (let j = 0; j < cookies.length; ++j) { headers.push([name, cookies[j]]) } } else { // 2. Otherwise: // 1. Let value be the result of getting name from list. // 2. Assert: value is non-null. assert(value !== null) // 3. Append (name, value) to headers. headers.push([name, value]) } } this[kHeadersList][kHeadersSortedMap] = headers // 4. Return headers. return headers } keys () { webidl.brandCheck(this, Headers) if (this[kGuard] === 'immutable') { const value = this[kHeadersSortedMap] return makeIterator(() => value, 'Headers', 'key') } return makeIterator( () => [...this[kHeadersSortedMap].values()], 'Headers', 'key' ) } values () { webidl.brandCheck(this, Headers) if (this[kGuard] === 'immutable') { const value = this[kHeadersSortedMap] return makeIterator(() => value, 'Headers', 'value') } return makeIterator( () => [...this[kHeadersSortedMap].values()], 'Headers', 'value' ) } entries () { webidl.brandCheck(this, Headers) if (this[kGuard] === 'immutable') { const value = this[kHeadersSortedMap] return makeIterator(() => value, 'Headers', 'key+value') } return makeIterator( () => [...this[kHeadersSortedMap].values()], 'Headers', 'key+value' ) } /** * @param {(value: string, key: string, self: Headers) => void} callbackFn * @param {unknown} thisArg */ forEach (callbackFn, thisArg = globalThis) { webidl.brandCheck(this, Headers) webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.forEach' }) if (typeof callbackFn !== 'function') { throw new TypeError( "Failed to execute 'forEach' on 'Headers': parameter 1 is not of type 'Function'." ) } for (const [key, value] of this) { callbackFn.apply(thisArg, [value, key, this]) } } [Symbol.for('nodejs.util.inspect.custom')] () { webidl.brandCheck(this, Headers) return this[kHeadersList] } } Headers.prototype[Symbol.iterator] = Headers.prototype.entries Object.defineProperties(Headers.prototype, { append: kEnumerableProperty, delete: kEnumerableProperty, get: kEnumerableProperty, has: kEnumerableProperty, set: kEnumerableProperty, getSetCookie: kEnumerableProperty, keys: kEnumerableProperty, values: kEnumerableProperty, entries: kEnumerableProperty, forEach: kEnumerableProperty, [Symbol.iterator]: { enumerable: false }, [Symbol.toStringTag]: { value: 'Headers', configurable: true } }) webidl.converters.HeadersInit = function (V) { if (webidl.util.Type(V) === 'Object') { if (V[Symbol.iterator]) { return webidl.converters['sequence>'](V) } return webidl.converters['record'](V) } throw webidl.errors.conversionFailed({ prefix: 'Headers constructor', argument: 'Argument 1', types: ['sequence>', 'record'] }) } module.exports = { fill, Headers, HeadersList } /***/ }), /***/ 74881: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // https://github.com/Ethan-Arrowood/undici-fetch const { Response, makeNetworkError, makeAppropriateNetworkError, filterResponse, makeResponse } = __nccwpck_require__(27823) const { Headers } = __nccwpck_require__(10554) const { Request, makeRequest } = __nccwpck_require__(48359) const zlib = __nccwpck_require__(59796) const { bytesMatch, makePolicyContainer, clonePolicyContainer, requestBadPort, TAOCheck, appendRequestOriginHeader, responseLocationURL, requestCurrentURL, setRequestReferrerPolicyOnRedirect, tryUpgradeRequestToAPotentiallyTrustworthyURL, createOpaqueTimingInfo, appendFetchMetadata, corsCheck, crossOriginResourcePolicyCheck, determineRequestsReferrer, coarsenedSharedCurrentTime, createDeferredPromise, isBlobLike, sameOrigin, isCancelled, isAborted, isErrorLike, fullyReadBody, readableStreamClose, isomorphicEncode, urlIsLocal, urlIsHttpHttpsScheme, urlHasHttpsScheme } = __nccwpck_require__(52538) const { kState, kHeaders, kGuard, kRealm } = __nccwpck_require__(15861) const assert = __nccwpck_require__(39491) const { safelyExtractBody } = __nccwpck_require__(41472) const { redirectStatusSet, nullBodyStatus, safeMethodsSet, requestBodyHeader, subresourceSet, DOMException } = __nccwpck_require__(41037) const { kHeadersList } = __nccwpck_require__(72785) const EE = __nccwpck_require__(82361) const { Readable, pipeline } = __nccwpck_require__(12781) const { addAbortListener, isErrored, isReadable, nodeMajor, nodeMinor } = __nccwpck_require__(83983) const { dataURLProcessor, serializeAMimeType } = __nccwpck_require__(685) const { TransformStream } = __nccwpck_require__(35356) const { getGlobalDispatcher } = __nccwpck_require__(21892) const { webidl } = __nccwpck_require__(21744) const { STATUS_CODES } = __nccwpck_require__(13685) const GET_OR_HEAD = ['GET', 'HEAD'] /** @type {import('buffer').resolveObjectURL} */ let resolveObjectURL let ReadableStream = globalThis.ReadableStream class Fetch extends EE { constructor (dispatcher) { super() this.dispatcher = dispatcher this.connection = null this.dump = false this.state = 'ongoing' // 2 terminated listeners get added per request, // but only 1 gets removed. If there are 20 redirects, // 21 listeners will be added. // See https://github.com/nodejs/undici/issues/1711 // TODO (fix): Find and fix root cause for leaked listener. this.setMaxListeners(21) } terminate (reason) { if (this.state !== 'ongoing') { return } this.state = 'terminated' this.connection?.destroy(reason) this.emit('terminated', reason) } // https://fetch.spec.whatwg.org/#fetch-controller-abort abort (error) { if (this.state !== 'ongoing') { return } // 1. Set controller’s state to "aborted". this.state = 'aborted' // 2. Let fallbackError be an "AbortError" DOMException. // 3. Set error to fallbackError if it is not given. if (!error) { error = new DOMException('The operation was aborted.', 'AbortError') } // 4. Let serializedError be StructuredSerialize(error). // If that threw an exception, catch it, and let // serializedError be StructuredSerialize(fallbackError). // 5. Set controller’s serialized abort reason to serializedError. this.serializedAbortReason = error this.connection?.destroy(error) this.emit('terminated', error) } } // https://fetch.spec.whatwg.org/#fetch-method function fetch (input, init = {}) { webidl.argumentLengthCheck(arguments, 1, { header: 'globalThis.fetch' }) // 1. Let p be a new promise. const p = createDeferredPromise() // 2. Let requestObject be the result of invoking the initial value of // Request as constructor with input and init as arguments. If this throws // an exception, reject p with it and return p. let requestObject try { requestObject = new Request(input, init) } catch (e) { p.reject(e) return p.promise } // 3. Let request be requestObject’s request. const request = requestObject[kState] // 4. If requestObject’s signal’s aborted flag is set, then: if (requestObject.signal.aborted) { // 1. Abort the fetch() call with p, request, null, and // requestObject’s signal’s abort reason. abortFetch(p, request, null, requestObject.signal.reason) // 2. Return p. return p.promise } // 5. Let globalObject be request’s client’s global object. const globalObject = request.client.globalObject // 6. If globalObject is a ServiceWorkerGlobalScope object, then set // request’s service-workers mode to "none". if (globalObject?.constructor?.name === 'ServiceWorkerGlobalScope') { request.serviceWorkers = 'none' } // 7. Let responseObject be null. let responseObject = null // 8. Let relevantRealm be this’s relevant Realm. const relevantRealm = null // 9. Let locallyAborted be false. let locallyAborted = false // 10. Let controller be null. let controller = null // 11. Add the following abort steps to requestObject’s signal: addAbortListener( requestObject.signal, () => { // 1. Set locallyAborted to true. locallyAborted = true // 2. Assert: controller is non-null. assert(controller != null) // 3. Abort controller with requestObject’s signal’s abort reason. controller.abort(requestObject.signal.reason) // 4. Abort the fetch() call with p, request, responseObject, // and requestObject’s signal’s abort reason. abortFetch(p, request, responseObject, requestObject.signal.reason) } ) // 12. Let handleFetchDone given response response be to finalize and // report timing with response, globalObject, and "fetch". const handleFetchDone = (response) => finalizeAndReportTiming(response, 'fetch') // 13. Set controller to the result of calling fetch given request, // with processResponseEndOfBody set to handleFetchDone, and processResponse // given response being these substeps: const processResponse = (response) => { // 1. If locallyAborted is true, terminate these substeps. if (locallyAborted) { return Promise.resolve() } // 2. If response’s aborted flag is set, then: if (response.aborted) { // 1. Let deserializedError be the result of deserialize a serialized // abort reason given controller’s serialized abort reason and // relevantRealm. // 2. Abort the fetch() call with p, request, responseObject, and // deserializedError. abortFetch(p, request, responseObject, controller.serializedAbortReason) return Promise.resolve() } // 3. If response is a network error, then reject p with a TypeError // and terminate these substeps. if (response.type === 'error') { p.reject( Object.assign(new TypeError('fetch failed'), { cause: response.error }) ) return Promise.resolve() } // 4. Set responseObject to the result of creating a Response object, // given response, "immutable", and relevantRealm. responseObject = new Response() responseObject[kState] = response responseObject[kRealm] = relevantRealm responseObject[kHeaders][kHeadersList] = response.headersList responseObject[kHeaders][kGuard] = 'immutable' responseObject[kHeaders][kRealm] = relevantRealm // 5. Resolve p with responseObject. p.resolve(responseObject) } controller = fetching({ request, processResponseEndOfBody: handleFetchDone, processResponse, dispatcher: init.dispatcher ?? getGlobalDispatcher() // undici }) // 14. Return p. return p.promise } // https://fetch.spec.whatwg.org/#finalize-and-report-timing function finalizeAndReportTiming (response, initiatorType = 'other') { // 1. If response is an aborted network error, then return. if (response.type === 'error' && response.aborted) { return } // 2. If response’s URL list is null or empty, then return. if (!response.urlList?.length) { return } // 3. Let originalURL be response’s URL list[0]. const originalURL = response.urlList[0] // 4. Let timingInfo be response’s timing info. let timingInfo = response.timingInfo // 5. Let cacheState be response’s cache state. let cacheState = response.cacheState // 6. If originalURL’s scheme is not an HTTP(S) scheme, then return. if (!urlIsHttpHttpsScheme(originalURL)) { return } // 7. If timingInfo is null, then return. if (timingInfo === null) { return } // 8. If response’s timing allow passed flag is not set, then: if (!response.timingAllowPassed) { // 1. Set timingInfo to a the result of creating an opaque timing info for timingInfo. timingInfo = createOpaqueTimingInfo({ startTime: timingInfo.startTime }) // 2. Set cacheState to the empty string. cacheState = '' } // 9. Set timingInfo’s end time to the coarsened shared current time // given global’s relevant settings object’s cross-origin isolated // capability. // TODO: given global’s relevant settings object’s cross-origin isolated // capability? timingInfo.endTime = coarsenedSharedCurrentTime() // 10. Set response’s timing info to timingInfo. response.timingInfo = timingInfo // 11. Mark resource timing for timingInfo, originalURL, initiatorType, // global, and cacheState. markResourceTiming( timingInfo, originalURL, initiatorType, globalThis, cacheState ) } // https://w3c.github.io/resource-timing/#dfn-mark-resource-timing function markResourceTiming (timingInfo, originalURL, initiatorType, globalThis, cacheState) { if (nodeMajor > 18 || (nodeMajor === 18 && nodeMinor >= 2)) { performance.markResourceTiming(timingInfo, originalURL.href, initiatorType, globalThis, cacheState) } } // https://fetch.spec.whatwg.org/#abort-fetch function abortFetch (p, request, responseObject, error) { // Note: AbortSignal.reason was added in node v17.2.0 // which would give us an undefined error to reject with. // Remove this once node v16 is no longer supported. if (!error) { error = new DOMException('The operation was aborted.', 'AbortError') } // 1. Reject promise with error. p.reject(error) // 2. If request’s body is not null and is readable, then cancel request’s // body with error. if (request.body != null && isReadable(request.body?.stream)) { request.body.stream.cancel(error).catch((err) => { if (err.code === 'ERR_INVALID_STATE') { // Node bug? return } throw err }) } // 3. If responseObject is null, then return. if (responseObject == null) { return } // 4. Let response be responseObject’s response. const response = responseObject[kState] // 5. If response’s body is not null and is readable, then error response’s // body with error. if (response.body != null && isReadable(response.body?.stream)) { response.body.stream.cancel(error).catch((err) => { if (err.code === 'ERR_INVALID_STATE') { // Node bug? return } throw err }) } } // https://fetch.spec.whatwg.org/#fetching function fetching ({ request, processRequestBodyChunkLength, processRequestEndOfBody, processResponse, processResponseEndOfBody, processResponseConsumeBody, useParallelQueue = false, dispatcher // undici }) { // 1. Let taskDestination be null. let taskDestination = null // 2. Let crossOriginIsolatedCapability be false. let crossOriginIsolatedCapability = false // 3. If request’s client is non-null, then: if (request.client != null) { // 1. Set taskDestination to request’s client’s global object. taskDestination = request.client.globalObject // 2. Set crossOriginIsolatedCapability to request’s client’s cross-origin // isolated capability. crossOriginIsolatedCapability = request.client.crossOriginIsolatedCapability } // 4. If useParallelQueue is true, then set taskDestination to the result of // starting a new parallel queue. // TODO // 5. Let timingInfo be a new fetch timing info whose start time and // post-redirect start time are the coarsened shared current time given // crossOriginIsolatedCapability. const currenTime = coarsenedSharedCurrentTime(crossOriginIsolatedCapability) const timingInfo = createOpaqueTimingInfo({ startTime: currenTime }) // 6. Let fetchParams be a new fetch params whose // request is request, // timing info is timingInfo, // process request body chunk length is processRequestBodyChunkLength, // process request end-of-body is processRequestEndOfBody, // process response is processResponse, // process response consume body is processResponseConsumeBody, // process response end-of-body is processResponseEndOfBody, // task destination is taskDestination, // and cross-origin isolated capability is crossOriginIsolatedCapability. const fetchParams = { controller: new Fetch(dispatcher), request, timingInfo, processRequestBodyChunkLength, processRequestEndOfBody, processResponse, processResponseConsumeBody, processResponseEndOfBody, taskDestination, crossOriginIsolatedCapability } // 7. If request’s body is a byte sequence, then set request’s body to // request’s body as a body. // NOTE: Since fetching is only called from fetch, body should already be // extracted. assert(!request.body || request.body.stream) // 8. If request’s window is "client", then set request’s window to request’s // client, if request’s client’s global object is a Window object; otherwise // "no-window". if (request.window === 'client') { // TODO: What if request.client is null? request.window = request.client?.globalObject?.constructor?.name === 'Window' ? request.client : 'no-window' } // 9. If request’s origin is "client", then set request’s origin to request’s // client’s origin. if (request.origin === 'client') { // TODO: What if request.client is null? request.origin = request.client?.origin } // 10. If all of the following conditions are true: // TODO // 11. If request’s policy container is "client", then: if (request.policyContainer === 'client') { // 1. If request’s client is non-null, then set request’s policy // container to a clone of request’s client’s policy container. [HTML] if (request.client != null) { request.policyContainer = clonePolicyContainer( request.client.policyContainer ) } else { // 2. Otherwise, set request’s policy container to a new policy // container. request.policyContainer = makePolicyContainer() } } // 12. If request’s header list does not contain `Accept`, then: if (!request.headersList.contains('accept')) { // 1. Let value be `*/*`. const value = '*/*' // 2. A user agent should set value to the first matching statement, if // any, switching on request’s destination: // "document" // "frame" // "iframe" // `text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8` // "image" // `image/png,image/svg+xml,image/*;q=0.8,*/*;q=0.5` // "style" // `text/css,*/*;q=0.1` // TODO // 3. Append `Accept`/value to request’s header list. request.headersList.append('accept', value) } // 13. If request’s header list does not contain `Accept-Language`, then // user agents should append `Accept-Language`/an appropriate value to // request’s header list. if (!request.headersList.contains('accept-language')) { request.headersList.append('accept-language', '*') } // 14. If request’s priority is null, then use request’s initiator and // destination appropriately in setting request’s priority to a // user-agent-defined object. if (request.priority === null) { // TODO } // 15. If request is a subresource request, then: if (subresourceSet.has(request.destination)) { // TODO } // 16. Run main fetch given fetchParams. mainFetch(fetchParams) .catch(err => { fetchParams.controller.terminate(err) }) // 17. Return fetchParam's controller return fetchParams.controller } // https://fetch.spec.whatwg.org/#concept-main-fetch async function mainFetch (fetchParams, recursive = false) { // 1. Let request be fetchParams’s request. const request = fetchParams.request // 2. Let response be null. let response = null // 3. If request’s local-URLs-only flag is set and request’s current URL is // not local, then set response to a network error. if (request.localURLsOnly && !urlIsLocal(requestCurrentURL(request))) { response = makeNetworkError('local URLs only') } // 4. Run report Content Security Policy violations for request. // TODO // 5. Upgrade request to a potentially trustworthy URL, if appropriate. tryUpgradeRequestToAPotentiallyTrustworthyURL(request) // 6. If should request be blocked due to a bad port, should fetching request // be blocked as mixed content, or should request be blocked by Content // Security Policy returns blocked, then set response to a network error. if (requestBadPort(request) === 'blocked') { response = makeNetworkError('bad port') } // TODO: should fetching request be blocked as mixed content? // TODO: should request be blocked by Content Security Policy? // 7. If request’s referrer policy is the empty string, then set request’s // referrer policy to request’s policy container’s referrer policy. if (request.referrerPolicy === '') { request.referrerPolicy = request.policyContainer.referrerPolicy } // 8. If request’s referrer is not "no-referrer", then set request’s // referrer to the result of invoking determine request’s referrer. if (request.referrer !== 'no-referrer') { request.referrer = determineRequestsReferrer(request) } // 9. Set request’s current URL’s scheme to "https" if all of the following // conditions are true: // - request’s current URL’s scheme is "http" // - request’s current URL’s host is a domain // - Matching request’s current URL’s host per Known HSTS Host Domain Name // Matching results in either a superdomain match with an asserted // includeSubDomains directive or a congruent match (with or without an // asserted includeSubDomains directive). [HSTS] // TODO // 10. If recursive is false, then run the remaining steps in parallel. // TODO // 11. If response is null, then set response to the result of running // the steps corresponding to the first matching statement: if (response === null) { response = await (async () => { const currentURL = requestCurrentURL(request) if ( // - request’s current URL’s origin is same origin with request’s origin, // and request’s response tainting is "basic" (sameOrigin(currentURL, request.url) && request.responseTainting === 'basic') || // request’s current URL’s scheme is "data" (currentURL.protocol === 'data:') || // - request’s mode is "navigate" or "websocket" (request.mode === 'navigate' || request.mode === 'websocket') ) { // 1. Set request’s response tainting to "basic". request.responseTainting = 'basic' // 2. Return the result of running scheme fetch given fetchParams. return await schemeFetch(fetchParams) } // request’s mode is "same-origin" if (request.mode === 'same-origin') { // 1. Return a network error. return makeNetworkError('request mode cannot be "same-origin"') } // request’s mode is "no-cors" if (request.mode === 'no-cors') { // 1. If request’s redirect mode is not "follow", then return a network // error. if (request.redirect !== 'follow') { return makeNetworkError( 'redirect mode cannot be "follow" for "no-cors" request' ) } // 2. Set request’s response tainting to "opaque". request.responseTainting = 'opaque' // 3. Return the result of running scheme fetch given fetchParams. return await schemeFetch(fetchParams) } // request’s current URL’s scheme is not an HTTP(S) scheme if (!urlIsHttpHttpsScheme(requestCurrentURL(request))) { // Return a network error. return makeNetworkError('URL scheme must be a HTTP(S) scheme') } // - request’s use-CORS-preflight flag is set // - request’s unsafe-request flag is set and either request’s method is // not a CORS-safelisted method or CORS-unsafe request-header names with // request’s header list is not empty // 1. Set request’s response tainting to "cors". // 2. Let corsWithPreflightResponse be the result of running HTTP fetch // given fetchParams and true. // 3. If corsWithPreflightResponse is a network error, then clear cache // entries using request. // 4. Return corsWithPreflightResponse. // TODO // Otherwise // 1. Set request’s response tainting to "cors". request.responseTainting = 'cors' // 2. Return the result of running HTTP fetch given fetchParams. return await httpFetch(fetchParams) })() } // 12. If recursive is true, then return response. if (recursive) { return response } // 13. If response is not a network error and response is not a filtered // response, then: if (response.status !== 0 && !response.internalResponse) { // If request’s response tainting is "cors", then: if (request.responseTainting === 'cors') { // 1. Let headerNames be the result of extracting header list values // given `Access-Control-Expose-Headers` and response’s header list. // TODO // 2. If request’s credentials mode is not "include" and headerNames // contains `*`, then set response’s CORS-exposed header-name list to // all unique header names in response’s header list. // TODO // 3. Otherwise, if headerNames is not null or failure, then set // response’s CORS-exposed header-name list to headerNames. // TODO } // Set response to the following filtered response with response as its // internal response, depending on request’s response tainting: if (request.responseTainting === 'basic') { response = filterResponse(response, 'basic') } else if (request.responseTainting === 'cors') { response = filterResponse(response, 'cors') } else if (request.responseTainting === 'opaque') { response = filterResponse(response, 'opaque') } else { assert(false) } } // 14. Let internalResponse be response, if response is a network error, // and response’s internal response otherwise. let internalResponse = response.status === 0 ? response : response.internalResponse // 15. If internalResponse’s URL list is empty, then set it to a clone of // request’s URL list. if (internalResponse.urlList.length === 0) { internalResponse.urlList.push(...request.urlList) } // 16. If request’s timing allow failed flag is unset, then set // internalResponse’s timing allow passed flag. if (!request.timingAllowFailed) { response.timingAllowPassed = true } // 17. If response is not a network error and any of the following returns // blocked // - should internalResponse to request be blocked as mixed content // - should internalResponse to request be blocked by Content Security Policy // - should internalResponse to request be blocked due to its MIME type // - should internalResponse to request be blocked due to nosniff // TODO // 18. If response’s type is "opaque", internalResponse’s status is 206, // internalResponse’s range-requested flag is set, and request’s header // list does not contain `Range`, then set response and internalResponse // to a network error. if ( response.type === 'opaque' && internalResponse.status === 206 && internalResponse.rangeRequested && !request.headers.contains('range') ) { response = internalResponse = makeNetworkError() } // 19. If response is not a network error and either request’s method is // `HEAD` or `CONNECT`, or internalResponse’s status is a null body status, // set internalResponse’s body to null and disregard any enqueuing toward // it (if any). if ( response.status !== 0 && (request.method === 'HEAD' || request.method === 'CONNECT' || nullBodyStatus.includes(internalResponse.status)) ) { internalResponse.body = null fetchParams.controller.dump = true } // 20. If request’s integrity metadata is not the empty string, then: if (request.integrity) { // 1. Let processBodyError be this step: run fetch finale given fetchParams // and a network error. const processBodyError = (reason) => fetchFinale(fetchParams, makeNetworkError(reason)) // 2. If request’s response tainting is "opaque", or response’s body is null, // then run processBodyError and abort these steps. if (request.responseTainting === 'opaque' || response.body == null) { processBodyError(response.error) return } // 3. Let processBody given bytes be these steps: const processBody = (bytes) => { // 1. If bytes do not match request’s integrity metadata, // then run processBodyError and abort these steps. [SRI] if (!bytesMatch(bytes, request.integrity)) { processBodyError('integrity mismatch') return } // 2. Set response’s body to bytes as a body. response.body = safelyExtractBody(bytes)[0] // 3. Run fetch finale given fetchParams and response. fetchFinale(fetchParams, response) } // 4. Fully read response’s body given processBody and processBodyError. await fullyReadBody(response.body, processBody, processBodyError) } else { // 21. Otherwise, run fetch finale given fetchParams and response. fetchFinale(fetchParams, response) } } // https://fetch.spec.whatwg.org/#concept-scheme-fetch // given a fetch params fetchParams function schemeFetch (fetchParams) { // Note: since the connection is destroyed on redirect, which sets fetchParams to a // cancelled state, we do not want this condition to trigger *unless* there have been // no redirects. See https://github.com/nodejs/undici/issues/1776 // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams. if (isCancelled(fetchParams) && fetchParams.request.redirectCount === 0) { return Promise.resolve(makeAppropriateNetworkError(fetchParams)) } // 2. Let request be fetchParams’s request. const { request } = fetchParams const { protocol: scheme } = requestCurrentURL(request) // 3. Switch on request’s current URL’s scheme and run the associated steps: switch (scheme) { case 'about:': { // If request’s current URL’s path is the string "blank", then return a new response // whose status message is `OK`, header list is « (`Content-Type`, `text/html;charset=utf-8`) », // and body is the empty byte sequence as a body. // Otherwise, return a network error. return Promise.resolve(makeNetworkError('about scheme is not supported')) } case 'blob:': { if (!resolveObjectURL) { resolveObjectURL = (__nccwpck_require__(14300).resolveObjectURL) } // 1. Let blobURLEntry be request’s current URL’s blob URL entry. const blobURLEntry = requestCurrentURL(request) // https://github.com/web-platform-tests/wpt/blob/7b0ebaccc62b566a1965396e5be7bb2bc06f841f/FileAPI/url/resources/fetch-tests.js#L52-L56 // Buffer.resolveObjectURL does not ignore URL queries. if (blobURLEntry.search.length !== 0) { return Promise.resolve(makeNetworkError('NetworkError when attempting to fetch resource.')) } const blobURLEntryObject = resolveObjectURL(blobURLEntry.toString()) // 2. If request’s method is not `GET`, blobURLEntry is null, or blobURLEntry’s // object is not a Blob object, then return a network error. if (request.method !== 'GET' || !isBlobLike(blobURLEntryObject)) { return Promise.resolve(makeNetworkError('invalid method')) } // 3. Let bodyWithType be the result of safely extracting blobURLEntry’s object. const bodyWithType = safelyExtractBody(blobURLEntryObject) // 4. Let body be bodyWithType’s body. const body = bodyWithType[0] // 5. Let length be body’s length, serialized and isomorphic encoded. const length = isomorphicEncode(`${body.length}`) // 6. Let type be bodyWithType’s type if it is non-null; otherwise the empty byte sequence. const type = bodyWithType[1] ?? '' // 7. Return a new response whose status message is `OK`, header list is // « (`Content-Length`, length), (`Content-Type`, type) », and body is body. const response = makeResponse({ statusText: 'OK', headersList: [ ['content-length', { name: 'Content-Length', value: length }], ['content-type', { name: 'Content-Type', value: type }] ] }) response.body = body return Promise.resolve(response) } case 'data:': { // 1. Let dataURLStruct be the result of running the // data: URL processor on request’s current URL. const currentURL = requestCurrentURL(request) const dataURLStruct = dataURLProcessor(currentURL) // 2. If dataURLStruct is failure, then return a // network error. if (dataURLStruct === 'failure') { return Promise.resolve(makeNetworkError('failed to fetch the data URL')) } // 3. Let mimeType be dataURLStruct’s MIME type, serialized. const mimeType = serializeAMimeType(dataURLStruct.mimeType) // 4. Return a response whose status message is `OK`, // header list is « (`Content-Type`, mimeType) », // and body is dataURLStruct’s body as a body. return Promise.resolve(makeResponse({ statusText: 'OK', headersList: [ ['content-type', { name: 'Content-Type', value: mimeType }] ], body: safelyExtractBody(dataURLStruct.body)[0] })) } case 'file:': { // For now, unfortunate as it is, file URLs are left as an exercise for the reader. // When in doubt, return a network error. return Promise.resolve(makeNetworkError('not implemented... yet...')) } case 'http:': case 'https:': { // Return the result of running HTTP fetch given fetchParams. return httpFetch(fetchParams) .catch((err) => makeNetworkError(err)) } default: { return Promise.resolve(makeNetworkError('unknown scheme')) } } } // https://fetch.spec.whatwg.org/#finalize-response function finalizeResponse (fetchParams, response) { // 1. Set fetchParams’s request’s done flag. fetchParams.request.done = true // 2, If fetchParams’s process response done is not null, then queue a fetch // task to run fetchParams’s process response done given response, with // fetchParams’s task destination. if (fetchParams.processResponseDone != null) { queueMicrotask(() => fetchParams.processResponseDone(response)) } } // https://fetch.spec.whatwg.org/#fetch-finale function fetchFinale (fetchParams, response) { // 1. If response is a network error, then: if (response.type === 'error') { // 1. Set response’s URL list to « fetchParams’s request’s URL list[0] ». response.urlList = [fetchParams.request.urlList[0]] // 2. Set response’s timing info to the result of creating an opaque timing // info for fetchParams’s timing info. response.timingInfo = createOpaqueTimingInfo({ startTime: fetchParams.timingInfo.startTime }) } // 2. Let processResponseEndOfBody be the following steps: const processResponseEndOfBody = () => { // 1. Set fetchParams’s request’s done flag. fetchParams.request.done = true // If fetchParams’s process response end-of-body is not null, // then queue a fetch task to run fetchParams’s process response // end-of-body given response with fetchParams’s task destination. if (fetchParams.processResponseEndOfBody != null) { queueMicrotask(() => fetchParams.processResponseEndOfBody(response)) } } // 3. If fetchParams’s process response is non-null, then queue a fetch task // to run fetchParams’s process response given response, with fetchParams’s // task destination. if (fetchParams.processResponse != null) { queueMicrotask(() => fetchParams.processResponse(response)) } // 4. If response’s body is null, then run processResponseEndOfBody. if (response.body == null) { processResponseEndOfBody() } else { // 5. Otherwise: // 1. Let transformStream be a new a TransformStream. // 2. Let identityTransformAlgorithm be an algorithm which, given chunk, // enqueues chunk in transformStream. const identityTransformAlgorithm = (chunk, controller) => { controller.enqueue(chunk) } // 3. Set up transformStream with transformAlgorithm set to identityTransformAlgorithm // and flushAlgorithm set to processResponseEndOfBody. const transformStream = new TransformStream({ start () {}, transform: identityTransformAlgorithm, flush: processResponseEndOfBody }, { size () { return 1 } }, { size () { return 1 } }) // 4. Set response’s body to the result of piping response’s body through transformStream. response.body = { stream: response.body.stream.pipeThrough(transformStream) } } // 6. If fetchParams’s process response consume body is non-null, then: if (fetchParams.processResponseConsumeBody != null) { // 1. Let processBody given nullOrBytes be this step: run fetchParams’s // process response consume body given response and nullOrBytes. const processBody = (nullOrBytes) => fetchParams.processResponseConsumeBody(response, nullOrBytes) // 2. Let processBodyError be this step: run fetchParams’s process // response consume body given response and failure. const processBodyError = (failure) => fetchParams.processResponseConsumeBody(response, failure) // 3. If response’s body is null, then queue a fetch task to run processBody // given null, with fetchParams’s task destination. if (response.body == null) { queueMicrotask(() => processBody(null)) } else { // 4. Otherwise, fully read response’s body given processBody, processBodyError, // and fetchParams’s task destination. return fullyReadBody(response.body, processBody, processBodyError) } return Promise.resolve() } } // https://fetch.spec.whatwg.org/#http-fetch async function httpFetch (fetchParams) { // 1. Let request be fetchParams’s request. const request = fetchParams.request // 2. Let response be null. let response = null // 3. Let actualResponse be null. let actualResponse = null // 4. Let timingInfo be fetchParams’s timing info. const timingInfo = fetchParams.timingInfo // 5. If request’s service-workers mode is "all", then: if (request.serviceWorkers === 'all') { // TODO } // 6. If response is null, then: if (response === null) { // 1. If makeCORSPreflight is true and one of these conditions is true: // TODO // 2. If request’s redirect mode is "follow", then set request’s // service-workers mode to "none". if (request.redirect === 'follow') { request.serviceWorkers = 'none' } // 3. Set response and actualResponse to the result of running // HTTP-network-or-cache fetch given fetchParams. actualResponse = response = await httpNetworkOrCacheFetch(fetchParams) // 4. If request’s response tainting is "cors" and a CORS check // for request and response returns failure, then return a network error. if ( request.responseTainting === 'cors' && corsCheck(request, response) === 'failure' ) { return makeNetworkError('cors failure') } // 5. If the TAO check for request and response returns failure, then set // request’s timing allow failed flag. if (TAOCheck(request, response) === 'failure') { request.timingAllowFailed = true } } // 7. If either request’s response tainting or response’s type // is "opaque", and the cross-origin resource policy check with // request’s origin, request’s client, request’s destination, // and actualResponse returns blocked, then return a network error. if ( (request.responseTainting === 'opaque' || response.type === 'opaque') && crossOriginResourcePolicyCheck( request.origin, request.client, request.destination, actualResponse ) === 'blocked' ) { return makeNetworkError('blocked') } // 8. If actualResponse’s status is a redirect status, then: if (redirectStatusSet.has(actualResponse.status)) { // 1. If actualResponse’s status is not 303, request’s body is not null, // and the connection uses HTTP/2, then user agents may, and are even // encouraged to, transmit an RST_STREAM frame. // See, https://github.com/whatwg/fetch/issues/1288 if (request.redirect !== 'manual') { fetchParams.controller.connection.destroy() } // 2. Switch on request’s redirect mode: if (request.redirect === 'error') { // Set response to a network error. response = makeNetworkError('unexpected redirect') } else if (request.redirect === 'manual') { // Set response to an opaque-redirect filtered response whose internal // response is actualResponse. // NOTE(spec): On the web this would return an `opaqueredirect` response, // but that doesn't make sense server side. // See https://github.com/nodejs/undici/issues/1193. response = actualResponse } else if (request.redirect === 'follow') { // Set response to the result of running HTTP-redirect fetch given // fetchParams and response. response = await httpRedirectFetch(fetchParams, response) } else { assert(false) } } // 9. Set response’s timing info to timingInfo. response.timingInfo = timingInfo // 10. Return response. return response } // https://fetch.spec.whatwg.org/#http-redirect-fetch function httpRedirectFetch (fetchParams, response) { // 1. Let request be fetchParams’s request. const request = fetchParams.request // 2. Let actualResponse be response, if response is not a filtered response, // and response’s internal response otherwise. const actualResponse = response.internalResponse ? response.internalResponse : response // 3. Let locationURL be actualResponse’s location URL given request’s current // URL’s fragment. let locationURL try { locationURL = responseLocationURL( actualResponse, requestCurrentURL(request).hash ) // 4. If locationURL is null, then return response. if (locationURL == null) { return response } } catch (err) { // 5. If locationURL is failure, then return a network error. return Promise.resolve(makeNetworkError(err)) } // 6. If locationURL’s scheme is not an HTTP(S) scheme, then return a network // error. if (!urlIsHttpHttpsScheme(locationURL)) { return Promise.resolve(makeNetworkError('URL scheme must be a HTTP(S) scheme')) } // 7. If request’s redirect count is 20, then return a network error. if (request.redirectCount === 20) { return Promise.resolve(makeNetworkError('redirect count exceeded')) } // 8. Increase request’s redirect count by 1. request.redirectCount += 1 // 9. If request’s mode is "cors", locationURL includes credentials, and // request’s origin is not same origin with locationURL’s origin, then return // a network error. if ( request.mode === 'cors' && (locationURL.username || locationURL.password) && !sameOrigin(request, locationURL) ) { return Promise.resolve(makeNetworkError('cross origin not allowed for request mode "cors"')) } // 10. If request’s response tainting is "cors" and locationURL includes // credentials, then return a network error. if ( request.responseTainting === 'cors' && (locationURL.username || locationURL.password) ) { return Promise.resolve(makeNetworkError( 'URL cannot contain credentials for request mode "cors"' )) } // 11. If actualResponse’s status is not 303, request’s body is non-null, // and request’s body’s source is null, then return a network error. if ( actualResponse.status !== 303 && request.body != null && request.body.source == null ) { return Promise.resolve(makeNetworkError()) } // 12. If one of the following is true // - actualResponse’s status is 301 or 302 and request’s method is `POST` // - actualResponse’s status is 303 and request’s method is not `GET` or `HEAD` if ( ([301, 302].includes(actualResponse.status) && request.method === 'POST') || (actualResponse.status === 303 && !GET_OR_HEAD.includes(request.method)) ) { // then: // 1. Set request’s method to `GET` and request’s body to null. request.method = 'GET' request.body = null // 2. For each headerName of request-body-header name, delete headerName from // request’s header list. for (const headerName of requestBodyHeader) { request.headersList.delete(headerName) } } // 13. If request’s current URL’s origin is not same origin with locationURL’s // origin, then for each headerName of CORS non-wildcard request-header name, // delete headerName from request’s header list. if (!sameOrigin(requestCurrentURL(request), locationURL)) { // https://fetch.spec.whatwg.org/#cors-non-wildcard-request-header-name request.headersList.delete('authorization') // https://fetch.spec.whatwg.org/#authentication-entries request.headersList.delete('proxy-authorization', true) // "Cookie" and "Host" are forbidden request-headers, which undici doesn't implement. request.headersList.delete('cookie') request.headersList.delete('host') } // 14. If request’s body is non-null, then set request’s body to the first return // value of safely extracting request’s body’s source. if (request.body != null) { assert(request.body.source != null) request.body = safelyExtractBody(request.body.source)[0] } // 15. Let timingInfo be fetchParams’s timing info. const timingInfo = fetchParams.timingInfo // 16. Set timingInfo’s redirect end time and post-redirect start time to the // coarsened shared current time given fetchParams’s cross-origin isolated // capability. timingInfo.redirectEndTime = timingInfo.postRedirectStartTime = coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability) // 17. If timingInfo’s redirect start time is 0, then set timingInfo’s // redirect start time to timingInfo’s start time. if (timingInfo.redirectStartTime === 0) { timingInfo.redirectStartTime = timingInfo.startTime } // 18. Append locationURL to request’s URL list. request.urlList.push(locationURL) // 19. Invoke set request’s referrer policy on redirect on request and // actualResponse. setRequestReferrerPolicyOnRedirect(request, actualResponse) // 20. Return the result of running main fetch given fetchParams and true. return mainFetch(fetchParams, true) } // https://fetch.spec.whatwg.org/#http-network-or-cache-fetch async function httpNetworkOrCacheFetch ( fetchParams, isAuthenticationFetch = false, isNewConnectionFetch = false ) { // 1. Let request be fetchParams’s request. const request = fetchParams.request // 2. Let httpFetchParams be null. let httpFetchParams = null // 3. Let httpRequest be null. let httpRequest = null // 4. Let response be null. let response = null // 5. Let storedResponse be null. // TODO: cache // 6. Let httpCache be null. const httpCache = null // 7. Let the revalidatingFlag be unset. const revalidatingFlag = false // 8. Run these steps, but abort when the ongoing fetch is terminated: // 1. If request’s window is "no-window" and request’s redirect mode is // "error", then set httpFetchParams to fetchParams and httpRequest to // request. if (request.window === 'no-window' && request.redirect === 'error') { httpFetchParams = fetchParams httpRequest = request } else { // Otherwise: // 1. Set httpRequest to a clone of request. httpRequest = makeRequest(request) // 2. Set httpFetchParams to a copy of fetchParams. httpFetchParams = { ...fetchParams } // 3. Set httpFetchParams’s request to httpRequest. httpFetchParams.request = httpRequest } // 3. Let includeCredentials be true if one of const includeCredentials = request.credentials === 'include' || (request.credentials === 'same-origin' && request.responseTainting === 'basic') // 4. Let contentLength be httpRequest’s body’s length, if httpRequest’s // body is non-null; otherwise null. const contentLength = httpRequest.body ? httpRequest.body.length : null // 5. Let contentLengthHeaderValue be null. let contentLengthHeaderValue = null // 6. If httpRequest’s body is null and httpRequest’s method is `POST` or // `PUT`, then set contentLengthHeaderValue to `0`. if ( httpRequest.body == null && ['POST', 'PUT'].includes(httpRequest.method) ) { contentLengthHeaderValue = '0' } // 7. If contentLength is non-null, then set contentLengthHeaderValue to // contentLength, serialized and isomorphic encoded. if (contentLength != null) { contentLengthHeaderValue = isomorphicEncode(`${contentLength}`) } // 8. If contentLengthHeaderValue is non-null, then append // `Content-Length`/contentLengthHeaderValue to httpRequest’s header // list. if (contentLengthHeaderValue != null) { httpRequest.headersList.append('content-length', contentLengthHeaderValue) } // 9. If contentLengthHeaderValue is non-null, then append (`Content-Length`, // contentLengthHeaderValue) to httpRequest’s header list. // 10. If contentLength is non-null and httpRequest’s keepalive is true, // then: if (contentLength != null && httpRequest.keepalive) { // NOTE: keepalive is a noop outside of browser context. } // 11. If httpRequest’s referrer is a URL, then append // `Referer`/httpRequest’s referrer, serialized and isomorphic encoded, // to httpRequest’s header list. if (httpRequest.referrer instanceof URL) { httpRequest.headersList.append('referer', isomorphicEncode(httpRequest.referrer.href)) } // 12. Append a request `Origin` header for httpRequest. appendRequestOriginHeader(httpRequest) // 13. Append the Fetch metadata headers for httpRequest. [FETCH-METADATA] appendFetchMetadata(httpRequest) // 14. If httpRequest’s header list does not contain `User-Agent`, then // user agents should append `User-Agent`/default `User-Agent` value to // httpRequest’s header list. if (!httpRequest.headersList.contains('user-agent')) { httpRequest.headersList.append('user-agent', typeof esbuildDetection === 'undefined' ? 'undici' : 'node') } // 15. If httpRequest’s cache mode is "default" and httpRequest’s header // list contains `If-Modified-Since`, `If-None-Match`, // `If-Unmodified-Since`, `If-Match`, or `If-Range`, then set // httpRequest’s cache mode to "no-store". if ( httpRequest.cache === 'default' && (httpRequest.headersList.contains('if-modified-since') || httpRequest.headersList.contains('if-none-match') || httpRequest.headersList.contains('if-unmodified-since') || httpRequest.headersList.contains('if-match') || httpRequest.headersList.contains('if-range')) ) { httpRequest.cache = 'no-store' } // 16. If httpRequest’s cache mode is "no-cache", httpRequest’s prevent // no-cache cache-control header modification flag is unset, and // httpRequest’s header list does not contain `Cache-Control`, then append // `Cache-Control`/`max-age=0` to httpRequest’s header list. if ( httpRequest.cache === 'no-cache' && !httpRequest.preventNoCacheCacheControlHeaderModification && !httpRequest.headersList.contains('cache-control') ) { httpRequest.headersList.append('cache-control', 'max-age=0') } // 17. If httpRequest’s cache mode is "no-store" or "reload", then: if (httpRequest.cache === 'no-store' || httpRequest.cache === 'reload') { // 1. If httpRequest’s header list does not contain `Pragma`, then append // `Pragma`/`no-cache` to httpRequest’s header list. if (!httpRequest.headersList.contains('pragma')) { httpRequest.headersList.append('pragma', 'no-cache') } // 2. If httpRequest’s header list does not contain `Cache-Control`, // then append `Cache-Control`/`no-cache` to httpRequest’s header list. if (!httpRequest.headersList.contains('cache-control')) { httpRequest.headersList.append('cache-control', 'no-cache') } } // 18. If httpRequest’s header list contains `Range`, then append // `Accept-Encoding`/`identity` to httpRequest’s header list. if (httpRequest.headersList.contains('range')) { httpRequest.headersList.append('accept-encoding', 'identity') } // 19. Modify httpRequest’s header list per HTTP. Do not append a given // header if httpRequest’s header list contains that header’s name. // TODO: https://github.com/whatwg/fetch/issues/1285#issuecomment-896560129 if (!httpRequest.headersList.contains('accept-encoding')) { if (urlHasHttpsScheme(requestCurrentURL(httpRequest))) { httpRequest.headersList.append('accept-encoding', 'br, gzip, deflate') } else { httpRequest.headersList.append('accept-encoding', 'gzip, deflate') } } httpRequest.headersList.delete('host') // 20. If includeCredentials is true, then: if (includeCredentials) { // 1. If the user agent is not configured to block cookies for httpRequest // (see section 7 of [COOKIES]), then: // TODO: credentials // 2. If httpRequest’s header list does not contain `Authorization`, then: // TODO: credentials } // 21. If there’s a proxy-authentication entry, use it as appropriate. // TODO: proxy-authentication // 22. Set httpCache to the result of determining the HTTP cache // partition, given httpRequest. // TODO: cache // 23. If httpCache is null, then set httpRequest’s cache mode to // "no-store". if (httpCache == null) { httpRequest.cache = 'no-store' } // 24. If httpRequest’s cache mode is neither "no-store" nor "reload", // then: if (httpRequest.mode !== 'no-store' && httpRequest.mode !== 'reload') { // TODO: cache } // 9. If aborted, then return the appropriate network error for fetchParams. // TODO // 10. If response is null, then: if (response == null) { // 1. If httpRequest’s cache mode is "only-if-cached", then return a // network error. if (httpRequest.mode === 'only-if-cached') { return makeNetworkError('only if cached') } // 2. Let forwardResponse be the result of running HTTP-network fetch // given httpFetchParams, includeCredentials, and isNewConnectionFetch. const forwardResponse = await httpNetworkFetch( httpFetchParams, includeCredentials, isNewConnectionFetch ) // 3. If httpRequest’s method is unsafe and forwardResponse’s status is // in the range 200 to 399, inclusive, invalidate appropriate stored // responses in httpCache, as per the "Invalidation" chapter of HTTP // Caching, and set storedResponse to null. [HTTP-CACHING] if ( !safeMethodsSet.has(httpRequest.method) && forwardResponse.status >= 200 && forwardResponse.status <= 399 ) { // TODO: cache } // 4. If the revalidatingFlag is set and forwardResponse’s status is 304, // then: if (revalidatingFlag && forwardResponse.status === 304) { // TODO: cache } // 5. If response is null, then: if (response == null) { // 1. Set response to forwardResponse. response = forwardResponse // 2. Store httpRequest and forwardResponse in httpCache, as per the // "Storing Responses in Caches" chapter of HTTP Caching. [HTTP-CACHING] // TODO: cache } } // 11. Set response’s URL list to a clone of httpRequest’s URL list. response.urlList = [...httpRequest.urlList] // 12. If httpRequest’s header list contains `Range`, then set response’s // range-requested flag. if (httpRequest.headersList.contains('range')) { response.rangeRequested = true } // 13. Set response’s request-includes-credentials to includeCredentials. response.requestIncludesCredentials = includeCredentials // 14. If response’s status is 401, httpRequest’s response tainting is not // "cors", includeCredentials is true, and request’s window is an environment // settings object, then: // TODO // 15. If response’s status is 407, then: if (response.status === 407) { // 1. If request’s window is "no-window", then return a network error. if (request.window === 'no-window') { return makeNetworkError() } // 2. ??? // 3. If fetchParams is canceled, then return the appropriate network error for fetchParams. if (isCancelled(fetchParams)) { return makeAppropriateNetworkError(fetchParams) } // 4. Prompt the end user as appropriate in request’s window and store // the result as a proxy-authentication entry. [HTTP-AUTH] // TODO: Invoke some kind of callback? // 5. Set response to the result of running HTTP-network-or-cache fetch given // fetchParams. // TODO return makeNetworkError('proxy authentication required') } // 16. If all of the following are true if ( // response’s status is 421 response.status === 421 && // isNewConnectionFetch is false !isNewConnectionFetch && // request’s body is null, or request’s body is non-null and request’s body’s source is non-null (request.body == null || request.body.source != null) ) { // then: // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams. if (isCancelled(fetchParams)) { return makeAppropriateNetworkError(fetchParams) } // 2. Set response to the result of running HTTP-network-or-cache // fetch given fetchParams, isAuthenticationFetch, and true. // TODO (spec): The spec doesn't specify this but we need to cancel // the active response before we can start a new one. // https://github.com/whatwg/fetch/issues/1293 fetchParams.controller.connection.destroy() response = await httpNetworkOrCacheFetch( fetchParams, isAuthenticationFetch, true ) } // 17. If isAuthenticationFetch is true, then create an authentication entry if (isAuthenticationFetch) { // TODO } // 18. Return response. return response } // https://fetch.spec.whatwg.org/#http-network-fetch async function httpNetworkFetch ( fetchParams, includeCredentials = false, forceNewConnection = false ) { assert(!fetchParams.controller.connection || fetchParams.controller.connection.destroyed) fetchParams.controller.connection = { abort: null, destroyed: false, destroy (err) { if (!this.destroyed) { this.destroyed = true this.abort?.(err ?? new DOMException('The operation was aborted.', 'AbortError')) } } } // 1. Let request be fetchParams’s request. const request = fetchParams.request // 2. Let response be null. let response = null // 3. Let timingInfo be fetchParams’s timing info. const timingInfo = fetchParams.timingInfo // 4. Let httpCache be the result of determining the HTTP cache partition, // given request. // TODO: cache const httpCache = null // 5. If httpCache is null, then set request’s cache mode to "no-store". if (httpCache == null) { request.cache = 'no-store' } // 6. Let networkPartitionKey be the result of determining the network // partition key given request. // TODO // 7. Let newConnection be "yes" if forceNewConnection is true; otherwise // "no". const newConnection = forceNewConnection ? 'yes' : 'no' // eslint-disable-line no-unused-vars // 8. Switch on request’s mode: if (request.mode === 'websocket') { // Let connection be the result of obtaining a WebSocket connection, // given request’s current URL. // TODO } else { // Let connection be the result of obtaining a connection, given // networkPartitionKey, request’s current URL’s origin, // includeCredentials, and forceNewConnection. // TODO } // 9. Run these steps, but abort when the ongoing fetch is terminated: // 1. If connection is failure, then return a network error. // 2. Set timingInfo’s final connection timing info to the result of // calling clamp and coarsen connection timing info with connection’s // timing info, timingInfo’s post-redirect start time, and fetchParams’s // cross-origin isolated capability. // 3. If connection is not an HTTP/2 connection, request’s body is non-null, // and request’s body’s source is null, then append (`Transfer-Encoding`, // `chunked`) to request’s header list. // 4. Set timingInfo’s final network-request start time to the coarsened // shared current time given fetchParams’s cross-origin isolated // capability. // 5. Set response to the result of making an HTTP request over connection // using request with the following caveats: // - Follow the relevant requirements from HTTP. [HTTP] [HTTP-SEMANTICS] // [HTTP-COND] [HTTP-CACHING] [HTTP-AUTH] // - If request’s body is non-null, and request’s body’s source is null, // then the user agent may have a buffer of up to 64 kibibytes and store // a part of request’s body in that buffer. If the user agent reads from // request’s body beyond that buffer’s size and the user agent needs to // resend request, then instead return a network error. // - Set timingInfo’s final network-response start time to the coarsened // shared current time given fetchParams’s cross-origin isolated capability, // immediately after the user agent’s HTTP parser receives the first byte // of the response (e.g., frame header bytes for HTTP/2 or response status // line for HTTP/1.x). // - Wait until all the headers are transmitted. // - Any responses whose status is in the range 100 to 199, inclusive, // and is not 101, are to be ignored, except for the purposes of setting // timingInfo’s final network-response start time above. // - If request’s header list contains `Transfer-Encoding`/`chunked` and // response is transferred via HTTP/1.0 or older, then return a network // error. // - If the HTTP request results in a TLS client certificate dialog, then: // 1. If request’s window is an environment settings object, make the // dialog available in request’s window. // 2. Otherwise, return a network error. // To transmit request’s body body, run these steps: let requestBody = null // 1. If body is null and fetchParams’s process request end-of-body is // non-null, then queue a fetch task given fetchParams’s process request // end-of-body and fetchParams’s task destination. if (request.body == null && fetchParams.processRequestEndOfBody) { queueMicrotask(() => fetchParams.processRequestEndOfBody()) } else if (request.body != null) { // 2. Otherwise, if body is non-null: // 1. Let processBodyChunk given bytes be these steps: const processBodyChunk = async function * (bytes) { // 1. If the ongoing fetch is terminated, then abort these steps. if (isCancelled(fetchParams)) { return } // 2. Run this step in parallel: transmit bytes. yield bytes // 3. If fetchParams’s process request body is non-null, then run // fetchParams’s process request body given bytes’s length. fetchParams.processRequestBodyChunkLength?.(bytes.byteLength) } // 2. Let processEndOfBody be these steps: const processEndOfBody = () => { // 1. If fetchParams is canceled, then abort these steps. if (isCancelled(fetchParams)) { return } // 2. If fetchParams’s process request end-of-body is non-null, // then run fetchParams’s process request end-of-body. if (fetchParams.processRequestEndOfBody) { fetchParams.processRequestEndOfBody() } } // 3. Let processBodyError given e be these steps: const processBodyError = (e) => { // 1. If fetchParams is canceled, then abort these steps. if (isCancelled(fetchParams)) { return } // 2. If e is an "AbortError" DOMException, then abort fetchParams’s controller. if (e.name === 'AbortError') { fetchParams.controller.abort() } else { fetchParams.controller.terminate(e) } } // 4. Incrementally read request’s body given processBodyChunk, processEndOfBody, // processBodyError, and fetchParams’s task destination. requestBody = (async function * () { try { for await (const bytes of request.body.stream) { yield * processBodyChunk(bytes) } processEndOfBody() } catch (err) { processBodyError(err) } })() } try { // socket is only provided for websockets const { body, status, statusText, headersList, socket } = await dispatch({ body: requestBody }) if (socket) { response = makeResponse({ status, statusText, headersList, socket }) } else { const iterator = body[Symbol.asyncIterator]() fetchParams.controller.next = () => iterator.next() response = makeResponse({ status, statusText, headersList }) } } catch (err) { // 10. If aborted, then: if (err.name === 'AbortError') { // 1. If connection uses HTTP/2, then transmit an RST_STREAM frame. fetchParams.controller.connection.destroy() // 2. Return the appropriate network error for fetchParams. return makeAppropriateNetworkError(fetchParams, err) } return makeNetworkError(err) } // 11. Let pullAlgorithm be an action that resumes the ongoing fetch // if it is suspended. const pullAlgorithm = () => { fetchParams.controller.resume() } // 12. Let cancelAlgorithm be an algorithm that aborts fetchParams’s // controller with reason, given reason. const cancelAlgorithm = (reason) => { fetchParams.controller.abort(reason) } // 13. Let highWaterMark be a non-negative, non-NaN number, chosen by // the user agent. // TODO // 14. Let sizeAlgorithm be an algorithm that accepts a chunk object // and returns a non-negative, non-NaN, non-infinite number, chosen by the user agent. // TODO // 15. Let stream be a new ReadableStream. // 16. Set up stream with pullAlgorithm set to pullAlgorithm, // cancelAlgorithm set to cancelAlgorithm, highWaterMark set to // highWaterMark, and sizeAlgorithm set to sizeAlgorithm. if (!ReadableStream) { ReadableStream = (__nccwpck_require__(35356).ReadableStream) } const stream = new ReadableStream( { async start (controller) { fetchParams.controller.controller = controller }, async pull (controller) { await pullAlgorithm(controller) }, async cancel (reason) { await cancelAlgorithm(reason) } }, { highWaterMark: 0, size () { return 1 } } ) // 17. Run these steps, but abort when the ongoing fetch is terminated: // 1. Set response’s body to a new body whose stream is stream. response.body = { stream } // 2. If response is not a network error and request’s cache mode is // not "no-store", then update response in httpCache for request. // TODO // 3. If includeCredentials is true and the user agent is not configured // to block cookies for request (see section 7 of [COOKIES]), then run the // "set-cookie-string" parsing algorithm (see section 5.2 of [COOKIES]) on // the value of each header whose name is a byte-case-insensitive match for // `Set-Cookie` in response’s header list, if any, and request’s current URL. // TODO // 18. If aborted, then: // TODO // 19. Run these steps in parallel: // 1. Run these steps, but abort when fetchParams is canceled: fetchParams.controller.on('terminated', onAborted) fetchParams.controller.resume = async () => { // 1. While true while (true) { // 1-3. See onData... // 4. Set bytes to the result of handling content codings given // codings and bytes. let bytes let isFailure try { const { done, value } = await fetchParams.controller.next() if (isAborted(fetchParams)) { break } bytes = done ? undefined : value } catch (err) { if (fetchParams.controller.ended && !timingInfo.encodedBodySize) { // zlib doesn't like empty streams. bytes = undefined } else { bytes = err // err may be propagated from the result of calling readablestream.cancel, // which might not be an error. https://github.com/nodejs/undici/issues/2009 isFailure = true } } if (bytes === undefined) { // 2. Otherwise, if the bytes transmission for response’s message // body is done normally and stream is readable, then close // stream, finalize response for fetchParams and response, and // abort these in-parallel steps. readableStreamClose(fetchParams.controller.controller) finalizeResponse(fetchParams, response) return } // 5. Increase timingInfo’s decoded body size by bytes’s length. timingInfo.decodedBodySize += bytes?.byteLength ?? 0 // 6. If bytes is failure, then terminate fetchParams’s controller. if (isFailure) { fetchParams.controller.terminate(bytes) return } // 7. Enqueue a Uint8Array wrapping an ArrayBuffer containing bytes // into stream. fetchParams.controller.controller.enqueue(new Uint8Array(bytes)) // 8. If stream is errored, then terminate the ongoing fetch. if (isErrored(stream)) { fetchParams.controller.terminate() return } // 9. If stream doesn’t need more data ask the user agent to suspend // the ongoing fetch. if (!fetchParams.controller.controller.desiredSize) { return } } } // 2. If aborted, then: function onAborted (reason) { // 2. If fetchParams is aborted, then: if (isAborted(fetchParams)) { // 1. Set response’s aborted flag. response.aborted = true // 2. If stream is readable, then error stream with the result of // deserialize a serialized abort reason given fetchParams’s // controller’s serialized abort reason and an // implementation-defined realm. if (isReadable(stream)) { fetchParams.controller.controller.error( fetchParams.controller.serializedAbortReason ) } } else { // 3. Otherwise, if stream is readable, error stream with a TypeError. if (isReadable(stream)) { fetchParams.controller.controller.error(new TypeError('terminated', { cause: isErrorLike(reason) ? reason : undefined })) } } // 4. If connection uses HTTP/2, then transmit an RST_STREAM frame. // 5. Otherwise, the user agent should close connection unless it would be bad for performance to do so. fetchParams.controller.connection.destroy() } // 20. Return response. return response async function dispatch ({ body }) { const url = requestCurrentURL(request) /** @type {import('../..').Agent} */ const agent = fetchParams.controller.dispatcher return new Promise((resolve, reject) => agent.dispatch( { path: url.pathname + url.search, origin: url.origin, method: request.method, body: fetchParams.controller.dispatcher.isMockActive ? request.body && (request.body.source || request.body.stream) : body, headers: request.headersList.entries, maxRedirections: 0, upgrade: request.mode === 'websocket' ? 'websocket' : undefined }, { body: null, abort: null, onConnect (abort) { // TODO (fix): Do we need connection here? const { connection } = fetchParams.controller if (connection.destroyed) { abort(new DOMException('The operation was aborted.', 'AbortError')) } else { fetchParams.controller.on('terminated', abort) this.abort = connection.abort = abort } }, onHeaders (status, headersList, resume, statusText) { if (status < 200) { return } let codings = [] let location = '' const headers = new Headers() // For H2, the headers are a plain JS object // We distinguish between them and iterate accordingly if (Array.isArray(headersList)) { for (let n = 0; n < headersList.length; n += 2) { const key = headersList[n + 0].toString('latin1') const val = headersList[n + 1].toString('latin1') if (key.toLowerCase() === 'content-encoding') { // https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1 // "All content-coding values are case-insensitive..." codings = val.toLowerCase().split(',').map((x) => x.trim()) } else if (key.toLowerCase() === 'location') { location = val } headers[kHeadersList].append(key, val) } } else { const keys = Object.keys(headersList) for (const key of keys) { const val = headersList[key] if (key.toLowerCase() === 'content-encoding') { // https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1 // "All content-coding values are case-insensitive..." codings = val.toLowerCase().split(',').map((x) => x.trim()).reverse() } else if (key.toLowerCase() === 'location') { location = val } headers[kHeadersList].append(key, val) } } this.body = new Readable({ read: resume }) const decoders = [] const willFollow = request.redirect === 'follow' && location && redirectStatusSet.has(status) // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding if (request.method !== 'HEAD' && request.method !== 'CONNECT' && !nullBodyStatus.includes(status) && !willFollow) { for (const coding of codings) { // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.2 if (coding === 'x-gzip' || coding === 'gzip') { decoders.push(zlib.createGunzip({ // Be less strict when decoding compressed responses, since sometimes // servers send slightly invalid responses that are still accepted // by common browsers. // Always using Z_SYNC_FLUSH is what cURL does. flush: zlib.constants.Z_SYNC_FLUSH, finishFlush: zlib.constants.Z_SYNC_FLUSH })) } else if (coding === 'deflate') { decoders.push(zlib.createInflate()) } else if (coding === 'br') { decoders.push(zlib.createBrotliDecompress()) } else { decoders.length = 0 break } } } resolve({ status, statusText, headersList: headers[kHeadersList], body: decoders.length ? pipeline(this.body, ...decoders, () => { }) : this.body.on('error', () => {}) }) return true }, onData (chunk) { if (fetchParams.controller.dump) { return } // 1. If one or more bytes have been transmitted from response’s // message body, then: // 1. Let bytes be the transmitted bytes. const bytes = chunk // 2. Let codings be the result of extracting header list values // given `Content-Encoding` and response’s header list. // See pullAlgorithm. // 3. Increase timingInfo’s encoded body size by bytes’s length. timingInfo.encodedBodySize += bytes.byteLength // 4. See pullAlgorithm... return this.body.push(bytes) }, onComplete () { if (this.abort) { fetchParams.controller.off('terminated', this.abort) } fetchParams.controller.ended = true this.body.push(null) }, onError (error) { if (this.abort) { fetchParams.controller.off('terminated', this.abort) } this.body?.destroy(error) fetchParams.controller.terminate(error) reject(error) }, onUpgrade (status, headersList, socket) { if (status !== 101) { return } const headers = new Headers() for (let n = 0; n < headersList.length; n += 2) { const key = headersList[n + 0].toString('latin1') const val = headersList[n + 1].toString('latin1') headers[kHeadersList].append(key, val) } resolve({ status, statusText: STATUS_CODES[status], headersList: headers[kHeadersList], socket }) return true } } )) } } module.exports = { fetch, Fetch, fetching, finalizeAndReportTiming } /***/ }), /***/ 48359: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /* globals AbortController */ const { extractBody, mixinBody, cloneBody } = __nccwpck_require__(41472) const { Headers, fill: fillHeaders, HeadersList } = __nccwpck_require__(10554) const { FinalizationRegistry } = __nccwpck_require__(56436)() const util = __nccwpck_require__(83983) const { isValidHTTPToken, sameOrigin, normalizeMethod, makePolicyContainer, normalizeMethodRecord } = __nccwpck_require__(52538) const { forbiddenMethodsSet, corsSafeListedMethodsSet, referrerPolicy, requestRedirect, requestMode, requestCredentials, requestCache, requestDuplex } = __nccwpck_require__(41037) const { kEnumerableProperty } = util const { kHeaders, kSignal, kState, kGuard, kRealm } = __nccwpck_require__(15861) const { webidl } = __nccwpck_require__(21744) const { getGlobalOrigin } = __nccwpck_require__(71246) const { URLSerializer } = __nccwpck_require__(685) const { kHeadersList, kConstruct } = __nccwpck_require__(72785) const assert = __nccwpck_require__(39491) const { getMaxListeners, setMaxListeners, getEventListeners, defaultMaxListeners } = __nccwpck_require__(82361) let TransformStream = globalThis.TransformStream const kAbortController = Symbol('abortController') const requestFinalizer = new FinalizationRegistry(({ signal, abort }) => { signal.removeEventListener('abort', abort) }) // https://fetch.spec.whatwg.org/#request-class class Request { // https://fetch.spec.whatwg.org/#dom-request constructor (input, init = {}) { if (input === kConstruct) { return } webidl.argumentLengthCheck(arguments, 1, { header: 'Request constructor' }) input = webidl.converters.RequestInfo(input) init = webidl.converters.RequestInit(init) // https://html.spec.whatwg.org/multipage/webappapis.html#environment-settings-object this[kRealm] = { settingsObject: { baseUrl: getGlobalOrigin(), get origin () { return this.baseUrl?.origin }, policyContainer: makePolicyContainer() } } // 1. Let request be null. let request = null // 2. Let fallbackMode be null. let fallbackMode = null // 3. Let baseURL be this’s relevant settings object’s API base URL. const baseUrl = this[kRealm].settingsObject.baseUrl // 4. Let signal be null. let signal = null // 5. If input is a string, then: if (typeof input === 'string') { // 1. Let parsedURL be the result of parsing input with baseURL. // 2. If parsedURL is failure, then throw a TypeError. let parsedURL try { parsedURL = new URL(input, baseUrl) } catch (err) { throw new TypeError('Failed to parse URL from ' + input, { cause: err }) } // 3. If parsedURL includes credentials, then throw a TypeError. if (parsedURL.username || parsedURL.password) { throw new TypeError( 'Request cannot be constructed from a URL that includes credentials: ' + input ) } // 4. Set request to a new request whose URL is parsedURL. request = makeRequest({ urlList: [parsedURL] }) // 5. Set fallbackMode to "cors". fallbackMode = 'cors' } else { // 6. Otherwise: // 7. Assert: input is a Request object. assert(input instanceof Request) // 8. Set request to input’s request. request = input[kState] // 9. Set signal to input’s signal. signal = input[kSignal] } // 7. Let origin be this’s relevant settings object’s origin. const origin = this[kRealm].settingsObject.origin // 8. Let window be "client". let window = 'client' // 9. If request’s window is an environment settings object and its origin // is same origin with origin, then set window to request’s window. if ( request.window?.constructor?.name === 'EnvironmentSettingsObject' && sameOrigin(request.window, origin) ) { window = request.window } // 10. If init["window"] exists and is non-null, then throw a TypeError. if (init.window != null) { throw new TypeError(`'window' option '${window}' must be null`) } // 11. If init["window"] exists, then set window to "no-window". if ('window' in init) { window = 'no-window' } // 12. Set request to a new request with the following properties: request = makeRequest({ // URL request’s URL. // undici implementation note: this is set as the first item in request's urlList in makeRequest // method request’s method. method: request.method, // header list A copy of request’s header list. // undici implementation note: headersList is cloned in makeRequest headersList: request.headersList, // unsafe-request flag Set. unsafeRequest: request.unsafeRequest, // client This’s relevant settings object. client: this[kRealm].settingsObject, // window window. window, // priority request’s priority. priority: request.priority, // origin request’s origin. The propagation of the origin is only significant for navigation requests // being handled by a service worker. In this scenario a request can have an origin that is different // from the current client. origin: request.origin, // referrer request’s referrer. referrer: request.referrer, // referrer policy request’s referrer policy. referrerPolicy: request.referrerPolicy, // mode request’s mode. mode: request.mode, // credentials mode request’s credentials mode. credentials: request.credentials, // cache mode request’s cache mode. cache: request.cache, // redirect mode request’s redirect mode. redirect: request.redirect, // integrity metadata request’s integrity metadata. integrity: request.integrity, // keepalive request’s keepalive. keepalive: request.keepalive, // reload-navigation flag request’s reload-navigation flag. reloadNavigation: request.reloadNavigation, // history-navigation flag request’s history-navigation flag. historyNavigation: request.historyNavigation, // URL list A clone of request’s URL list. urlList: [...request.urlList] }) const initHasKey = Object.keys(init).length !== 0 // 13. If init is not empty, then: if (initHasKey) { // 1. If request’s mode is "navigate", then set it to "same-origin". if (request.mode === 'navigate') { request.mode = 'same-origin' } // 2. Unset request’s reload-navigation flag. request.reloadNavigation = false // 3. Unset request’s history-navigation flag. request.historyNavigation = false // 4. Set request’s origin to "client". request.origin = 'client' // 5. Set request’s referrer to "client" request.referrer = 'client' // 6. Set request’s referrer policy to the empty string. request.referrerPolicy = '' // 7. Set request’s URL to request’s current URL. request.url = request.urlList[request.urlList.length - 1] // 8. Set request’s URL list to « request’s URL ». request.urlList = [request.url] } // 14. If init["referrer"] exists, then: if (init.referrer !== undefined) { // 1. Let referrer be init["referrer"]. const referrer = init.referrer // 2. If referrer is the empty string, then set request’s referrer to "no-referrer". if (referrer === '') { request.referrer = 'no-referrer' } else { // 1. Let parsedReferrer be the result of parsing referrer with // baseURL. // 2. If parsedReferrer is failure, then throw a TypeError. let parsedReferrer try { parsedReferrer = new URL(referrer, baseUrl) } catch (err) { throw new TypeError(`Referrer "${referrer}" is not a valid URL.`, { cause: err }) } // 3. If one of the following is true // - parsedReferrer’s scheme is "about" and path is the string "client" // - parsedReferrer’s origin is not same origin with origin // then set request’s referrer to "client". if ( (parsedReferrer.protocol === 'about:' && parsedReferrer.hostname === 'client') || (origin && !sameOrigin(parsedReferrer, this[kRealm].settingsObject.baseUrl)) ) { request.referrer = 'client' } else { // 4. Otherwise, set request’s referrer to parsedReferrer. request.referrer = parsedReferrer } } } // 15. If init["referrerPolicy"] exists, then set request’s referrer policy // to it. if (init.referrerPolicy !== undefined) { request.referrerPolicy = init.referrerPolicy } // 16. Let mode be init["mode"] if it exists, and fallbackMode otherwise. let mode if (init.mode !== undefined) { mode = init.mode } else { mode = fallbackMode } // 17. If mode is "navigate", then throw a TypeError. if (mode === 'navigate') { throw webidl.errors.exception({ header: 'Request constructor', message: 'invalid request mode navigate.' }) } // 18. If mode is non-null, set request’s mode to mode. if (mode != null) { request.mode = mode } // 19. If init["credentials"] exists, then set request’s credentials mode // to it. if (init.credentials !== undefined) { request.credentials = init.credentials } // 18. If init["cache"] exists, then set request’s cache mode to it. if (init.cache !== undefined) { request.cache = init.cache } // 21. If request’s cache mode is "only-if-cached" and request’s mode is // not "same-origin", then throw a TypeError. if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') { throw new TypeError( "'only-if-cached' can be set only with 'same-origin' mode" ) } // 22. If init["redirect"] exists, then set request’s redirect mode to it. if (init.redirect !== undefined) { request.redirect = init.redirect } // 23. If init["integrity"] exists, then set request’s integrity metadata to it. if (init.integrity != null) { request.integrity = String(init.integrity) } // 24. If init["keepalive"] exists, then set request’s keepalive to it. if (init.keepalive !== undefined) { request.keepalive = Boolean(init.keepalive) } // 25. If init["method"] exists, then: if (init.method !== undefined) { // 1. Let method be init["method"]. let method = init.method // 2. If method is not a method or method is a forbidden method, then // throw a TypeError. if (!isValidHTTPToken(method)) { throw new TypeError(`'${method}' is not a valid HTTP method.`) } if (forbiddenMethodsSet.has(method.toUpperCase())) { throw new TypeError(`'${method}' HTTP method is unsupported.`) } // 3. Normalize method. method = normalizeMethodRecord[method] ?? normalizeMethod(method) // 4. Set request’s method to method. request.method = method } // 26. If init["signal"] exists, then set signal to it. if (init.signal !== undefined) { signal = init.signal } // 27. Set this’s request to request. this[kState] = request // 28. Set this’s signal to a new AbortSignal object with this’s relevant // Realm. // TODO: could this be simplified with AbortSignal.any // (https://dom.spec.whatwg.org/#dom-abortsignal-any) const ac = new AbortController() this[kSignal] = ac.signal this[kSignal][kRealm] = this[kRealm] // 29. If signal is not null, then make this’s signal follow signal. if (signal != null) { if ( !signal || typeof signal.aborted !== 'boolean' || typeof signal.addEventListener !== 'function' ) { throw new TypeError( "Failed to construct 'Request': member signal is not of type AbortSignal." ) } if (signal.aborted) { ac.abort(signal.reason) } else { // Keep a strong ref to ac while request object // is alive. This is needed to prevent AbortController // from being prematurely garbage collected. // See, https://github.com/nodejs/undici/issues/1926. this[kAbortController] = ac const acRef = new WeakRef(ac) const abort = function () { const ac = acRef.deref() if (ac !== undefined) { ac.abort(this.reason) } } // Third-party AbortControllers may not work with these. // See, https://github.com/nodejs/undici/pull/1910#issuecomment-1464495619. try { // If the max amount of listeners is equal to the default, increase it // This is only available in node >= v19.9.0 if (typeof getMaxListeners === 'function' && getMaxListeners(signal) === defaultMaxListeners) { setMaxListeners(100, signal) } else if (getEventListeners(signal, 'abort').length >= defaultMaxListeners) { setMaxListeners(100, signal) } } catch {} util.addAbortListener(signal, abort) requestFinalizer.register(ac, { signal, abort }) } } // 30. Set this’s headers to a new Headers object with this’s relevant // Realm, whose header list is request’s header list and guard is // "request". this[kHeaders] = new Headers(kConstruct) this[kHeaders][kHeadersList] = request.headersList this[kHeaders][kGuard] = 'request' this[kHeaders][kRealm] = this[kRealm] // 31. If this’s request’s mode is "no-cors", then: if (mode === 'no-cors') { // 1. If this’s request’s method is not a CORS-safelisted method, // then throw a TypeError. if (!corsSafeListedMethodsSet.has(request.method)) { throw new TypeError( `'${request.method} is unsupported in no-cors mode.` ) } // 2. Set this’s headers’s guard to "request-no-cors". this[kHeaders][kGuard] = 'request-no-cors' } // 32. If init is not empty, then: if (initHasKey) { /** @type {HeadersList} */ const headersList = this[kHeaders][kHeadersList] // 1. Let headers be a copy of this’s headers and its associated header // list. // 2. If init["headers"] exists, then set headers to init["headers"]. const headers = init.headers !== undefined ? init.headers : new HeadersList(headersList) // 3. Empty this’s headers’s header list. headersList.clear() // 4. If headers is a Headers object, then for each header in its header // list, append header’s name/header’s value to this’s headers. if (headers instanceof HeadersList) { for (const [key, val] of headers) { headersList.append(key, val) } // Note: Copy the `set-cookie` meta-data. headersList.cookies = headers.cookies } else { // 5. Otherwise, fill this’s headers with headers. fillHeaders(this[kHeaders], headers) } } // 33. Let inputBody be input’s request’s body if input is a Request // object; otherwise null. const inputBody = input instanceof Request ? input[kState].body : null // 34. If either init["body"] exists and is non-null or inputBody is // non-null, and request’s method is `GET` or `HEAD`, then throw a // TypeError. if ( (init.body != null || inputBody != null) && (request.method === 'GET' || request.method === 'HEAD') ) { throw new TypeError('Request with GET/HEAD method cannot have body.') } // 35. Let initBody be null. let initBody = null // 36. If init["body"] exists and is non-null, then: if (init.body != null) { // 1. Let Content-Type be null. // 2. Set initBody and Content-Type to the result of extracting // init["body"], with keepalive set to request’s keepalive. const [extractedBody, contentType] = extractBody( init.body, request.keepalive ) initBody = extractedBody // 3, If Content-Type is non-null and this’s headers’s header list does // not contain `Content-Type`, then append `Content-Type`/Content-Type to // this’s headers. if (contentType && !this[kHeaders][kHeadersList].contains('content-type')) { this[kHeaders].append('content-type', contentType) } } // 37. Let inputOrInitBody be initBody if it is non-null; otherwise // inputBody. const inputOrInitBody = initBody ?? inputBody // 38. If inputOrInitBody is non-null and inputOrInitBody’s source is // null, then: if (inputOrInitBody != null && inputOrInitBody.source == null) { // 1. If initBody is non-null and init["duplex"] does not exist, // then throw a TypeError. if (initBody != null && init.duplex == null) { throw new TypeError('RequestInit: duplex option is required when sending a body.') } // 2. If this’s request’s mode is neither "same-origin" nor "cors", // then throw a TypeError. if (request.mode !== 'same-origin' && request.mode !== 'cors') { throw new TypeError( 'If request is made from ReadableStream, mode should be "same-origin" or "cors"' ) } // 3. Set this’s request’s use-CORS-preflight flag. request.useCORSPreflightFlag = true } // 39. Let finalBody be inputOrInitBody. let finalBody = inputOrInitBody // 40. If initBody is null and inputBody is non-null, then: if (initBody == null && inputBody != null) { // 1. If input is unusable, then throw a TypeError. if (util.isDisturbed(inputBody.stream) || inputBody.stream.locked) { throw new TypeError( 'Cannot construct a Request with a Request object that has already been used.' ) } // 2. Set finalBody to the result of creating a proxy for inputBody. if (!TransformStream) { TransformStream = (__nccwpck_require__(35356).TransformStream) } // https://streams.spec.whatwg.org/#readablestream-create-a-proxy const identityTransform = new TransformStream() inputBody.stream.pipeThrough(identityTransform) finalBody = { source: inputBody.source, length: inputBody.length, stream: identityTransform.readable } } // 41. Set this’s request’s body to finalBody. this[kState].body = finalBody } // Returns request’s HTTP method, which is "GET" by default. get method () { webidl.brandCheck(this, Request) // The method getter steps are to return this’s request’s method. return this[kState].method } // Returns the URL of request as a string. get url () { webidl.brandCheck(this, Request) // The url getter steps are to return this’s request’s URL, serialized. return URLSerializer(this[kState].url) } // Returns a Headers object consisting of the headers associated with request. // Note that headers added in the network layer by the user agent will not // be accounted for in this object, e.g., the "Host" header. get headers () { webidl.brandCheck(this, Request) // The headers getter steps are to return this’s headers. return this[kHeaders] } // Returns the kind of resource requested by request, e.g., "document" // or "script". get destination () { webidl.brandCheck(this, Request) // The destination getter are to return this’s request’s destination. return this[kState].destination } // Returns the referrer of request. Its value can be a same-origin URL if // explicitly set in init, the empty string to indicate no referrer, and // "about:client" when defaulting to the global’s default. This is used // during fetching to determine the value of the `Referer` header of the // request being made. get referrer () { webidl.brandCheck(this, Request) // 1. If this’s request’s referrer is "no-referrer", then return the // empty string. if (this[kState].referrer === 'no-referrer') { return '' } // 2. If this’s request’s referrer is "client", then return // "about:client". if (this[kState].referrer === 'client') { return 'about:client' } // Return this’s request’s referrer, serialized. return this[kState].referrer.toString() } // Returns the referrer policy associated with request. // This is used during fetching to compute the value of the request’s // referrer. get referrerPolicy () { webidl.brandCheck(this, Request) // The referrerPolicy getter steps are to return this’s request’s referrer policy. return this[kState].referrerPolicy } // Returns the mode associated with request, which is a string indicating // whether the request will use CORS, or will be restricted to same-origin // URLs. get mode () { webidl.brandCheck(this, Request) // The mode getter steps are to return this’s request’s mode. return this[kState].mode } // Returns the credentials mode associated with request, // which is a string indicating whether credentials will be sent with the // request always, never, or only when sent to a same-origin URL. get credentials () { // The credentials getter steps are to return this’s request’s credentials mode. return this[kState].credentials } // Returns the cache mode associated with request, // which is a string indicating how the request will // interact with the browser’s cache when fetching. get cache () { webidl.brandCheck(this, Request) // The cache getter steps are to return this’s request’s cache mode. return this[kState].cache } // Returns the redirect mode associated with request, // which is a string indicating how redirects for the // request will be handled during fetching. A request // will follow redirects by default. get redirect () { webidl.brandCheck(this, Request) // The redirect getter steps are to return this’s request’s redirect mode. return this[kState].redirect } // Returns request’s subresource integrity metadata, which is a // cryptographic hash of the resource being fetched. Its value // consists of multiple hashes separated by whitespace. [SRI] get integrity () { webidl.brandCheck(this, Request) // The integrity getter steps are to return this’s request’s integrity // metadata. return this[kState].integrity } // Returns a boolean indicating whether or not request can outlive the // global in which it was created. get keepalive () { webidl.brandCheck(this, Request) // The keepalive getter steps are to return this’s request’s keepalive. return this[kState].keepalive } // Returns a boolean indicating whether or not request is for a reload // navigation. get isReloadNavigation () { webidl.brandCheck(this, Request) // The isReloadNavigation getter steps are to return true if this’s // request’s reload-navigation flag is set; otherwise false. return this[kState].reloadNavigation } // Returns a boolean indicating whether or not request is for a history // navigation (a.k.a. back-foward navigation). get isHistoryNavigation () { webidl.brandCheck(this, Request) // The isHistoryNavigation getter steps are to return true if this’s request’s // history-navigation flag is set; otherwise false. return this[kState].historyNavigation } // Returns the signal associated with request, which is an AbortSignal // object indicating whether or not request has been aborted, and its // abort event handler. get signal () { webidl.brandCheck(this, Request) // The signal getter steps are to return this’s signal. return this[kSignal] } get body () { webidl.brandCheck(this, Request) return this[kState].body ? this[kState].body.stream : null } get bodyUsed () { webidl.brandCheck(this, Request) return !!this[kState].body && util.isDisturbed(this[kState].body.stream) } get duplex () { webidl.brandCheck(this, Request) return 'half' } // Returns a clone of request. clone () { webidl.brandCheck(this, Request) // 1. If this is unusable, then throw a TypeError. if (this.bodyUsed || this.body?.locked) { throw new TypeError('unusable') } // 2. Let clonedRequest be the result of cloning this’s request. const clonedRequest = cloneRequest(this[kState]) // 3. Let clonedRequestObject be the result of creating a Request object, // given clonedRequest, this’s headers’s guard, and this’s relevant Realm. const clonedRequestObject = new Request(kConstruct) clonedRequestObject[kState] = clonedRequest clonedRequestObject[kRealm] = this[kRealm] clonedRequestObject[kHeaders] = new Headers(kConstruct) clonedRequestObject[kHeaders][kHeadersList] = clonedRequest.headersList clonedRequestObject[kHeaders][kGuard] = this[kHeaders][kGuard] clonedRequestObject[kHeaders][kRealm] = this[kHeaders][kRealm] // 4. Make clonedRequestObject’s signal follow this’s signal. const ac = new AbortController() if (this.signal.aborted) { ac.abort(this.signal.reason) } else { util.addAbortListener( this.signal, () => { ac.abort(this.signal.reason) } ) } clonedRequestObject[kSignal] = ac.signal // 4. Return clonedRequestObject. return clonedRequestObject } } mixinBody(Request) function makeRequest (init) { // https://fetch.spec.whatwg.org/#requests const request = { method: 'GET', localURLsOnly: false, unsafeRequest: false, body: null, client: null, reservedClient: null, replacesClientId: '', window: 'client', keepalive: false, serviceWorkers: 'all', initiator: '', destination: '', priority: null, origin: 'client', policyContainer: 'client', referrer: 'client', referrerPolicy: '', mode: 'no-cors', useCORSPreflightFlag: false, credentials: 'same-origin', useCredentials: false, cache: 'default', redirect: 'follow', integrity: '', cryptoGraphicsNonceMetadata: '', parserMetadata: '', reloadNavigation: false, historyNavigation: false, userActivation: false, taintedOrigin: false, redirectCount: 0, responseTainting: 'basic', preventNoCacheCacheControlHeaderModification: false, done: false, timingAllowFailed: false, ...init, headersList: init.headersList ? new HeadersList(init.headersList) : new HeadersList() } request.url = request.urlList[0] return request } // https://fetch.spec.whatwg.org/#concept-request-clone function cloneRequest (request) { // To clone a request request, run these steps: // 1. Let newRequest be a copy of request, except for its body. const newRequest = makeRequest({ ...request, body: null }) // 2. If request’s body is non-null, set newRequest’s body to the // result of cloning request’s body. if (request.body != null) { newRequest.body = cloneBody(request.body) } // 3. Return newRequest. return newRequest } Object.defineProperties(Request.prototype, { method: kEnumerableProperty, url: kEnumerableProperty, headers: kEnumerableProperty, redirect: kEnumerableProperty, clone: kEnumerableProperty, signal: kEnumerableProperty, duplex: kEnumerableProperty, destination: kEnumerableProperty, body: kEnumerableProperty, bodyUsed: kEnumerableProperty, isHistoryNavigation: kEnumerableProperty, isReloadNavigation: kEnumerableProperty, keepalive: kEnumerableProperty, integrity: kEnumerableProperty, cache: kEnumerableProperty, credentials: kEnumerableProperty, attribute: kEnumerableProperty, referrerPolicy: kEnumerableProperty, referrer: kEnumerableProperty, mode: kEnumerableProperty, [Symbol.toStringTag]: { value: 'Request', configurable: true } }) webidl.converters.Request = webidl.interfaceConverter( Request ) // https://fetch.spec.whatwg.org/#requestinfo webidl.converters.RequestInfo = function (V) { if (typeof V === 'string') { return webidl.converters.USVString(V) } if (V instanceof Request) { return webidl.converters.Request(V) } return webidl.converters.USVString(V) } webidl.converters.AbortSignal = webidl.interfaceConverter( AbortSignal ) // https://fetch.spec.whatwg.org/#requestinit webidl.converters.RequestInit = webidl.dictionaryConverter([ { key: 'method', converter: webidl.converters.ByteString }, { key: 'headers', converter: webidl.converters.HeadersInit }, { key: 'body', converter: webidl.nullableConverter( webidl.converters.BodyInit ) }, { key: 'referrer', converter: webidl.converters.USVString }, { key: 'referrerPolicy', converter: webidl.converters.DOMString, // https://w3c.github.io/webappsec-referrer-policy/#referrer-policy allowedValues: referrerPolicy }, { key: 'mode', converter: webidl.converters.DOMString, // https://fetch.spec.whatwg.org/#concept-request-mode allowedValues: requestMode }, { key: 'credentials', converter: webidl.converters.DOMString, // https://fetch.spec.whatwg.org/#requestcredentials allowedValues: requestCredentials }, { key: 'cache', converter: webidl.converters.DOMString, // https://fetch.spec.whatwg.org/#requestcache allowedValues: requestCache }, { key: 'redirect', converter: webidl.converters.DOMString, // https://fetch.spec.whatwg.org/#requestredirect allowedValues: requestRedirect }, { key: 'integrity', converter: webidl.converters.DOMString }, { key: 'keepalive', converter: webidl.converters.boolean }, { key: 'signal', converter: webidl.nullableConverter( (signal) => webidl.converters.AbortSignal( signal, { strict: false } ) ) }, { key: 'window', converter: webidl.converters.any }, { key: 'duplex', converter: webidl.converters.DOMString, allowedValues: requestDuplex } ]) module.exports = { Request, makeRequest } /***/ }), /***/ 27823: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { Headers, HeadersList, fill } = __nccwpck_require__(10554) const { extractBody, cloneBody, mixinBody } = __nccwpck_require__(41472) const util = __nccwpck_require__(83983) const { kEnumerableProperty } = util const { isValidReasonPhrase, isCancelled, isAborted, isBlobLike, serializeJavascriptValueToJSONString, isErrorLike, isomorphicEncode } = __nccwpck_require__(52538) const { redirectStatusSet, nullBodyStatus, DOMException } = __nccwpck_require__(41037) const { kState, kHeaders, kGuard, kRealm } = __nccwpck_require__(15861) const { webidl } = __nccwpck_require__(21744) const { FormData } = __nccwpck_require__(72015) const { getGlobalOrigin } = __nccwpck_require__(71246) const { URLSerializer } = __nccwpck_require__(685) const { kHeadersList, kConstruct } = __nccwpck_require__(72785) const assert = __nccwpck_require__(39491) const { types } = __nccwpck_require__(73837) const ReadableStream = globalThis.ReadableStream || (__nccwpck_require__(35356).ReadableStream) const textEncoder = new TextEncoder('utf-8') // https://fetch.spec.whatwg.org/#response-class class Response { // Creates network error Response. static error () { // TODO const relevantRealm = { settingsObject: {} } // The static error() method steps are to return the result of creating a // Response object, given a new network error, "immutable", and this’s // relevant Realm. const responseObject = new Response() responseObject[kState] = makeNetworkError() responseObject[kRealm] = relevantRealm responseObject[kHeaders][kHeadersList] = responseObject[kState].headersList responseObject[kHeaders][kGuard] = 'immutable' responseObject[kHeaders][kRealm] = relevantRealm return responseObject } // https://fetch.spec.whatwg.org/#dom-response-json static json (data, init = {}) { webidl.argumentLengthCheck(arguments, 1, { header: 'Response.json' }) if (init !== null) { init = webidl.converters.ResponseInit(init) } // 1. Let bytes the result of running serialize a JavaScript value to JSON bytes on data. const bytes = textEncoder.encode( serializeJavascriptValueToJSONString(data) ) // 2. Let body be the result of extracting bytes. const body = extractBody(bytes) // 3. Let responseObject be the result of creating a Response object, given a new response, // "response", and this’s relevant Realm. const relevantRealm = { settingsObject: {} } const responseObject = new Response() responseObject[kRealm] = relevantRealm responseObject[kHeaders][kGuard] = 'response' responseObject[kHeaders][kRealm] = relevantRealm // 4. Perform initialize a response given responseObject, init, and (body, "application/json"). initializeResponse(responseObject, init, { body: body[0], type: 'application/json' }) // 5. Return responseObject. return responseObject } // Creates a redirect Response that redirects to url with status status. static redirect (url, status = 302) { const relevantRealm = { settingsObject: {} } webidl.argumentLengthCheck(arguments, 1, { header: 'Response.redirect' }) url = webidl.converters.USVString(url) status = webidl.converters['unsigned short'](status) // 1. Let parsedURL be the result of parsing url with current settings // object’s API base URL. // 2. If parsedURL is failure, then throw a TypeError. // TODO: base-URL? let parsedURL try { parsedURL = new URL(url, getGlobalOrigin()) } catch (err) { throw Object.assign(new TypeError('Failed to parse URL from ' + url), { cause: err }) } // 3. If status is not a redirect status, then throw a RangeError. if (!redirectStatusSet.has(status)) { throw new RangeError('Invalid status code ' + status) } // 4. Let responseObject be the result of creating a Response object, // given a new response, "immutable", and this’s relevant Realm. const responseObject = new Response() responseObject[kRealm] = relevantRealm responseObject[kHeaders][kGuard] = 'immutable' responseObject[kHeaders][kRealm] = relevantRealm // 5. Set responseObject’s response’s status to status. responseObject[kState].status = status // 6. Let value be parsedURL, serialized and isomorphic encoded. const value = isomorphicEncode(URLSerializer(parsedURL)) // 7. Append `Location`/value to responseObject’s response’s header list. responseObject[kState].headersList.append('location', value) // 8. Return responseObject. return responseObject } // https://fetch.spec.whatwg.org/#dom-response constructor (body = null, init = {}) { if (body !== null) { body = webidl.converters.BodyInit(body) } init = webidl.converters.ResponseInit(init) // TODO this[kRealm] = { settingsObject: {} } // 1. Set this’s response to a new response. this[kState] = makeResponse({}) // 2. Set this’s headers to a new Headers object with this’s relevant // Realm, whose header list is this’s response’s header list and guard // is "response". this[kHeaders] = new Headers(kConstruct) this[kHeaders][kGuard] = 'response' this[kHeaders][kHeadersList] = this[kState].headersList this[kHeaders][kRealm] = this[kRealm] // 3. Let bodyWithType be null. let bodyWithType = null // 4. If body is non-null, then set bodyWithType to the result of extracting body. if (body != null) { const [extractedBody, type] = extractBody(body) bodyWithType = { body: extractedBody, type } } // 5. Perform initialize a response given this, init, and bodyWithType. initializeResponse(this, init, bodyWithType) } // Returns response’s type, e.g., "cors". get type () { webidl.brandCheck(this, Response) // The type getter steps are to return this’s response’s type. return this[kState].type } // Returns response’s URL, if it has one; otherwise the empty string. get url () { webidl.brandCheck(this, Response) const urlList = this[kState].urlList // The url getter steps are to return the empty string if this’s // response’s URL is null; otherwise this’s response’s URL, // serialized with exclude fragment set to true. const url = urlList[urlList.length - 1] ?? null if (url === null) { return '' } return URLSerializer(url, true) } // Returns whether response was obtained through a redirect. get redirected () { webidl.brandCheck(this, Response) // The redirected getter steps are to return true if this’s response’s URL // list has more than one item; otherwise false. return this[kState].urlList.length > 1 } // Returns response’s status. get status () { webidl.brandCheck(this, Response) // The status getter steps are to return this’s response’s status. return this[kState].status } // Returns whether response’s status is an ok status. get ok () { webidl.brandCheck(this, Response) // The ok getter steps are to return true if this’s response’s status is an // ok status; otherwise false. return this[kState].status >= 200 && this[kState].status <= 299 } // Returns response’s status message. get statusText () { webidl.brandCheck(this, Response) // The statusText getter steps are to return this’s response’s status // message. return this[kState].statusText } // Returns response’s headers as Headers. get headers () { webidl.brandCheck(this, Response) // The headers getter steps are to return this’s headers. return this[kHeaders] } get body () { webidl.brandCheck(this, Response) return this[kState].body ? this[kState].body.stream : null } get bodyUsed () { webidl.brandCheck(this, Response) return !!this[kState].body && util.isDisturbed(this[kState].body.stream) } // Returns a clone of response. clone () { webidl.brandCheck(this, Response) // 1. If this is unusable, then throw a TypeError. if (this.bodyUsed || (this.body && this.body.locked)) { throw webidl.errors.exception({ header: 'Response.clone', message: 'Body has already been consumed.' }) } // 2. Let clonedResponse be the result of cloning this’s response. const clonedResponse = cloneResponse(this[kState]) // 3. Return the result of creating a Response object, given // clonedResponse, this’s headers’s guard, and this’s relevant Realm. const clonedResponseObject = new Response() clonedResponseObject[kState] = clonedResponse clonedResponseObject[kRealm] = this[kRealm] clonedResponseObject[kHeaders][kHeadersList] = clonedResponse.headersList clonedResponseObject[kHeaders][kGuard] = this[kHeaders][kGuard] clonedResponseObject[kHeaders][kRealm] = this[kHeaders][kRealm] return clonedResponseObject } } mixinBody(Response) Object.defineProperties(Response.prototype, { type: kEnumerableProperty, url: kEnumerableProperty, status: kEnumerableProperty, ok: kEnumerableProperty, redirected: kEnumerableProperty, statusText: kEnumerableProperty, headers: kEnumerableProperty, clone: kEnumerableProperty, body: kEnumerableProperty, bodyUsed: kEnumerableProperty, [Symbol.toStringTag]: { value: 'Response', configurable: true } }) Object.defineProperties(Response, { json: kEnumerableProperty, redirect: kEnumerableProperty, error: kEnumerableProperty }) // https://fetch.spec.whatwg.org/#concept-response-clone function cloneResponse (response) { // To clone a response response, run these steps: // 1. If response is a filtered response, then return a new identical // filtered response whose internal response is a clone of response’s // internal response. if (response.internalResponse) { return filterResponse( cloneResponse(response.internalResponse), response.type ) } // 2. Let newResponse be a copy of response, except for its body. const newResponse = makeResponse({ ...response, body: null }) // 3. If response’s body is non-null, then set newResponse’s body to the // result of cloning response’s body. if (response.body != null) { newResponse.body = cloneBody(response.body) } // 4. Return newResponse. return newResponse } function makeResponse (init) { return { aborted: false, rangeRequested: false, timingAllowPassed: false, requestIncludesCredentials: false, type: 'default', status: 200, timingInfo: null, cacheState: '', statusText: '', ...init, headersList: init.headersList ? new HeadersList(init.headersList) : new HeadersList(), urlList: init.urlList ? [...init.urlList] : [] } } function makeNetworkError (reason) { const isError = isErrorLike(reason) return makeResponse({ type: 'error', status: 0, error: isError ? reason : new Error(reason ? String(reason) : reason), aborted: reason && reason.name === 'AbortError' }) } function makeFilteredResponse (response, state) { state = { internalResponse: response, ...state } return new Proxy(response, { get (target, p) { return p in state ? state[p] : target[p] }, set (target, p, value) { assert(!(p in state)) target[p] = value return true } }) } // https://fetch.spec.whatwg.org/#concept-filtered-response function filterResponse (response, type) { // Set response to the following filtered response with response as its // internal response, depending on request’s response tainting: if (type === 'basic') { // A basic filtered response is a filtered response whose type is "basic" // and header list excludes any headers in internal response’s header list // whose name is a forbidden response-header name. // Note: undici does not implement forbidden response-header names return makeFilteredResponse(response, { type: 'basic', headersList: response.headersList }) } else if (type === 'cors') { // A CORS filtered response is a filtered response whose type is "cors" // and header list excludes any headers in internal response’s header // list whose name is not a CORS-safelisted response-header name, given // internal response’s CORS-exposed header-name list. // Note: undici does not implement CORS-safelisted response-header names return makeFilteredResponse(response, { type: 'cors', headersList: response.headersList }) } else if (type === 'opaque') { // An opaque filtered response is a filtered response whose type is // "opaque", URL list is the empty list, status is 0, status message // is the empty byte sequence, header list is empty, and body is null. return makeFilteredResponse(response, { type: 'opaque', urlList: Object.freeze([]), status: 0, statusText: '', body: null }) } else if (type === 'opaqueredirect') { // An opaque-redirect filtered response is a filtered response whose type // is "opaqueredirect", status is 0, status message is the empty byte // sequence, header list is empty, and body is null. return makeFilteredResponse(response, { type: 'opaqueredirect', status: 0, statusText: '', headersList: [], body: null }) } else { assert(false) } } // https://fetch.spec.whatwg.org/#appropriate-network-error function makeAppropriateNetworkError (fetchParams, err = null) { // 1. Assert: fetchParams is canceled. assert(isCancelled(fetchParams)) // 2. Return an aborted network error if fetchParams is aborted; // otherwise return a network error. return isAborted(fetchParams) ? makeNetworkError(Object.assign(new DOMException('The operation was aborted.', 'AbortError'), { cause: err })) : makeNetworkError(Object.assign(new DOMException('Request was cancelled.'), { cause: err })) } // https://whatpr.org/fetch/1392.html#initialize-a-response function initializeResponse (response, init, body) { // 1. If init["status"] is not in the range 200 to 599, inclusive, then // throw a RangeError. if (init.status !== null && (init.status < 200 || init.status > 599)) { throw new RangeError('init["status"] must be in the range of 200 to 599, inclusive.') } // 2. If init["statusText"] does not match the reason-phrase token production, // then throw a TypeError. if ('statusText' in init && init.statusText != null) { // See, https://datatracker.ietf.org/doc/html/rfc7230#section-3.1.2: // reason-phrase = *( HTAB / SP / VCHAR / obs-text ) if (!isValidReasonPhrase(String(init.statusText))) { throw new TypeError('Invalid statusText') } } // 3. Set response’s response’s status to init["status"]. if ('status' in init && init.status != null) { response[kState].status = init.status } // 4. Set response’s response’s status message to init["statusText"]. if ('statusText' in init && init.statusText != null) { response[kState].statusText = init.statusText } // 5. If init["headers"] exists, then fill response’s headers with init["headers"]. if ('headers' in init && init.headers != null) { fill(response[kHeaders], init.headers) } // 6. If body was given, then: if (body) { // 1. If response's status is a null body status, then throw a TypeError. if (nullBodyStatus.includes(response.status)) { throw webidl.errors.exception({ header: 'Response constructor', message: 'Invalid response status code ' + response.status }) } // 2. Set response's body to body's body. response[kState].body = body.body // 3. If body's type is non-null and response's header list does not contain // `Content-Type`, then append (`Content-Type`, body's type) to response's header list. if (body.type != null && !response[kState].headersList.contains('Content-Type')) { response[kState].headersList.append('content-type', body.type) } } } webidl.converters.ReadableStream = webidl.interfaceConverter( ReadableStream ) webidl.converters.FormData = webidl.interfaceConverter( FormData ) webidl.converters.URLSearchParams = webidl.interfaceConverter( URLSearchParams ) // https://fetch.spec.whatwg.org/#typedefdef-xmlhttprequestbodyinit webidl.converters.XMLHttpRequestBodyInit = function (V) { if (typeof V === 'string') { return webidl.converters.USVString(V) } if (isBlobLike(V)) { return webidl.converters.Blob(V, { strict: false }) } if (types.isArrayBuffer(V) || types.isTypedArray(V) || types.isDataView(V)) { return webidl.converters.BufferSource(V) } if (util.isFormDataLike(V)) { return webidl.converters.FormData(V, { strict: false }) } if (V instanceof URLSearchParams) { return webidl.converters.URLSearchParams(V) } return webidl.converters.DOMString(V) } // https://fetch.spec.whatwg.org/#bodyinit webidl.converters.BodyInit = function (V) { if (V instanceof ReadableStream) { return webidl.converters.ReadableStream(V) } // Note: the spec doesn't include async iterables, // this is an undici extension. if (V?.[Symbol.asyncIterator]) { return V } return webidl.converters.XMLHttpRequestBodyInit(V) } webidl.converters.ResponseInit = webidl.dictionaryConverter([ { key: 'status', converter: webidl.converters['unsigned short'], defaultValue: 200 }, { key: 'statusText', converter: webidl.converters.ByteString, defaultValue: '' }, { key: 'headers', converter: webidl.converters.HeadersInit } ]) module.exports = { makeNetworkError, makeResponse, makeAppropriateNetworkError, filterResponse, Response, cloneResponse } /***/ }), /***/ 15861: /***/ ((module) => { "use strict"; module.exports = { kUrl: Symbol('url'), kHeaders: Symbol('headers'), kSignal: Symbol('signal'), kState: Symbol('state'), kGuard: Symbol('guard'), kRealm: Symbol('realm') } /***/ }), /***/ 52538: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { redirectStatusSet, referrerPolicySet: referrerPolicyTokens, badPortsSet } = __nccwpck_require__(41037) const { getGlobalOrigin } = __nccwpck_require__(71246) const { performance } = __nccwpck_require__(4074) const { isBlobLike, toUSVString, ReadableStreamFrom } = __nccwpck_require__(83983) const assert = __nccwpck_require__(39491) const { isUint8Array } = __nccwpck_require__(29830) // https://nodejs.org/api/crypto.html#determining-if-crypto-support-is-unavailable /** @type {import('crypto')|undefined} */ let crypto try { crypto = __nccwpck_require__(6113) } catch { } function responseURL (response) { // https://fetch.spec.whatwg.org/#responses // A response has an associated URL. It is a pointer to the last URL // in response’s URL list and null if response’s URL list is empty. const urlList = response.urlList const length = urlList.length return length === 0 ? null : urlList[length - 1].toString() } // https://fetch.spec.whatwg.org/#concept-response-location-url function responseLocationURL (response, requestFragment) { // 1. If response’s status is not a redirect status, then return null. if (!redirectStatusSet.has(response.status)) { return null } // 2. Let location be the result of extracting header list values given // `Location` and response’s header list. let location = response.headersList.get('location') // 3. If location is a header value, then set location to the result of // parsing location with response’s URL. if (location !== null && isValidHeaderValue(location)) { location = new URL(location, responseURL(response)) } // 4. If location is a URL whose fragment is null, then set location’s // fragment to requestFragment. if (location && !location.hash) { location.hash = requestFragment } // 5. Return location. return location } /** @returns {URL} */ function requestCurrentURL (request) { return request.urlList[request.urlList.length - 1] } function requestBadPort (request) { // 1. Let url be request’s current URL. const url = requestCurrentURL(request) // 2. If url’s scheme is an HTTP(S) scheme and url’s port is a bad port, // then return blocked. if (urlIsHttpHttpsScheme(url) && badPortsSet.has(url.port)) { return 'blocked' } // 3. Return allowed. return 'allowed' } function isErrorLike (object) { return object instanceof Error || ( object?.constructor?.name === 'Error' || object?.constructor?.name === 'DOMException' ) } // Check whether |statusText| is a ByteString and // matches the Reason-Phrase token production. // RFC 2616: https://tools.ietf.org/html/rfc2616 // RFC 7230: https://tools.ietf.org/html/rfc7230 // "reason-phrase = *( HTAB / SP / VCHAR / obs-text )" // https://github.com/chromium/chromium/blob/94.0.4604.1/third_party/blink/renderer/core/fetch/response.cc#L116 function isValidReasonPhrase (statusText) { for (let i = 0; i < statusText.length; ++i) { const c = statusText.charCodeAt(i) if ( !( ( c === 0x09 || // HTAB (c >= 0x20 && c <= 0x7e) || // SP / VCHAR (c >= 0x80 && c <= 0xff) ) // obs-text ) ) { return false } } return true } /** * @see https://tools.ietf.org/html/rfc7230#section-3.2.6 * @param {number} c */ function isTokenCharCode (c) { switch (c) { case 0x22: case 0x28: case 0x29: case 0x2c: case 0x2f: case 0x3a: case 0x3b: case 0x3c: case 0x3d: case 0x3e: case 0x3f: case 0x40: case 0x5b: case 0x5c: case 0x5d: case 0x7b: case 0x7d: // DQUOTE and "(),/:;<=>?@[\]{}" return false default: // VCHAR %x21-7E return c >= 0x21 && c <= 0x7e } } /** * @param {string} characters */ function isValidHTTPToken (characters) { if (characters.length === 0) { return false } for (let i = 0; i < characters.length; ++i) { if (!isTokenCharCode(characters.charCodeAt(i))) { return false } } return true } /** * @see https://fetch.spec.whatwg.org/#header-name * @param {string} potentialValue */ function isValidHeaderName (potentialValue) { return isValidHTTPToken(potentialValue) } /** * @see https://fetch.spec.whatwg.org/#header-value * @param {string} potentialValue */ function isValidHeaderValue (potentialValue) { // - Has no leading or trailing HTTP tab or space bytes. // - Contains no 0x00 (NUL) or HTTP newline bytes. if ( potentialValue.startsWith('\t') || potentialValue.startsWith(' ') || potentialValue.endsWith('\t') || potentialValue.endsWith(' ') ) { return false } if ( potentialValue.includes('\0') || potentialValue.includes('\r') || potentialValue.includes('\n') ) { return false } return true } // https://w3c.github.io/webappsec-referrer-policy/#set-requests-referrer-policy-on-redirect function setRequestReferrerPolicyOnRedirect (request, actualResponse) { // Given a request request and a response actualResponse, this algorithm // updates request’s referrer policy according to the Referrer-Policy // header (if any) in actualResponse. // 1. Let policy be the result of executing § 8.1 Parse a referrer policy // from a Referrer-Policy header on actualResponse. // 8.1 Parse a referrer policy from a Referrer-Policy header // 1. Let policy-tokens be the result of extracting header list values given `Referrer-Policy` and response’s header list. const { headersList } = actualResponse // 2. Let policy be the empty string. // 3. For each token in policy-tokens, if token is a referrer policy and token is not the empty string, then set policy to token. // 4. Return policy. const policyHeader = (headersList.get('referrer-policy') ?? '').split(',') // Note: As the referrer-policy can contain multiple policies // separated by comma, we need to loop through all of them // and pick the first valid one. // Ref: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy#specify_a_fallback_policy let policy = '' if (policyHeader.length > 0) { // The right-most policy takes precedence. // The left-most policy is the fallback. for (let i = policyHeader.length; i !== 0; i--) { const token = policyHeader[i - 1].trim() if (referrerPolicyTokens.has(token)) { policy = token break } } } // 2. If policy is not the empty string, then set request’s referrer policy to policy. if (policy !== '') { request.referrerPolicy = policy } } // https://fetch.spec.whatwg.org/#cross-origin-resource-policy-check function crossOriginResourcePolicyCheck () { // TODO return 'allowed' } // https://fetch.spec.whatwg.org/#concept-cors-check function corsCheck () { // TODO return 'success' } // https://fetch.spec.whatwg.org/#concept-tao-check function TAOCheck () { // TODO return 'success' } function appendFetchMetadata (httpRequest) { // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-dest-header // TODO // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-mode-header // 1. Assert: r’s url is a potentially trustworthy URL. // TODO // 2. Let header be a Structured Header whose value is a token. let header = null // 3. Set header’s value to r’s mode. header = httpRequest.mode // 4. Set a structured field value `Sec-Fetch-Mode`/header in r’s header list. httpRequest.headersList.set('sec-fetch-mode', header) // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-site-header // TODO // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-user-header // TODO } // https://fetch.spec.whatwg.org/#append-a-request-origin-header function appendRequestOriginHeader (request) { // 1. Let serializedOrigin be the result of byte-serializing a request origin with request. let serializedOrigin = request.origin // 2. If request’s response tainting is "cors" or request’s mode is "websocket", then append (`Origin`, serializedOrigin) to request’s header list. if (request.responseTainting === 'cors' || request.mode === 'websocket') { if (serializedOrigin) { request.headersList.append('origin', serializedOrigin) } // 3. Otherwise, if request’s method is neither `GET` nor `HEAD`, then: } else if (request.method !== 'GET' && request.method !== 'HEAD') { // 1. Switch on request’s referrer policy: switch (request.referrerPolicy) { case 'no-referrer': // Set serializedOrigin to `null`. serializedOrigin = null break case 'no-referrer-when-downgrade': case 'strict-origin': case 'strict-origin-when-cross-origin': // If request’s origin is a tuple origin, its scheme is "https", and request’s current URL’s scheme is not "https", then set serializedOrigin to `null`. if (request.origin && urlHasHttpsScheme(request.origin) && !urlHasHttpsScheme(requestCurrentURL(request))) { serializedOrigin = null } break case 'same-origin': // If request’s origin is not same origin with request’s current URL’s origin, then set serializedOrigin to `null`. if (!sameOrigin(request, requestCurrentURL(request))) { serializedOrigin = null } break default: // Do nothing. } if (serializedOrigin) { // 2. Append (`Origin`, serializedOrigin) to request’s header list. request.headersList.append('origin', serializedOrigin) } } } function coarsenedSharedCurrentTime (crossOriginIsolatedCapability) { // TODO return performance.now() } // https://fetch.spec.whatwg.org/#create-an-opaque-timing-info function createOpaqueTimingInfo (timingInfo) { return { startTime: timingInfo.startTime ?? 0, redirectStartTime: 0, redirectEndTime: 0, postRedirectStartTime: timingInfo.startTime ?? 0, finalServiceWorkerStartTime: 0, finalNetworkResponseStartTime: 0, finalNetworkRequestStartTime: 0, endTime: 0, encodedBodySize: 0, decodedBodySize: 0, finalConnectionTimingInfo: null } } // https://html.spec.whatwg.org/multipage/origin.html#policy-container function makePolicyContainer () { // Note: the fetch spec doesn't make use of embedder policy or CSP list return { referrerPolicy: 'strict-origin-when-cross-origin' } } // https://html.spec.whatwg.org/multipage/origin.html#clone-a-policy-container function clonePolicyContainer (policyContainer) { return { referrerPolicy: policyContainer.referrerPolicy } } // https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer function determineRequestsReferrer (request) { // 1. Let policy be request's referrer policy. const policy = request.referrerPolicy // Note: policy cannot (shouldn't) be null or an empty string. assert(policy) // 2. Let environment be request’s client. let referrerSource = null // 3. Switch on request’s referrer: if (request.referrer === 'client') { // Note: node isn't a browser and doesn't implement document/iframes, // so we bypass this step and replace it with our own. const globalOrigin = getGlobalOrigin() if (!globalOrigin || globalOrigin.origin === 'null') { return 'no-referrer' } // note: we need to clone it as it's mutated referrerSource = new URL(globalOrigin) } else if (request.referrer instanceof URL) { // Let referrerSource be request’s referrer. referrerSource = request.referrer } // 4. Let request’s referrerURL be the result of stripping referrerSource for // use as a referrer. let referrerURL = stripURLForReferrer(referrerSource) // 5. Let referrerOrigin be the result of stripping referrerSource for use as // a referrer, with the origin-only flag set to true. const referrerOrigin = stripURLForReferrer(referrerSource, true) // 6. If the result of serializing referrerURL is a string whose length is // greater than 4096, set referrerURL to referrerOrigin. if (referrerURL.toString().length > 4096) { referrerURL = referrerOrigin } const areSameOrigin = sameOrigin(request, referrerURL) const isNonPotentiallyTrustWorthy = isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(request.url) // 8. Execute the switch statements corresponding to the value of policy: switch (policy) { case 'origin': return referrerOrigin != null ? referrerOrigin : stripURLForReferrer(referrerSource, true) case 'unsafe-url': return referrerURL case 'same-origin': return areSameOrigin ? referrerOrigin : 'no-referrer' case 'origin-when-cross-origin': return areSameOrigin ? referrerURL : referrerOrigin case 'strict-origin-when-cross-origin': { const currentURL = requestCurrentURL(request) // 1. If the origin of referrerURL and the origin of request’s current // URL are the same, then return referrerURL. if (sameOrigin(referrerURL, currentURL)) { return referrerURL } // 2. If referrerURL is a potentially trustworthy URL and request’s // current URL is not a potentially trustworthy URL, then return no // referrer. if (isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(currentURL)) { return 'no-referrer' } // 3. Return referrerOrigin. return referrerOrigin } case 'strict-origin': // eslint-disable-line /** * 1. If referrerURL is a potentially trustworthy URL and * request’s current URL is not a potentially trustworthy URL, * then return no referrer. * 2. Return referrerOrigin */ case 'no-referrer-when-downgrade': // eslint-disable-line /** * 1. If referrerURL is a potentially trustworthy URL and * request’s current URL is not a potentially trustworthy URL, * then return no referrer. * 2. Return referrerOrigin */ default: // eslint-disable-line return isNonPotentiallyTrustWorthy ? 'no-referrer' : referrerOrigin } } /** * @see https://w3c.github.io/webappsec-referrer-policy/#strip-url * @param {URL} url * @param {boolean|undefined} originOnly */ function stripURLForReferrer (url, originOnly) { // 1. Assert: url is a URL. assert(url instanceof URL) // 2. If url’s scheme is a local scheme, then return no referrer. if (url.protocol === 'file:' || url.protocol === 'about:' || url.protocol === 'blank:') { return 'no-referrer' } // 3. Set url’s username to the empty string. url.username = '' // 4. Set url’s password to the empty string. url.password = '' // 5. Set url’s fragment to null. url.hash = '' // 6. If the origin-only flag is true, then: if (originOnly) { // 1. Set url’s path to « the empty string ». url.pathname = '' // 2. Set url’s query to null. url.search = '' } // 7. Return url. return url } function isURLPotentiallyTrustworthy (url) { if (!(url instanceof URL)) { return false } // If child of about, return true if (url.href === 'about:blank' || url.href === 'about:srcdoc') { return true } // If scheme is data, return true if (url.protocol === 'data:') return true // If file, return true if (url.protocol === 'file:') return true return isOriginPotentiallyTrustworthy(url.origin) function isOriginPotentiallyTrustworthy (origin) { // If origin is explicitly null, return false if (origin == null || origin === 'null') return false const originAsURL = new URL(origin) // If secure, return true if (originAsURL.protocol === 'https:' || originAsURL.protocol === 'wss:') { return true } // If localhost or variants, return true if (/^127(?:\.[0-9]+){0,2}\.[0-9]+$|^\[(?:0*:)*?:?0*1\]$/.test(originAsURL.hostname) || (originAsURL.hostname === 'localhost' || originAsURL.hostname.includes('localhost.')) || (originAsURL.hostname.endsWith('.localhost'))) { return true } // If any other, return false return false } } /** * @see https://w3c.github.io/webappsec-subresource-integrity/#does-response-match-metadatalist * @param {Uint8Array} bytes * @param {string} metadataList */ function bytesMatch (bytes, metadataList) { // If node is not built with OpenSSL support, we cannot check // a request's integrity, so allow it by default (the spec will // allow requests if an invalid hash is given, as precedence). /* istanbul ignore if: only if node is built with --without-ssl */ if (crypto === undefined) { return true } // 1. Let parsedMetadata be the result of parsing metadataList. const parsedMetadata = parseMetadata(metadataList) // 2. If parsedMetadata is no metadata, return true. if (parsedMetadata === 'no metadata') { return true } // 3. If parsedMetadata is the empty set, return true. if (parsedMetadata.length === 0) { return true } // 4. Let metadata be the result of getting the strongest // metadata from parsedMetadata. const list = parsedMetadata.sort((c, d) => d.algo.localeCompare(c.algo)) // get the strongest algorithm const strongest = list[0].algo // get all entries that use the strongest algorithm; ignore weaker const metadata = list.filter((item) => item.algo === strongest) // 5. For each item in metadata: for (const item of metadata) { // 1. Let algorithm be the alg component of item. const algorithm = item.algo // 2. Let expectedValue be the val component of item. let expectedValue = item.hash // See https://github.com/web-platform-tests/wpt/commit/e4c5cc7a5e48093220528dfdd1c4012dc3837a0e // "be liberal with padding". This is annoying, and it's not even in the spec. if (expectedValue.endsWith('==')) { expectedValue = expectedValue.slice(0, -2) } // 3. Let actualValue be the result of applying algorithm to bytes. let actualValue = crypto.createHash(algorithm).update(bytes).digest('base64') if (actualValue.endsWith('==')) { actualValue = actualValue.slice(0, -2) } // 4. If actualValue is a case-sensitive match for expectedValue, // return true. if (actualValue === expectedValue) { return true } let actualBase64URL = crypto.createHash(algorithm).update(bytes).digest('base64url') if (actualBase64URL.endsWith('==')) { actualBase64URL = actualBase64URL.slice(0, -2) } if (actualBase64URL === expectedValue) { return true } } // 6. Return false. return false } // https://w3c.github.io/webappsec-subresource-integrity/#grammardef-hash-with-options // https://www.w3.org/TR/CSP2/#source-list-syntax // https://www.rfc-editor.org/rfc/rfc5234#appendix-B.1 const parseHashWithOptions = /((?sha256|sha384|sha512)-(?[A-z0-9+/]{1}.*={0,2}))( +[\x21-\x7e]?)?/i /** * @see https://w3c.github.io/webappsec-subresource-integrity/#parse-metadata * @param {string} metadata */ function parseMetadata (metadata) { // 1. Let result be the empty set. /** @type {{ algo: string, hash: string }[]} */ const result = [] // 2. Let empty be equal to true. let empty = true const supportedHashes = crypto.getHashes() // 3. For each token returned by splitting metadata on spaces: for (const token of metadata.split(' ')) { // 1. Set empty to false. empty = false // 2. Parse token as a hash-with-options. const parsedToken = parseHashWithOptions.exec(token) // 3. If token does not parse, continue to the next token. if (parsedToken === null || parsedToken.groups === undefined) { // Note: Chromium blocks the request at this point, but Firefox // gives a warning that an invalid integrity was given. The // correct behavior is to ignore these, and subsequently not // check the integrity of the resource. continue } // 4. Let algorithm be the hash-algo component of token. const algorithm = parsedToken.groups.algo // 5. If algorithm is a hash function recognized by the user // agent, add the parsed token to result. if (supportedHashes.includes(algorithm.toLowerCase())) { result.push(parsedToken.groups) } } // 4. Return no metadata if empty is true, otherwise return result. if (empty === true) { return 'no metadata' } return result } // https://w3c.github.io/webappsec-upgrade-insecure-requests/#upgrade-request function tryUpgradeRequestToAPotentiallyTrustworthyURL (request) { // TODO } /** * @link {https://html.spec.whatwg.org/multipage/origin.html#same-origin} * @param {URL} A * @param {URL} B */ function sameOrigin (A, B) { // 1. If A and B are the same opaque origin, then return true. if (A.origin === B.origin && A.origin === 'null') { return true } // 2. If A and B are both tuple origins and their schemes, // hosts, and port are identical, then return true. if (A.protocol === B.protocol && A.hostname === B.hostname && A.port === B.port) { return true } // 3. Return false. return false } function createDeferredPromise () { let res let rej const promise = new Promise((resolve, reject) => { res = resolve rej = reject }) return { promise, resolve: res, reject: rej } } function isAborted (fetchParams) { return fetchParams.controller.state === 'aborted' } function isCancelled (fetchParams) { return fetchParams.controller.state === 'aborted' || fetchParams.controller.state === 'terminated' } const normalizeMethodRecord = { delete: 'DELETE', DELETE: 'DELETE', get: 'GET', GET: 'GET', head: 'HEAD', HEAD: 'HEAD', options: 'OPTIONS', OPTIONS: 'OPTIONS', post: 'POST', POST: 'POST', put: 'PUT', PUT: 'PUT' } // Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`. Object.setPrototypeOf(normalizeMethodRecord, null) /** * @see https://fetch.spec.whatwg.org/#concept-method-normalize * @param {string} method */ function normalizeMethod (method) { return normalizeMethodRecord[method.toLowerCase()] ?? method } // https://infra.spec.whatwg.org/#serialize-a-javascript-value-to-a-json-string function serializeJavascriptValueToJSONString (value) { // 1. Let result be ? Call(%JSON.stringify%, undefined, « value »). const result = JSON.stringify(value) // 2. If result is undefined, then throw a TypeError. if (result === undefined) { throw new TypeError('Value is not JSON serializable') } // 3. Assert: result is a string. assert(typeof result === 'string') // 4. Return result. return result } // https://tc39.es/ecma262/#sec-%25iteratorprototype%25-object const esIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())) /** * @see https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object * @param {() => unknown[]} iterator * @param {string} name name of the instance * @param {'key'|'value'|'key+value'} kind */ function makeIterator (iterator, name, kind) { const object = { index: 0, kind, target: iterator } const i = { next () { // 1. Let interface be the interface for which the iterator prototype object exists. // 2. Let thisValue be the this value. // 3. Let object be ? ToObject(thisValue). // 4. If object is a platform object, then perform a security // check, passing: // 5. If object is not a default iterator object for interface, // then throw a TypeError. if (Object.getPrototypeOf(this) !== i) { throw new TypeError( `'next' called on an object that does not implement interface ${name} Iterator.` ) } // 6. Let index be object’s index. // 7. Let kind be object’s kind. // 8. Let values be object’s target's value pairs to iterate over. const { index, kind, target } = object const values = target() // 9. Let len be the length of values. const len = values.length // 10. If index is greater than or equal to len, then return // CreateIterResultObject(undefined, true). if (index >= len) { return { value: undefined, done: true } } // 11. Let pair be the entry in values at index index. const pair = values[index] // 12. Set object’s index to index + 1. object.index = index + 1 // 13. Return the iterator result for pair and kind. return iteratorResult(pair, kind) }, // The class string of an iterator prototype object for a given interface is the // result of concatenating the identifier of the interface and the string " Iterator". [Symbol.toStringTag]: `${name} Iterator` } // The [[Prototype]] internal slot of an iterator prototype object must be %IteratorPrototype%. Object.setPrototypeOf(i, esIteratorPrototype) // esIteratorPrototype needs to be the prototype of i // which is the prototype of an empty object. Yes, it's confusing. return Object.setPrototypeOf({}, i) } // https://webidl.spec.whatwg.org/#iterator-result function iteratorResult (pair, kind) { let result // 1. Let result be a value determined by the value of kind: switch (kind) { case 'key': { // 1. Let idlKey be pair’s key. // 2. Let key be the result of converting idlKey to an // ECMAScript value. // 3. result is key. result = pair[0] break } case 'value': { // 1. Let idlValue be pair’s value. // 2. Let value be the result of converting idlValue to // an ECMAScript value. // 3. result is value. result = pair[1] break } case 'key+value': { // 1. Let idlKey be pair’s key. // 2. Let idlValue be pair’s value. // 3. Let key be the result of converting idlKey to an // ECMAScript value. // 4. Let value be the result of converting idlValue to // an ECMAScript value. // 5. Let array be ! ArrayCreate(2). // 6. Call ! CreateDataProperty(array, "0", key). // 7. Call ! CreateDataProperty(array, "1", value). // 8. result is array. result = pair break } } // 2. Return CreateIterResultObject(result, false). return { value: result, done: false } } /** * @see https://fetch.spec.whatwg.org/#body-fully-read */ async function fullyReadBody (body, processBody, processBodyError) { // 1. If taskDestination is null, then set taskDestination to // the result of starting a new parallel queue. // 2. Let successSteps given a byte sequence bytes be to queue a // fetch task to run processBody given bytes, with taskDestination. const successSteps = processBody // 3. Let errorSteps be to queue a fetch task to run processBodyError, // with taskDestination. const errorSteps = processBodyError // 4. Let reader be the result of getting a reader for body’s stream. // If that threw an exception, then run errorSteps with that // exception and return. let reader try { reader = body.stream.getReader() } catch (e) { errorSteps(e) return } // 5. Read all bytes from reader, given successSteps and errorSteps. try { const result = await readAllBytes(reader) successSteps(result) } catch (e) { errorSteps(e) } } /** @type {ReadableStream} */ let ReadableStream = globalThis.ReadableStream function isReadableStreamLike (stream) { if (!ReadableStream) { ReadableStream = (__nccwpck_require__(35356).ReadableStream) } return stream instanceof ReadableStream || ( stream[Symbol.toStringTag] === 'ReadableStream' && typeof stream.tee === 'function' ) } const MAXIMUM_ARGUMENT_LENGTH = 65535 /** * @see https://infra.spec.whatwg.org/#isomorphic-decode * @param {number[]|Uint8Array} input */ function isomorphicDecode (input) { // 1. To isomorphic decode a byte sequence input, return a string whose code point // length is equal to input’s length and whose code points have the same values // as the values of input’s bytes, in the same order. if (input.length < MAXIMUM_ARGUMENT_LENGTH) { return String.fromCharCode(...input) } return input.reduce((previous, current) => previous + String.fromCharCode(current), '') } /** * @param {ReadableStreamController} controller */ function readableStreamClose (controller) { try { controller.close() } catch (err) { // TODO: add comment explaining why this error occurs. if (!err.message.includes('Controller is already closed')) { throw err } } } /** * @see https://infra.spec.whatwg.org/#isomorphic-encode * @param {string} input */ function isomorphicEncode (input) { // 1. Assert: input contains no code points greater than U+00FF. for (let i = 0; i < input.length; i++) { assert(input.charCodeAt(i) <= 0xFF) } // 2. Return a byte sequence whose length is equal to input’s code // point length and whose bytes have the same values as the // values of input’s code points, in the same order return input } /** * @see https://streams.spec.whatwg.org/#readablestreamdefaultreader-read-all-bytes * @see https://streams.spec.whatwg.org/#read-loop * @param {ReadableStreamDefaultReader} reader */ async function readAllBytes (reader) { const bytes = [] let byteLength = 0 while (true) { const { done, value: chunk } = await reader.read() if (done) { // 1. Call successSteps with bytes. return Buffer.concat(bytes, byteLength) } // 1. If chunk is not a Uint8Array object, call failureSteps // with a TypeError and abort these steps. if (!isUint8Array(chunk)) { throw new TypeError('Received non-Uint8Array chunk') } // 2. Append the bytes represented by chunk to bytes. bytes.push(chunk) byteLength += chunk.length // 3. Read-loop given reader, bytes, successSteps, and failureSteps. } } /** * @see https://fetch.spec.whatwg.org/#is-local * @param {URL} url */ function urlIsLocal (url) { assert('protocol' in url) // ensure it's a url object const protocol = url.protocol return protocol === 'about:' || protocol === 'blob:' || protocol === 'data:' } /** * @param {string|URL} url */ function urlHasHttpsScheme (url) { if (typeof url === 'string') { return url.startsWith('https:') } return url.protocol === 'https:' } /** * @see https://fetch.spec.whatwg.org/#http-scheme * @param {URL} url */ function urlIsHttpHttpsScheme (url) { assert('protocol' in url) // ensure it's a url object const protocol = url.protocol return protocol === 'http:' || protocol === 'https:' } /** * Fetch supports node >= 16.8.0, but Object.hasOwn was added in v16.9.0. */ const hasOwn = Object.hasOwn || ((dict, key) => Object.prototype.hasOwnProperty.call(dict, key)) module.exports = { isAborted, isCancelled, createDeferredPromise, ReadableStreamFrom, toUSVString, tryUpgradeRequestToAPotentiallyTrustworthyURL, coarsenedSharedCurrentTime, determineRequestsReferrer, makePolicyContainer, clonePolicyContainer, appendFetchMetadata, appendRequestOriginHeader, TAOCheck, corsCheck, crossOriginResourcePolicyCheck, createOpaqueTimingInfo, setRequestReferrerPolicyOnRedirect, isValidHTTPToken, requestBadPort, requestCurrentURL, responseURL, responseLocationURL, isBlobLike, isURLPotentiallyTrustworthy, isValidReasonPhrase, sameOrigin, normalizeMethod, serializeJavascriptValueToJSONString, makeIterator, isValidHeaderName, isValidHeaderValue, hasOwn, isErrorLike, fullyReadBody, bytesMatch, isReadableStreamLike, readableStreamClose, isomorphicEncode, isomorphicDecode, urlIsLocal, urlHasHttpsScheme, urlIsHttpHttpsScheme, readAllBytes, normalizeMethodRecord } /***/ }), /***/ 21744: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { types } = __nccwpck_require__(73837) const { hasOwn, toUSVString } = __nccwpck_require__(52538) /** @type {import('../../types/webidl').Webidl} */ const webidl = {} webidl.converters = {} webidl.util = {} webidl.errors = {} webidl.errors.exception = function (message) { return new TypeError(`${message.header}: ${message.message}`) } webidl.errors.conversionFailed = function (context) { const plural = context.types.length === 1 ? '' : ' one of' const message = `${context.argument} could not be converted to` + `${plural}: ${context.types.join(', ')}.` return webidl.errors.exception({ header: context.prefix, message }) } webidl.errors.invalidArgument = function (context) { return webidl.errors.exception({ header: context.prefix, message: `"${context.value}" is an invalid ${context.type}.` }) } // https://webidl.spec.whatwg.org/#implements webidl.brandCheck = function (V, I, opts = undefined) { if (opts?.strict !== false && !(V instanceof I)) { throw new TypeError('Illegal invocation') } else { return V?.[Symbol.toStringTag] === I.prototype[Symbol.toStringTag] } } webidl.argumentLengthCheck = function ({ length }, min, ctx) { if (length < min) { throw webidl.errors.exception({ message: `${min} argument${min !== 1 ? 's' : ''} required, ` + `but${length ? ' only' : ''} ${length} found.`, ...ctx }) } } webidl.illegalConstructor = function () { throw webidl.errors.exception({ header: 'TypeError', message: 'Illegal constructor' }) } // https://tc39.es/ecma262/#sec-ecmascript-data-types-and-values webidl.util.Type = function (V) { switch (typeof V) { case 'undefined': return 'Undefined' case 'boolean': return 'Boolean' case 'string': return 'String' case 'symbol': return 'Symbol' case 'number': return 'Number' case 'bigint': return 'BigInt' case 'function': case 'object': { if (V === null) { return 'Null' } return 'Object' } } } // https://webidl.spec.whatwg.org/#abstract-opdef-converttoint webidl.util.ConvertToInt = function (V, bitLength, signedness, opts = {}) { let upperBound let lowerBound // 1. If bitLength is 64, then: if (bitLength === 64) { // 1. Let upperBound be 2^53 − 1. upperBound = Math.pow(2, 53) - 1 // 2. If signedness is "unsigned", then let lowerBound be 0. if (signedness === 'unsigned') { lowerBound = 0 } else { // 3. Otherwise let lowerBound be −2^53 + 1. lowerBound = Math.pow(-2, 53) + 1 } } else if (signedness === 'unsigned') { // 2. Otherwise, if signedness is "unsigned", then: // 1. Let lowerBound be 0. lowerBound = 0 // 2. Let upperBound be 2^bitLength − 1. upperBound = Math.pow(2, bitLength) - 1 } else { // 3. Otherwise: // 1. Let lowerBound be -2^bitLength − 1. lowerBound = Math.pow(-2, bitLength) - 1 // 2. Let upperBound be 2^bitLength − 1 − 1. upperBound = Math.pow(2, bitLength - 1) - 1 } // 4. Let x be ? ToNumber(V). let x = Number(V) // 5. If x is −0, then set x to +0. if (x === 0) { x = 0 } // 6. If the conversion is to an IDL type associated // with the [EnforceRange] extended attribute, then: if (opts.enforceRange === true) { // 1. If x is NaN, +∞, or −∞, then throw a TypeError. if ( Number.isNaN(x) || x === Number.POSITIVE_INFINITY || x === Number.NEGATIVE_INFINITY ) { throw webidl.errors.exception({ header: 'Integer conversion', message: `Could not convert ${V} to an integer.` }) } // 2. Set x to IntegerPart(x). x = webidl.util.IntegerPart(x) // 3. If x < lowerBound or x > upperBound, then // throw a TypeError. if (x < lowerBound || x > upperBound) { throw webidl.errors.exception({ header: 'Integer conversion', message: `Value must be between ${lowerBound}-${upperBound}, got ${x}.` }) } // 4. Return x. return x } // 7. If x is not NaN and the conversion is to an IDL // type associated with the [Clamp] extended // attribute, then: if (!Number.isNaN(x) && opts.clamp === true) { // 1. Set x to min(max(x, lowerBound), upperBound). x = Math.min(Math.max(x, lowerBound), upperBound) // 2. Round x to the nearest integer, choosing the // even integer if it lies halfway between two, // and choosing +0 rather than −0. if (Math.floor(x) % 2 === 0) { x = Math.floor(x) } else { x = Math.ceil(x) } // 3. Return x. return x } // 8. If x is NaN, +0, +∞, or −∞, then return +0. if ( Number.isNaN(x) || (x === 0 && Object.is(0, x)) || x === Number.POSITIVE_INFINITY || x === Number.NEGATIVE_INFINITY ) { return 0 } // 9. Set x to IntegerPart(x). x = webidl.util.IntegerPart(x) // 10. Set x to x modulo 2^bitLength. x = x % Math.pow(2, bitLength) // 11. If signedness is "signed" and x ≥ 2^bitLength − 1, // then return x − 2^bitLength. if (signedness === 'signed' && x >= Math.pow(2, bitLength) - 1) { return x - Math.pow(2, bitLength) } // 12. Otherwise, return x. return x } // https://webidl.spec.whatwg.org/#abstract-opdef-integerpart webidl.util.IntegerPart = function (n) { // 1. Let r be floor(abs(n)). const r = Math.floor(Math.abs(n)) // 2. If n < 0, then return -1 × r. if (n < 0) { return -1 * r } // 3. Otherwise, return r. return r } // https://webidl.spec.whatwg.org/#es-sequence webidl.sequenceConverter = function (converter) { return (V) => { // 1. If Type(V) is not Object, throw a TypeError. if (webidl.util.Type(V) !== 'Object') { throw webidl.errors.exception({ header: 'Sequence', message: `Value of type ${webidl.util.Type(V)} is not an Object.` }) } // 2. Let method be ? GetMethod(V, @@iterator). /** @type {Generator} */ const method = V?.[Symbol.iterator]?.() const seq = [] // 3. If method is undefined, throw a TypeError. if ( method === undefined || typeof method.next !== 'function' ) { throw webidl.errors.exception({ header: 'Sequence', message: 'Object is not an iterator.' }) } // https://webidl.spec.whatwg.org/#create-sequence-from-iterable while (true) { const { done, value } = method.next() if (done) { break } seq.push(converter(value)) } return seq } } // https://webidl.spec.whatwg.org/#es-to-record webidl.recordConverter = function (keyConverter, valueConverter) { return (O) => { // 1. If Type(O) is not Object, throw a TypeError. if (webidl.util.Type(O) !== 'Object') { throw webidl.errors.exception({ header: 'Record', message: `Value of type ${webidl.util.Type(O)} is not an Object.` }) } // 2. Let result be a new empty instance of record. const result = {} if (!types.isProxy(O)) { // Object.keys only returns enumerable properties const keys = Object.keys(O) for (const key of keys) { // 1. Let typedKey be key converted to an IDL value of type K. const typedKey = keyConverter(key) // 2. Let value be ? Get(O, key). // 3. Let typedValue be value converted to an IDL value of type V. const typedValue = valueConverter(O[key]) // 4. Set result[typedKey] to typedValue. result[typedKey] = typedValue } // 5. Return result. return result } // 3. Let keys be ? O.[[OwnPropertyKeys]](). const keys = Reflect.ownKeys(O) // 4. For each key of keys. for (const key of keys) { // 1. Let desc be ? O.[[GetOwnProperty]](key). const desc = Reflect.getOwnPropertyDescriptor(O, key) // 2. If desc is not undefined and desc.[[Enumerable]] is true: if (desc?.enumerable) { // 1. Let typedKey be key converted to an IDL value of type K. const typedKey = keyConverter(key) // 2. Let value be ? Get(O, key). // 3. Let typedValue be value converted to an IDL value of type V. const typedValue = valueConverter(O[key]) // 4. Set result[typedKey] to typedValue. result[typedKey] = typedValue } } // 5. Return result. return result } } webidl.interfaceConverter = function (i) { return (V, opts = {}) => { if (opts.strict !== false && !(V instanceof i)) { throw webidl.errors.exception({ header: i.name, message: `Expected ${V} to be an instance of ${i.name}.` }) } return V } } webidl.dictionaryConverter = function (converters) { return (dictionary) => { const type = webidl.util.Type(dictionary) const dict = {} if (type === 'Null' || type === 'Undefined') { return dict } else if (type !== 'Object') { throw webidl.errors.exception({ header: 'Dictionary', message: `Expected ${dictionary} to be one of: Null, Undefined, Object.` }) } for (const options of converters) { const { key, defaultValue, required, converter } = options if (required === true) { if (!hasOwn(dictionary, key)) { throw webidl.errors.exception({ header: 'Dictionary', message: `Missing required key "${key}".` }) } } let value = dictionary[key] const hasDefault = hasOwn(options, 'defaultValue') // Only use defaultValue if value is undefined and // a defaultValue options was provided. if (hasDefault && value !== null) { value = value ?? defaultValue } // A key can be optional and have no default value. // When this happens, do not perform a conversion, // and do not assign the key a value. if (required || hasDefault || value !== undefined) { value = converter(value) if ( options.allowedValues && !options.allowedValues.includes(value) ) { throw webidl.errors.exception({ header: 'Dictionary', message: `${value} is not an accepted type. Expected one of ${options.allowedValues.join(', ')}.` }) } dict[key] = value } } return dict } } webidl.nullableConverter = function (converter) { return (V) => { if (V === null) { return V } return converter(V) } } // https://webidl.spec.whatwg.org/#es-DOMString webidl.converters.DOMString = function (V, opts = {}) { // 1. If V is null and the conversion is to an IDL type // associated with the [LegacyNullToEmptyString] // extended attribute, then return the DOMString value // that represents the empty string. if (V === null && opts.legacyNullToEmptyString) { return '' } // 2. Let x be ? ToString(V). if (typeof V === 'symbol') { throw new TypeError('Could not convert argument of type symbol to string.') } // 3. Return the IDL DOMString value that represents the // same sequence of code units as the one the // ECMAScript String value x represents. return String(V) } // https://webidl.spec.whatwg.org/#es-ByteString webidl.converters.ByteString = function (V) { // 1. Let x be ? ToString(V). // Note: DOMString converter perform ? ToString(V) const x = webidl.converters.DOMString(V) // 2. If the value of any element of x is greater than // 255, then throw a TypeError. for (let index = 0; index < x.length; index++) { if (x.charCodeAt(index) > 255) { throw new TypeError( 'Cannot convert argument to a ByteString because the character at ' + `index ${index} has a value of ${x.charCodeAt(index)} which is greater than 255.` ) } } // 3. Return an IDL ByteString value whose length is the // length of x, and where the value of each element is // the value of the corresponding element of x. return x } // https://webidl.spec.whatwg.org/#es-USVString webidl.converters.USVString = toUSVString // https://webidl.spec.whatwg.org/#es-boolean webidl.converters.boolean = function (V) { // 1. Let x be the result of computing ToBoolean(V). const x = Boolean(V) // 2. Return the IDL boolean value that is the one that represents // the same truth value as the ECMAScript Boolean value x. return x } // https://webidl.spec.whatwg.org/#es-any webidl.converters.any = function (V) { return V } // https://webidl.spec.whatwg.org/#es-long-long webidl.converters['long long'] = function (V) { // 1. Let x be ? ConvertToInt(V, 64, "signed"). const x = webidl.util.ConvertToInt(V, 64, 'signed') // 2. Return the IDL long long value that represents // the same numeric value as x. return x } // https://webidl.spec.whatwg.org/#es-unsigned-long-long webidl.converters['unsigned long long'] = function (V) { // 1. Let x be ? ConvertToInt(V, 64, "unsigned"). const x = webidl.util.ConvertToInt(V, 64, 'unsigned') // 2. Return the IDL unsigned long long value that // represents the same numeric value as x. return x } // https://webidl.spec.whatwg.org/#es-unsigned-long webidl.converters['unsigned long'] = function (V) { // 1. Let x be ? ConvertToInt(V, 32, "unsigned"). const x = webidl.util.ConvertToInt(V, 32, 'unsigned') // 2. Return the IDL unsigned long value that // represents the same numeric value as x. return x } // https://webidl.spec.whatwg.org/#es-unsigned-short webidl.converters['unsigned short'] = function (V, opts) { // 1. Let x be ? ConvertToInt(V, 16, "unsigned"). const x = webidl.util.ConvertToInt(V, 16, 'unsigned', opts) // 2. Return the IDL unsigned short value that represents // the same numeric value as x. return x } // https://webidl.spec.whatwg.org/#idl-ArrayBuffer webidl.converters.ArrayBuffer = function (V, opts = {}) { // 1. If Type(V) is not Object, or V does not have an // [[ArrayBufferData]] internal slot, then throw a // TypeError. // see: https://tc39.es/ecma262/#sec-properties-of-the-arraybuffer-instances // see: https://tc39.es/ecma262/#sec-properties-of-the-sharedarraybuffer-instances if ( webidl.util.Type(V) !== 'Object' || !types.isAnyArrayBuffer(V) ) { throw webidl.errors.conversionFailed({ prefix: `${V}`, argument: `${V}`, types: ['ArrayBuffer'] }) } // 2. If the conversion is not to an IDL type associated // with the [AllowShared] extended attribute, and // IsSharedArrayBuffer(V) is true, then throw a // TypeError. if (opts.allowShared === false && types.isSharedArrayBuffer(V)) { throw webidl.errors.exception({ header: 'ArrayBuffer', message: 'SharedArrayBuffer is not allowed.' }) } // 3. If the conversion is not to an IDL type associated // with the [AllowResizable] extended attribute, and // IsResizableArrayBuffer(V) is true, then throw a // TypeError. // Note: resizable ArrayBuffers are currently a proposal. // 4. Return the IDL ArrayBuffer value that is a // reference to the same object as V. return V } webidl.converters.TypedArray = function (V, T, opts = {}) { // 1. Let T be the IDL type V is being converted to. // 2. If Type(V) is not Object, or V does not have a // [[TypedArrayName]] internal slot with a value // equal to T’s name, then throw a TypeError. if ( webidl.util.Type(V) !== 'Object' || !types.isTypedArray(V) || V.constructor.name !== T.name ) { throw webidl.errors.conversionFailed({ prefix: `${T.name}`, argument: `${V}`, types: [T.name] }) } // 3. If the conversion is not to an IDL type associated // with the [AllowShared] extended attribute, and // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is // true, then throw a TypeError. if (opts.allowShared === false && types.isSharedArrayBuffer(V.buffer)) { throw webidl.errors.exception({ header: 'ArrayBuffer', message: 'SharedArrayBuffer is not allowed.' }) } // 4. If the conversion is not to an IDL type associated // with the [AllowResizable] extended attribute, and // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is // true, then throw a TypeError. // Note: resizable array buffers are currently a proposal // 5. Return the IDL value of type T that is a reference // to the same object as V. return V } webidl.converters.DataView = function (V, opts = {}) { // 1. If Type(V) is not Object, or V does not have a // [[DataView]] internal slot, then throw a TypeError. if (webidl.util.Type(V) !== 'Object' || !types.isDataView(V)) { throw webidl.errors.exception({ header: 'DataView', message: 'Object is not a DataView.' }) } // 2. If the conversion is not to an IDL type associated // with the [AllowShared] extended attribute, and // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is true, // then throw a TypeError. if (opts.allowShared === false && types.isSharedArrayBuffer(V.buffer)) { throw webidl.errors.exception({ header: 'ArrayBuffer', message: 'SharedArrayBuffer is not allowed.' }) } // 3. If the conversion is not to an IDL type associated // with the [AllowResizable] extended attribute, and // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is // true, then throw a TypeError. // Note: resizable ArrayBuffers are currently a proposal // 4. Return the IDL DataView value that is a reference // to the same object as V. return V } // https://webidl.spec.whatwg.org/#BufferSource webidl.converters.BufferSource = function (V, opts = {}) { if (types.isAnyArrayBuffer(V)) { return webidl.converters.ArrayBuffer(V, opts) } if (types.isTypedArray(V)) { return webidl.converters.TypedArray(V, V.constructor) } if (types.isDataView(V)) { return webidl.converters.DataView(V, opts) } throw new TypeError(`Could not convert ${V} to a BufferSource.`) } webidl.converters['sequence'] = webidl.sequenceConverter( webidl.converters.ByteString ) webidl.converters['sequence>'] = webidl.sequenceConverter( webidl.converters['sequence'] ) webidl.converters['record'] = webidl.recordConverter( webidl.converters.ByteString, webidl.converters.ByteString ) module.exports = { webidl } /***/ }), /***/ 84854: /***/ ((module) => { "use strict"; /** * @see https://encoding.spec.whatwg.org/#concept-encoding-get * @param {string|undefined} label */ function getEncoding (label) { if (!label) { return 'failure' } // 1. Remove any leading and trailing ASCII whitespace from label. // 2. If label is an ASCII case-insensitive match for any of the // labels listed in the table below, then return the // corresponding encoding; otherwise return failure. switch (label.trim().toLowerCase()) { case 'unicode-1-1-utf-8': case 'unicode11utf8': case 'unicode20utf8': case 'utf-8': case 'utf8': case 'x-unicode20utf8': return 'UTF-8' case '866': case 'cp866': case 'csibm866': case 'ibm866': return 'IBM866' case 'csisolatin2': case 'iso-8859-2': case 'iso-ir-101': case 'iso8859-2': case 'iso88592': case 'iso_8859-2': case 'iso_8859-2:1987': case 'l2': case 'latin2': return 'ISO-8859-2' case 'csisolatin3': case 'iso-8859-3': case 'iso-ir-109': case 'iso8859-3': case 'iso88593': case 'iso_8859-3': case 'iso_8859-3:1988': case 'l3': case 'latin3': return 'ISO-8859-3' case 'csisolatin4': case 'iso-8859-4': case 'iso-ir-110': case 'iso8859-4': case 'iso88594': case 'iso_8859-4': case 'iso_8859-4:1988': case 'l4': case 'latin4': return 'ISO-8859-4' case 'csisolatincyrillic': case 'cyrillic': case 'iso-8859-5': case 'iso-ir-144': case 'iso8859-5': case 'iso88595': case 'iso_8859-5': case 'iso_8859-5:1988': return 'ISO-8859-5' case 'arabic': case 'asmo-708': case 'csiso88596e': case 'csiso88596i': case 'csisolatinarabic': case 'ecma-114': case 'iso-8859-6': case 'iso-8859-6-e': case 'iso-8859-6-i': case 'iso-ir-127': case 'iso8859-6': case 'iso88596': case 'iso_8859-6': case 'iso_8859-6:1987': return 'ISO-8859-6' case 'csisolatingreek': case 'ecma-118': case 'elot_928': case 'greek': case 'greek8': case 'iso-8859-7': case 'iso-ir-126': case 'iso8859-7': case 'iso88597': case 'iso_8859-7': case 'iso_8859-7:1987': case 'sun_eu_greek': return 'ISO-8859-7' case 'csiso88598e': case 'csisolatinhebrew': case 'hebrew': case 'iso-8859-8': case 'iso-8859-8-e': case 'iso-ir-138': case 'iso8859-8': case 'iso88598': case 'iso_8859-8': case 'iso_8859-8:1988': case 'visual': return 'ISO-8859-8' case 'csiso88598i': case 'iso-8859-8-i': case 'logical': return 'ISO-8859-8-I' case 'csisolatin6': case 'iso-8859-10': case 'iso-ir-157': case 'iso8859-10': case 'iso885910': case 'l6': case 'latin6': return 'ISO-8859-10' case 'iso-8859-13': case 'iso8859-13': case 'iso885913': return 'ISO-8859-13' case 'iso-8859-14': case 'iso8859-14': case 'iso885914': return 'ISO-8859-14' case 'csisolatin9': case 'iso-8859-15': case 'iso8859-15': case 'iso885915': case 'iso_8859-15': case 'l9': return 'ISO-8859-15' case 'iso-8859-16': return 'ISO-8859-16' case 'cskoi8r': case 'koi': case 'koi8': case 'koi8-r': case 'koi8_r': return 'KOI8-R' case 'koi8-ru': case 'koi8-u': return 'KOI8-U' case 'csmacintosh': case 'mac': case 'macintosh': case 'x-mac-roman': return 'macintosh' case 'iso-8859-11': case 'iso8859-11': case 'iso885911': case 'tis-620': case 'windows-874': return 'windows-874' case 'cp1250': case 'windows-1250': case 'x-cp1250': return 'windows-1250' case 'cp1251': case 'windows-1251': case 'x-cp1251': return 'windows-1251' case 'ansi_x3.4-1968': case 'ascii': case 'cp1252': case 'cp819': case 'csisolatin1': case 'ibm819': case 'iso-8859-1': case 'iso-ir-100': case 'iso8859-1': case 'iso88591': case 'iso_8859-1': case 'iso_8859-1:1987': case 'l1': case 'latin1': case 'us-ascii': case 'windows-1252': case 'x-cp1252': return 'windows-1252' case 'cp1253': case 'windows-1253': case 'x-cp1253': return 'windows-1253' case 'cp1254': case 'csisolatin5': case 'iso-8859-9': case 'iso-ir-148': case 'iso8859-9': case 'iso88599': case 'iso_8859-9': case 'iso_8859-9:1989': case 'l5': case 'latin5': case 'windows-1254': case 'x-cp1254': return 'windows-1254' case 'cp1255': case 'windows-1255': case 'x-cp1255': return 'windows-1255' case 'cp1256': case 'windows-1256': case 'x-cp1256': return 'windows-1256' case 'cp1257': case 'windows-1257': case 'x-cp1257': return 'windows-1257' case 'cp1258': case 'windows-1258': case 'x-cp1258': return 'windows-1258' case 'x-mac-cyrillic': case 'x-mac-ukrainian': return 'x-mac-cyrillic' case 'chinese': case 'csgb2312': case 'csiso58gb231280': case 'gb2312': case 'gb_2312': case 'gb_2312-80': case 'gbk': case 'iso-ir-58': case 'x-gbk': return 'GBK' case 'gb18030': return 'gb18030' case 'big5': case 'big5-hkscs': case 'cn-big5': case 'csbig5': case 'x-x-big5': return 'Big5' case 'cseucpkdfmtjapanese': case 'euc-jp': case 'x-euc-jp': return 'EUC-JP' case 'csiso2022jp': case 'iso-2022-jp': return 'ISO-2022-JP' case 'csshiftjis': case 'ms932': case 'ms_kanji': case 'shift-jis': case 'shift_jis': case 'sjis': case 'windows-31j': case 'x-sjis': return 'Shift_JIS' case 'cseuckr': case 'csksc56011987': case 'euc-kr': case 'iso-ir-149': case 'korean': case 'ks_c_5601-1987': case 'ks_c_5601-1989': case 'ksc5601': case 'ksc_5601': case 'windows-949': return 'EUC-KR' case 'csiso2022kr': case 'hz-gb-2312': case 'iso-2022-cn': case 'iso-2022-cn-ext': case 'iso-2022-kr': case 'replacement': return 'replacement' case 'unicodefffe': case 'utf-16be': return 'UTF-16BE' case 'csunicode': case 'iso-10646-ucs-2': case 'ucs-2': case 'unicode': case 'unicodefeff': case 'utf-16': case 'utf-16le': return 'UTF-16LE' case 'x-user-defined': return 'x-user-defined' default: return 'failure' } } module.exports = { getEncoding } /***/ }), /***/ 1446: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { staticPropertyDescriptors, readOperation, fireAProgressEvent } = __nccwpck_require__(87530) const { kState, kError, kResult, kEvents, kAborted } = __nccwpck_require__(29054) const { webidl } = __nccwpck_require__(21744) const { kEnumerableProperty } = __nccwpck_require__(83983) class FileReader extends EventTarget { constructor () { super() this[kState] = 'empty' this[kResult] = null this[kError] = null this[kEvents] = { loadend: null, error: null, abort: null, load: null, progress: null, loadstart: null } } /** * @see https://w3c.github.io/FileAPI/#dfn-readAsArrayBuffer * @param {import('buffer').Blob} blob */ readAsArrayBuffer (blob) { webidl.brandCheck(this, FileReader) webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsArrayBuffer' }) blob = webidl.converters.Blob(blob, { strict: false }) // The readAsArrayBuffer(blob) method, when invoked, // must initiate a read operation for blob with ArrayBuffer. readOperation(this, blob, 'ArrayBuffer') } /** * @see https://w3c.github.io/FileAPI/#readAsBinaryString * @param {import('buffer').Blob} blob */ readAsBinaryString (blob) { webidl.brandCheck(this, FileReader) webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsBinaryString' }) blob = webidl.converters.Blob(blob, { strict: false }) // The readAsBinaryString(blob) method, when invoked, // must initiate a read operation for blob with BinaryString. readOperation(this, blob, 'BinaryString') } /** * @see https://w3c.github.io/FileAPI/#readAsDataText * @param {import('buffer').Blob} blob * @param {string?} encoding */ readAsText (blob, encoding = undefined) { webidl.brandCheck(this, FileReader) webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsText' }) blob = webidl.converters.Blob(blob, { strict: false }) if (encoding !== undefined) { encoding = webidl.converters.DOMString(encoding) } // The readAsText(blob, encoding) method, when invoked, // must initiate a read operation for blob with Text and encoding. readOperation(this, blob, 'Text', encoding) } /** * @see https://w3c.github.io/FileAPI/#dfn-readAsDataURL * @param {import('buffer').Blob} blob */ readAsDataURL (blob) { webidl.brandCheck(this, FileReader) webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsDataURL' }) blob = webidl.converters.Blob(blob, { strict: false }) // The readAsDataURL(blob) method, when invoked, must // initiate a read operation for blob with DataURL. readOperation(this, blob, 'DataURL') } /** * @see https://w3c.github.io/FileAPI/#dfn-abort */ abort () { // 1. If this's state is "empty" or if this's state is // "done" set this's result to null and terminate // this algorithm. if (this[kState] === 'empty' || this[kState] === 'done') { this[kResult] = null return } // 2. If this's state is "loading" set this's state to // "done" and set this's result to null. if (this[kState] === 'loading') { this[kState] = 'done' this[kResult] = null } // 3. If there are any tasks from this on the file reading // task source in an affiliated task queue, then remove // those tasks from that task queue. this[kAborted] = true // 4. Terminate the algorithm for the read method being processed. // TODO // 5. Fire a progress event called abort at this. fireAProgressEvent('abort', this) // 6. If this's state is not "loading", fire a progress // event called loadend at this. if (this[kState] !== 'loading') { fireAProgressEvent('loadend', this) } } /** * @see https://w3c.github.io/FileAPI/#dom-filereader-readystate */ get readyState () { webidl.brandCheck(this, FileReader) switch (this[kState]) { case 'empty': return this.EMPTY case 'loading': return this.LOADING case 'done': return this.DONE } } /** * @see https://w3c.github.io/FileAPI/#dom-filereader-result */ get result () { webidl.brandCheck(this, FileReader) // The result attribute’s getter, when invoked, must return // this's result. return this[kResult] } /** * @see https://w3c.github.io/FileAPI/#dom-filereader-error */ get error () { webidl.brandCheck(this, FileReader) // The error attribute’s getter, when invoked, must return // this's error. return this[kError] } get onloadend () { webidl.brandCheck(this, FileReader) return this[kEvents].loadend } set onloadend (fn) { webidl.brandCheck(this, FileReader) if (this[kEvents].loadend) { this.removeEventListener('loadend', this[kEvents].loadend) } if (typeof fn === 'function') { this[kEvents].loadend = fn this.addEventListener('loadend', fn) } else { this[kEvents].loadend = null } } get onerror () { webidl.brandCheck(this, FileReader) return this[kEvents].error } set onerror (fn) { webidl.brandCheck(this, FileReader) if (this[kEvents].error) { this.removeEventListener('error', this[kEvents].error) } if (typeof fn === 'function') { this[kEvents].error = fn this.addEventListener('error', fn) } else { this[kEvents].error = null } } get onloadstart () { webidl.brandCheck(this, FileReader) return this[kEvents].loadstart } set onloadstart (fn) { webidl.brandCheck(this, FileReader) if (this[kEvents].loadstart) { this.removeEventListener('loadstart', this[kEvents].loadstart) } if (typeof fn === 'function') { this[kEvents].loadstart = fn this.addEventListener('loadstart', fn) } else { this[kEvents].loadstart = null } } get onprogress () { webidl.brandCheck(this, FileReader) return this[kEvents].progress } set onprogress (fn) { webidl.brandCheck(this, FileReader) if (this[kEvents].progress) { this.removeEventListener('progress', this[kEvents].progress) } if (typeof fn === 'function') { this[kEvents].progress = fn this.addEventListener('progress', fn) } else { this[kEvents].progress = null } } get onload () { webidl.brandCheck(this, FileReader) return this[kEvents].load } set onload (fn) { webidl.brandCheck(this, FileReader) if (this[kEvents].load) { this.removeEventListener('load', this[kEvents].load) } if (typeof fn === 'function') { this[kEvents].load = fn this.addEventListener('load', fn) } else { this[kEvents].load = null } } get onabort () { webidl.brandCheck(this, FileReader) return this[kEvents].abort } set onabort (fn) { webidl.brandCheck(this, FileReader) if (this[kEvents].abort) { this.removeEventListener('abort', this[kEvents].abort) } if (typeof fn === 'function') { this[kEvents].abort = fn this.addEventListener('abort', fn) } else { this[kEvents].abort = null } } } // https://w3c.github.io/FileAPI/#dom-filereader-empty FileReader.EMPTY = FileReader.prototype.EMPTY = 0 // https://w3c.github.io/FileAPI/#dom-filereader-loading FileReader.LOADING = FileReader.prototype.LOADING = 1 // https://w3c.github.io/FileAPI/#dom-filereader-done FileReader.DONE = FileReader.prototype.DONE = 2 Object.defineProperties(FileReader.prototype, { EMPTY: staticPropertyDescriptors, LOADING: staticPropertyDescriptors, DONE: staticPropertyDescriptors, readAsArrayBuffer: kEnumerableProperty, readAsBinaryString: kEnumerableProperty, readAsText: kEnumerableProperty, readAsDataURL: kEnumerableProperty, abort: kEnumerableProperty, readyState: kEnumerableProperty, result: kEnumerableProperty, error: kEnumerableProperty, onloadstart: kEnumerableProperty, onprogress: kEnumerableProperty, onload: kEnumerableProperty, onabort: kEnumerableProperty, onerror: kEnumerableProperty, onloadend: kEnumerableProperty, [Symbol.toStringTag]: { value: 'FileReader', writable: false, enumerable: false, configurable: true } }) Object.defineProperties(FileReader, { EMPTY: staticPropertyDescriptors, LOADING: staticPropertyDescriptors, DONE: staticPropertyDescriptors }) module.exports = { FileReader } /***/ }), /***/ 55504: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { webidl } = __nccwpck_require__(21744) const kState = Symbol('ProgressEvent state') /** * @see https://xhr.spec.whatwg.org/#progressevent */ class ProgressEvent extends Event { constructor (type, eventInitDict = {}) { type = webidl.converters.DOMString(type) eventInitDict = webidl.converters.ProgressEventInit(eventInitDict ?? {}) super(type, eventInitDict) this[kState] = { lengthComputable: eventInitDict.lengthComputable, loaded: eventInitDict.loaded, total: eventInitDict.total } } get lengthComputable () { webidl.brandCheck(this, ProgressEvent) return this[kState].lengthComputable } get loaded () { webidl.brandCheck(this, ProgressEvent) return this[kState].loaded } get total () { webidl.brandCheck(this, ProgressEvent) return this[kState].total } } webidl.converters.ProgressEventInit = webidl.dictionaryConverter([ { key: 'lengthComputable', converter: webidl.converters.boolean, defaultValue: false }, { key: 'loaded', converter: webidl.converters['unsigned long long'], defaultValue: 0 }, { key: 'total', converter: webidl.converters['unsigned long long'], defaultValue: 0 }, { key: 'bubbles', converter: webidl.converters.boolean, defaultValue: false }, { key: 'cancelable', converter: webidl.converters.boolean, defaultValue: false }, { key: 'composed', converter: webidl.converters.boolean, defaultValue: false } ]) module.exports = { ProgressEvent } /***/ }), /***/ 29054: /***/ ((module) => { "use strict"; module.exports = { kState: Symbol('FileReader state'), kResult: Symbol('FileReader result'), kError: Symbol('FileReader error'), kLastProgressEventFired: Symbol('FileReader last progress event fired timestamp'), kEvents: Symbol('FileReader events'), kAborted: Symbol('FileReader aborted') } /***/ }), /***/ 87530: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { kState, kError, kResult, kAborted, kLastProgressEventFired } = __nccwpck_require__(29054) const { ProgressEvent } = __nccwpck_require__(55504) const { getEncoding } = __nccwpck_require__(84854) const { DOMException } = __nccwpck_require__(41037) const { serializeAMimeType, parseMIMEType } = __nccwpck_require__(685) const { types } = __nccwpck_require__(73837) const { StringDecoder } = __nccwpck_require__(71576) const { btoa } = __nccwpck_require__(14300) /** @type {PropertyDescriptor} */ const staticPropertyDescriptors = { enumerable: true, writable: false, configurable: false } /** * @see https://w3c.github.io/FileAPI/#readOperation * @param {import('./filereader').FileReader} fr * @param {import('buffer').Blob} blob * @param {string} type * @param {string?} encodingName */ function readOperation (fr, blob, type, encodingName) { // 1. If fr’s state is "loading", throw an InvalidStateError // DOMException. if (fr[kState] === 'loading') { throw new DOMException('Invalid state', 'InvalidStateError') } // 2. Set fr’s state to "loading". fr[kState] = 'loading' // 3. Set fr’s result to null. fr[kResult] = null // 4. Set fr’s error to null. fr[kError] = null // 5. Let stream be the result of calling get stream on blob. /** @type {import('stream/web').ReadableStream} */ const stream = blob.stream() // 6. Let reader be the result of getting a reader from stream. const reader = stream.getReader() // 7. Let bytes be an empty byte sequence. /** @type {Uint8Array[]} */ const bytes = [] // 8. Let chunkPromise be the result of reading a chunk from // stream with reader. let chunkPromise = reader.read() // 9. Let isFirstChunk be true. let isFirstChunk = true // 10. In parallel, while true: // Note: "In parallel" just means non-blocking // Note 2: readOperation itself cannot be async as double // reading the body would then reject the promise, instead // of throwing an error. ;(async () => { while (!fr[kAborted]) { // 1. Wait for chunkPromise to be fulfilled or rejected. try { const { done, value } = await chunkPromise // 2. If chunkPromise is fulfilled, and isFirstChunk is // true, queue a task to fire a progress event called // loadstart at fr. if (isFirstChunk && !fr[kAborted]) { queueMicrotask(() => { fireAProgressEvent('loadstart', fr) }) } // 3. Set isFirstChunk to false. isFirstChunk = false // 4. If chunkPromise is fulfilled with an object whose // done property is false and whose value property is // a Uint8Array object, run these steps: if (!done && types.isUint8Array(value)) { // 1. Let bs be the byte sequence represented by the // Uint8Array object. // 2. Append bs to bytes. bytes.push(value) // 3. If roughly 50ms have passed since these steps // were last invoked, queue a task to fire a // progress event called progress at fr. if ( ( fr[kLastProgressEventFired] === undefined || Date.now() - fr[kLastProgressEventFired] >= 50 ) && !fr[kAborted] ) { fr[kLastProgressEventFired] = Date.now() queueMicrotask(() => { fireAProgressEvent('progress', fr) }) } // 4. Set chunkPromise to the result of reading a // chunk from stream with reader. chunkPromise = reader.read() } else if (done) { // 5. Otherwise, if chunkPromise is fulfilled with an // object whose done property is true, queue a task // to run the following steps and abort this algorithm: queueMicrotask(() => { // 1. Set fr’s state to "done". fr[kState] = 'done' // 2. Let result be the result of package data given // bytes, type, blob’s type, and encodingName. try { const result = packageData(bytes, type, blob.type, encodingName) // 4. Else: if (fr[kAborted]) { return } // 1. Set fr’s result to result. fr[kResult] = result // 2. Fire a progress event called load at the fr. fireAProgressEvent('load', fr) } catch (error) { // 3. If package data threw an exception error: // 1. Set fr’s error to error. fr[kError] = error // 2. Fire a progress event called error at fr. fireAProgressEvent('error', fr) } // 5. If fr’s state is not "loading", fire a progress // event called loadend at the fr. if (fr[kState] !== 'loading') { fireAProgressEvent('loadend', fr) } }) break } } catch (error) { if (fr[kAborted]) { return } // 6. Otherwise, if chunkPromise is rejected with an // error error, queue a task to run the following // steps and abort this algorithm: queueMicrotask(() => { // 1. Set fr’s state to "done". fr[kState] = 'done' // 2. Set fr’s error to error. fr[kError] = error // 3. Fire a progress event called error at fr. fireAProgressEvent('error', fr) // 4. If fr’s state is not "loading", fire a progress // event called loadend at fr. if (fr[kState] !== 'loading') { fireAProgressEvent('loadend', fr) } }) break } } })() } /** * @see https://w3c.github.io/FileAPI/#fire-a-progress-event * @see https://dom.spec.whatwg.org/#concept-event-fire * @param {string} e The name of the event * @param {import('./filereader').FileReader} reader */ function fireAProgressEvent (e, reader) { // The progress event e does not bubble. e.bubbles must be false // The progress event e is NOT cancelable. e.cancelable must be false const event = new ProgressEvent(e, { bubbles: false, cancelable: false }) reader.dispatchEvent(event) } /** * @see https://w3c.github.io/FileAPI/#blob-package-data * @param {Uint8Array[]} bytes * @param {string} type * @param {string?} mimeType * @param {string?} encodingName */ function packageData (bytes, type, mimeType, encodingName) { // 1. A Blob has an associated package data algorithm, given // bytes, a type, a optional mimeType, and a optional // encodingName, which switches on type and runs the // associated steps: switch (type) { case 'DataURL': { // 1. Return bytes as a DataURL [RFC2397] subject to // the considerations below: // * Use mimeType as part of the Data URL if it is // available in keeping with the Data URL // specification [RFC2397]. // * If mimeType is not available return a Data URL // without a media-type. [RFC2397]. // https://datatracker.ietf.org/doc/html/rfc2397#section-3 // dataurl := "data:" [ mediatype ] [ ";base64" ] "," data // mediatype := [ type "/" subtype ] *( ";" parameter ) // data := *urlchar // parameter := attribute "=" value let dataURL = 'data:' const parsed = parseMIMEType(mimeType || 'application/octet-stream') if (parsed !== 'failure') { dataURL += serializeAMimeType(parsed) } dataURL += ';base64,' const decoder = new StringDecoder('latin1') for (const chunk of bytes) { dataURL += btoa(decoder.write(chunk)) } dataURL += btoa(decoder.end()) return dataURL } case 'Text': { // 1. Let encoding be failure let encoding = 'failure' // 2. If the encodingName is present, set encoding to the // result of getting an encoding from encodingName. if (encodingName) { encoding = getEncoding(encodingName) } // 3. If encoding is failure, and mimeType is present: if (encoding === 'failure' && mimeType) { // 1. Let type be the result of parse a MIME type // given mimeType. const type = parseMIMEType(mimeType) // 2. If type is not failure, set encoding to the result // of getting an encoding from type’s parameters["charset"]. if (type !== 'failure') { encoding = getEncoding(type.parameters.get('charset')) } } // 4. If encoding is failure, then set encoding to UTF-8. if (encoding === 'failure') { encoding = 'UTF-8' } // 5. Decode bytes using fallback encoding encoding, and // return the result. return decode(bytes, encoding) } case 'ArrayBuffer': { // Return a new ArrayBuffer whose contents are bytes. const sequence = combineByteSequences(bytes) return sequence.buffer } case 'BinaryString': { // Return bytes as a binary string, in which every byte // is represented by a code unit of equal value [0..255]. let binaryString = '' const decoder = new StringDecoder('latin1') for (const chunk of bytes) { binaryString += decoder.write(chunk) } binaryString += decoder.end() return binaryString } } } /** * @see https://encoding.spec.whatwg.org/#decode * @param {Uint8Array[]} ioQueue * @param {string} encoding */ function decode (ioQueue, encoding) { const bytes = combineByteSequences(ioQueue) // 1. Let BOMEncoding be the result of BOM sniffing ioQueue. const BOMEncoding = BOMSniffing(bytes) let slice = 0 // 2. If BOMEncoding is non-null: if (BOMEncoding !== null) { // 1. Set encoding to BOMEncoding. encoding = BOMEncoding // 2. Read three bytes from ioQueue, if BOMEncoding is // UTF-8; otherwise read two bytes. // (Do nothing with those bytes.) slice = BOMEncoding === 'UTF-8' ? 3 : 2 } // 3. Process a queue with an instance of encoding’s // decoder, ioQueue, output, and "replacement". // 4. Return output. const sliced = bytes.slice(slice) return new TextDecoder(encoding).decode(sliced) } /** * @see https://encoding.spec.whatwg.org/#bom-sniff * @param {Uint8Array} ioQueue */ function BOMSniffing (ioQueue) { // 1. Let BOM be the result of peeking 3 bytes from ioQueue, // converted to a byte sequence. const [a, b, c] = ioQueue // 2. For each of the rows in the table below, starting with // the first one and going down, if BOM starts with the // bytes given in the first column, then return the // encoding given in the cell in the second column of that // row. Otherwise, return null. if (a === 0xEF && b === 0xBB && c === 0xBF) { return 'UTF-8' } else if (a === 0xFE && b === 0xFF) { return 'UTF-16BE' } else if (a === 0xFF && b === 0xFE) { return 'UTF-16LE' } return null } /** * @param {Uint8Array[]} sequences */ function combineByteSequences (sequences) { const size = sequences.reduce((a, b) => { return a + b.byteLength }, 0) let offset = 0 return sequences.reduce((a, b) => { a.set(b, offset) offset += b.byteLength return a }, new Uint8Array(size)) } module.exports = { staticPropertyDescriptors, readOperation, fireAProgressEvent } /***/ }), /***/ 21892: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // We include a version number for the Dispatcher API. In case of breaking changes, // this version number must be increased to avoid conflicts. const globalDispatcher = Symbol.for('undici.globalDispatcher.1') const { InvalidArgumentError } = __nccwpck_require__(48045) const Agent = __nccwpck_require__(7890) if (getGlobalDispatcher() === undefined) { setGlobalDispatcher(new Agent()) } function setGlobalDispatcher (agent) { if (!agent || typeof agent.dispatch !== 'function') { throw new InvalidArgumentError('Argument agent must implement Agent') } Object.defineProperty(globalThis, globalDispatcher, { value: agent, writable: true, enumerable: false, configurable: false }) } function getGlobalDispatcher () { return globalThis[globalDispatcher] } module.exports = { setGlobalDispatcher, getGlobalDispatcher } /***/ }), /***/ 46930: /***/ ((module) => { "use strict"; module.exports = class DecoratorHandler { constructor (handler) { this.handler = handler } onConnect (...args) { return this.handler.onConnect(...args) } onError (...args) { return this.handler.onError(...args) } onUpgrade (...args) { return this.handler.onUpgrade(...args) } onHeaders (...args) { return this.handler.onHeaders(...args) } onData (...args) { return this.handler.onData(...args) } onComplete (...args) { return this.handler.onComplete(...args) } onBodySent (...args) { return this.handler.onBodySent(...args) } } /***/ }), /***/ 72860: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const util = __nccwpck_require__(83983) const { kBodyUsed } = __nccwpck_require__(72785) const assert = __nccwpck_require__(39491) const { InvalidArgumentError } = __nccwpck_require__(48045) const EE = __nccwpck_require__(82361) const redirectableStatusCodes = [300, 301, 302, 303, 307, 308] const kBody = Symbol('body') class BodyAsyncIterable { constructor (body) { this[kBody] = body this[kBodyUsed] = false } async * [Symbol.asyncIterator] () { assert(!this[kBodyUsed], 'disturbed') this[kBodyUsed] = true yield * this[kBody] } } class RedirectHandler { constructor (dispatch, maxRedirections, opts, handler) { if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) { throw new InvalidArgumentError('maxRedirections must be a positive number') } util.validateHandler(handler, opts.method, opts.upgrade) this.dispatch = dispatch this.location = null this.abort = null this.opts = { ...opts, maxRedirections: 0 } // opts must be a copy this.maxRedirections = maxRedirections this.handler = handler this.history = [] if (util.isStream(this.opts.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 (util.bodyLength(this.opts.body) === 0) { this.opts.body .on('data', function () { assert(false) }) } if (typeof this.opts.body.readableDidRead !== 'boolean') { this.opts.body[kBodyUsed] = false EE.prototype.on.call(this.opts.body, 'data', function () { this[kBodyUsed] = true }) } } else if (this.opts.body && typeof this.opts.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. this.opts.body = new BodyAsyncIterable(this.opts.body) } else if ( this.opts.body && typeof this.opts.body !== 'string' && !ArrayBuffer.isView(this.opts.body) && util.isIterable(this.opts.body) ) { // TODO: Should we allow re-using iterable if !this.opts.idempotent // or through some other flag? this.opts.body = new BodyAsyncIterable(this.opts.body) } } onConnect (abort) { this.abort = abort this.handler.onConnect(abort, { history: this.history }) } onUpgrade (statusCode, headers, socket) { this.handler.onUpgrade(statusCode, headers, socket) } onError (error) { this.handler.onError(error) } onHeaders (statusCode, headers, resume, statusText) { this.location = this.history.length >= this.maxRedirections || util.isDisturbed(this.opts.body) ? null : parseLocation(statusCode, headers) if (this.opts.origin) { this.history.push(new URL(this.opts.path, this.opts.origin)) } if (!this.location) { return this.handler.onHeaders(statusCode, headers, resume, statusText) } const { origin, pathname, search } = util.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin))) const path = search ? `${pathname}${search}` : pathname // Remove headers referring to the original URL. // By default it is Host only, unless it's a 303 (see below), which removes also all Content-* headers. // https://tools.ietf.org/html/rfc7231#section-6.4 this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin) this.opts.path = path this.opts.origin = origin this.opts.maxRedirections = 0 this.opts.query = null // https://tools.ietf.org/html/rfc7231#section-6.4.4 // In case of HTTP 303, always replace method to be either HEAD or GET if (statusCode === 303 && this.opts.method !== 'HEAD') { this.opts.method = 'GET' this.opts.body = null } } onData (chunk) { if (this.location) { /* https://tools.ietf.org/html/rfc7231#section-6.4 TLDR: undici always ignores 3xx response bodies. Redirection is used to serve the requested resource from another URL, so it is assumes that no body is generated (and thus can be ignored). Even though generating a body is not prohibited. For status 301, 302, 303, 307 and 308 (the latter from RFC 7238), the specs mention that the body usually (which means it's optional and not mandated) contain just an hyperlink to the value of the Location response header, so the body can be ignored safely. For status 300, which is "Multiple Choices", the spec mentions both generating a Location response header AND a response body with the other possible location to follow. Since the spec explicitily chooses not to specify a format for such body and leave it to servers and browsers implementors, we ignore the body as there is no specified way to eventually parse it. */ } else { return this.handler.onData(chunk) } } onComplete (trailers) { if (this.location) { /* https://tools.ietf.org/html/rfc7231#section-6.4 TLDR: undici always ignores 3xx response trailers as they are not expected in case of redirections and neither are useful if present. See comment on onData method above for more detailed informations. */ this.location = null this.abort = null this.dispatch(this.opts, this) } else { this.handler.onComplete(trailers) } } onBodySent (chunk) { if (this.handler.onBodySent) { this.handler.onBodySent(chunk) } } } function parseLocation (statusCode, headers) { if (redirectableStatusCodes.indexOf(statusCode) === -1) { return null } for (let i = 0; i < headers.length; i += 2) { if (headers[i].toString().toLowerCase() === 'location') { return headers[i + 1] } } } // https://tools.ietf.org/html/rfc7231#section-6.4.4 function shouldRemoveHeader (header, removeContent, unknownOrigin) { return ( (header.length === 4 && header.toString().toLowerCase() === 'host') || (removeContent && header.toString().toLowerCase().indexOf('content-') === 0) || (unknownOrigin && header.length === 13 && header.toString().toLowerCase() === 'authorization') || (unknownOrigin && header.length === 6 && header.toString().toLowerCase() === 'cookie') ) } // https://tools.ietf.org/html/rfc7231#section-6.4 function cleanRequestHeaders (headers, removeContent, unknownOrigin) { const ret = [] if (Array.isArray(headers)) { for (let i = 0; i < headers.length; i += 2) { if (!shouldRemoveHeader(headers[i], removeContent, unknownOrigin)) { ret.push(headers[i], headers[i + 1]) } } } else if (headers && typeof headers === 'object') { for (const key of Object.keys(headers)) { if (!shouldRemoveHeader(key, removeContent, unknownOrigin)) { ret.push(key, headers[key]) } } } else { assert(headers == null, 'headers must be an object or an array') } return ret } module.exports = RedirectHandler /***/ }), /***/ 82286: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const assert = __nccwpck_require__(39491) const { kRetryHandlerDefaultRetry } = __nccwpck_require__(72785) const { RequestRetryError } = __nccwpck_require__(48045) const { isDisturbed, parseHeaders, parseRangeHeader } = __nccwpck_require__(83983) function calculateRetryAfterHeader (retryAfter) { const current = Date.now() const diff = new Date(retryAfter).getTime() - current return diff } class RetryHandler { constructor (opts, handlers) { const { retryOptions, ...dispatchOpts } = opts const { // Retry scoped retry: retryFn, maxRetries, maxTimeout, minTimeout, timeoutFactor, // Response scoped methods, errorCodes, retryAfter, statusCodes } = retryOptions ?? {} this.dispatch = handlers.dispatch this.handler = handlers.handler this.opts = dispatchOpts this.abort = null this.aborted = false this.retryOpts = { retry: retryFn ?? RetryHandler[kRetryHandlerDefaultRetry], retryAfter: retryAfter ?? true, maxTimeout: maxTimeout ?? 30 * 1000, // 30s, timeout: minTimeout ?? 500, // .5s timeoutFactor: timeoutFactor ?? 2, maxRetries: maxRetries ?? 5, // What errors we should retry methods: methods ?? ['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE', 'TRACE'], // Indicates which errors to retry statusCodes: statusCodes ?? [500, 502, 503, 504, 429], // List of errors to retry errorCodes: errorCodes ?? [ 'ECONNRESET', 'ECONNREFUSED', 'ENOTFOUND', 'ENETDOWN', 'ENETUNREACH', 'EHOSTDOWN', 'EHOSTUNREACH', 'EPIPE' ] } this.retryCount = 0 this.start = 0 this.end = null this.etag = null this.resume = null // Handle possible onConnect duplication this.handler.onConnect(reason => { this.aborted = true if (this.abort) { this.abort(reason) } else { this.reason = reason } }) } onRequestSent () { if (this.handler.onRequestSent) { this.handler.onRequestSent() } } onUpgrade (statusCode, headers, socket) { if (this.handler.onUpgrade) { this.handler.onUpgrade(statusCode, headers, socket) } } onConnect (abort) { if (this.aborted) { abort(this.reason) } else { this.abort = abort } } onBodySent (chunk) { if (this.handler.onBodySent) return this.handler.onBodySent(chunk) } static [kRetryHandlerDefaultRetry] (err, { state, opts }, cb) { const { statusCode, code, headers } = err const { method, retryOptions } = opts const { maxRetries, timeout, maxTimeout, timeoutFactor, statusCodes, errorCodes, methods } = retryOptions let { counter, currentTimeout } = state currentTimeout = currentTimeout != null && currentTimeout > 0 ? currentTimeout : timeout // Any code that is not a Undici's originated and allowed to retry if ( code && code !== 'UND_ERR_REQ_RETRY' && code !== 'UND_ERR_SOCKET' && !errorCodes.includes(code) ) { cb(err) return } // If a set of method are provided and the current method is not in the list if (Array.isArray(methods) && !methods.includes(method)) { cb(err) return } // If a set of status code are provided and the current status code is not in the list if ( statusCode != null && Array.isArray(statusCodes) && !statusCodes.includes(statusCode) ) { cb(err) return } // If we reached the max number of retries if (counter > maxRetries) { cb(err) return } let retryAfterHeader = headers != null && headers['retry-after'] if (retryAfterHeader) { retryAfterHeader = Number(retryAfterHeader) retryAfterHeader = isNaN(retryAfterHeader) ? calculateRetryAfterHeader(retryAfterHeader) : retryAfterHeader * 1e3 // Retry-After is in seconds } const retryTimeout = retryAfterHeader > 0 ? Math.min(retryAfterHeader, maxTimeout) : Math.min(currentTimeout * timeoutFactor ** counter, maxTimeout) state.currentTimeout = retryTimeout setTimeout(() => cb(null), retryTimeout) } onHeaders (statusCode, rawHeaders, resume, statusMessage) { const headers = parseHeaders(rawHeaders) this.retryCount += 1 if (statusCode >= 300) { this.abort( new RequestRetryError('Request failed', statusCode, { headers, count: this.retryCount }) ) return false } // Checkpoint for resume from where we left it if (this.resume != null) { this.resume = null if (statusCode !== 206) { return true } const contentRange = parseRangeHeader(headers['content-range']) // If no content range if (!contentRange) { this.abort( new RequestRetryError('Content-Range mismatch', statusCode, { headers, count: this.retryCount }) ) return false } // Let's start with a weak etag check if (this.etag != null && this.etag !== headers.etag) { this.abort( new RequestRetryError('ETag mismatch', statusCode, { headers, count: this.retryCount }) ) return false } const { start, size, end = size } = contentRange assert(this.start === start, 'content-range mismatch') assert(this.end == null || this.end === end, 'content-range mismatch') this.resume = resume return true } if (this.end == null) { if (statusCode === 206) { // First time we receive 206 const range = parseRangeHeader(headers['content-range']) if (range == null) { return this.handler.onHeaders( statusCode, rawHeaders, resume, statusMessage ) } const { start, size, end = size } = range assert( start != null && Number.isFinite(start) && this.start !== start, 'content-range mismatch' ) assert(Number.isFinite(start)) assert( end != null && Number.isFinite(end) && this.end !== end, 'invalid content-length' ) this.start = start this.end = end } // We make our best to checkpoint the body for further range headers if (this.end == null) { const contentLength = headers['content-length'] this.end = contentLength != null ? Number(contentLength) : null } assert(Number.isFinite(this.start)) assert( this.end == null || Number.isFinite(this.end), 'invalid content-length' ) this.resume = resume this.etag = headers.etag != null ? headers.etag : null return this.handler.onHeaders( statusCode, rawHeaders, resume, statusMessage ) } const err = new RequestRetryError('Request failed', statusCode, { headers, count: this.retryCount }) this.abort(err) return false } onData (chunk) { this.start += chunk.length return this.handler.onData(chunk) } onComplete (rawTrailers) { this.retryCount = 0 return this.handler.onComplete(rawTrailers) } onError (err) { if (this.aborted || isDisturbed(this.opts.body)) { return this.handler.onError(err) } this.retryOpts.retry( err, { state: { counter: this.retryCount++, currentTimeout: this.retryAfter }, opts: { retryOptions: this.retryOpts, ...this.opts } }, onRetry.bind(this) ) function onRetry (err) { if (err != null || this.aborted || isDisturbed(this.opts.body)) { return this.handler.onError(err) } if (this.start !== 0) { this.opts = { ...this.opts, headers: { ...this.opts.headers, range: `bytes=${this.start}-${this.end ?? ''}` } } } try { this.dispatch(this.opts, this) } catch (err) { this.handler.onError(err) } } } } module.exports = RetryHandler /***/ }), /***/ 38861: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const RedirectHandler = __nccwpck_require__(72860) function createRedirectInterceptor ({ maxRedirections: defaultMaxRedirections }) { return (dispatch) => { return function Intercept (opts, handler) { const { maxRedirections = defaultMaxRedirections } = opts if (!maxRedirections) { return dispatch(opts, handler) } const redirectHandler = new RedirectHandler(dispatch, maxRedirections, opts, handler) opts = { ...opts, maxRedirections: 0 } // Stop sub dispatcher from also redirecting. return dispatch(opts, redirectHandler) } } } module.exports = createRedirectInterceptor /***/ }), /***/ 30953: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SPECIAL_HEADERS = exports.HEADER_STATE = exports.MINOR = exports.MAJOR = exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS = exports.TOKEN = exports.STRICT_TOKEN = exports.HEX = exports.URL_CHAR = exports.STRICT_URL_CHAR = exports.USERINFO_CHARS = exports.MARK = exports.ALPHANUM = exports.NUM = exports.HEX_MAP = exports.NUM_MAP = exports.ALPHA = exports.FINISH = exports.H_METHOD_MAP = exports.METHOD_MAP = exports.METHODS_RTSP = exports.METHODS_ICE = exports.METHODS_HTTP = exports.METHODS = exports.LENIENT_FLAGS = exports.FLAGS = exports.TYPE = exports.ERROR = void 0; const utils_1 = __nccwpck_require__(41891); // C headers var ERROR; (function (ERROR) { ERROR[ERROR["OK"] = 0] = "OK"; ERROR[ERROR["INTERNAL"] = 1] = "INTERNAL"; ERROR[ERROR["STRICT"] = 2] = "STRICT"; ERROR[ERROR["LF_EXPECTED"] = 3] = "LF_EXPECTED"; ERROR[ERROR["UNEXPECTED_CONTENT_LENGTH"] = 4] = "UNEXPECTED_CONTENT_LENGTH"; ERROR[ERROR["CLOSED_CONNECTION"] = 5] = "CLOSED_CONNECTION"; ERROR[ERROR["INVALID_METHOD"] = 6] = "INVALID_METHOD"; ERROR[ERROR["INVALID_URL"] = 7] = "INVALID_URL"; ERROR[ERROR["INVALID_CONSTANT"] = 8] = "INVALID_CONSTANT"; ERROR[ERROR["INVALID_VERSION"] = 9] = "INVALID_VERSION"; ERROR[ERROR["INVALID_HEADER_TOKEN"] = 10] = "INVALID_HEADER_TOKEN"; ERROR[ERROR["INVALID_CONTENT_LENGTH"] = 11] = "INVALID_CONTENT_LENGTH"; ERROR[ERROR["INVALID_CHUNK_SIZE"] = 12] = "INVALID_CHUNK_SIZE"; ERROR[ERROR["INVALID_STATUS"] = 13] = "INVALID_STATUS"; ERROR[ERROR["INVALID_EOF_STATE"] = 14] = "INVALID_EOF_STATE"; ERROR[ERROR["INVALID_TRANSFER_ENCODING"] = 15] = "INVALID_TRANSFER_ENCODING"; ERROR[ERROR["CB_MESSAGE_BEGIN"] = 16] = "CB_MESSAGE_BEGIN"; ERROR[ERROR["CB_HEADERS_COMPLETE"] = 17] = "CB_HEADERS_COMPLETE"; ERROR[ERROR["CB_MESSAGE_COMPLETE"] = 18] = "CB_MESSAGE_COMPLETE"; ERROR[ERROR["CB_CHUNK_HEADER"] = 19] = "CB_CHUNK_HEADER"; ERROR[ERROR["CB_CHUNK_COMPLETE"] = 20] = "CB_CHUNK_COMPLETE"; ERROR[ERROR["PAUSED"] = 21] = "PAUSED"; ERROR[ERROR["PAUSED_UPGRADE"] = 22] = "PAUSED_UPGRADE"; ERROR[ERROR["PAUSED_H2_UPGRADE"] = 23] = "PAUSED_H2_UPGRADE"; ERROR[ERROR["USER"] = 24] = "USER"; })(ERROR = exports.ERROR || (exports.ERROR = {})); var TYPE; (function (TYPE) { TYPE[TYPE["BOTH"] = 0] = "BOTH"; TYPE[TYPE["REQUEST"] = 1] = "REQUEST"; TYPE[TYPE["RESPONSE"] = 2] = "RESPONSE"; })(TYPE = exports.TYPE || (exports.TYPE = {})); var FLAGS; (function (FLAGS) { FLAGS[FLAGS["CONNECTION_KEEP_ALIVE"] = 1] = "CONNECTION_KEEP_ALIVE"; FLAGS[FLAGS["CONNECTION_CLOSE"] = 2] = "CONNECTION_CLOSE"; FLAGS[FLAGS["CONNECTION_UPGRADE"] = 4] = "CONNECTION_UPGRADE"; FLAGS[FLAGS["CHUNKED"] = 8] = "CHUNKED"; FLAGS[FLAGS["UPGRADE"] = 16] = "UPGRADE"; FLAGS[FLAGS["CONTENT_LENGTH"] = 32] = "CONTENT_LENGTH"; FLAGS[FLAGS["SKIPBODY"] = 64] = "SKIPBODY"; FLAGS[FLAGS["TRAILING"] = 128] = "TRAILING"; // 1 << 8 is unused FLAGS[FLAGS["TRANSFER_ENCODING"] = 512] = "TRANSFER_ENCODING"; })(FLAGS = exports.FLAGS || (exports.FLAGS = {})); var LENIENT_FLAGS; (function (LENIENT_FLAGS) { LENIENT_FLAGS[LENIENT_FLAGS["HEADERS"] = 1] = "HEADERS"; LENIENT_FLAGS[LENIENT_FLAGS["CHUNKED_LENGTH"] = 2] = "CHUNKED_LENGTH"; LENIENT_FLAGS[LENIENT_FLAGS["KEEP_ALIVE"] = 4] = "KEEP_ALIVE"; })(LENIENT_FLAGS = exports.LENIENT_FLAGS || (exports.LENIENT_FLAGS = {})); var METHODS; (function (METHODS) { METHODS[METHODS["DELETE"] = 0] = "DELETE"; METHODS[METHODS["GET"] = 1] = "GET"; METHODS[METHODS["HEAD"] = 2] = "HEAD"; METHODS[METHODS["POST"] = 3] = "POST"; METHODS[METHODS["PUT"] = 4] = "PUT"; /* pathological */ METHODS[METHODS["CONNECT"] = 5] = "CONNECT"; METHODS[METHODS["OPTIONS"] = 6] = "OPTIONS"; METHODS[METHODS["TRACE"] = 7] = "TRACE"; /* WebDAV */ METHODS[METHODS["COPY"] = 8] = "COPY"; METHODS[METHODS["LOCK"] = 9] = "LOCK"; METHODS[METHODS["MKCOL"] = 10] = "MKCOL"; METHODS[METHODS["MOVE"] = 11] = "MOVE"; METHODS[METHODS["PROPFIND"] = 12] = "PROPFIND"; METHODS[METHODS["PROPPATCH"] = 13] = "PROPPATCH"; METHODS[METHODS["SEARCH"] = 14] = "SEARCH"; METHODS[METHODS["UNLOCK"] = 15] = "UNLOCK"; METHODS[METHODS["BIND"] = 16] = "BIND"; METHODS[METHODS["REBIND"] = 17] = "REBIND"; METHODS[METHODS["UNBIND"] = 18] = "UNBIND"; METHODS[METHODS["ACL"] = 19] = "ACL"; /* subversion */ METHODS[METHODS["REPORT"] = 20] = "REPORT"; METHODS[METHODS["MKACTIVITY"] = 21] = "MKACTIVITY"; METHODS[METHODS["CHECKOUT"] = 22] = "CHECKOUT"; METHODS[METHODS["MERGE"] = 23] = "MERGE"; /* upnp */ METHODS[METHODS["M-SEARCH"] = 24] = "M-SEARCH"; METHODS[METHODS["NOTIFY"] = 25] = "NOTIFY"; METHODS[METHODS["SUBSCRIBE"] = 26] = "SUBSCRIBE"; METHODS[METHODS["UNSUBSCRIBE"] = 27] = "UNSUBSCRIBE"; /* RFC-5789 */ METHODS[METHODS["PATCH"] = 28] = "PATCH"; METHODS[METHODS["PURGE"] = 29] = "PURGE"; /* CalDAV */ METHODS[METHODS["MKCALENDAR"] = 30] = "MKCALENDAR"; /* RFC-2068, section 19.6.1.2 */ METHODS[METHODS["LINK"] = 31] = "LINK"; METHODS[METHODS["UNLINK"] = 32] = "UNLINK"; /* icecast */ METHODS[METHODS["SOURCE"] = 33] = "SOURCE"; /* RFC-7540, section 11.6 */ METHODS[METHODS["PRI"] = 34] = "PRI"; /* RFC-2326 RTSP */ METHODS[METHODS["DESCRIBE"] = 35] = "DESCRIBE"; METHODS[METHODS["ANNOUNCE"] = 36] = "ANNOUNCE"; METHODS[METHODS["SETUP"] = 37] = "SETUP"; METHODS[METHODS["PLAY"] = 38] = "PLAY"; METHODS[METHODS["PAUSE"] = 39] = "PAUSE"; METHODS[METHODS["TEARDOWN"] = 40] = "TEARDOWN"; METHODS[METHODS["GET_PARAMETER"] = 41] = "GET_PARAMETER"; METHODS[METHODS["SET_PARAMETER"] = 42] = "SET_PARAMETER"; METHODS[METHODS["REDIRECT"] = 43] = "REDIRECT"; METHODS[METHODS["RECORD"] = 44] = "RECORD"; /* RAOP */ METHODS[METHODS["FLUSH"] = 45] = "FLUSH"; })(METHODS = exports.METHODS || (exports.METHODS = {})); exports.METHODS_HTTP = [ METHODS.DELETE, METHODS.GET, METHODS.HEAD, METHODS.POST, METHODS.PUT, METHODS.CONNECT, METHODS.OPTIONS, METHODS.TRACE, METHODS.COPY, METHODS.LOCK, METHODS.MKCOL, METHODS.MOVE, METHODS.PROPFIND, METHODS.PROPPATCH, METHODS.SEARCH, METHODS.UNLOCK, METHODS.BIND, METHODS.REBIND, METHODS.UNBIND, METHODS.ACL, METHODS.REPORT, METHODS.MKACTIVITY, METHODS.CHECKOUT, METHODS.MERGE, METHODS['M-SEARCH'], METHODS.NOTIFY, METHODS.SUBSCRIBE, METHODS.UNSUBSCRIBE, METHODS.PATCH, METHODS.PURGE, METHODS.MKCALENDAR, METHODS.LINK, METHODS.UNLINK, METHODS.PRI, // TODO(indutny): should we allow it with HTTP? METHODS.SOURCE, ]; exports.METHODS_ICE = [ METHODS.SOURCE, ]; exports.METHODS_RTSP = [ METHODS.OPTIONS, METHODS.DESCRIBE, METHODS.ANNOUNCE, METHODS.SETUP, METHODS.PLAY, METHODS.PAUSE, METHODS.TEARDOWN, METHODS.GET_PARAMETER, METHODS.SET_PARAMETER, METHODS.REDIRECT, METHODS.RECORD, METHODS.FLUSH, // For AirPlay METHODS.GET, METHODS.POST, ]; exports.METHOD_MAP = utils_1.enumToMap(METHODS); exports.H_METHOD_MAP = {}; Object.keys(exports.METHOD_MAP).forEach((key) => { if (/^H/.test(key)) { exports.H_METHOD_MAP[key] = exports.METHOD_MAP[key]; } }); var FINISH; (function (FINISH) { FINISH[FINISH["SAFE"] = 0] = "SAFE"; FINISH[FINISH["SAFE_WITH_CB"] = 1] = "SAFE_WITH_CB"; FINISH[FINISH["UNSAFE"] = 2] = "UNSAFE"; })(FINISH = exports.FINISH || (exports.FINISH = {})); exports.ALPHA = []; for (let i = 'A'.charCodeAt(0); i <= 'Z'.charCodeAt(0); i++) { // Upper case exports.ALPHA.push(String.fromCharCode(i)); // Lower case exports.ALPHA.push(String.fromCharCode(i + 0x20)); } exports.NUM_MAP = { 0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, }; exports.HEX_MAP = { 0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, A: 0XA, B: 0XB, C: 0XC, D: 0XD, E: 0XE, F: 0XF, a: 0xa, b: 0xb, c: 0xc, d: 0xd, e: 0xe, f: 0xf, }; exports.NUM = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ]; exports.ALPHANUM = exports.ALPHA.concat(exports.NUM); exports.MARK = ['-', '_', '.', '!', '~', '*', '\'', '(', ')']; exports.USERINFO_CHARS = exports.ALPHANUM .concat(exports.MARK) .concat(['%', ';', ':', '&', '=', '+', '$', ',']); // TODO(indutny): use RFC exports.STRICT_URL_CHAR = [ '!', '"', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~', ].concat(exports.ALPHANUM); exports.URL_CHAR = exports.STRICT_URL_CHAR .concat(['\t', '\f']); // All characters with 0x80 bit set to 1 for (let i = 0x80; i <= 0xff; i++) { exports.URL_CHAR.push(i); } exports.HEX = exports.NUM.concat(['a', 'b', 'c', 'd', 'e', 'f', 'A', 'B', 'C', 'D', 'E', 'F']); /* Tokens as defined by rfc 2616. Also lowercases them. * token = 1* * separators = "(" | ")" | "<" | ">" | "@" * | "," | ";" | ":" | "\" | <"> * | "/" | "[" | "]" | "?" | "=" * | "{" | "}" | SP | HT */ exports.STRICT_TOKEN = [ '!', '#', '$', '%', '&', '\'', '*', '+', '-', '.', '^', '_', '`', '|', '~', ].concat(exports.ALPHANUM); exports.TOKEN = exports.STRICT_TOKEN.concat([' ']); /* * Verify that a char is a valid visible (printable) US-ASCII * character or %x80-FF */ exports.HEADER_CHARS = ['\t']; for (let i = 32; i <= 255; i++) { if (i !== 127) { exports.HEADER_CHARS.push(i); } } // ',' = \x44 exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS.filter((c) => c !== 44); exports.MAJOR = exports.NUM_MAP; exports.MINOR = exports.MAJOR; var HEADER_STATE; (function (HEADER_STATE) { HEADER_STATE[HEADER_STATE["GENERAL"] = 0] = "GENERAL"; HEADER_STATE[HEADER_STATE["CONNECTION"] = 1] = "CONNECTION"; HEADER_STATE[HEADER_STATE["CONTENT_LENGTH"] = 2] = "CONTENT_LENGTH"; HEADER_STATE[HEADER_STATE["TRANSFER_ENCODING"] = 3] = "TRANSFER_ENCODING"; HEADER_STATE[HEADER_STATE["UPGRADE"] = 4] = "UPGRADE"; HEADER_STATE[HEADER_STATE["CONNECTION_KEEP_ALIVE"] = 5] = "CONNECTION_KEEP_ALIVE"; HEADER_STATE[HEADER_STATE["CONNECTION_CLOSE"] = 6] = "CONNECTION_CLOSE"; HEADER_STATE[HEADER_STATE["CONNECTION_UPGRADE"] = 7] = "CONNECTION_UPGRADE"; HEADER_STATE[HEADER_STATE["TRANSFER_ENCODING_CHUNKED"] = 8] = "TRANSFER_ENCODING_CHUNKED"; })(HEADER_STATE = exports.HEADER_STATE || (exports.HEADER_STATE = {})); exports.SPECIAL_HEADERS = { 'connection': HEADER_STATE.CONNECTION, 'content-length': HEADER_STATE.CONTENT_LENGTH, 'proxy-connection': HEADER_STATE.CONNECTION, 'transfer-encoding': HEADER_STATE.TRANSFER_ENCODING, 'upgrade': HEADER_STATE.UPGRADE, }; //# sourceMappingURL=constants.js.map /***/ }), /***/ 61145: /***/ ((module) => { module.exports = 'AGFzbQEAAAABMAhgAX8Bf2ADf39/AX9gBH9/f38Bf2AAAGADf39/AGABfwBgAn9/AGAGf39/f39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQACA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl9ib2R5AAEDZW52GHdhc21fb25fbWVzc2FnZV9jb21wbGV0ZQAAA0ZFAwMEAAAFAAAAAAAABQEFAAUFBQAABgAAAAAGBgYGAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAAABAQcAAAUFAwABBAUBcAESEgUDAQACBggBfwFBgNQECwfRBSIGbWVtb3J5AgALX2luaXRpYWxpemUACRlfX2luZGlyZWN0X2Z1bmN0aW9uX3RhYmxlAQALbGxodHRwX2luaXQAChhsbGh0dHBfc2hvdWxkX2tlZXBfYWxpdmUAQQxsbGh0dHBfYWxsb2MADAZtYWxsb2MARgtsbGh0dHBfZnJlZQANBGZyZWUASA9sbGh0dHBfZ2V0X3R5cGUADhVsbGh0dHBfZ2V0X2h0dHBfbWFqb3IADxVsbGh0dHBfZ2V0X2h0dHBfbWlub3IAEBFsbGh0dHBfZ2V0X21ldGhvZAARFmxsaHR0cF9nZXRfc3RhdHVzX2NvZGUAEhJsbGh0dHBfZ2V0X3VwZ3JhZGUAEwxsbGh0dHBfcmVzZXQAFA5sbGh0dHBfZXhlY3V0ZQAVFGxsaHR0cF9zZXR0aW5nc19pbml0ABYNbGxodHRwX2ZpbmlzaAAXDGxsaHR0cF9wYXVzZQAYDWxsaHR0cF9yZXN1bWUAGRtsbGh0dHBfcmVzdW1lX2FmdGVyX3VwZ3JhZGUAGhBsbGh0dHBfZ2V0X2Vycm5vABsXbGxodHRwX2dldF9lcnJvcl9yZWFzb24AHBdsbGh0dHBfc2V0X2Vycm9yX3JlYXNvbgAdFGxsaHR0cF9nZXRfZXJyb3JfcG9zAB4RbGxodHRwX2Vycm5vX25hbWUAHxJsbGh0dHBfbWV0aG9kX25hbWUAIBJsbGh0dHBfc3RhdHVzX25hbWUAIRpsbGh0dHBfc2V0X2xlbmllbnRfaGVhZGVycwAiIWxsaHR0cF9zZXRfbGVuaWVudF9jaHVua2VkX2xlbmd0aAAjHWxsaHR0cF9zZXRfbGVuaWVudF9rZWVwX2FsaXZlACQkbGxodHRwX3NldF9sZW5pZW50X3RyYW5zZmVyX2VuY29kaW5nACUYbGxodHRwX21lc3NhZ2VfbmVlZHNfZW9mAD8JFwEAQQELEQECAwQFCwYHNTk3MS8tJyspCsLgAkUCAAsIABCIgICAAAsZACAAEMKAgIAAGiAAIAI2AjggACABOgAoCxwAIAAgAC8BMiAALQAuIAAQwYCAgAAQgICAgAALKgEBf0HAABDGgICAACIBEMKAgIAAGiABQYCIgIAANgI4IAEgADoAKCABCwoAIAAQyICAgAALBwAgAC0AKAsHACAALQAqCwcAIAAtACsLBwAgAC0AKQsHACAALwEyCwcAIAAtAC4LRQEEfyAAKAIYIQEgAC0ALSECIAAtACghAyAAKAI4IQQgABDCgICAABogACAENgI4IAAgAzoAKCAAIAI6AC0gACABNgIYCxEAIAAgASABIAJqEMOAgIAACxAAIABBAEHcABDMgICAABoLZwEBf0EAIQECQCAAKAIMDQACQAJAAkACQCAALQAvDgMBAAMCCyAAKAI4IgFFDQAgASgCLCIBRQ0AIAAgARGAgICAAAAiAQ0DC0EADwsQyoCAgAAACyAAQcOWgIAANgIQQQ4hAQsgAQseAAJAIAAoAgwNACAAQdGbgIAANgIQIABBFTYCDAsLFgACQCAAKAIMQRVHDQAgAEEANgIMCwsWAAJAIAAoAgxBFkcNACAAQQA2AgwLCwcAIAAoAgwLBwAgACgCEAsJACAAIAE2AhALBwAgACgCFAsiAAJAIABBJEkNABDKgICAAAALIABBAnRBoLOAgABqKAIACyIAAkAgAEEuSQ0AEMqAgIAAAAsgAEECdEGwtICAAGooAgAL7gsBAX9B66iAgAAhAQJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIABBnH9qDvQDY2IAAWFhYWFhYQIDBAVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhBgcICQoLDA0OD2FhYWFhEGFhYWFhYWFhYWFhEWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYRITFBUWFxgZGhthYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhHB0eHyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2YTc4OTphYWFhYWFhYTthYWE8YWFhYT0+P2FhYWFhYWFhQGFhQWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYUJDREVGR0hJSktMTU5PUFFSU2FhYWFhYWFhVFVWV1hZWlthXF1hYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFeYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhX2BhC0Hhp4CAAA8LQaShgIAADwtBy6yAgAAPC0H+sYCAAA8LQcCkgIAADwtBq6SAgAAPC0GNqICAAA8LQeKmgIAADwtBgLCAgAAPC0G5r4CAAA8LQdekgIAADwtB75+AgAAPC0Hhn4CAAA8LQfqfgIAADwtB8qCAgAAPC0Gor4CAAA8LQa6ygIAADwtBiLCAgAAPC0Hsp4CAAA8LQYKigIAADwtBjp2AgAAPC0HQroCAAA8LQcqjgIAADwtBxbKAgAAPC0HfnICAAA8LQdKcgIAADwtBxKCAgAAPC0HXoICAAA8LQaKfgIAADwtB7a6AgAAPC0GrsICAAA8LQdSlgIAADwtBzK6AgAAPC0H6roCAAA8LQfyrgIAADwtB0rCAgAAPC0HxnYCAAA8LQbuggIAADwtB96uAgAAPC0GQsYCAAA8LQdexgIAADwtBoq2AgAAPC0HUp4CAAA8LQeCrgIAADwtBn6yAgAAPC0HrsYCAAA8LQdWfgIAADwtByrGAgAAPC0HepYCAAA8LQdSegIAADwtB9JyAgAAPC0GnsoCAAA8LQbGdgIAADwtBoJ2AgAAPC0G5sYCAAA8LQbywgIAADwtBkqGAgAAPC0GzpoCAAA8LQemsgIAADwtBrJ6AgAAPC0HUq4CAAA8LQfemgIAADwtBgKaAgAAPC0GwoYCAAA8LQf6egIAADwtBjaOAgAAPC0GJrYCAAA8LQfeigIAADwtBoLGAgAAPC0Gun4CAAA8LQcalgIAADwtB6J6AgAAPC0GTooCAAA8LQcKvgIAADwtBw52AgAAPC0GLrICAAA8LQeGdgIAADwtBja+AgAAPC0HqoYCAAA8LQbStgIAADwtB0q+AgAAPC0HfsoCAAA8LQdKygIAADwtB8LCAgAAPC0GpooCAAA8LQfmjgIAADwtBmZ6AgAAPC0G1rICAAA8LQZuwgIAADwtBkrKAgAAPC0G2q4CAAA8LQcKigIAADwtB+LKAgAAPC0GepYCAAA8LQdCigIAADwtBup6AgAAPC0GBnoCAAA8LEMqAgIAAAAtB1qGAgAAhAQsgAQsWACAAIAAtAC1B/gFxIAFBAEdyOgAtCxkAIAAgAC0ALUH9AXEgAUEAR0EBdHI6AC0LGQAgACAALQAtQfsBcSABQQBHQQJ0cjoALQsZACAAIAAtAC1B9wFxIAFBAEdBA3RyOgAtCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAgAiBEUNACAAIAQRgICAgAAAIQMLIAMLSQECf0EAIQMCQCAAKAI4IgRFDQAgBCgCBCIERQ0AIAAgASACIAFrIAQRgYCAgAAAIgNBf0cNACAAQcaRgIAANgIQQRghAwsgAwsuAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIwIgRFDQAgACAEEYCAgIAAACEDCyADC0kBAn9BACEDAkAgACgCOCIERQ0AIAQoAggiBEUNACAAIAEgAiABayAEEYGAgIAAACIDQX9HDQAgAEH2ioCAADYCEEEYIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCNCIERQ0AIAAgBBGAgICAAAAhAwsgAwtJAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIMIgRFDQAgACABIAIgAWsgBBGBgICAAAAiA0F/Rw0AIABB7ZqAgAA2AhBBGCEDCyADCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAjgiBEUNACAAIAQRgICAgAAAIQMLIAMLSQECf0EAIQMCQCAAKAI4IgRFDQAgBCgCECIERQ0AIAAgASACIAFrIAQRgYCAgAAAIgNBf0cNACAAQZWQgIAANgIQQRghAwsgAwsuAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAI8IgRFDQAgACAEEYCAgIAAACEDCyADC0kBAn9BACEDAkAgACgCOCIERQ0AIAQoAhQiBEUNACAAIAEgAiABayAEEYGAgIAAACIDQX9HDQAgAEGqm4CAADYCEEEYIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCQCIERQ0AIAAgBBGAgICAAAAhAwsgAwtJAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIYIgRFDQAgACABIAIgAWsgBBGBgICAAAAiA0F/Rw0AIABB7ZOAgAA2AhBBGCEDCyADCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAkQiBEUNACAAIAQRgICAgAAAIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCJCIERQ0AIAAgBBGAgICAAAAhAwsgAwsuAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIsIgRFDQAgACAEEYCAgIAAACEDCyADC0kBAn9BACEDAkAgACgCOCIERQ0AIAQoAigiBEUNACAAIAEgAiABayAEEYGAgIAAACIDQX9HDQAgAEH2iICAADYCEEEYIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCUCIERQ0AIAAgBBGAgICAAAAhAwsgAwtJAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIcIgRFDQAgACABIAIgAWsgBBGBgICAAAAiA0F/Rw0AIABBwpmAgAA2AhBBGCEDCyADCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAkgiBEUNACAAIAQRgICAgAAAIQMLIAMLSQECf0EAIQMCQCAAKAI4IgRFDQAgBCgCICIERQ0AIAAgASACIAFrIAQRgYCAgAAAIgNBf0cNACAAQZSUgIAANgIQQRghAwsgAwsuAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAJMIgRFDQAgACAEEYCAgIAAACEDCyADCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAlQiBEUNACAAIAQRgICAgAAAIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCWCIERQ0AIAAgBBGAgICAAAAhAwsgAwtFAQF/AkACQCAALwEwQRRxQRRHDQBBASEDIAAtAChBAUYNASAALwEyQeUARiEDDAELIAAtAClBBUYhAwsgACADOgAuQQAL/gEBA39BASEDAkAgAC8BMCIEQQhxDQAgACkDIEIAUiEDCwJAAkAgAC0ALkUNAEEBIQUgAC0AKUEFRg0BQQEhBSAEQcAAcUUgA3FBAUcNAQtBACEFIARBwABxDQBBAiEFIARB//8DcSIDQQhxDQACQCADQYAEcUUNAAJAIAAtAChBAUcNACAALQAtQQpxDQBBBQ8LQQQPCwJAIANBIHENAAJAIAAtAChBAUYNACAALwEyQf//A3EiAEGcf2pB5ABJDQAgAEHMAUYNACAAQbACRg0AQQQhBSAEQShxRQ0CIANBiARxQYAERg0CC0EADwtBAEEDIAApAyBQGyEFCyAFC2IBAn9BACEBAkAgAC0AKEEBRg0AIAAvATJB//8DcSICQZx/akHkAEkNACACQcwBRg0AIAJBsAJGDQAgAC8BMCIAQcAAcQ0AQQEhASAAQYgEcUGABEYNACAAQShxRSEBCyABC6cBAQN/AkACQAJAIAAtACpFDQAgAC0AK0UNAEEAIQMgAC8BMCIEQQJxRQ0BDAILQQAhAyAALwEwIgRBAXFFDQELQQEhAyAALQAoQQFGDQAgAC8BMkH//wNxIgVBnH9qQeQASQ0AIAVBzAFGDQAgBUGwAkYNACAEQcAAcQ0AQQAhAyAEQYgEcUGABEYNACAEQShxQQBHIQMLIABBADsBMCAAQQA6AC8gAwuZAQECfwJAAkACQCAALQAqRQ0AIAAtACtFDQBBACEBIAAvATAiAkECcUUNAQwCC0EAIQEgAC8BMCICQQFxRQ0BC0EBIQEgAC0AKEEBRg0AIAAvATJB//8DcSIAQZx/akHkAEkNACAAQcwBRg0AIABBsAJGDQAgAkHAAHENAEEAIQEgAkGIBHFBgARGDQAgAkEocUEARyEBCyABC1kAIABBGGpCADcDACAAQgA3AwAgAEE4akIANwMAIABBMGpCADcDACAAQShqQgA3AwAgAEEgakIANwMAIABBEGpCADcDACAAQQhqQgA3AwAgAEHdATYCHEEAC3sBAX8CQCAAKAIMIgMNAAJAIAAoAgRFDQAgACABNgIECwJAIAAgASACEMSAgIAAIgMNACAAKAIMDwsgACADNgIcQQAhAyAAKAIEIgFFDQAgACABIAIgACgCCBGBgICAAAAiAUUNACAAIAI2AhQgACABNgIMIAEhAwsgAwvk8wEDDn8DfgR/I4CAgIAAQRBrIgMkgICAgAAgASEEIAEhBSABIQYgASEHIAEhCCABIQkgASEKIAEhCyABIQwgASENIAEhDiABIQ8CQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgACgCHCIQQX9qDt0B2gEB2QECAwQFBgcICQoLDA0O2AEPENcBERLWARMUFRYXGBkaG+AB3wEcHR7VAR8gISIjJCXUASYnKCkqKyzTAdIBLS7RAdABLzAxMjM0NTY3ODk6Ozw9Pj9AQUJDREVG2wFHSElKzwHOAUvNAUzMAU1OT1BRUlNUVVZXWFlaW1xdXl9gYWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXp7fH1+f4ABgQGCAYMBhAGFAYYBhwGIAYkBigGLAYwBjQGOAY8BkAGRAZIBkwGUAZUBlgGXAZgBmQGaAZsBnAGdAZ4BnwGgAaEBogGjAaQBpQGmAacBqAGpAaoBqwGsAa0BrgGvAbABsQGyAbMBtAG1AbYBtwHLAcoBuAHJAbkByAG6AbsBvAG9Ab4BvwHAAcEBwgHDAcQBxQHGAQDcAQtBACEQDMYBC0EOIRAMxQELQQ0hEAzEAQtBDyEQDMMBC0EQIRAMwgELQRMhEAzBAQtBFCEQDMABC0EVIRAMvwELQRYhEAy+AQtBFyEQDL0BC0EYIRAMvAELQRkhEAy7AQtBGiEQDLoBC0EbIRAMuQELQRwhEAy4AQtBCCEQDLcBC0EdIRAMtgELQSAhEAy1AQtBHyEQDLQBC0EHIRAMswELQSEhEAyyAQtBIiEQDLEBC0EeIRAMsAELQSMhEAyvAQtBEiEQDK4BC0ERIRAMrQELQSQhEAysAQtBJSEQDKsBC0EmIRAMqgELQSchEAypAQtBwwEhEAyoAQtBKSEQDKcBC0ErIRAMpgELQSwhEAylAQtBLSEQDKQBC0EuIRAMowELQS8hEAyiAQtBxAEhEAyhAQtBMCEQDKABC0E0IRAMnwELQQwhEAyeAQtBMSEQDJ0BC0EyIRAMnAELQTMhEAybAQtBOSEQDJoBC0E1IRAMmQELQcUBIRAMmAELQQshEAyXAQtBOiEQDJYBC0E2IRAMlQELQQohEAyUAQtBNyEQDJMBC0E4IRAMkgELQTwhEAyRAQtBOyEQDJABC0E9IRAMjwELQQkhEAyOAQtBKCEQDI0BC0E+IRAMjAELQT8hEAyLAQtBwAAhEAyKAQtBwQAhEAyJAQtBwgAhEAyIAQtBwwAhEAyHAQtBxAAhEAyGAQtBxQAhEAyFAQtBxgAhEAyEAQtBKiEQDIMBC0HHACEQDIIBC0HIACEQDIEBC0HJACEQDIABC0HKACEQDH8LQcsAIRAMfgtBzQAhEAx9C0HMACEQDHwLQc4AIRAMewtBzwAhEAx6C0HQACEQDHkLQdEAIRAMeAtB0gAhEAx3C0HTACEQDHYLQdQAIRAMdQtB1gAhEAx0C0HVACEQDHMLQQYhEAxyC0HXACEQDHELQQUhEAxwC0HYACEQDG8LQQQhEAxuC0HZACEQDG0LQdoAIRAMbAtB2wAhEAxrC0HcACEQDGoLQQMhEAxpC0HdACEQDGgLQd4AIRAMZwtB3wAhEAxmC0HhACEQDGULQeAAIRAMZAtB4gAhEAxjC0HjACEQDGILQQIhEAxhC0HkACEQDGALQeUAIRAMXwtB5gAhEAxeC0HnACEQDF0LQegAIRAMXAtB6QAhEAxbC0HqACEQDFoLQesAIRAMWQtB7AAhEAxYC0HtACEQDFcLQe4AIRAMVgtB7wAhEAxVC0HwACEQDFQLQfEAIRAMUwtB8gAhEAxSC0HzACEQDFELQfQAIRAMUAtB9QAhEAxPC0H2ACEQDE4LQfcAIRAMTQtB+AAhEAxMC0H5ACEQDEsLQfoAIRAMSgtB+wAhEAxJC0H8ACEQDEgLQf0AIRAMRwtB/gAhEAxGC0H/ACEQDEULQYABIRAMRAtBgQEhEAxDC0GCASEQDEILQYMBIRAMQQtBhAEhEAxAC0GFASEQDD8LQYYBIRAMPgtBhwEhEAw9C0GIASEQDDwLQYkBIRAMOwtBigEhEAw6C0GLASEQDDkLQYwBIRAMOAtBjQEhEAw3C0GOASEQDDYLQY8BIRAMNQtBkAEhEAw0C0GRASEQDDMLQZIBIRAMMgtBkwEhEAwxC0GUASEQDDALQZUBIRAMLwtBlgEhEAwuC0GXASEQDC0LQZgBIRAMLAtBmQEhEAwrC0GaASEQDCoLQZsBIRAMKQtBnAEhEAwoC0GdASEQDCcLQZ4BIRAMJgtBnwEhEAwlC0GgASEQDCQLQaEBIRAMIwtBogEhEAwiC0GjASEQDCELQaQBIRAMIAtBpQEhEAwfC0GmASEQDB4LQacBIRAMHQtBqAEhEAwcC0GpASEQDBsLQaoBIRAMGgtBqwEhEAwZC0GsASEQDBgLQa0BIRAMFwtBrgEhEAwWC0EBIRAMFQtBrwEhEAwUC0GwASEQDBMLQbEBIRAMEgtBswEhEAwRC0GyASEQDBALQbQBIRAMDwtBtQEhEAwOC0G2ASEQDA0LQbcBIRAMDAtBuAEhEAwLC0G5ASEQDAoLQboBIRAMCQtBuwEhEAwIC0HGASEQDAcLQbwBIRAMBgtBvQEhEAwFC0G+ASEQDAQLQb8BIRAMAwtBwAEhEAwCC0HCASEQDAELQcEBIRALA0ACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCAQDscBAAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxweHyAhIyUoP0BBREVGR0hJSktMTU9QUVJT3gNXWVtcXWBiZWZnaGlqa2xtb3BxcnN0dXZ3eHl6e3x9foABggGFAYYBhwGJAYsBjAGNAY4BjwGQAZEBlAGVAZYBlwGYAZkBmgGbAZwBnQGeAZ8BoAGhAaIBowGkAaUBpgGnAagBqQGqAasBrAGtAa4BrwGwAbEBsgGzAbQBtQG2AbcBuAG5AboBuwG8Ab0BvgG/AcABwQHCAcMBxAHFAcYBxwHIAckBygHLAcwBzQHOAc8B0AHRAdIB0wHUAdUB1gHXAdgB2QHaAdsB3AHdAd4B4AHhAeIB4wHkAeUB5gHnAegB6QHqAesB7AHtAe4B7wHwAfEB8gHzAZkCpAKwAv4C/gILIAEiBCACRw3zAUHdASEQDP8DCyABIhAgAkcN3QFBwwEhEAz+AwsgASIBIAJHDZABQfcAIRAM/QMLIAEiASACRw2GAUHvACEQDPwDCyABIgEgAkcNf0HqACEQDPsDCyABIgEgAkcNe0HoACEQDPoDCyABIgEgAkcNeEHmACEQDPkDCyABIgEgAkcNGkEYIRAM+AMLIAEiASACRw0UQRIhEAz3AwsgASIBIAJHDVlBxQAhEAz2AwsgASIBIAJHDUpBPyEQDPUDCyABIgEgAkcNSEE8IRAM9AMLIAEiASACRw1BQTEhEAzzAwsgAC0ALkEBRg3rAwyHAgsgACABIgEgAhDAgICAAEEBRw3mASAAQgA3AyAM5wELIAAgASIBIAIQtICAgAAiEA3nASABIQEM9QILAkAgASIBIAJHDQBBBiEQDPADCyAAIAFBAWoiASACELuAgIAAIhAN6AEgASEBDDELIABCADcDIEESIRAM1QMLIAEiECACRw0rQR0hEAztAwsCQCABIgEgAkYNACABQQFqIQFBECEQDNQDC0EHIRAM7AMLIABCACAAKQMgIhEgAiABIhBrrSISfSITIBMgEVYbNwMgIBEgElYiFEUN5QFBCCEQDOsDCwJAIAEiASACRg0AIABBiYCAgAA2AgggACABNgIEIAEhAUEUIRAM0gMLQQkhEAzqAwsgASEBIAApAyBQDeQBIAEhAQzyAgsCQCABIgEgAkcNAEELIRAM6QMLIAAgAUEBaiIBIAIQtoCAgAAiEA3lASABIQEM8gILIAAgASIBIAIQuICAgAAiEA3lASABIQEM8gILIAAgASIBIAIQuICAgAAiEA3mASABIQEMDQsgACABIgEgAhC6gICAACIQDecBIAEhAQzwAgsCQCABIgEgAkcNAEEPIRAM5QMLIAEtAAAiEEE7Rg0IIBBBDUcN6AEgAUEBaiEBDO8CCyAAIAEiASACELqAgIAAIhAN6AEgASEBDPICCwNAAkAgAS0AAEHwtYCAAGotAAAiEEEBRg0AIBBBAkcN6wEgACgCBCEQIABBADYCBCAAIBAgAUEBaiIBELmAgIAAIhAN6gEgASEBDPQCCyABQQFqIgEgAkcNAAtBEiEQDOIDCyAAIAEiASACELqAgIAAIhAN6QEgASEBDAoLIAEiASACRw0GQRshEAzgAwsCQCABIgEgAkcNAEEWIRAM4AMLIABBioCAgAA2AgggACABNgIEIAAgASACELiAgIAAIhAN6gEgASEBQSAhEAzGAwsCQCABIgEgAkYNAANAAkAgAS0AAEHwt4CAAGotAAAiEEECRg0AAkAgEEF/ag4E5QHsAQDrAewBCyABQQFqIQFBCCEQDMgDCyABQQFqIgEgAkcNAAtBFSEQDN8DC0EVIRAM3gMLA0ACQCABLQAAQfC5gIAAai0AACIQQQJGDQAgEEF/ag4E3gHsAeAB6wHsAQsgAUEBaiIBIAJHDQALQRghEAzdAwsCQCABIgEgAkYNACAAQYuAgIAANgIIIAAgATYCBCABIQFBByEQDMQDC0EZIRAM3AMLIAFBAWohAQwCCwJAIAEiFCACRw0AQRohEAzbAwsgFCEBAkAgFC0AAEFzag4U3QLuAu4C7gLuAu4C7gLuAu4C7gLuAu4C7gLuAu4C7gLuAu4C7gIA7gILQQAhECAAQQA2AhwgAEGvi4CAADYCECAAQQI2AgwgACAUQQFqNgIUDNoDCwJAIAEtAAAiEEE7Rg0AIBBBDUcN6AEgAUEBaiEBDOUCCyABQQFqIQELQSIhEAy/AwsCQCABIhAgAkcNAEEcIRAM2AMLQgAhESAQIQEgEC0AAEFQag435wHmAQECAwQFBgcIAAAAAAAAAAkKCwwNDgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADxAREhMUAAtBHiEQDL0DC0ICIREM5QELQgMhEQzkAQtCBCERDOMBC0IFIREM4gELQgYhEQzhAQtCByERDOABC0IIIREM3wELQgkhEQzeAQtCCiERDN0BC0ILIREM3AELQgwhEQzbAQtCDSERDNoBC0IOIREM2QELQg8hEQzYAQtCCiERDNcBC0ILIREM1gELQgwhEQzVAQtCDSERDNQBC0IOIREM0wELQg8hEQzSAQtCACERAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCAQLQAAQVBqDjflAeQBAAECAwQFBgfmAeYB5gHmAeYB5gHmAQgJCgsMDeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gEODxAREhPmAQtCAiERDOQBC0IDIREM4wELQgQhEQziAQtCBSERDOEBC0IGIREM4AELQgchEQzfAQtCCCERDN4BC0IJIREM3QELQgohEQzcAQtCCyERDNsBC0IMIREM2gELQg0hEQzZAQtCDiERDNgBC0IPIREM1wELQgohEQzWAQtCCyERDNUBC0IMIREM1AELQg0hEQzTAQtCDiERDNIBC0IPIREM0QELIABCACAAKQMgIhEgAiABIhBrrSISfSITIBMgEVYbNwMgIBEgElYiFEUN0gFBHyEQDMADCwJAIAEiASACRg0AIABBiYCAgAA2AgggACABNgIEIAEhAUEkIRAMpwMLQSAhEAy/AwsgACABIhAgAhC+gICAAEF/ag4FtgEAxQIB0QHSAQtBESEQDKQDCyAAQQE6AC8gECEBDLsDCyABIgEgAkcN0gFBJCEQDLsDCyABIg0gAkcNHkHGACEQDLoDCyAAIAEiASACELKAgIAAIhAN1AEgASEBDLUBCyABIhAgAkcNJkHQACEQDLgDCwJAIAEiASACRw0AQSghEAy4AwsgAEEANgIEIABBjICAgAA2AgggACABIAEQsYCAgAAiEA3TASABIQEM2AELAkAgASIQIAJHDQBBKSEQDLcDCyAQLQAAIgFBIEYNFCABQQlHDdMBIBBBAWohAQwVCwJAIAEiASACRg0AIAFBAWohAQwXC0EqIRAMtQMLAkAgASIQIAJHDQBBKyEQDLUDCwJAIBAtAAAiAUEJRg0AIAFBIEcN1QELIAAtACxBCEYN0wEgECEBDJEDCwJAIAEiASACRw0AQSwhEAy0AwsgAS0AAEEKRw3VASABQQFqIQEMyQILIAEiDiACRw3VAUEvIRAMsgMLA0ACQCABLQAAIhBBIEYNAAJAIBBBdmoOBADcAdwBANoBCyABIQEM4AELIAFBAWoiASACRw0AC0ExIRAMsQMLQTIhECABIhQgAkYNsAMgAiAUayAAKAIAIgFqIRUgFCABa0EDaiEWAkADQCAULQAAIhdBIHIgFyAXQb9/akH/AXFBGkkbQf8BcSABQfC7gIAAai0AAEcNAQJAIAFBA0cNAEEGIQEMlgMLIAFBAWohASAUQQFqIhQgAkcNAAsgACAVNgIADLEDCyAAQQA2AgAgFCEBDNkBC0EzIRAgASIUIAJGDa8DIAIgFGsgACgCACIBaiEVIBQgAWtBCGohFgJAA0AgFC0AACIXQSByIBcgF0G/f2pB/wFxQRpJG0H/AXEgAUH0u4CAAGotAABHDQECQCABQQhHDQBBBSEBDJUDCyABQQFqIQEgFEEBaiIUIAJHDQALIAAgFTYCAAywAwsgAEEANgIAIBQhAQzYAQtBNCEQIAEiFCACRg2uAyACIBRrIAAoAgAiAWohFSAUIAFrQQVqIRYCQANAIBQtAAAiF0EgciAXIBdBv39qQf8BcUEaSRtB/wFxIAFB0MKAgABqLQAARw0BAkAgAUEFRw0AQQchAQyUAwsgAUEBaiEBIBRBAWoiFCACRw0ACyAAIBU2AgAMrwMLIABBADYCACAUIQEM1wELAkAgASIBIAJGDQADQAJAIAEtAABBgL6AgABqLQAAIhBBAUYNACAQQQJGDQogASEBDN0BCyABQQFqIgEgAkcNAAtBMCEQDK4DC0EwIRAMrQMLAkAgASIBIAJGDQADQAJAIAEtAAAiEEEgRg0AIBBBdmoOBNkB2gHaAdkB2gELIAFBAWoiASACRw0AC0E4IRAMrQMLQTghEAysAwsDQAJAIAEtAAAiEEEgRg0AIBBBCUcNAwsgAUEBaiIBIAJHDQALQTwhEAyrAwsDQAJAIAEtAAAiEEEgRg0AAkACQCAQQXZqDgTaAQEB2gEACyAQQSxGDdsBCyABIQEMBAsgAUEBaiIBIAJHDQALQT8hEAyqAwsgASEBDNsBC0HAACEQIAEiFCACRg2oAyACIBRrIAAoAgAiAWohFiAUIAFrQQZqIRcCQANAIBQtAABBIHIgAUGAwICAAGotAABHDQEgAUEGRg2OAyABQQFqIQEgFEEBaiIUIAJHDQALIAAgFjYCAAypAwsgAEEANgIAIBQhAQtBNiEQDI4DCwJAIAEiDyACRw0AQcEAIRAMpwMLIABBjICAgAA2AgggACAPNgIEIA8hASAALQAsQX9qDgTNAdUB1wHZAYcDCyABQQFqIQEMzAELAkAgASIBIAJGDQADQAJAIAEtAAAiEEEgciAQIBBBv39qQf8BcUEaSRtB/wFxIhBBCUYNACAQQSBGDQACQAJAAkACQCAQQZ1/ag4TAAMDAwMDAwMBAwMDAwMDAwMDAgMLIAFBAWohAUExIRAMkQMLIAFBAWohAUEyIRAMkAMLIAFBAWohAUEzIRAMjwMLIAEhAQzQAQsgAUEBaiIBIAJHDQALQTUhEAylAwtBNSEQDKQDCwJAIAEiASACRg0AA0ACQCABLQAAQYC8gIAAai0AAEEBRg0AIAEhAQzTAQsgAUEBaiIBIAJHDQALQT0hEAykAwtBPSEQDKMDCyAAIAEiASACELCAgIAAIhAN1gEgASEBDAELIBBBAWohAQtBPCEQDIcDCwJAIAEiASACRw0AQcIAIRAMoAMLAkADQAJAIAEtAABBd2oOGAAC/gL+AoQD/gL+Av4C/gL+Av4C/gL+Av4C/gL+Av4C/gL+Av4C/gL+Av4CAP4CCyABQQFqIgEgAkcNAAtBwgAhEAygAwsgAUEBaiEBIAAtAC1BAXFFDb0BIAEhAQtBLCEQDIUDCyABIgEgAkcN0wFBxAAhEAydAwsDQAJAIAEtAABBkMCAgABqLQAAQQFGDQAgASEBDLcCCyABQQFqIgEgAkcNAAtBxQAhEAycAwsgDS0AACIQQSBGDbMBIBBBOkcNgQMgACgCBCEBIABBADYCBCAAIAEgDRCvgICAACIBDdABIA1BAWohAQyzAgtBxwAhECABIg0gAkYNmgMgAiANayAAKAIAIgFqIRYgDSABa0EFaiEXA0AgDS0AACIUQSByIBQgFEG/f2pB/wFxQRpJG0H/AXEgAUGQwoCAAGotAABHDYADIAFBBUYN9AIgAUEBaiEBIA1BAWoiDSACRw0ACyAAIBY2AgAMmgMLQcgAIRAgASINIAJGDZkDIAIgDWsgACgCACIBaiEWIA0gAWtBCWohFwNAIA0tAAAiFEEgciAUIBRBv39qQf8BcUEaSRtB/wFxIAFBlsKAgABqLQAARw3/AgJAIAFBCUcNAEECIQEM9QILIAFBAWohASANQQFqIg0gAkcNAAsgACAWNgIADJkDCwJAIAEiDSACRw0AQckAIRAMmQMLAkACQCANLQAAIgFBIHIgASABQb9/akH/AXFBGkkbQf8BcUGSf2oOBwCAA4ADgAOAA4ADAYADCyANQQFqIQFBPiEQDIADCyANQQFqIQFBPyEQDP8CC0HKACEQIAEiDSACRg2XAyACIA1rIAAoAgAiAWohFiANIAFrQQFqIRcDQCANLQAAIhRBIHIgFCAUQb9/akH/AXFBGkkbQf8BcSABQaDCgIAAai0AAEcN/QIgAUEBRg3wAiABQQFqIQEgDUEBaiINIAJHDQALIAAgFjYCAAyXAwtBywAhECABIg0gAkYNlgMgAiANayAAKAIAIgFqIRYgDSABa0EOaiEXA0AgDS0AACIUQSByIBQgFEG/f2pB/wFxQRpJG0H/AXEgAUGiwoCAAGotAABHDfwCIAFBDkYN8AIgAUEBaiEBIA1BAWoiDSACRw0ACyAAIBY2AgAMlgMLQcwAIRAgASINIAJGDZUDIAIgDWsgACgCACIBaiEWIA0gAWtBD2ohFwNAIA0tAAAiFEEgciAUIBRBv39qQf8BcUEaSRtB/wFxIAFBwMKAgABqLQAARw37AgJAIAFBD0cNAEEDIQEM8QILIAFBAWohASANQQFqIg0gAkcNAAsgACAWNgIADJUDC0HNACEQIAEiDSACRg2UAyACIA1rIAAoAgAiAWohFiANIAFrQQVqIRcDQCANLQAAIhRBIHIgFCAUQb9/akH/AXFBGkkbQf8BcSABQdDCgIAAai0AAEcN+gICQCABQQVHDQBBBCEBDPACCyABQQFqIQEgDUEBaiINIAJHDQALIAAgFjYCAAyUAwsCQCABIg0gAkcNAEHOACEQDJQDCwJAAkACQAJAIA0tAAAiAUEgciABIAFBv39qQf8BcUEaSRtB/wFxQZ1/ag4TAP0C/QL9Av0C/QL9Av0C/QL9Av0C/QL9AgH9Av0C/QICA/0CCyANQQFqIQFBwQAhEAz9AgsgDUEBaiEBQcIAIRAM/AILIA1BAWohAUHDACEQDPsCCyANQQFqIQFBxAAhEAz6AgsCQCABIgEgAkYNACAAQY2AgIAANgIIIAAgATYCBCABIQFBxQAhEAz6AgtBzwAhEAySAwsgECEBAkACQCAQLQAAQXZqDgQBqAKoAgCoAgsgEEEBaiEBC0EnIRAM+AILAkAgASIBIAJHDQBB0QAhEAyRAwsCQCABLQAAQSBGDQAgASEBDI0BCyABQQFqIQEgAC0ALUEBcUUNxwEgASEBDIwBCyABIhcgAkcNyAFB0gAhEAyPAwtB0wAhECABIhQgAkYNjgMgAiAUayAAKAIAIgFqIRYgFCABa0EBaiEXA0AgFC0AACABQdbCgIAAai0AAEcNzAEgAUEBRg3HASABQQFqIQEgFEEBaiIUIAJHDQALIAAgFjYCAAyOAwsCQCABIgEgAkcNAEHVACEQDI4DCyABLQAAQQpHDcwBIAFBAWohAQzHAQsCQCABIgEgAkcNAEHWACEQDI0DCwJAAkAgAS0AAEF2ag4EAM0BzQEBzQELIAFBAWohAQzHAQsgAUEBaiEBQcoAIRAM8wILIAAgASIBIAIQroCAgAAiEA3LASABIQFBzQAhEAzyAgsgAC0AKUEiRg2FAwymAgsCQCABIgEgAkcNAEHbACEQDIoDC0EAIRRBASEXQQEhFkEAIRACQAJAAkACQAJAAkACQAJAAkAgAS0AAEFQag4K1AHTAQABAgMEBQYI1QELQQIhEAwGC0EDIRAMBQtBBCEQDAQLQQUhEAwDC0EGIRAMAgtBByEQDAELQQghEAtBACEXQQAhFkEAIRQMzAELQQkhEEEBIRRBACEXQQAhFgzLAQsCQCABIgEgAkcNAEHdACEQDIkDCyABLQAAQS5HDcwBIAFBAWohAQymAgsgASIBIAJHDcwBQd8AIRAMhwMLAkAgASIBIAJGDQAgAEGOgICAADYCCCAAIAE2AgQgASEBQdAAIRAM7gILQeAAIRAMhgMLQeEAIRAgASIBIAJGDYUDIAIgAWsgACgCACIUaiEWIAEgFGtBA2ohFwNAIAEtAAAgFEHiwoCAAGotAABHDc0BIBRBA0YNzAEgFEEBaiEUIAFBAWoiASACRw0ACyAAIBY2AgAMhQMLQeIAIRAgASIBIAJGDYQDIAIgAWsgACgCACIUaiEWIAEgFGtBAmohFwNAIAEtAAAgFEHmwoCAAGotAABHDcwBIBRBAkYNzgEgFEEBaiEUIAFBAWoiASACRw0ACyAAIBY2AgAMhAMLQeMAIRAgASIBIAJGDYMDIAIgAWsgACgCACIUaiEWIAEgFGtBA2ohFwNAIAEtAAAgFEHpwoCAAGotAABHDcsBIBRBA0YNzgEgFEEBaiEUIAFBAWoiASACRw0ACyAAIBY2AgAMgwMLAkAgASIBIAJHDQBB5QAhEAyDAwsgACABQQFqIgEgAhCogICAACIQDc0BIAEhAUHWACEQDOkCCwJAIAEiASACRg0AA0ACQCABLQAAIhBBIEYNAAJAAkACQCAQQbh/ag4LAAHPAc8BzwHPAc8BzwHPAc8BAs8BCyABQQFqIQFB0gAhEAztAgsgAUEBaiEBQdMAIRAM7AILIAFBAWohAUHUACEQDOsCCyABQQFqIgEgAkcNAAtB5AAhEAyCAwtB5AAhEAyBAwsDQAJAIAEtAABB8MKAgABqLQAAIhBBAUYNACAQQX5qDgPPAdAB0QHSAQsgAUEBaiIBIAJHDQALQeYAIRAMgAMLAkAgASIBIAJGDQAgAUEBaiEBDAMLQecAIRAM/wILA0ACQCABLQAAQfDEgIAAai0AACIQQQFGDQACQCAQQX5qDgTSAdMB1AEA1QELIAEhAUHXACEQDOcCCyABQQFqIgEgAkcNAAtB6AAhEAz+AgsCQCABIgEgAkcNAEHpACEQDP4CCwJAIAEtAAAiEEF2ag4augHVAdUBvAHVAdUB1QHVAdUB1QHVAdUB1QHVAdUB1QHVAdUB1QHVAdUB1QHKAdUB1QEA0wELIAFBAWohAQtBBiEQDOMCCwNAAkAgAS0AAEHwxoCAAGotAABBAUYNACABIQEMngILIAFBAWoiASACRw0AC0HqACEQDPsCCwJAIAEiASACRg0AIAFBAWohAQwDC0HrACEQDPoCCwJAIAEiASACRw0AQewAIRAM+gILIAFBAWohAQwBCwJAIAEiASACRw0AQe0AIRAM+QILIAFBAWohAQtBBCEQDN4CCwJAIAEiFCACRw0AQe4AIRAM9wILIBQhAQJAAkACQCAULQAAQfDIgIAAai0AAEF/ag4H1AHVAdYBAJwCAQLXAQsgFEEBaiEBDAoLIBRBAWohAQzNAQtBACEQIABBADYCHCAAQZuSgIAANgIQIABBBzYCDCAAIBRBAWo2AhQM9gILAkADQAJAIAEtAABB8MiAgABqLQAAIhBBBEYNAAJAAkAgEEF/ag4H0gHTAdQB2QEABAHZAQsgASEBQdoAIRAM4AILIAFBAWohAUHcACEQDN8CCyABQQFqIgEgAkcNAAtB7wAhEAz2AgsgAUEBaiEBDMsBCwJAIAEiFCACRw0AQfAAIRAM9QILIBQtAABBL0cN1AEgFEEBaiEBDAYLAkAgASIUIAJHDQBB8QAhEAz0AgsCQCAULQAAIgFBL0cNACAUQQFqIQFB3QAhEAzbAgsgAUF2aiIEQRZLDdMBQQEgBHRBiYCAAnFFDdMBDMoCCwJAIAEiASACRg0AIAFBAWohAUHeACEQDNoCC0HyACEQDPICCwJAIAEiFCACRw0AQfQAIRAM8gILIBQhAQJAIBQtAABB8MyAgABqLQAAQX9qDgPJApQCANQBC0HhACEQDNgCCwJAIAEiFCACRg0AA0ACQCAULQAAQfDKgIAAai0AACIBQQNGDQACQCABQX9qDgLLAgDVAQsgFCEBQd8AIRAM2gILIBRBAWoiFCACRw0AC0HzACEQDPECC0HzACEQDPACCwJAIAEiASACRg0AIABBj4CAgAA2AgggACABNgIEIAEhAUHgACEQDNcCC0H1ACEQDO8CCwJAIAEiASACRw0AQfYAIRAM7wILIABBj4CAgAA2AgggACABNgIEIAEhAQtBAyEQDNQCCwNAIAEtAABBIEcNwwIgAUEBaiIBIAJHDQALQfcAIRAM7AILAkAgASIBIAJHDQBB+AAhEAzsAgsgAS0AAEEgRw3OASABQQFqIQEM7wELIAAgASIBIAIQrICAgAAiEA3OASABIQEMjgILAkAgASIEIAJHDQBB+gAhEAzqAgsgBC0AAEHMAEcN0QEgBEEBaiEBQRMhEAzPAQsCQCABIgQgAkcNAEH7ACEQDOkCCyACIARrIAAoAgAiAWohFCAEIAFrQQVqIRADQCAELQAAIAFB8M6AgABqLQAARw3QASABQQVGDc4BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQfsAIRAM6AILAkAgASIEIAJHDQBB/AAhEAzoAgsCQAJAIAQtAABBvX9qDgwA0QHRAdEB0QHRAdEB0QHRAdEB0QEB0QELIARBAWohAUHmACEQDM8CCyAEQQFqIQFB5wAhEAzOAgsCQCABIgQgAkcNAEH9ACEQDOcCCyACIARrIAAoAgAiAWohFCAEIAFrQQJqIRACQANAIAQtAAAgAUHtz4CAAGotAABHDc8BIAFBAkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEH9ACEQDOcCCyAAQQA2AgAgEEEBaiEBQRAhEAzMAQsCQCABIgQgAkcNAEH+ACEQDOYCCyACIARrIAAoAgAiAWohFCAEIAFrQQVqIRACQANAIAQtAAAgAUH2zoCAAGotAABHDc4BIAFBBUYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEH+ACEQDOYCCyAAQQA2AgAgEEEBaiEBQRYhEAzLAQsCQCABIgQgAkcNAEH/ACEQDOUCCyACIARrIAAoAgAiAWohFCAEIAFrQQNqIRACQANAIAQtAAAgAUH8zoCAAGotAABHDc0BIAFBA0YNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEH/ACEQDOUCCyAAQQA2AgAgEEEBaiEBQQUhEAzKAQsCQCABIgQgAkcNAEGAASEQDOQCCyAELQAAQdkARw3LASAEQQFqIQFBCCEQDMkBCwJAIAEiBCACRw0AQYEBIRAM4wILAkACQCAELQAAQbJ/ag4DAMwBAcwBCyAEQQFqIQFB6wAhEAzKAgsgBEEBaiEBQewAIRAMyQILAkAgASIEIAJHDQBBggEhEAziAgsCQAJAIAQtAABBuH9qDggAywHLAcsBywHLAcsBAcsBCyAEQQFqIQFB6gAhEAzJAgsgBEEBaiEBQe0AIRAMyAILAkAgASIEIAJHDQBBgwEhEAzhAgsgAiAEayAAKAIAIgFqIRAgBCABa0ECaiEUAkADQCAELQAAIAFBgM+AgABqLQAARw3JASABQQJGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBA2AgBBgwEhEAzhAgtBACEQIABBADYCACAUQQFqIQEMxgELAkAgASIEIAJHDQBBhAEhEAzgAgsgAiAEayAAKAIAIgFqIRQgBCABa0EEaiEQAkADQCAELQAAIAFBg8+AgABqLQAARw3IASABQQRGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBhAEhEAzgAgsgAEEANgIAIBBBAWohAUEjIRAMxQELAkAgASIEIAJHDQBBhQEhEAzfAgsCQAJAIAQtAABBtH9qDggAyAHIAcgByAHIAcgBAcgBCyAEQQFqIQFB7wAhEAzGAgsgBEEBaiEBQfAAIRAMxQILAkAgASIEIAJHDQBBhgEhEAzeAgsgBC0AAEHFAEcNxQEgBEEBaiEBDIMCCwJAIAEiBCACRw0AQYcBIRAM3QILIAIgBGsgACgCACIBaiEUIAQgAWtBA2ohEAJAA0AgBC0AACABQYjPgIAAai0AAEcNxQEgAUEDRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQYcBIRAM3QILIABBADYCACAQQQFqIQFBLSEQDMIBCwJAIAEiBCACRw0AQYgBIRAM3AILIAIgBGsgACgCACIBaiEUIAQgAWtBCGohEAJAA0AgBC0AACABQdDPgIAAai0AAEcNxAEgAUEIRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQYgBIRAM3AILIABBADYCACAQQQFqIQFBKSEQDMEBCwJAIAEiASACRw0AQYkBIRAM2wILQQEhECABLQAAQd8ARw3AASABQQFqIQEMgQILAkAgASIEIAJHDQBBigEhEAzaAgsgAiAEayAAKAIAIgFqIRQgBCABa0EBaiEQA0AgBC0AACABQYzPgIAAai0AAEcNwQEgAUEBRg2vAiABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGKASEQDNkCCwJAIAEiBCACRw0AQYsBIRAM2QILIAIgBGsgACgCACIBaiEUIAQgAWtBAmohEAJAA0AgBC0AACABQY7PgIAAai0AAEcNwQEgAUECRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQYsBIRAM2QILIABBADYCACAQQQFqIQFBAiEQDL4BCwJAIAEiBCACRw0AQYwBIRAM2AILIAIgBGsgACgCACIBaiEUIAQgAWtBAWohEAJAA0AgBC0AACABQfDPgIAAai0AAEcNwAEgAUEBRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQYwBIRAM2AILIABBADYCACAQQQFqIQFBHyEQDL0BCwJAIAEiBCACRw0AQY0BIRAM1wILIAIgBGsgACgCACIBaiEUIAQgAWtBAWohEAJAA0AgBC0AACABQfLPgIAAai0AAEcNvwEgAUEBRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQY0BIRAM1wILIABBADYCACAQQQFqIQFBCSEQDLwBCwJAIAEiBCACRw0AQY4BIRAM1gILAkACQCAELQAAQbd/ag4HAL8BvwG/Ab8BvwEBvwELIARBAWohAUH4ACEQDL0CCyAEQQFqIQFB+QAhEAy8AgsCQCABIgQgAkcNAEGPASEQDNUCCyACIARrIAAoAgAiAWohFCAEIAFrQQVqIRACQANAIAQtAAAgAUGRz4CAAGotAABHDb0BIAFBBUYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGPASEQDNUCCyAAQQA2AgAgEEEBaiEBQRghEAy6AQsCQCABIgQgAkcNAEGQASEQDNQCCyACIARrIAAoAgAiAWohFCAEIAFrQQJqIRACQANAIAQtAAAgAUGXz4CAAGotAABHDbwBIAFBAkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGQASEQDNQCCyAAQQA2AgAgEEEBaiEBQRchEAy5AQsCQCABIgQgAkcNAEGRASEQDNMCCyACIARrIAAoAgAiAWohFCAEIAFrQQZqIRACQANAIAQtAAAgAUGaz4CAAGotAABHDbsBIAFBBkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGRASEQDNMCCyAAQQA2AgAgEEEBaiEBQRUhEAy4AQsCQCABIgQgAkcNAEGSASEQDNICCyACIARrIAAoAgAiAWohFCAEIAFrQQVqIRACQANAIAQtAAAgAUGhz4CAAGotAABHDboBIAFBBUYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGSASEQDNICCyAAQQA2AgAgEEEBaiEBQR4hEAy3AQsCQCABIgQgAkcNAEGTASEQDNECCyAELQAAQcwARw24ASAEQQFqIQFBCiEQDLYBCwJAIAQgAkcNAEGUASEQDNACCwJAAkAgBC0AAEG/f2oODwC5AbkBuQG5AbkBuQG5AbkBuQG5AbkBuQG5AQG5AQsgBEEBaiEBQf4AIRAMtwILIARBAWohAUH/ACEQDLYCCwJAIAQgAkcNAEGVASEQDM8CCwJAAkAgBC0AAEG/f2oOAwC4AQG4AQsgBEEBaiEBQf0AIRAMtgILIARBAWohBEGAASEQDLUCCwJAIAQgAkcNAEGWASEQDM4CCyACIARrIAAoAgAiAWohFCAEIAFrQQFqIRACQANAIAQtAAAgAUGnz4CAAGotAABHDbYBIAFBAUYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGWASEQDM4CCyAAQQA2AgAgEEEBaiEBQQshEAyzAQsCQCAEIAJHDQBBlwEhEAzNAgsCQAJAAkACQCAELQAAQVNqDiMAuAG4AbgBuAG4AbgBuAG4AbgBuAG4AbgBuAG4AbgBuAG4AbgBuAG4AbgBuAG4AQG4AbgBuAG4AbgBArgBuAG4AQO4AQsgBEEBaiEBQfsAIRAMtgILIARBAWohAUH8ACEQDLUCCyAEQQFqIQRBgQEhEAy0AgsgBEEBaiEEQYIBIRAMswILAkAgBCACRw0AQZgBIRAMzAILIAIgBGsgACgCACIBaiEUIAQgAWtBBGohEAJAA0AgBC0AACABQanPgIAAai0AAEcNtAEgAUEERg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQZgBIRAMzAILIABBADYCACAQQQFqIQFBGSEQDLEBCwJAIAQgAkcNAEGZASEQDMsCCyACIARrIAAoAgAiAWohFCAEIAFrQQVqIRACQANAIAQtAAAgAUGuz4CAAGotAABHDbMBIAFBBUYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGZASEQDMsCCyAAQQA2AgAgEEEBaiEBQQYhEAywAQsCQCAEIAJHDQBBmgEhEAzKAgsgAiAEayAAKAIAIgFqIRQgBCABa0EBaiEQAkADQCAELQAAIAFBtM+AgABqLQAARw2yASABQQFGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBmgEhEAzKAgsgAEEANgIAIBBBAWohAUEcIRAMrwELAkAgBCACRw0AQZsBIRAMyQILIAIgBGsgACgCACIBaiEUIAQgAWtBAWohEAJAA0AgBC0AACABQbbPgIAAai0AAEcNsQEgAUEBRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQZsBIRAMyQILIABBADYCACAQQQFqIQFBJyEQDK4BCwJAIAQgAkcNAEGcASEQDMgCCwJAAkAgBC0AAEGsf2oOAgABsQELIARBAWohBEGGASEQDK8CCyAEQQFqIQRBhwEhEAyuAgsCQCAEIAJHDQBBnQEhEAzHAgsgAiAEayAAKAIAIgFqIRQgBCABa0EBaiEQAkADQCAELQAAIAFBuM+AgABqLQAARw2vASABQQFGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBnQEhEAzHAgsgAEEANgIAIBBBAWohAUEmIRAMrAELAkAgBCACRw0AQZ4BIRAMxgILIAIgBGsgACgCACIBaiEUIAQgAWtBAWohEAJAA0AgBC0AACABQbrPgIAAai0AAEcNrgEgAUEBRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQZ4BIRAMxgILIABBADYCACAQQQFqIQFBAyEQDKsBCwJAIAQgAkcNAEGfASEQDMUCCyACIARrIAAoAgAiAWohFCAEIAFrQQJqIRACQANAIAQtAAAgAUHtz4CAAGotAABHDa0BIAFBAkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGfASEQDMUCCyAAQQA2AgAgEEEBaiEBQQwhEAyqAQsCQCAEIAJHDQBBoAEhEAzEAgsgAiAEayAAKAIAIgFqIRQgBCABa0EDaiEQAkADQCAELQAAIAFBvM+AgABqLQAARw2sASABQQNGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBoAEhEAzEAgsgAEEANgIAIBBBAWohAUENIRAMqQELAkAgBCACRw0AQaEBIRAMwwILAkACQCAELQAAQbp/ag4LAKwBrAGsAawBrAGsAawBrAGsAQGsAQsgBEEBaiEEQYsBIRAMqgILIARBAWohBEGMASEQDKkCCwJAIAQgAkcNAEGiASEQDMICCyAELQAAQdAARw2pASAEQQFqIQQM6QELAkAgBCACRw0AQaMBIRAMwQILAkACQCAELQAAQbd/ag4HAaoBqgGqAaoBqgEAqgELIARBAWohBEGOASEQDKgCCyAEQQFqIQFBIiEQDKYBCwJAIAQgAkcNAEGkASEQDMACCyACIARrIAAoAgAiAWohFCAEIAFrQQFqIRACQANAIAQtAAAgAUHAz4CAAGotAABHDagBIAFBAUYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGkASEQDMACCyAAQQA2AgAgEEEBaiEBQR0hEAylAQsCQCAEIAJHDQBBpQEhEAy/AgsCQAJAIAQtAABBrn9qDgMAqAEBqAELIARBAWohBEGQASEQDKYCCyAEQQFqIQFBBCEQDKQBCwJAIAQgAkcNAEGmASEQDL4CCwJAAkACQAJAAkAgBC0AAEG/f2oOFQCqAaoBqgGqAaoBqgGqAaoBqgGqAQGqAaoBAqoBqgEDqgGqAQSqAQsgBEEBaiEEQYgBIRAMqAILIARBAWohBEGJASEQDKcCCyAEQQFqIQRBigEhEAymAgsgBEEBaiEEQY8BIRAMpQILIARBAWohBEGRASEQDKQCCwJAIAQgAkcNAEGnASEQDL0CCyACIARrIAAoAgAiAWohFCAEIAFrQQJqIRACQANAIAQtAAAgAUHtz4CAAGotAABHDaUBIAFBAkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGnASEQDL0CCyAAQQA2AgAgEEEBaiEBQREhEAyiAQsCQCAEIAJHDQBBqAEhEAy8AgsgAiAEayAAKAIAIgFqIRQgBCABa0ECaiEQAkADQCAELQAAIAFBws+AgABqLQAARw2kASABQQJGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBqAEhEAy8AgsgAEEANgIAIBBBAWohAUEsIRAMoQELAkAgBCACRw0AQakBIRAMuwILIAIgBGsgACgCACIBaiEUIAQgAWtBBGohEAJAA0AgBC0AACABQcXPgIAAai0AAEcNowEgAUEERg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQakBIRAMuwILIABBADYCACAQQQFqIQFBKyEQDKABCwJAIAQgAkcNAEGqASEQDLoCCyACIARrIAAoAgAiAWohFCAEIAFrQQJqIRACQANAIAQtAAAgAUHKz4CAAGotAABHDaIBIAFBAkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGqASEQDLoCCyAAQQA2AgAgEEEBaiEBQRQhEAyfAQsCQCAEIAJHDQBBqwEhEAy5AgsCQAJAAkACQCAELQAAQb5/ag4PAAECpAGkAaQBpAGkAaQBpAGkAaQBpAGkAQOkAQsgBEEBaiEEQZMBIRAMogILIARBAWohBEGUASEQDKECCyAEQQFqIQRBlQEhEAygAgsgBEEBaiEEQZYBIRAMnwILAkAgBCACRw0AQawBIRAMuAILIAQtAABBxQBHDZ8BIARBAWohBAzgAQsCQCAEIAJHDQBBrQEhEAy3AgsgAiAEayAAKAIAIgFqIRQgBCABa0ECaiEQAkADQCAELQAAIAFBzc+AgABqLQAARw2fASABQQJGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBrQEhEAy3AgsgAEEANgIAIBBBAWohAUEOIRAMnAELAkAgBCACRw0AQa4BIRAMtgILIAQtAABB0ABHDZ0BIARBAWohAUElIRAMmwELAkAgBCACRw0AQa8BIRAMtQILIAIgBGsgACgCACIBaiEUIAQgAWtBCGohEAJAA0AgBC0AACABQdDPgIAAai0AAEcNnQEgAUEIRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQa8BIRAMtQILIABBADYCACAQQQFqIQFBKiEQDJoBCwJAIAQgAkcNAEGwASEQDLQCCwJAAkAgBC0AAEGrf2oOCwCdAZ0BnQGdAZ0BnQGdAZ0BnQEBnQELIARBAWohBEGaASEQDJsCCyAEQQFqIQRBmwEhEAyaAgsCQCAEIAJHDQBBsQEhEAyzAgsCQAJAIAQtAABBv39qDhQAnAGcAZwBnAGcAZwBnAGcAZwBnAGcAZwBnAGcAZwBnAGcAZwBAZwBCyAEQQFqIQRBmQEhEAyaAgsgBEEBaiEEQZwBIRAMmQILAkAgBCACRw0AQbIBIRAMsgILIAIgBGsgACgCACIBaiEUIAQgAWtBA2ohEAJAA0AgBC0AACABQdnPgIAAai0AAEcNmgEgAUEDRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQbIBIRAMsgILIABBADYCACAQQQFqIQFBISEQDJcBCwJAIAQgAkcNAEGzASEQDLECCyACIARrIAAoAgAiAWohFCAEIAFrQQZqIRACQANAIAQtAAAgAUHdz4CAAGotAABHDZkBIAFBBkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGzASEQDLECCyAAQQA2AgAgEEEBaiEBQRohEAyWAQsCQCAEIAJHDQBBtAEhEAywAgsCQAJAAkAgBC0AAEG7f2oOEQCaAZoBmgGaAZoBmgGaAZoBmgEBmgGaAZoBmgGaAQKaAQsgBEEBaiEEQZ0BIRAMmAILIARBAWohBEGeASEQDJcCCyAEQQFqIQRBnwEhEAyWAgsCQCAEIAJHDQBBtQEhEAyvAgsgAiAEayAAKAIAIgFqIRQgBCABa0EFaiEQAkADQCAELQAAIAFB5M+AgABqLQAARw2XASABQQVGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBtQEhEAyvAgsgAEEANgIAIBBBAWohAUEoIRAMlAELAkAgBCACRw0AQbYBIRAMrgILIAIgBGsgACgCACIBaiEUIAQgAWtBAmohEAJAA0AgBC0AACABQerPgIAAai0AAEcNlgEgAUECRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQbYBIRAMrgILIABBADYCACAQQQFqIQFBByEQDJMBCwJAIAQgAkcNAEG3ASEQDK0CCwJAAkAgBC0AAEG7f2oODgCWAZYBlgGWAZYBlgGWAZYBlgGWAZYBlgEBlgELIARBAWohBEGhASEQDJQCCyAEQQFqIQRBogEhEAyTAgsCQCAEIAJHDQBBuAEhEAysAgsgAiAEayAAKAIAIgFqIRQgBCABa0ECaiEQAkADQCAELQAAIAFB7c+AgABqLQAARw2UASABQQJGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBuAEhEAysAgsgAEEANgIAIBBBAWohAUESIRAMkQELAkAgBCACRw0AQbkBIRAMqwILIAIgBGsgACgCACIBaiEUIAQgAWtBAWohEAJAA0AgBC0AACABQfDPgIAAai0AAEcNkwEgAUEBRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQbkBIRAMqwILIABBADYCACAQQQFqIQFBICEQDJABCwJAIAQgAkcNAEG6ASEQDKoCCyACIARrIAAoAgAiAWohFCAEIAFrQQFqIRACQANAIAQtAAAgAUHyz4CAAGotAABHDZIBIAFBAUYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEG6ASEQDKoCCyAAQQA2AgAgEEEBaiEBQQ8hEAyPAQsCQCAEIAJHDQBBuwEhEAypAgsCQAJAIAQtAABBt39qDgcAkgGSAZIBkgGSAQGSAQsgBEEBaiEEQaUBIRAMkAILIARBAWohBEGmASEQDI8CCwJAIAQgAkcNAEG8ASEQDKgCCyACIARrIAAoAgAiAWohFCAEIAFrQQdqIRACQANAIAQtAAAgAUH0z4CAAGotAABHDZABIAFBB0YNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEG8ASEQDKgCCyAAQQA2AgAgEEEBaiEBQRshEAyNAQsCQCAEIAJHDQBBvQEhEAynAgsCQAJAAkAgBC0AAEG+f2oOEgCRAZEBkQGRAZEBkQGRAZEBkQEBkQGRAZEBkQGRAZEBApEBCyAEQQFqIQRBpAEhEAyPAgsgBEEBaiEEQacBIRAMjgILIARBAWohBEGoASEQDI0CCwJAIAQgAkcNAEG+ASEQDKYCCyAELQAAQc4ARw2NASAEQQFqIQQMzwELAkAgBCACRw0AQb8BIRAMpQILAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgBC0AAEG/f2oOFQABAgOcAQQFBpwBnAGcAQcICQoLnAEMDQ4PnAELIARBAWohAUHoACEQDJoCCyAEQQFqIQFB6QAhEAyZAgsgBEEBaiEBQe4AIRAMmAILIARBAWohAUHyACEQDJcCCyAEQQFqIQFB8wAhEAyWAgsgBEEBaiEBQfYAIRAMlQILIARBAWohAUH3ACEQDJQCCyAEQQFqIQFB+gAhEAyTAgsgBEEBaiEEQYMBIRAMkgILIARBAWohBEGEASEQDJECCyAEQQFqIQRBhQEhEAyQAgsgBEEBaiEEQZIBIRAMjwILIARBAWohBEGYASEQDI4CCyAEQQFqIQRBoAEhEAyNAgsgBEEBaiEEQaMBIRAMjAILIARBAWohBEGqASEQDIsCCwJAIAQgAkYNACAAQZCAgIAANgIIIAAgBDYCBEGrASEQDIsCC0HAASEQDKMCCyAAIAUgAhCqgICAACIBDYsBIAUhAQxcCwJAIAYgAkYNACAGQQFqIQUMjQELQcIBIRAMoQILA0ACQCAQLQAAQXZqDgSMAQAAjwEACyAQQQFqIhAgAkcNAAtBwwEhEAygAgsCQCAHIAJGDQAgAEGRgICAADYCCCAAIAc2AgQgByEBQQEhEAyHAgtBxAEhEAyfAgsCQCAHIAJHDQBBxQEhEAyfAgsCQAJAIActAABBdmoOBAHOAc4BAM4BCyAHQQFqIQYMjQELIAdBAWohBQyJAQsCQCAHIAJHDQBBxgEhEAyeAgsCQAJAIActAABBdmoOFwGPAY8BAY8BjwGPAY8BjwGPAY8BjwGPAY8BjwGPAY8BjwGPAY8BjwGPAQCPAQsgB0EBaiEHC0GwASEQDIQCCwJAIAggAkcNAEHIASEQDJ0CCyAILQAAQSBHDY0BIABBADsBMiAIQQFqIQFBswEhEAyDAgsgASEXAkADQCAXIgcgAkYNASAHLQAAQVBqQf8BcSIQQQpPDcwBAkAgAC8BMiIUQZkzSw0AIAAgFEEKbCIUOwEyIBBB//8DcyAUQf7/A3FJDQAgB0EBaiEXIAAgFCAQaiIQOwEyIBBB//8DcUHoB0kNAQsLQQAhECAAQQA2AhwgAEHBiYCAADYCECAAQQ02AgwgACAHQQFqNgIUDJwCC0HHASEQDJsCCyAAIAggAhCugICAACIQRQ3KASAQQRVHDYwBIABByAE2AhwgACAINgIUIABByZeAgAA2AhAgAEEVNgIMQQAhEAyaAgsCQCAJIAJHDQBBzAEhEAyaAgtBACEUQQEhF0EBIRZBACEQAkACQAJAAkACQAJAAkACQAJAIAktAABBUGoOCpYBlQEAAQIDBAUGCJcBC0ECIRAMBgtBAyEQDAULQQQhEAwEC0EFIRAMAwtBBiEQDAILQQchEAwBC0EIIRALQQAhF0EAIRZBACEUDI4BC0EJIRBBASEUQQAhF0EAIRYMjQELAkAgCiACRw0AQc4BIRAMmQILIAotAABBLkcNjgEgCkEBaiEJDMoBCyALIAJHDY4BQdABIRAMlwILAkAgCyACRg0AIABBjoCAgAA2AgggACALNgIEQbcBIRAM/gELQdEBIRAMlgILAkAgBCACRw0AQdIBIRAMlgILIAIgBGsgACgCACIQaiEUIAQgEGtBBGohCwNAIAQtAAAgEEH8z4CAAGotAABHDY4BIBBBBEYN6QEgEEEBaiEQIARBAWoiBCACRw0ACyAAIBQ2AgBB0gEhEAyVAgsgACAMIAIQrICAgAAiAQ2NASAMIQEMuAELAkAgBCACRw0AQdQBIRAMlAILIAIgBGsgACgCACIQaiEUIAQgEGtBAWohDANAIAQtAAAgEEGB0ICAAGotAABHDY8BIBBBAUYNjgEgEEEBaiEQIARBAWoiBCACRw0ACyAAIBQ2AgBB1AEhEAyTAgsCQCAEIAJHDQBB1gEhEAyTAgsgAiAEayAAKAIAIhBqIRQgBCAQa0ECaiELA0AgBC0AACAQQYPQgIAAai0AAEcNjgEgEEECRg2QASAQQQFqIRAgBEEBaiIEIAJHDQALIAAgFDYCAEHWASEQDJICCwJAIAQgAkcNAEHXASEQDJICCwJAAkAgBC0AAEG7f2oOEACPAY8BjwGPAY8BjwGPAY8BjwGPAY8BjwGPAY8BAY8BCyAEQQFqIQRBuwEhEAz5AQsgBEEBaiEEQbwBIRAM+AELAkAgBCACRw0AQdgBIRAMkQILIAQtAABByABHDYwBIARBAWohBAzEAQsCQCAEIAJGDQAgAEGQgICAADYCCCAAIAQ2AgRBvgEhEAz3AQtB2QEhEAyPAgsCQCAEIAJHDQBB2gEhEAyPAgsgBC0AAEHIAEYNwwEgAEEBOgAoDLkBCyAAQQI6AC8gACAEIAIQpoCAgAAiEA2NAUHCASEQDPQBCyAALQAoQX9qDgK3AbkBuAELA0ACQCAELQAAQXZqDgQAjgGOAQCOAQsgBEEBaiIEIAJHDQALQd0BIRAMiwILIABBADoALyAALQAtQQRxRQ2EAgsgAEEAOgAvIABBAToANCABIQEMjAELIBBBFUYN2gEgAEEANgIcIAAgATYCFCAAQaeOgIAANgIQIABBEjYCDEEAIRAMiAILAkAgACAQIAIQtICAgAAiBA0AIBAhAQyBAgsCQCAEQRVHDQAgAEEDNgIcIAAgEDYCFCAAQbCYgIAANgIQIABBFTYCDEEAIRAMiAILIABBADYCHCAAIBA2AhQgAEGnjoCAADYCECAAQRI2AgxBACEQDIcCCyAQQRVGDdYBIABBADYCHCAAIAE2AhQgAEHajYCAADYCECAAQRQ2AgxBACEQDIYCCyAAKAIEIRcgAEEANgIEIBAgEadqIhYhASAAIBcgECAWIBQbIhAQtYCAgAAiFEUNjQEgAEEHNgIcIAAgEDYCFCAAIBQ2AgxBACEQDIUCCyAAIAAvATBBgAFyOwEwIAEhAQtBKiEQDOoBCyAQQRVGDdEBIABBADYCHCAAIAE2AhQgAEGDjICAADYCECAAQRM2AgxBACEQDIICCyAQQRVGDc8BIABBADYCHCAAIAE2AhQgAEGaj4CAADYCECAAQSI2AgxBACEQDIECCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQt4CAgAAiEA0AIAFBAWohAQyNAQsgAEEMNgIcIAAgEDYCDCAAIAFBAWo2AhRBACEQDIACCyAQQRVGDcwBIABBADYCHCAAIAE2AhQgAEGaj4CAADYCECAAQSI2AgxBACEQDP8BCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQt4CAgAAiEA0AIAFBAWohAQyMAQsgAEENNgIcIAAgEDYCDCAAIAFBAWo2AhRBACEQDP4BCyAQQRVGDckBIABBADYCHCAAIAE2AhQgAEHGjICAADYCECAAQSM2AgxBACEQDP0BCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQuYCAgAAiEA0AIAFBAWohAQyLAQsgAEEONgIcIAAgEDYCDCAAIAFBAWo2AhRBACEQDPwBCyAAQQA2AhwgACABNgIUIABBwJWAgAA2AhAgAEECNgIMQQAhEAz7AQsgEEEVRg3FASAAQQA2AhwgACABNgIUIABBxoyAgAA2AhAgAEEjNgIMQQAhEAz6AQsgAEEQNgIcIAAgATYCFCAAIBA2AgxBACEQDPkBCyAAKAIEIQQgAEEANgIEAkAgACAEIAEQuYCAgAAiBA0AIAFBAWohAQzxAQsgAEERNgIcIAAgBDYCDCAAIAFBAWo2AhRBACEQDPgBCyAQQRVGDcEBIABBADYCHCAAIAE2AhQgAEHGjICAADYCECAAQSM2AgxBACEQDPcBCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQuYCAgAAiEA0AIAFBAWohAQyIAQsgAEETNgIcIAAgEDYCDCAAIAFBAWo2AhRBACEQDPYBCyAAKAIEIQQgAEEANgIEAkAgACAEIAEQuYCAgAAiBA0AIAFBAWohAQztAQsgAEEUNgIcIAAgBDYCDCAAIAFBAWo2AhRBACEQDPUBCyAQQRVGDb0BIABBADYCHCAAIAE2AhQgAEGaj4CAADYCECAAQSI2AgxBACEQDPQBCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQt4CAgAAiEA0AIAFBAWohAQyGAQsgAEEWNgIcIAAgEDYCDCAAIAFBAWo2AhRBACEQDPMBCyAAKAIEIQQgAEEANgIEAkAgACAEIAEQt4CAgAAiBA0AIAFBAWohAQzpAQsgAEEXNgIcIAAgBDYCDCAAIAFBAWo2AhRBACEQDPIBCyAAQQA2AhwgACABNgIUIABBzZOAgAA2AhAgAEEMNgIMQQAhEAzxAQtCASERCyAQQQFqIQECQCAAKQMgIhJC//////////8PVg0AIAAgEkIEhiARhDcDICABIQEMhAELIABBADYCHCAAIAE2AhQgAEGtiYCAADYCECAAQQw2AgxBACEQDO8BCyAAQQA2AhwgACAQNgIUIABBzZOAgAA2AhAgAEEMNgIMQQAhEAzuAQsgACgCBCEXIABBADYCBCAQIBGnaiIWIQEgACAXIBAgFiAUGyIQELWAgIAAIhRFDXMgAEEFNgIcIAAgEDYCFCAAIBQ2AgxBACEQDO0BCyAAQQA2AhwgACAQNgIUIABBqpyAgAA2AhAgAEEPNgIMQQAhEAzsAQsgACAQIAIQtICAgAAiAQ0BIBAhAQtBDiEQDNEBCwJAIAFBFUcNACAAQQI2AhwgACAQNgIUIABBsJiAgAA2AhAgAEEVNgIMQQAhEAzqAQsgAEEANgIcIAAgEDYCFCAAQaeOgIAANgIQIABBEjYCDEEAIRAM6QELIAFBAWohEAJAIAAvATAiAUGAAXFFDQACQCAAIBAgAhC7gICAACIBDQAgECEBDHALIAFBFUcNugEgAEEFNgIcIAAgEDYCFCAAQfmXgIAANgIQIABBFTYCDEEAIRAM6QELAkAgAUGgBHFBoARHDQAgAC0ALUECcQ0AIABBADYCHCAAIBA2AhQgAEGWk4CAADYCECAAQQQ2AgxBACEQDOkBCyAAIBAgAhC9gICAABogECEBAkACQAJAAkACQCAAIBAgAhCzgICAAA4WAgEABAQEBAQEBAQEBAQEBAQEBAQEAwQLIABBAToALgsgACAALwEwQcAAcjsBMCAQIQELQSYhEAzRAQsgAEEjNgIcIAAgEDYCFCAAQaWWgIAANgIQIABBFTYCDEEAIRAM6QELIABBADYCHCAAIBA2AhQgAEHVi4CAADYCECAAQRE2AgxBACEQDOgBCyAALQAtQQFxRQ0BQcMBIRAMzgELAkAgDSACRg0AA0ACQCANLQAAQSBGDQAgDSEBDMQBCyANQQFqIg0gAkcNAAtBJSEQDOcBC0ElIRAM5gELIAAoAgQhBCAAQQA2AgQgACAEIA0Qr4CAgAAiBEUNrQEgAEEmNgIcIAAgBDYCDCAAIA1BAWo2AhRBACEQDOUBCyAQQRVGDasBIABBADYCHCAAIAE2AhQgAEH9jYCAADYCECAAQR02AgxBACEQDOQBCyAAQSc2AhwgACABNgIUIAAgEDYCDEEAIRAM4wELIBAhAUEBIRQCQAJAAkACQAJAAkACQCAALQAsQX5qDgcGBQUDAQIABQsgACAALwEwQQhyOwEwDAMLQQIhFAwBC0EEIRQLIABBAToALCAAIAAvATAgFHI7ATALIBAhAQtBKyEQDMoBCyAAQQA2AhwgACAQNgIUIABBq5KAgAA2AhAgAEELNgIMQQAhEAziAQsgAEEANgIcIAAgATYCFCAAQeGPgIAANgIQIABBCjYCDEEAIRAM4QELIABBADoALCAQIQEMvQELIBAhAUEBIRQCQAJAAkACQAJAIAAtACxBe2oOBAMBAgAFCyAAIAAvATBBCHI7ATAMAwtBAiEUDAELQQQhFAsgAEEBOgAsIAAgAC8BMCAUcjsBMAsgECEBC0EpIRAMxQELIABBADYCHCAAIAE2AhQgAEHwlICAADYCECAAQQM2AgxBACEQDN0BCwJAIA4tAABBDUcNACAAKAIEIQEgAEEANgIEAkAgACABIA4QsYCAgAAiAQ0AIA5BAWohAQx1CyAAQSw2AhwgACABNgIMIAAgDkEBajYCFEEAIRAM3QELIAAtAC1BAXFFDQFBxAEhEAzDAQsCQCAOIAJHDQBBLSEQDNwBCwJAAkADQAJAIA4tAABBdmoOBAIAAAMACyAOQQFqIg4gAkcNAAtBLSEQDN0BCyAAKAIEIQEgAEEANgIEAkAgACABIA4QsYCAgAAiAQ0AIA4hAQx0CyAAQSw2AhwgACAONgIUIAAgATYCDEEAIRAM3AELIAAoAgQhASAAQQA2AgQCQCAAIAEgDhCxgICAACIBDQAgDkEBaiEBDHMLIABBLDYCHCAAIAE2AgwgACAOQQFqNgIUQQAhEAzbAQsgACgCBCEEIABBADYCBCAAIAQgDhCxgICAACIEDaABIA4hAQzOAQsgEEEsRw0BIAFBAWohEEEBIQECQAJAAkACQAJAIAAtACxBe2oOBAMBAgQACyAQIQEMBAtBAiEBDAELQQQhAQsgAEEBOgAsIAAgAC8BMCABcjsBMCAQIQEMAQsgACAALwEwQQhyOwEwIBAhAQtBOSEQDL8BCyAAQQA6ACwgASEBC0E0IRAMvQELIAAgAC8BMEEgcjsBMCABIQEMAgsgACgCBCEEIABBADYCBAJAIAAgBCABELGAgIAAIgQNACABIQEMxwELIABBNzYCHCAAIAE2AhQgACAENgIMQQAhEAzUAQsgAEEIOgAsIAEhAQtBMCEQDLkBCwJAIAAtAChBAUYNACABIQEMBAsgAC0ALUEIcUUNkwEgASEBDAMLIAAtADBBIHENlAFBxQEhEAy3AQsCQCAPIAJGDQACQANAAkAgDy0AAEFQaiIBQf8BcUEKSQ0AIA8hAUE1IRAMugELIAApAyAiEUKZs+bMmbPmzBlWDQEgACARQgp+IhE3AyAgESABrUL/AYMiEkJ/hVYNASAAIBEgEnw3AyAgD0EBaiIPIAJHDQALQTkhEAzRAQsgACgCBCECIABBADYCBCAAIAIgD0EBaiIEELGAgIAAIgINlQEgBCEBDMMBC0E5IRAMzwELAkAgAC8BMCIBQQhxRQ0AIAAtAChBAUcNACAALQAtQQhxRQ2QAQsgACABQff7A3FBgARyOwEwIA8hAQtBNyEQDLQBCyAAIAAvATBBEHI7ATAMqwELIBBBFUYNiwEgAEEANgIcIAAgATYCFCAAQfCOgIAANgIQIABBHDYCDEEAIRAMywELIABBwwA2AhwgACABNgIMIAAgDUEBajYCFEEAIRAMygELAkAgAS0AAEE6Rw0AIAAoAgQhECAAQQA2AgQCQCAAIBAgARCvgICAACIQDQAgAUEBaiEBDGMLIABBwwA2AhwgACAQNgIMIAAgAUEBajYCFEEAIRAMygELIABBADYCHCAAIAE2AhQgAEGxkYCAADYCECAAQQo2AgxBACEQDMkBCyAAQQA2AhwgACABNgIUIABBoJmAgAA2AhAgAEEeNgIMQQAhEAzIAQsgAEEANgIACyAAQYASOwEqIAAgF0EBaiIBIAIQqICAgAAiEA0BIAEhAQtBxwAhEAysAQsgEEEVRw2DASAAQdEANgIcIAAgATYCFCAAQeOXgIAANgIQIABBFTYCDEEAIRAMxAELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDF4LIABB0gA2AhwgACABNgIUIAAgEDYCDEEAIRAMwwELIABBADYCHCAAIBQ2AhQgAEHBqICAADYCECAAQQc2AgwgAEEANgIAQQAhEAzCAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMXQsgAEHTADYCHCAAIAE2AhQgACAQNgIMQQAhEAzBAQtBACEQIABBADYCHCAAIAE2AhQgAEGAkYCAADYCECAAQQk2AgwMwAELIBBBFUYNfSAAQQA2AhwgACABNgIUIABBlI2AgAA2AhAgAEEhNgIMQQAhEAy/AQtBASEWQQAhF0EAIRRBASEQCyAAIBA6ACsgAUEBaiEBAkACQCAALQAtQRBxDQACQAJAAkAgAC0AKg4DAQACBAsgFkUNAwwCCyAUDQEMAgsgF0UNAQsgACgCBCEQIABBADYCBAJAIAAgECABEK2AgIAAIhANACABIQEMXAsgAEHYADYCHCAAIAE2AhQgACAQNgIMQQAhEAy+AQsgACgCBCEEIABBADYCBAJAIAAgBCABEK2AgIAAIgQNACABIQEMrQELIABB2QA2AhwgACABNgIUIAAgBDYCDEEAIRAMvQELIAAoAgQhBCAAQQA2AgQCQCAAIAQgARCtgICAACIEDQAgASEBDKsBCyAAQdoANgIcIAAgATYCFCAAIAQ2AgxBACEQDLwBCyAAKAIEIQQgAEEANgIEAkAgACAEIAEQrYCAgAAiBA0AIAEhAQypAQsgAEHcADYCHCAAIAE2AhQgACAENgIMQQAhEAy7AQsCQCABLQAAQVBqIhBB/wFxQQpPDQAgACAQOgAqIAFBAWohAUHPACEQDKIBCyAAKAIEIQQgAEEANgIEAkAgACAEIAEQrYCAgAAiBA0AIAEhAQynAQsgAEHeADYCHCAAIAE2AhQgACAENgIMQQAhEAy6AQsgAEEANgIAIBdBAWohAQJAIAAtAClBI08NACABIQEMWQsgAEEANgIcIAAgATYCFCAAQdOJgIAANgIQIABBCDYCDEEAIRAMuQELIABBADYCAAtBACEQIABBADYCHCAAIAE2AhQgAEGQs4CAADYCECAAQQg2AgwMtwELIABBADYCACAXQQFqIQECQCAALQApQSFHDQAgASEBDFYLIABBADYCHCAAIAE2AhQgAEGbioCAADYCECAAQQg2AgxBACEQDLYBCyAAQQA2AgAgF0EBaiEBAkAgAC0AKSIQQV1qQQtPDQAgASEBDFULAkAgEEEGSw0AQQEgEHRBygBxRQ0AIAEhAQxVC0EAIRAgAEEANgIcIAAgATYCFCAAQfeJgIAANgIQIABBCDYCDAy1AQsgEEEVRg1xIABBADYCHCAAIAE2AhQgAEG5jYCAADYCECAAQRo2AgxBACEQDLQBCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxUCyAAQeUANgIcIAAgATYCFCAAIBA2AgxBACEQDLMBCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxNCyAAQdIANgIcIAAgATYCFCAAIBA2AgxBACEQDLIBCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxNCyAAQdMANgIcIAAgATYCFCAAIBA2AgxBACEQDLEBCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxRCyAAQeUANgIcIAAgATYCFCAAIBA2AgxBACEQDLABCyAAQQA2AhwgACABNgIUIABBxoqAgAA2AhAgAEEHNgIMQQAhEAyvAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMSQsgAEHSADYCHCAAIAE2AhQgACAQNgIMQQAhEAyuAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMSQsgAEHTADYCHCAAIAE2AhQgACAQNgIMQQAhEAytAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMTQsgAEHlADYCHCAAIAE2AhQgACAQNgIMQQAhEAysAQsgAEEANgIcIAAgATYCFCAAQdyIgIAANgIQIABBBzYCDEEAIRAMqwELIBBBP0cNASABQQFqIQELQQUhEAyQAQtBACEQIABBADYCHCAAIAE2AhQgAEH9koCAADYCECAAQQc2AgwMqAELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDEILIABB0gA2AhwgACABNgIUIAAgEDYCDEEAIRAMpwELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDEILIABB0wA2AhwgACABNgIUIAAgEDYCDEEAIRAMpgELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDEYLIABB5QA2AhwgACABNgIUIAAgEDYCDEEAIRAMpQELIAAoAgQhASAAQQA2AgQCQCAAIAEgFBCngICAACIBDQAgFCEBDD8LIABB0gA2AhwgACAUNgIUIAAgATYCDEEAIRAMpAELIAAoAgQhASAAQQA2AgQCQCAAIAEgFBCngICAACIBDQAgFCEBDD8LIABB0wA2AhwgACAUNgIUIAAgATYCDEEAIRAMowELIAAoAgQhASAAQQA2AgQCQCAAIAEgFBCngICAACIBDQAgFCEBDEMLIABB5QA2AhwgACAUNgIUIAAgATYCDEEAIRAMogELIABBADYCHCAAIBQ2AhQgAEHDj4CAADYCECAAQQc2AgxBACEQDKEBCyAAQQA2AhwgACABNgIUIABBw4+AgAA2AhAgAEEHNgIMQQAhEAygAQtBACEQIABBADYCHCAAIBQ2AhQgAEGMnICAADYCECAAQQc2AgwMnwELIABBADYCHCAAIBQ2AhQgAEGMnICAADYCECAAQQc2AgxBACEQDJ4BCyAAQQA2AhwgACAUNgIUIABB/pGAgAA2AhAgAEEHNgIMQQAhEAydAQsgAEEANgIcIAAgATYCFCAAQY6bgIAANgIQIABBBjYCDEEAIRAMnAELIBBBFUYNVyAAQQA2AhwgACABNgIUIABBzI6AgAA2AhAgAEEgNgIMQQAhEAybAQsgAEEANgIAIBBBAWohAUEkIRALIAAgEDoAKSAAKAIEIRAgAEEANgIEIAAgECABEKuAgIAAIhANVCABIQEMPgsgAEEANgIAC0EAIRAgAEEANgIcIAAgBDYCFCAAQfGbgIAANgIQIABBBjYCDAyXAQsgAUEVRg1QIABBADYCHCAAIAU2AhQgAEHwjICAADYCECAAQRs2AgxBACEQDJYBCyAAKAIEIQUgAEEANgIEIAAgBSAQEKmAgIAAIgUNASAQQQFqIQULQa0BIRAMewsgAEHBATYCHCAAIAU2AgwgACAQQQFqNgIUQQAhEAyTAQsgACgCBCEGIABBADYCBCAAIAYgEBCpgICAACIGDQEgEEEBaiEGC0GuASEQDHgLIABBwgE2AhwgACAGNgIMIAAgEEEBajYCFEEAIRAMkAELIABBADYCHCAAIAc2AhQgAEGXi4CAADYCECAAQQ02AgxBACEQDI8BCyAAQQA2AhwgACAINgIUIABB45CAgAA2AhAgAEEJNgIMQQAhEAyOAQsgAEEANgIcIAAgCDYCFCAAQZSNgIAANgIQIABBITYCDEEAIRAMjQELQQEhFkEAIRdBACEUQQEhEAsgACAQOgArIAlBAWohCAJAAkAgAC0ALUEQcQ0AAkACQAJAIAAtACoOAwEAAgQLIBZFDQMMAgsgFA0BDAILIBdFDQELIAAoAgQhECAAQQA2AgQgACAQIAgQrYCAgAAiEEUNPSAAQckBNgIcIAAgCDYCFCAAIBA2AgxBACEQDIwBCyAAKAIEIQQgAEEANgIEIAAgBCAIEK2AgIAAIgRFDXYgAEHKATYCHCAAIAg2AhQgACAENgIMQQAhEAyLAQsgACgCBCEEIABBADYCBCAAIAQgCRCtgICAACIERQ10IABBywE2AhwgACAJNgIUIAAgBDYCDEEAIRAMigELIAAoAgQhBCAAQQA2AgQgACAEIAoQrYCAgAAiBEUNciAAQc0BNgIcIAAgCjYCFCAAIAQ2AgxBACEQDIkBCwJAIAstAABBUGoiEEH/AXFBCk8NACAAIBA6ACogC0EBaiEKQbYBIRAMcAsgACgCBCEEIABBADYCBCAAIAQgCxCtgICAACIERQ1wIABBzwE2AhwgACALNgIUIAAgBDYCDEEAIRAMiAELIABBADYCHCAAIAQ2AhQgAEGQs4CAADYCECAAQQg2AgwgAEEANgIAQQAhEAyHAQsgAUEVRg0/IABBADYCHCAAIAw2AhQgAEHMjoCAADYCECAAQSA2AgxBACEQDIYBCyAAQYEEOwEoIAAoAgQhECAAQgA3AwAgACAQIAxBAWoiDBCrgICAACIQRQ04IABB0wE2AhwgACAMNgIUIAAgEDYCDEEAIRAMhQELIABBADYCAAtBACEQIABBADYCHCAAIAQ2AhQgAEHYm4CAADYCECAAQQg2AgwMgwELIAAoAgQhECAAQgA3AwAgACAQIAtBAWoiCxCrgICAACIQDQFBxgEhEAxpCyAAQQI6ACgMVQsgAEHVATYCHCAAIAs2AhQgACAQNgIMQQAhEAyAAQsgEEEVRg03IABBADYCHCAAIAQ2AhQgAEGkjICAADYCECAAQRA2AgxBACEQDH8LIAAtADRBAUcNNCAAIAQgAhC8gICAACIQRQ00IBBBFUcNNSAAQdwBNgIcIAAgBDYCFCAAQdWWgIAANgIQIABBFTYCDEEAIRAMfgtBACEQIABBADYCHCAAQa+LgIAANgIQIABBAjYCDCAAIBRBAWo2AhQMfQtBACEQDGMLQQIhEAxiC0ENIRAMYQtBDyEQDGALQSUhEAxfC0ETIRAMXgtBFSEQDF0LQRYhEAxcC0EXIRAMWwtBGCEQDFoLQRkhEAxZC0EaIRAMWAtBGyEQDFcLQRwhEAxWC0EdIRAMVQtBHyEQDFQLQSEhEAxTC0EjIRAMUgtBxgAhEAxRC0EuIRAMUAtBLyEQDE8LQTshEAxOC0E9IRAMTQtByAAhEAxMC0HJACEQDEsLQcsAIRAMSgtBzAAhEAxJC0HOACEQDEgLQdEAIRAMRwtB1QAhEAxGC0HYACEQDEULQdkAIRAMRAtB2wAhEAxDC0HkACEQDEILQeUAIRAMQQtB8QAhEAxAC0H0ACEQDD8LQY0BIRAMPgtBlwEhEAw9C0GpASEQDDwLQawBIRAMOwtBwAEhEAw6C0G5ASEQDDkLQa8BIRAMOAtBsQEhEAw3C0GyASEQDDYLQbQBIRAMNQtBtQEhEAw0C0G6ASEQDDMLQb0BIRAMMgtBvwEhEAwxC0HBASEQDDALIABBADYCHCAAIAQ2AhQgAEHpi4CAADYCECAAQR82AgxBACEQDEgLIABB2wE2AhwgACAENgIUIABB+paAgAA2AhAgAEEVNgIMQQAhEAxHCyAAQfgANgIcIAAgDDYCFCAAQcqYgIAANgIQIABBFTYCDEEAIRAMRgsgAEHRADYCHCAAIAU2AhQgAEGwl4CAADYCECAAQRU2AgxBACEQDEULIABB+QA2AhwgACABNgIUIAAgEDYCDEEAIRAMRAsgAEH4ADYCHCAAIAE2AhQgAEHKmICAADYCECAAQRU2AgxBACEQDEMLIABB5AA2AhwgACABNgIUIABB45eAgAA2AhAgAEEVNgIMQQAhEAxCCyAAQdcANgIcIAAgATYCFCAAQcmXgIAANgIQIABBFTYCDEEAIRAMQQsgAEEANgIcIAAgATYCFCAAQbmNgIAANgIQIABBGjYCDEEAIRAMQAsgAEHCADYCHCAAIAE2AhQgAEHjmICAADYCECAAQRU2AgxBACEQDD8LIABBADYCBCAAIA8gDxCxgICAACIERQ0BIABBOjYCHCAAIAQ2AgwgACAPQQFqNgIUQQAhEAw+CyAAKAIEIQQgAEEANgIEAkAgACAEIAEQsYCAgAAiBEUNACAAQTs2AhwgACAENgIMIAAgAUEBajYCFEEAIRAMPgsgAUEBaiEBDC0LIA9BAWohAQwtCyAAQQA2AhwgACAPNgIUIABB5JKAgAA2AhAgAEEENgIMQQAhEAw7CyAAQTY2AhwgACAENgIUIAAgAjYCDEEAIRAMOgsgAEEuNgIcIAAgDjYCFCAAIAQ2AgxBACEQDDkLIABB0AA2AhwgACABNgIUIABBkZiAgAA2AhAgAEEVNgIMQQAhEAw4CyANQQFqIQEMLAsgAEEVNgIcIAAgATYCFCAAQYKZgIAANgIQIABBFTYCDEEAIRAMNgsgAEEbNgIcIAAgATYCFCAAQZGXgIAANgIQIABBFTYCDEEAIRAMNQsgAEEPNgIcIAAgATYCFCAAQZGXgIAANgIQIABBFTYCDEEAIRAMNAsgAEELNgIcIAAgATYCFCAAQZGXgIAANgIQIABBFTYCDEEAIRAMMwsgAEEaNgIcIAAgATYCFCAAQYKZgIAANgIQIABBFTYCDEEAIRAMMgsgAEELNgIcIAAgATYCFCAAQYKZgIAANgIQIABBFTYCDEEAIRAMMQsgAEEKNgIcIAAgATYCFCAAQeSWgIAANgIQIABBFTYCDEEAIRAMMAsgAEEeNgIcIAAgATYCFCAAQfmXgIAANgIQIABBFTYCDEEAIRAMLwsgAEEANgIcIAAgEDYCFCAAQdqNgIAANgIQIABBFDYCDEEAIRAMLgsgAEEENgIcIAAgATYCFCAAQbCYgIAANgIQIABBFTYCDEEAIRAMLQsgAEEANgIAIAtBAWohCwtBuAEhEAwSCyAAQQA2AgAgEEEBaiEBQfUAIRAMEQsgASEBAkAgAC0AKUEFRw0AQeMAIRAMEQtB4gAhEAwQC0EAIRAgAEEANgIcIABB5JGAgAA2AhAgAEEHNgIMIAAgFEEBajYCFAwoCyAAQQA2AgAgF0EBaiEBQcAAIRAMDgtBASEBCyAAIAE6ACwgAEEANgIAIBdBAWohAQtBKCEQDAsLIAEhAQtBOCEQDAkLAkAgASIPIAJGDQADQAJAIA8tAABBgL6AgABqLQAAIgFBAUYNACABQQJHDQMgD0EBaiEBDAQLIA9BAWoiDyACRw0AC0E+IRAMIgtBPiEQDCELIABBADoALCAPIQEMAQtBCyEQDAYLQTohEAwFCyABQQFqIQFBLSEQDAQLIAAgAToALCAAQQA2AgAgFkEBaiEBQQwhEAwDCyAAQQA2AgAgF0EBaiEBQQohEAwCCyAAQQA2AgALIABBADoALCANIQFBCSEQDAALC0EAIRAgAEEANgIcIAAgCzYCFCAAQc2QgIAANgIQIABBCTYCDAwXC0EAIRAgAEEANgIcIAAgCjYCFCAAQemKgIAANgIQIABBCTYCDAwWC0EAIRAgAEEANgIcIAAgCTYCFCAAQbeQgIAANgIQIABBCTYCDAwVC0EAIRAgAEEANgIcIAAgCDYCFCAAQZyRgIAANgIQIABBCTYCDAwUC0EAIRAgAEEANgIcIAAgATYCFCAAQc2QgIAANgIQIABBCTYCDAwTC0EAIRAgAEEANgIcIAAgATYCFCAAQemKgIAANgIQIABBCTYCDAwSC0EAIRAgAEEANgIcIAAgATYCFCAAQbeQgIAANgIQIABBCTYCDAwRC0EAIRAgAEEANgIcIAAgATYCFCAAQZyRgIAANgIQIABBCTYCDAwQC0EAIRAgAEEANgIcIAAgATYCFCAAQZeVgIAANgIQIABBDzYCDAwPC0EAIRAgAEEANgIcIAAgATYCFCAAQZeVgIAANgIQIABBDzYCDAwOC0EAIRAgAEEANgIcIAAgATYCFCAAQcCSgIAANgIQIABBCzYCDAwNC0EAIRAgAEEANgIcIAAgATYCFCAAQZWJgIAANgIQIABBCzYCDAwMC0EAIRAgAEEANgIcIAAgATYCFCAAQeGPgIAANgIQIABBCjYCDAwLC0EAIRAgAEEANgIcIAAgATYCFCAAQfuPgIAANgIQIABBCjYCDAwKC0EAIRAgAEEANgIcIAAgATYCFCAAQfGZgIAANgIQIABBAjYCDAwJC0EAIRAgAEEANgIcIAAgATYCFCAAQcSUgIAANgIQIABBAjYCDAwIC0EAIRAgAEEANgIcIAAgATYCFCAAQfKVgIAANgIQIABBAjYCDAwHCyAAQQI2AhwgACABNgIUIABBnJqAgAA2AhAgAEEWNgIMQQAhEAwGC0EBIRAMBQtB1AAhECABIgQgAkYNBCADQQhqIAAgBCACQdjCgIAAQQoQxYCAgAAgAygCDCEEIAMoAggOAwEEAgALEMqAgIAAAAsgAEEANgIcIABBtZqAgAA2AhAgAEEXNgIMIAAgBEEBajYCFEEAIRAMAgsgAEEANgIcIAAgBDYCFCAAQcqagIAANgIQIABBCTYCDEEAIRAMAQsCQCABIgQgAkcNAEEiIRAMAQsgAEGJgICAADYCCCAAIAQ2AgRBISEQCyADQRBqJICAgIAAIBALrwEBAn8gASgCACEGAkACQCACIANGDQAgBCAGaiEEIAYgA2ogAmshByACIAZBf3MgBWoiBmohBQNAAkAgAi0AACAELQAARg0AQQIhBAwDCwJAIAYNAEEAIQQgBSECDAMLIAZBf2ohBiAEQQFqIQQgAkEBaiICIANHDQALIAchBiADIQILIABBATYCACABIAY2AgAgACACNgIEDwsgAUEANgIAIAAgBDYCACAAIAI2AgQLCgAgABDHgICAAAvyNgELfyOAgICAAEEQayIBJICAgIAAAkBBACgCoNCAgAANAEEAEMuAgIAAQYDUhIAAayICQdkASQ0AQQAhAwJAQQAoAuDTgIAAIgQNAEEAQn83AuzTgIAAQQBCgICEgICAwAA3AuTTgIAAQQAgAUEIakFwcUHYqtWqBXMiBDYC4NOAgABBAEEANgL004CAAEEAQQA2AsTTgIAAC0EAIAI2AszTgIAAQQBBgNSEgAA2AsjTgIAAQQBBgNSEgAA2ApjQgIAAQQAgBDYCrNCAgABBAEF/NgKo0ICAAANAIANBxNCAgABqIANBuNCAgABqIgQ2AgAgBCADQbDQgIAAaiIFNgIAIANBvNCAgABqIAU2AgAgA0HM0ICAAGogA0HA0ICAAGoiBTYCACAFIAQ2AgAgA0HU0ICAAGogA0HI0ICAAGoiBDYCACAEIAU2AgAgA0HQ0ICAAGogBDYCACADQSBqIgNBgAJHDQALQYDUhIAAQXhBgNSEgABrQQ9xQQBBgNSEgABBCGpBD3EbIgNqIgRBBGogAkFIaiIFIANrIgNBAXI2AgBBAEEAKALw04CAADYCpNCAgABBACADNgKU0ICAAEEAIAQ2AqDQgIAAQYDUhIAAIAVqQTg2AgQLAkACQAJAAkACQAJAAkACQAJAAkACQAJAIABB7AFLDQACQEEAKAKI0ICAACIGQRAgAEETakFwcSAAQQtJGyICQQN2IgR2IgNBA3FFDQACQAJAIANBAXEgBHJBAXMiBUEDdCIEQbDQgIAAaiIDIARBuNCAgABqKAIAIgQoAggiAkcNAEEAIAZBfiAFd3E2AojQgIAADAELIAMgAjYCCCACIAM2AgwLIARBCGohAyAEIAVBA3QiBUEDcjYCBCAEIAVqIgQgBCgCBEEBcjYCBAwMCyACQQAoApDQgIAAIgdNDQECQCADRQ0AAkACQCADIAR0QQIgBHQiA0EAIANrcnEiA0EAIANrcUF/aiIDIANBDHZBEHEiA3YiBEEFdkEIcSIFIANyIAQgBXYiA0ECdkEEcSIEciADIAR2IgNBAXZBAnEiBHIgAyAEdiIDQQF2QQFxIgRyIAMgBHZqIgRBA3QiA0Gw0ICAAGoiBSADQbjQgIAAaigCACIDKAIIIgBHDQBBACAGQX4gBHdxIgY2AojQgIAADAELIAUgADYCCCAAIAU2AgwLIAMgAkEDcjYCBCADIARBA3QiBGogBCACayIFNgIAIAMgAmoiACAFQQFyNgIEAkAgB0UNACAHQXhxQbDQgIAAaiECQQAoApzQgIAAIQQCQAJAIAZBASAHQQN2dCIIcQ0AQQAgBiAIcjYCiNCAgAAgAiEIDAELIAIoAgghCAsgCCAENgIMIAIgBDYCCCAEIAI2AgwgBCAINgIICyADQQhqIQNBACAANgKc0ICAAEEAIAU2ApDQgIAADAwLQQAoAozQgIAAIglFDQEgCUEAIAlrcUF/aiIDIANBDHZBEHEiA3YiBEEFdkEIcSIFIANyIAQgBXYiA0ECdkEEcSIEciADIAR2IgNBAXZBAnEiBHIgAyAEdiIDQQF2QQFxIgRyIAMgBHZqQQJ0QbjSgIAAaigCACIAKAIEQXhxIAJrIQQgACEFAkADQAJAIAUoAhAiAw0AIAVBFGooAgAiA0UNAgsgAygCBEF4cSACayIFIAQgBSAESSIFGyEEIAMgACAFGyEAIAMhBQwACwsgACgCGCEKAkAgACgCDCIIIABGDQAgACgCCCIDQQAoApjQgIAASRogCCADNgIIIAMgCDYCDAwLCwJAIABBFGoiBSgCACIDDQAgACgCECIDRQ0DIABBEGohBQsDQCAFIQsgAyIIQRRqIgUoAgAiAw0AIAhBEGohBSAIKAIQIgMNAAsgC0EANgIADAoLQX8hAiAAQb9/Sw0AIABBE2oiA0FwcSECQQAoAozQgIAAIgdFDQBBACELAkAgAkGAAkkNAEEfIQsgAkH///8HSw0AIANBCHYiAyADQYD+P2pBEHZBCHEiA3QiBCAEQYDgH2pBEHZBBHEiBHQiBSAFQYCAD2pBEHZBAnEiBXRBD3YgAyAEciAFcmsiA0EBdCACIANBFWp2QQFxckEcaiELC0EAIAJrIQQCQAJAAkACQCALQQJ0QbjSgIAAaigCACIFDQBBACEDQQAhCAwBC0EAIQMgAkEAQRkgC0EBdmsgC0EfRht0IQBBACEIA0ACQCAFKAIEQXhxIAJrIgYgBE8NACAGIQQgBSEIIAYNAEEAIQQgBSEIIAUhAwwDCyADIAVBFGooAgAiBiAGIAUgAEEddkEEcWpBEGooAgAiBUYbIAMgBhshAyAAQQF0IQAgBQ0ACwsCQCADIAhyDQBBACEIQQIgC3QiA0EAIANrciAHcSIDRQ0DIANBACADa3FBf2oiAyADQQx2QRBxIgN2IgVBBXZBCHEiACADciAFIAB2IgNBAnZBBHEiBXIgAyAFdiIDQQF2QQJxIgVyIAMgBXYiA0EBdkEBcSIFciADIAV2akECdEG40oCAAGooAgAhAwsgA0UNAQsDQCADKAIEQXhxIAJrIgYgBEkhAAJAIAMoAhAiBQ0AIANBFGooAgAhBQsgBiAEIAAbIQQgAyAIIAAbIQggBSEDIAUNAAsLIAhFDQAgBEEAKAKQ0ICAACACa08NACAIKAIYIQsCQCAIKAIMIgAgCEYNACAIKAIIIgNBACgCmNCAgABJGiAAIAM2AgggAyAANgIMDAkLAkAgCEEUaiIFKAIAIgMNACAIKAIQIgNFDQMgCEEQaiEFCwNAIAUhBiADIgBBFGoiBSgCACIDDQAgAEEQaiEFIAAoAhAiAw0ACyAGQQA2AgAMCAsCQEEAKAKQ0ICAACIDIAJJDQBBACgCnNCAgAAhBAJAAkAgAyACayIFQRBJDQAgBCACaiIAIAVBAXI2AgRBACAFNgKQ0ICAAEEAIAA2ApzQgIAAIAQgA2ogBTYCACAEIAJBA3I2AgQMAQsgBCADQQNyNgIEIAQgA2oiAyADKAIEQQFyNgIEQQBBADYCnNCAgABBAEEANgKQ0ICAAAsgBEEIaiEDDAoLAkBBACgClNCAgAAiACACTQ0AQQAoAqDQgIAAIgMgAmoiBCAAIAJrIgVBAXI2AgRBACAFNgKU0ICAAEEAIAQ2AqDQgIAAIAMgAkEDcjYCBCADQQhqIQMMCgsCQAJAQQAoAuDTgIAARQ0AQQAoAujTgIAAIQQMAQtBAEJ/NwLs04CAAEEAQoCAhICAgMAANwLk04CAAEEAIAFBDGpBcHFB2KrVqgVzNgLg04CAAEEAQQA2AvTTgIAAQQBBADYCxNOAgABBgIAEIQQLQQAhAwJAIAQgAkHHAGoiB2oiBkEAIARrIgtxIgggAksNAEEAQTA2AvjTgIAADAoLAkBBACgCwNOAgAAiA0UNAAJAQQAoArjTgIAAIgQgCGoiBSAETQ0AIAUgA00NAQtBACEDQQBBMDYC+NOAgAAMCgtBAC0AxNOAgABBBHENBAJAAkACQEEAKAKg0ICAACIERQ0AQcjTgIAAIQMDQAJAIAMoAgAiBSAESw0AIAUgAygCBGogBEsNAwsgAygCCCIDDQALC0EAEMuAgIAAIgBBf0YNBSAIIQYCQEEAKALk04CAACIDQX9qIgQgAHFFDQAgCCAAayAEIABqQQAgA2txaiEGCyAGIAJNDQUgBkH+////B0sNBQJAQQAoAsDTgIAAIgNFDQBBACgCuNOAgAAiBCAGaiIFIARNDQYgBSADSw0GCyAGEMuAgIAAIgMgAEcNAQwHCyAGIABrIAtxIgZB/v///wdLDQQgBhDLgICAACIAIAMoAgAgAygCBGpGDQMgACEDCwJAIANBf0YNACACQcgAaiAGTQ0AAkAgByAGa0EAKALo04CAACIEakEAIARrcSIEQf7///8HTQ0AIAMhAAwHCwJAIAQQy4CAgABBf0YNACAEIAZqIQYgAyEADAcLQQAgBmsQy4CAgAAaDAQLIAMhACADQX9HDQUMAwtBACEIDAcLQQAhAAwFCyAAQX9HDQILQQBBACgCxNOAgABBBHI2AsTTgIAACyAIQf7///8HSw0BIAgQy4CAgAAhAEEAEMuAgIAAIQMgAEF/Rg0BIANBf0YNASAAIANPDQEgAyAAayIGIAJBOGpNDQELQQBBACgCuNOAgAAgBmoiAzYCuNOAgAACQCADQQAoArzTgIAATQ0AQQAgAzYCvNOAgAALAkACQAJAAkBBACgCoNCAgAAiBEUNAEHI04CAACEDA0AgACADKAIAIgUgAygCBCIIakYNAiADKAIIIgMNAAwDCwsCQAJAQQAoApjQgIAAIgNFDQAgACADTw0BC0EAIAA2ApjQgIAAC0EAIQNBACAGNgLM04CAAEEAIAA2AsjTgIAAQQBBfzYCqNCAgABBAEEAKALg04CAADYCrNCAgABBAEEANgLU04CAAANAIANBxNCAgABqIANBuNCAgABqIgQ2AgAgBCADQbDQgIAAaiIFNgIAIANBvNCAgABqIAU2AgAgA0HM0ICAAGogA0HA0ICAAGoiBTYCACAFIAQ2AgAgA0HU0ICAAGogA0HI0ICAAGoiBDYCACAEIAU2AgAgA0HQ0ICAAGogBDYCACADQSBqIgNBgAJHDQALIABBeCAAa0EPcUEAIABBCGpBD3EbIgNqIgQgBkFIaiIFIANrIgNBAXI2AgRBAEEAKALw04CAADYCpNCAgABBACADNgKU0ICAAEEAIAQ2AqDQgIAAIAAgBWpBODYCBAwCCyADLQAMQQhxDQAgBCAFSQ0AIAQgAE8NACAEQXggBGtBD3FBACAEQQhqQQ9xGyIFaiIAQQAoApTQgIAAIAZqIgsgBWsiBUEBcjYCBCADIAggBmo2AgRBAEEAKALw04CAADYCpNCAgABBACAFNgKU0ICAAEEAIAA2AqDQgIAAIAQgC2pBODYCBAwBCwJAIABBACgCmNCAgAAiCE8NAEEAIAA2ApjQgIAAIAAhCAsgACAGaiEFQcjTgIAAIQMCQAJAAkACQAJAAkACQANAIAMoAgAgBUYNASADKAIIIgMNAAwCCwsgAy0ADEEIcUUNAQtByNOAgAAhAwNAAkAgAygCACIFIARLDQAgBSADKAIEaiIFIARLDQMLIAMoAgghAwwACwsgAyAANgIAIAMgAygCBCAGajYCBCAAQXggAGtBD3FBACAAQQhqQQ9xG2oiCyACQQNyNgIEIAVBeCAFa0EPcUEAIAVBCGpBD3EbaiIGIAsgAmoiAmshAwJAIAYgBEcNAEEAIAI2AqDQgIAAQQBBACgClNCAgAAgA2oiAzYClNCAgAAgAiADQQFyNgIEDAMLAkAgBkEAKAKc0ICAAEcNAEEAIAI2ApzQgIAAQQBBACgCkNCAgAAgA2oiAzYCkNCAgAAgAiADQQFyNgIEIAIgA2ogAzYCAAwDCwJAIAYoAgQiBEEDcUEBRw0AIARBeHEhBwJAAkAgBEH/AUsNACAGKAIIIgUgBEEDdiIIQQN0QbDQgIAAaiIARhoCQCAGKAIMIgQgBUcNAEEAQQAoAojQgIAAQX4gCHdxNgKI0ICAAAwCCyAEIABGGiAEIAU2AgggBSAENgIMDAELIAYoAhghCQJAAkAgBigCDCIAIAZGDQAgBigCCCIEIAhJGiAAIAQ2AgggBCAANgIMDAELAkAgBkEUaiIEKAIAIgUNACAGQRBqIgQoAgAiBQ0AQQAhAAwBCwNAIAQhCCAFIgBBFGoiBCgCACIFDQAgAEEQaiEEIAAoAhAiBQ0ACyAIQQA2AgALIAlFDQACQAJAIAYgBigCHCIFQQJ0QbjSgIAAaiIEKAIARw0AIAQgADYCACAADQFBAEEAKAKM0ICAAEF+IAV3cTYCjNCAgAAMAgsgCUEQQRQgCSgCECAGRhtqIAA2AgAgAEUNAQsgACAJNgIYAkAgBigCECIERQ0AIAAgBDYCECAEIAA2AhgLIAYoAhQiBEUNACAAQRRqIAQ2AgAgBCAANgIYCyAHIANqIQMgBiAHaiIGKAIEIQQLIAYgBEF+cTYCBCACIANqIAM2AgAgAiADQQFyNgIEAkAgA0H/AUsNACADQXhxQbDQgIAAaiEEAkACQEEAKAKI0ICAACIFQQEgA0EDdnQiA3ENAEEAIAUgA3I2AojQgIAAIAQhAwwBCyAEKAIIIQMLIAMgAjYCDCAEIAI2AgggAiAENgIMIAIgAzYCCAwDC0EfIQQCQCADQf///wdLDQAgA0EIdiIEIARBgP4/akEQdkEIcSIEdCIFIAVBgOAfakEQdkEEcSIFdCIAIABBgIAPakEQdkECcSIAdEEPdiAEIAVyIAByayIEQQF0IAMgBEEVanZBAXFyQRxqIQQLIAIgBDYCHCACQgA3AhAgBEECdEG40oCAAGohBQJAQQAoAozQgIAAIgBBASAEdCIIcQ0AIAUgAjYCAEEAIAAgCHI2AozQgIAAIAIgBTYCGCACIAI2AgggAiACNgIMDAMLIANBAEEZIARBAXZrIARBH0YbdCEEIAUoAgAhAANAIAAiBSgCBEF4cSADRg0CIARBHXYhACAEQQF0IQQgBSAAQQRxakEQaiIIKAIAIgANAAsgCCACNgIAIAIgBTYCGCACIAI2AgwgAiACNgIIDAILIABBeCAAa0EPcUEAIABBCGpBD3EbIgNqIgsgBkFIaiIIIANrIgNBAXI2AgQgACAIakE4NgIEIAQgBUE3IAVrQQ9xQQAgBUFJakEPcRtqQUFqIgggCCAEQRBqSRsiCEEjNgIEQQBBACgC8NOAgAA2AqTQgIAAQQAgAzYClNCAgABBACALNgKg0ICAACAIQRBqQQApAtDTgIAANwIAIAhBACkCyNOAgAA3AghBACAIQQhqNgLQ04CAAEEAIAY2AszTgIAAQQAgADYCyNOAgABBAEEANgLU04CAACAIQSRqIQMDQCADQQc2AgAgA0EEaiIDIAVJDQALIAggBEYNAyAIIAgoAgRBfnE2AgQgCCAIIARrIgA2AgAgBCAAQQFyNgIEAkAgAEH/AUsNACAAQXhxQbDQgIAAaiEDAkACQEEAKAKI0ICAACIFQQEgAEEDdnQiAHENAEEAIAUgAHI2AojQgIAAIAMhBQwBCyADKAIIIQULIAUgBDYCDCADIAQ2AgggBCADNgIMIAQgBTYCCAwEC0EfIQMCQCAAQf///wdLDQAgAEEIdiIDIANBgP4/akEQdkEIcSIDdCIFIAVBgOAfakEQdkEEcSIFdCIIIAhBgIAPakEQdkECcSIIdEEPdiADIAVyIAhyayIDQQF0IAAgA0EVanZBAXFyQRxqIQMLIAQgAzYCHCAEQgA3AhAgA0ECdEG40oCAAGohBQJAQQAoAozQgIAAIghBASADdCIGcQ0AIAUgBDYCAEEAIAggBnI2AozQgIAAIAQgBTYCGCAEIAQ2AgggBCAENgIMDAQLIABBAEEZIANBAXZrIANBH0YbdCEDIAUoAgAhCANAIAgiBSgCBEF4cSAARg0DIANBHXYhCCADQQF0IQMgBSAIQQRxakEQaiIGKAIAIggNAAsgBiAENgIAIAQgBTYCGCAEIAQ2AgwgBCAENgIIDAMLIAUoAggiAyACNgIMIAUgAjYCCCACQQA2AhggAiAFNgIMIAIgAzYCCAsgC0EIaiEDDAULIAUoAggiAyAENgIMIAUgBDYCCCAEQQA2AhggBCAFNgIMIAQgAzYCCAtBACgClNCAgAAiAyACTQ0AQQAoAqDQgIAAIgQgAmoiBSADIAJrIgNBAXI2AgRBACADNgKU0ICAAEEAIAU2AqDQgIAAIAQgAkEDcjYCBCAEQQhqIQMMAwtBACEDQQBBMDYC+NOAgAAMAgsCQCALRQ0AAkACQCAIIAgoAhwiBUECdEG40oCAAGoiAygCAEcNACADIAA2AgAgAA0BQQAgB0F+IAV3cSIHNgKM0ICAAAwCCyALQRBBFCALKAIQIAhGG2ogADYCACAARQ0BCyAAIAs2AhgCQCAIKAIQIgNFDQAgACADNgIQIAMgADYCGAsgCEEUaigCACIDRQ0AIABBFGogAzYCACADIAA2AhgLAkACQCAEQQ9LDQAgCCAEIAJqIgNBA3I2AgQgCCADaiIDIAMoAgRBAXI2AgQMAQsgCCACaiIAIARBAXI2AgQgCCACQQNyNgIEIAAgBGogBDYCAAJAIARB/wFLDQAgBEF4cUGw0ICAAGohAwJAAkBBACgCiNCAgAAiBUEBIARBA3Z0IgRxDQBBACAFIARyNgKI0ICAACADIQQMAQsgAygCCCEECyAEIAA2AgwgAyAANgIIIAAgAzYCDCAAIAQ2AggMAQtBHyEDAkAgBEH///8HSw0AIARBCHYiAyADQYD+P2pBEHZBCHEiA3QiBSAFQYDgH2pBEHZBBHEiBXQiAiACQYCAD2pBEHZBAnEiAnRBD3YgAyAFciACcmsiA0EBdCAEIANBFWp2QQFxckEcaiEDCyAAIAM2AhwgAEIANwIQIANBAnRBuNKAgABqIQUCQCAHQQEgA3QiAnENACAFIAA2AgBBACAHIAJyNgKM0ICAACAAIAU2AhggACAANgIIIAAgADYCDAwBCyAEQQBBGSADQQF2ayADQR9GG3QhAyAFKAIAIQICQANAIAIiBSgCBEF4cSAERg0BIANBHXYhAiADQQF0IQMgBSACQQRxakEQaiIGKAIAIgINAAsgBiAANgIAIAAgBTYCGCAAIAA2AgwgACAANgIIDAELIAUoAggiAyAANgIMIAUgADYCCCAAQQA2AhggACAFNgIMIAAgAzYCCAsgCEEIaiEDDAELAkAgCkUNAAJAAkAgACAAKAIcIgVBAnRBuNKAgABqIgMoAgBHDQAgAyAINgIAIAgNAUEAIAlBfiAFd3E2AozQgIAADAILIApBEEEUIAooAhAgAEYbaiAINgIAIAhFDQELIAggCjYCGAJAIAAoAhAiA0UNACAIIAM2AhAgAyAINgIYCyAAQRRqKAIAIgNFDQAgCEEUaiADNgIAIAMgCDYCGAsCQAJAIARBD0sNACAAIAQgAmoiA0EDcjYCBCAAIANqIgMgAygCBEEBcjYCBAwBCyAAIAJqIgUgBEEBcjYCBCAAIAJBA3I2AgQgBSAEaiAENgIAAkAgB0UNACAHQXhxQbDQgIAAaiECQQAoApzQgIAAIQMCQAJAQQEgB0EDdnQiCCAGcQ0AQQAgCCAGcjYCiNCAgAAgAiEIDAELIAIoAgghCAsgCCADNgIMIAIgAzYCCCADIAI2AgwgAyAINgIIC0EAIAU2ApzQgIAAQQAgBDYCkNCAgAALIABBCGohAwsgAUEQaiSAgICAACADCwoAIAAQyYCAgAAL4g0BB38CQCAARQ0AIABBeGoiASAAQXxqKAIAIgJBeHEiAGohAwJAIAJBAXENACACQQNxRQ0BIAEgASgCACICayIBQQAoApjQgIAAIgRJDQEgAiAAaiEAAkAgAUEAKAKc0ICAAEYNAAJAIAJB/wFLDQAgASgCCCIEIAJBA3YiBUEDdEGw0ICAAGoiBkYaAkAgASgCDCICIARHDQBBAEEAKAKI0ICAAEF+IAV3cTYCiNCAgAAMAwsgAiAGRhogAiAENgIIIAQgAjYCDAwCCyABKAIYIQcCQAJAIAEoAgwiBiABRg0AIAEoAggiAiAESRogBiACNgIIIAIgBjYCDAwBCwJAIAFBFGoiAigCACIEDQAgAUEQaiICKAIAIgQNAEEAIQYMAQsDQCACIQUgBCIGQRRqIgIoAgAiBA0AIAZBEGohAiAGKAIQIgQNAAsgBUEANgIACyAHRQ0BAkACQCABIAEoAhwiBEECdEG40oCAAGoiAigCAEcNACACIAY2AgAgBg0BQQBBACgCjNCAgABBfiAEd3E2AozQgIAADAMLIAdBEEEUIAcoAhAgAUYbaiAGNgIAIAZFDQILIAYgBzYCGAJAIAEoAhAiAkUNACAGIAI2AhAgAiAGNgIYCyABKAIUIgJFDQEgBkEUaiACNgIAIAIgBjYCGAwBCyADKAIEIgJBA3FBA0cNACADIAJBfnE2AgRBACAANgKQ0ICAACABIABqIAA2AgAgASAAQQFyNgIEDwsgASADTw0AIAMoAgQiAkEBcUUNAAJAAkAgAkECcQ0AAkAgA0EAKAKg0ICAAEcNAEEAIAE2AqDQgIAAQQBBACgClNCAgAAgAGoiADYClNCAgAAgASAAQQFyNgIEIAFBACgCnNCAgABHDQNBAEEANgKQ0ICAAEEAQQA2ApzQgIAADwsCQCADQQAoApzQgIAARw0AQQAgATYCnNCAgABBAEEAKAKQ0ICAACAAaiIANgKQ0ICAACABIABBAXI2AgQgASAAaiAANgIADwsgAkF4cSAAaiEAAkACQCACQf8BSw0AIAMoAggiBCACQQN2IgVBA3RBsNCAgABqIgZGGgJAIAMoAgwiAiAERw0AQQBBACgCiNCAgABBfiAFd3E2AojQgIAADAILIAIgBkYaIAIgBDYCCCAEIAI2AgwMAQsgAygCGCEHAkACQCADKAIMIgYgA0YNACADKAIIIgJBACgCmNCAgABJGiAGIAI2AgggAiAGNgIMDAELAkAgA0EUaiICKAIAIgQNACADQRBqIgIoAgAiBA0AQQAhBgwBCwNAIAIhBSAEIgZBFGoiAigCACIEDQAgBkEQaiECIAYoAhAiBA0ACyAFQQA2AgALIAdFDQACQAJAIAMgAygCHCIEQQJ0QbjSgIAAaiICKAIARw0AIAIgBjYCACAGDQFBAEEAKAKM0ICAAEF+IAR3cTYCjNCAgAAMAgsgB0EQQRQgBygCECADRhtqIAY2AgAgBkUNAQsgBiAHNgIYAkAgAygCECICRQ0AIAYgAjYCECACIAY2AhgLIAMoAhQiAkUNACAGQRRqIAI2AgAgAiAGNgIYCyABIABqIAA2AgAgASAAQQFyNgIEIAFBACgCnNCAgABHDQFBACAANgKQ0ICAAA8LIAMgAkF+cTYCBCABIABqIAA2AgAgASAAQQFyNgIECwJAIABB/wFLDQAgAEF4cUGw0ICAAGohAgJAAkBBACgCiNCAgAAiBEEBIABBA3Z0IgBxDQBBACAEIAByNgKI0ICAACACIQAMAQsgAigCCCEACyAAIAE2AgwgAiABNgIIIAEgAjYCDCABIAA2AggPC0EfIQICQCAAQf///wdLDQAgAEEIdiICIAJBgP4/akEQdkEIcSICdCIEIARBgOAfakEQdkEEcSIEdCIGIAZBgIAPakEQdkECcSIGdEEPdiACIARyIAZyayICQQF0IAAgAkEVanZBAXFyQRxqIQILIAEgAjYCHCABQgA3AhAgAkECdEG40oCAAGohBAJAAkBBACgCjNCAgAAiBkEBIAJ0IgNxDQAgBCABNgIAQQAgBiADcjYCjNCAgAAgASAENgIYIAEgATYCCCABIAE2AgwMAQsgAEEAQRkgAkEBdmsgAkEfRht0IQIgBCgCACEGAkADQCAGIgQoAgRBeHEgAEYNASACQR12IQYgAkEBdCECIAQgBkEEcWpBEGoiAygCACIGDQALIAMgATYCACABIAQ2AhggASABNgIMIAEgATYCCAwBCyAEKAIIIgAgATYCDCAEIAE2AgggAUEANgIYIAEgBDYCDCABIAA2AggLQQBBACgCqNCAgABBf2oiAUF/IAEbNgKo0ICAAAsLBAAAAAtOAAJAIAANAD8AQRB0DwsCQCAAQf//A3ENACAAQX9MDQACQCAAQRB2QAAiAEF/Rw0AQQBBMDYC+NOAgABBfw8LIABBEHQPCxDKgICAAAAL8gICA38BfgJAIAJFDQAgACABOgAAIAIgAGoiA0F/aiABOgAAIAJBA0kNACAAIAE6AAIgACABOgABIANBfWogAToAACADQX5qIAE6AAAgAkEHSQ0AIAAgAToAAyADQXxqIAE6AAAgAkEJSQ0AIABBACAAa0EDcSIEaiIDIAFB/wFxQYGChAhsIgE2AgAgAyACIARrQXxxIgRqIgJBfGogATYCACAEQQlJDQAgAyABNgIIIAMgATYCBCACQXhqIAE2AgAgAkF0aiABNgIAIARBGUkNACADIAE2AhggAyABNgIUIAMgATYCECADIAE2AgwgAkFwaiABNgIAIAJBbGogATYCACACQWhqIAE2AgAgAkFkaiABNgIAIAQgA0EEcUEYciIFayICQSBJDQAgAa1CgYCAgBB+IQYgAyAFaiEBA0AgASAGNwMYIAEgBjcDECABIAY3AwggASAGNwMAIAFBIGohASACQWBqIgJBH0sNAAsLIAALC45IAQBBgAgLhkgBAAAAAgAAAAMAAAAAAAAAAAAAAAQAAAAFAAAAAAAAAAAAAAAGAAAABwAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEludmFsaWQgY2hhciBpbiB1cmwgcXVlcnkAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9ib2R5AENvbnRlbnQtTGVuZ3RoIG92ZXJmbG93AENodW5rIHNpemUgb3ZlcmZsb3cAUmVzcG9uc2Ugb3ZlcmZsb3cASW52YWxpZCBtZXRob2QgZm9yIEhUVFAveC54IHJlcXVlc3QASW52YWxpZCBtZXRob2QgZm9yIFJUU1AveC54IHJlcXVlc3QARXhwZWN0ZWQgU09VUkNFIG1ldGhvZCBmb3IgSUNFL3gueCByZXF1ZXN0AEludmFsaWQgY2hhciBpbiB1cmwgZnJhZ21lbnQgc3RhcnQARXhwZWN0ZWQgZG90AFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25fc3RhdHVzAEludmFsaWQgcmVzcG9uc2Ugc3RhdHVzAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIGV4dGVuc2lvbnMAVXNlciBjYWxsYmFjayBlcnJvcgBgb25fcmVzZXRgIGNhbGxiYWNrIGVycm9yAGBvbl9jaHVua19oZWFkZXJgIGNhbGxiYWNrIGVycm9yAGBvbl9tZXNzYWdlX2JlZ2luYCBjYWxsYmFjayBlcnJvcgBgb25fY2h1bmtfZXh0ZW5zaW9uX3ZhbHVlYCBjYWxsYmFjayBlcnJvcgBgb25fc3RhdHVzX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fdmVyc2lvbl9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX3VybF9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX2NodW5rX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25faGVhZGVyX3ZhbHVlX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fbWVzc2FnZV9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX21ldGhvZF9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX2hlYWRlcl9maWVsZF9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX2NodW5rX2V4dGVuc2lvbl9uYW1lYCBjYWxsYmFjayBlcnJvcgBVbmV4cGVjdGVkIGNoYXIgaW4gdXJsIHNlcnZlcgBJbnZhbGlkIGhlYWRlciB2YWx1ZSBjaGFyAEludmFsaWQgaGVhZGVyIGZpZWxkIGNoYXIAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl92ZXJzaW9uAEludmFsaWQgbWlub3IgdmVyc2lvbgBJbnZhbGlkIG1ham9yIHZlcnNpb24ARXhwZWN0ZWQgc3BhY2UgYWZ0ZXIgdmVyc2lvbgBFeHBlY3RlZCBDUkxGIGFmdGVyIHZlcnNpb24ASW52YWxpZCBIVFRQIHZlcnNpb24ASW52YWxpZCBoZWFkZXIgdG9rZW4AU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl91cmwASW52YWxpZCBjaGFyYWN0ZXJzIGluIHVybABVbmV4cGVjdGVkIHN0YXJ0IGNoYXIgaW4gdXJsAERvdWJsZSBAIGluIHVybABFbXB0eSBDb250ZW50LUxlbmd0aABJbnZhbGlkIGNoYXJhY3RlciBpbiBDb250ZW50LUxlbmd0aABEdXBsaWNhdGUgQ29udGVudC1MZW5ndGgASW52YWxpZCBjaGFyIGluIHVybCBwYXRoAENvbnRlbnQtTGVuZ3RoIGNhbid0IGJlIHByZXNlbnQgd2l0aCBUcmFuc2Zlci1FbmNvZGluZwBJbnZhbGlkIGNoYXJhY3RlciBpbiBjaHVuayBzaXplAFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25faGVhZGVyX3ZhbHVlAFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25fY2h1bmtfZXh0ZW5zaW9uX3ZhbHVlAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIGV4dGVuc2lvbnMgdmFsdWUATWlzc2luZyBleHBlY3RlZCBMRiBhZnRlciBoZWFkZXIgdmFsdWUASW52YWxpZCBgVHJhbnNmZXItRW5jb2RpbmdgIGhlYWRlciB2YWx1ZQBJbnZhbGlkIGNoYXJhY3RlciBpbiBjaHVuayBleHRlbnNpb25zIHF1b3RlIHZhbHVlAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIGV4dGVuc2lvbnMgcXVvdGVkIHZhbHVlAFBhdXNlZCBieSBvbl9oZWFkZXJzX2NvbXBsZXRlAEludmFsaWQgRU9GIHN0YXRlAG9uX3Jlc2V0IHBhdXNlAG9uX2NodW5rX2hlYWRlciBwYXVzZQBvbl9tZXNzYWdlX2JlZ2luIHBhdXNlAG9uX2NodW5rX2V4dGVuc2lvbl92YWx1ZSBwYXVzZQBvbl9zdGF0dXNfY29tcGxldGUgcGF1c2UAb25fdmVyc2lvbl9jb21wbGV0ZSBwYXVzZQBvbl91cmxfY29tcGxldGUgcGF1c2UAb25fY2h1bmtfY29tcGxldGUgcGF1c2UAb25faGVhZGVyX3ZhbHVlX2NvbXBsZXRlIHBhdXNlAG9uX21lc3NhZ2VfY29tcGxldGUgcGF1c2UAb25fbWV0aG9kX2NvbXBsZXRlIHBhdXNlAG9uX2hlYWRlcl9maWVsZF9jb21wbGV0ZSBwYXVzZQBvbl9jaHVua19leHRlbnNpb25fbmFtZSBwYXVzZQBVbmV4cGVjdGVkIHNwYWNlIGFmdGVyIHN0YXJ0IGxpbmUAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9jaHVua19leHRlbnNpb25fbmFtZQBJbnZhbGlkIGNoYXJhY3RlciBpbiBjaHVuayBleHRlbnNpb25zIG5hbWUAUGF1c2Ugb24gQ09OTkVDVC9VcGdyYWRlAFBhdXNlIG9uIFBSSS9VcGdyYWRlAEV4cGVjdGVkIEhUVFAvMiBDb25uZWN0aW9uIFByZWZhY2UAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9tZXRob2QARXhwZWN0ZWQgc3BhY2UgYWZ0ZXIgbWV0aG9kAFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25faGVhZGVyX2ZpZWxkAFBhdXNlZABJbnZhbGlkIHdvcmQgZW5jb3VudGVyZWQASW52YWxpZCBtZXRob2QgZW5jb3VudGVyZWQAVW5leHBlY3RlZCBjaGFyIGluIHVybCBzY2hlbWEAUmVxdWVzdCBoYXMgaW52YWxpZCBgVHJhbnNmZXItRW5jb2RpbmdgAFNXSVRDSF9QUk9YWQBVU0VfUFJPWFkATUtBQ1RJVklUWQBVTlBST0NFU1NBQkxFX0VOVElUWQBDT1BZAE1PVkVEX1BFUk1BTkVOVExZAFRPT19FQVJMWQBOT1RJRlkARkFJTEVEX0RFUEVOREVOQ1kAQkFEX0dBVEVXQVkAUExBWQBQVVQAQ0hFQ0tPVVQAR0FURVdBWV9USU1FT1VUAFJFUVVFU1RfVElNRU9VVABORVRXT1JLX0NPTk5FQ1RfVElNRU9VVABDT05ORUNUSU9OX1RJTUVPVVQATE9HSU5fVElNRU9VVABORVRXT1JLX1JFQURfVElNRU9VVABQT1NUAE1JU0RJUkVDVEVEX1JFUVVFU1QAQ0xJRU5UX0NMT1NFRF9SRVFVRVNUAENMSUVOVF9DTE9TRURfTE9BRF9CQUxBTkNFRF9SRVFVRVNUAEJBRF9SRVFVRVNUAEhUVFBfUkVRVUVTVF9TRU5UX1RPX0hUVFBTX1BPUlQAUkVQT1JUAElNX0FfVEVBUE9UAFJFU0VUX0NPTlRFTlQATk9fQ09OVEVOVABQQVJUSUFMX0NPTlRFTlQASFBFX0lOVkFMSURfQ09OU1RBTlQASFBFX0NCX1JFU0VUAEdFVABIUEVfU1RSSUNUAENPTkZMSUNUAFRFTVBPUkFSWV9SRURJUkVDVABQRVJNQU5FTlRfUkVESVJFQ1QAQ09OTkVDVABNVUxUSV9TVEFUVVMASFBFX0lOVkFMSURfU1RBVFVTAFRPT19NQU5ZX1JFUVVFU1RTAEVBUkxZX0hJTlRTAFVOQVZBSUxBQkxFX0ZPUl9MRUdBTF9SRUFTT05TAE9QVElPTlMAU1dJVENISU5HX1BST1RPQ09MUwBWQVJJQU5UX0FMU09fTkVHT1RJQVRFUwBNVUxUSVBMRV9DSE9JQ0VTAElOVEVSTkFMX1NFUlZFUl9FUlJPUgBXRUJfU0VSVkVSX1VOS05PV05fRVJST1IAUkFJTEdVTl9FUlJPUgBJREVOVElUWV9QUk9WSURFUl9BVVRIRU5USUNBVElPTl9FUlJPUgBTU0xfQ0VSVElGSUNBVEVfRVJST1IASU5WQUxJRF9YX0ZPUldBUkRFRF9GT1IAU0VUX1BBUkFNRVRFUgBHRVRfUEFSQU1FVEVSAEhQRV9VU0VSAFNFRV9PVEhFUgBIUEVfQ0JfQ0hVTktfSEVBREVSAE1LQ0FMRU5EQVIAU0VUVVAAV0VCX1NFUlZFUl9JU19ET1dOAFRFQVJET1dOAEhQRV9DTE9TRURfQ09OTkVDVElPTgBIRVVSSVNUSUNfRVhQSVJBVElPTgBESVNDT05ORUNURURfT1BFUkFUSU9OAE5PTl9BVVRIT1JJVEFUSVZFX0lORk9STUFUSU9OAEhQRV9JTlZBTElEX1ZFUlNJT04ASFBFX0NCX01FU1NBR0VfQkVHSU4AU0lURV9JU19GUk9aRU4ASFBFX0lOVkFMSURfSEVBREVSX1RPS0VOAElOVkFMSURfVE9LRU4ARk9SQklEREVOAEVOSEFOQ0VfWU9VUl9DQUxNAEhQRV9JTlZBTElEX1VSTABCTE9DS0VEX0JZX1BBUkVOVEFMX0NPTlRST0wATUtDT0wAQUNMAEhQRV9JTlRFUk5BTABSRVFVRVNUX0hFQURFUl9GSUVMRFNfVE9PX0xBUkdFX1VOT0ZGSUNJQUwASFBFX09LAFVOTElOSwBVTkxPQ0sAUFJJAFJFVFJZX1dJVEgASFBFX0lOVkFMSURfQ09OVEVOVF9MRU5HVEgASFBFX1VORVhQRUNURURfQ09OVEVOVF9MRU5HVEgARkxVU0gAUFJPUFBBVENIAE0tU0VBUkNIAFVSSV9UT09fTE9ORwBQUk9DRVNTSU5HAE1JU0NFTExBTkVPVVNfUEVSU0lTVEVOVF9XQVJOSU5HAE1JU0NFTExBTkVPVVNfV0FSTklORwBIUEVfSU5WQUxJRF9UUkFOU0ZFUl9FTkNPRElORwBFeHBlY3RlZCBDUkxGAEhQRV9JTlZBTElEX0NIVU5LX1NJWkUATU9WRQBDT05USU5VRQBIUEVfQ0JfU1RBVFVTX0NPTVBMRVRFAEhQRV9DQl9IRUFERVJTX0NPTVBMRVRFAEhQRV9DQl9WRVJTSU9OX0NPTVBMRVRFAEhQRV9DQl9VUkxfQ09NUExFVEUASFBFX0NCX0NIVU5LX0NPTVBMRVRFAEhQRV9DQl9IRUFERVJfVkFMVUVfQ09NUExFVEUASFBFX0NCX0NIVU5LX0VYVEVOU0lPTl9WQUxVRV9DT01QTEVURQBIUEVfQ0JfQ0hVTktfRVhURU5TSU9OX05BTUVfQ09NUExFVEUASFBFX0NCX01FU1NBR0VfQ09NUExFVEUASFBFX0NCX01FVEhPRF9DT01QTEVURQBIUEVfQ0JfSEVBREVSX0ZJRUxEX0NPTVBMRVRFAERFTEVURQBIUEVfSU5WQUxJRF9FT0ZfU1RBVEUASU5WQUxJRF9TU0xfQ0VSVElGSUNBVEUAUEFVU0UATk9fUkVTUE9OU0UAVU5TVVBQT1JURURfTUVESUFfVFlQRQBHT05FAE5PVF9BQ0NFUFRBQkxFAFNFUlZJQ0VfVU5BVkFJTEFCTEUAUkFOR0VfTk9UX1NBVElTRklBQkxFAE9SSUdJTl9JU19VTlJFQUNIQUJMRQBSRVNQT05TRV9JU19TVEFMRQBQVVJHRQBNRVJHRQBSRVFVRVNUX0hFQURFUl9GSUVMRFNfVE9PX0xBUkdFAFJFUVVFU1RfSEVBREVSX1RPT19MQVJHRQBQQVlMT0FEX1RPT19MQVJHRQBJTlNVRkZJQ0lFTlRfU1RPUkFHRQBIUEVfUEFVU0VEX1VQR1JBREUASFBFX1BBVVNFRF9IMl9VUEdSQURFAFNPVVJDRQBBTk5PVU5DRQBUUkFDRQBIUEVfVU5FWFBFQ1RFRF9TUEFDRQBERVNDUklCRQBVTlNVQlNDUklCRQBSRUNPUkQASFBFX0lOVkFMSURfTUVUSE9EAE5PVF9GT1VORABQUk9QRklORABVTkJJTkQAUkVCSU5EAFVOQVVUSE9SSVpFRABNRVRIT0RfTk9UX0FMTE9XRUQASFRUUF9WRVJTSU9OX05PVF9TVVBQT1JURUQAQUxSRUFEWV9SRVBPUlRFRABBQ0NFUFRFRABOT1RfSU1QTEVNRU5URUQATE9PUF9ERVRFQ1RFRABIUEVfQ1JfRVhQRUNURUQASFBFX0xGX0VYUEVDVEVEAENSRUFURUQASU1fVVNFRABIUEVfUEFVU0VEAFRJTUVPVVRfT0NDVVJFRABQQVlNRU5UX1JFUVVJUkVEAFBSRUNPTkRJVElPTl9SRVFVSVJFRABQUk9YWV9BVVRIRU5USUNBVElPTl9SRVFVSVJFRABORVRXT1JLX0FVVEhFTlRJQ0FUSU9OX1JFUVVJUkVEAExFTkdUSF9SRVFVSVJFRABTU0xfQ0VSVElGSUNBVEVfUkVRVUlSRUQAVVBHUkFERV9SRVFVSVJFRABQQUdFX0VYUElSRUQAUFJFQ09ORElUSU9OX0ZBSUxFRABFWFBFQ1RBVElPTl9GQUlMRUQAUkVWQUxJREFUSU9OX0ZBSUxFRABTU0xfSEFORFNIQUtFX0ZBSUxFRABMT0NLRUQAVFJBTlNGT1JNQVRJT05fQVBQTElFRABOT1RfTU9ESUZJRUQATk9UX0VYVEVOREVEAEJBTkRXSURUSF9MSU1JVF9FWENFRURFRABTSVRFX0lTX09WRVJMT0FERUQASEVBRABFeHBlY3RlZCBIVFRQLwAAXhMAACYTAAAwEAAA8BcAAJ0TAAAVEgAAORcAAPASAAAKEAAAdRIAAK0SAACCEwAATxQAAH8QAACgFQAAIxQAAIkSAACLFAAATRUAANQRAADPFAAAEBgAAMkWAADcFgAAwREAAOAXAAC7FAAAdBQAAHwVAADlFAAACBcAAB8QAABlFQAAoxQAACgVAAACFQAAmRUAACwQAACLGQAATw8AANQOAABqEAAAzhAAAAIXAACJDgAAbhMAABwTAABmFAAAVhcAAMETAADNEwAAbBMAAGgXAABmFwAAXxcAACITAADODwAAaQ4AANgOAABjFgAAyxMAAKoOAAAoFwAAJhcAAMUTAABdFgAA6BEAAGcTAABlEwAA8hYAAHMTAAAdFwAA+RYAAPMRAADPDgAAzhUAAAwSAACzEQAApREAAGEQAAAyFwAAuxMAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAQIBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAIDAgICAgIAAAICAAICAAICAgICAgICAgIABAAAAAAAAgICAgICAgICAgICAgICAgICAgICAgICAgIAAAACAgICAgICAgICAgICAgICAgICAgICAgICAgICAgACAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAACAAICAgICAAACAgACAgACAgICAgICAgICAAMABAAAAAICAgICAgICAgICAgICAgICAgICAgICAgICAAAAAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAAgACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAbG9zZWVlcC1hbGl2ZQAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEBAQEBAQEBAQEBAQIBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBY2h1bmtlZAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQEAAQEBAQEAAAEBAAEBAAEBAQEBAQEBAQEAAAAAAAAAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAAABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABlY3Rpb25lbnQtbGVuZ3Rob25yb3h5LWNvbm5lY3Rpb24AAAAAAAAAAAAAAAAAAAByYW5zZmVyLWVuY29kaW5ncGdyYWRlDQoNCg0KU00NCg0KVFRQL0NFL1RTUC8AAAAAAAAAAAAAAAABAgABAwAAAAAAAAAAAAAAAAAAAAAAAAQBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAAAAAAAAAAAAQIAAQMAAAAAAAAAAAAAAAAAAAAAAAAEAQEFAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQAAAAAAAAAAAAEAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAEBAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAAAAAAAAAAAAAQAAAgAAAAAAAAAAAAAAAAAAAAAAAAMEAAAEBAQEBAQEBAQEBAUEBAQEBAQEBAQEBAQABAAGBwQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEAAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAEAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwAAAAAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAABAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAIAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABOT1VOQ0VFQ0tPVVRORUNURVRFQ1JJQkVMVVNIRVRFQURTRUFSQ0hSR0VDVElWSVRZTEVOREFSVkVPVElGWVBUSU9OU0NIU0VBWVNUQVRDSEdFT1JESVJFQ1RPUlRSQ0hQQVJBTUVURVJVUkNFQlNDUklCRUFSRE9XTkFDRUlORE5LQ0tVQlNDUklCRUhUVFAvQURUUC8=' /***/ }), /***/ 95627: /***/ ((module) => { module.exports = 'AGFzbQEAAAABMAhgAX8Bf2ADf39/AX9gBH9/f38Bf2AAAGADf39/AGABfwBgAn9/AGAGf39/f39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQACA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl9ib2R5AAEDZW52GHdhc21fb25fbWVzc2FnZV9jb21wbGV0ZQAAA0ZFAwMEAAAFAAAAAAAABQEFAAUFBQAABgAAAAAGBgYGAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAAABAQcAAAUFAwABBAUBcAESEgUDAQACBggBfwFBgNQECwfRBSIGbWVtb3J5AgALX2luaXRpYWxpemUACRlfX2luZGlyZWN0X2Z1bmN0aW9uX3RhYmxlAQALbGxodHRwX2luaXQAChhsbGh0dHBfc2hvdWxkX2tlZXBfYWxpdmUAQQxsbGh0dHBfYWxsb2MADAZtYWxsb2MARgtsbGh0dHBfZnJlZQANBGZyZWUASA9sbGh0dHBfZ2V0X3R5cGUADhVsbGh0dHBfZ2V0X2h0dHBfbWFqb3IADxVsbGh0dHBfZ2V0X2h0dHBfbWlub3IAEBFsbGh0dHBfZ2V0X21ldGhvZAARFmxsaHR0cF9nZXRfc3RhdHVzX2NvZGUAEhJsbGh0dHBfZ2V0X3VwZ3JhZGUAEwxsbGh0dHBfcmVzZXQAFA5sbGh0dHBfZXhlY3V0ZQAVFGxsaHR0cF9zZXR0aW5nc19pbml0ABYNbGxodHRwX2ZpbmlzaAAXDGxsaHR0cF9wYXVzZQAYDWxsaHR0cF9yZXN1bWUAGRtsbGh0dHBfcmVzdW1lX2FmdGVyX3VwZ3JhZGUAGhBsbGh0dHBfZ2V0X2Vycm5vABsXbGxodHRwX2dldF9lcnJvcl9yZWFzb24AHBdsbGh0dHBfc2V0X2Vycm9yX3JlYXNvbgAdFGxsaHR0cF9nZXRfZXJyb3JfcG9zAB4RbGxodHRwX2Vycm5vX25hbWUAHxJsbGh0dHBfbWV0aG9kX25hbWUAIBJsbGh0dHBfc3RhdHVzX25hbWUAIRpsbGh0dHBfc2V0X2xlbmllbnRfaGVhZGVycwAiIWxsaHR0cF9zZXRfbGVuaWVudF9jaHVua2VkX2xlbmd0aAAjHWxsaHR0cF9zZXRfbGVuaWVudF9rZWVwX2FsaXZlACQkbGxodHRwX3NldF9sZW5pZW50X3RyYW5zZmVyX2VuY29kaW5nACUYbGxodHRwX21lc3NhZ2VfbmVlZHNfZW9mAD8JFwEAQQELEQECAwQFCwYHNTk3MS8tJyspCrLgAkUCAAsIABCIgICAAAsZACAAEMKAgIAAGiAAIAI2AjggACABOgAoCxwAIAAgAC8BMiAALQAuIAAQwYCAgAAQgICAgAALKgEBf0HAABDGgICAACIBEMKAgIAAGiABQYCIgIAANgI4IAEgADoAKCABCwoAIAAQyICAgAALBwAgAC0AKAsHACAALQAqCwcAIAAtACsLBwAgAC0AKQsHACAALwEyCwcAIAAtAC4LRQEEfyAAKAIYIQEgAC0ALSECIAAtACghAyAAKAI4IQQgABDCgICAABogACAENgI4IAAgAzoAKCAAIAI6AC0gACABNgIYCxEAIAAgASABIAJqEMOAgIAACxAAIABBAEHcABDMgICAABoLZwEBf0EAIQECQCAAKAIMDQACQAJAAkACQCAALQAvDgMBAAMCCyAAKAI4IgFFDQAgASgCLCIBRQ0AIAAgARGAgICAAAAiAQ0DC0EADwsQyoCAgAAACyAAQcOWgIAANgIQQQ4hAQsgAQseAAJAIAAoAgwNACAAQdGbgIAANgIQIABBFTYCDAsLFgACQCAAKAIMQRVHDQAgAEEANgIMCwsWAAJAIAAoAgxBFkcNACAAQQA2AgwLCwcAIAAoAgwLBwAgACgCEAsJACAAIAE2AhALBwAgACgCFAsiAAJAIABBJEkNABDKgICAAAALIABBAnRBoLOAgABqKAIACyIAAkAgAEEuSQ0AEMqAgIAAAAsgAEECdEGwtICAAGooAgAL7gsBAX9B66iAgAAhAQJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIABBnH9qDvQDY2IAAWFhYWFhYQIDBAVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhBgcICQoLDA0OD2FhYWFhEGFhYWFhYWFhYWFhEWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYRITFBUWFxgZGhthYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhHB0eHyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2YTc4OTphYWFhYWFhYTthYWE8YWFhYT0+P2FhYWFhYWFhQGFhQWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYUJDREVGR0hJSktMTU5PUFFSU2FhYWFhYWFhVFVWV1hZWlthXF1hYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFeYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhX2BhC0Hhp4CAAA8LQaShgIAADwtBy6yAgAAPC0H+sYCAAA8LQcCkgIAADwtBq6SAgAAPC0GNqICAAA8LQeKmgIAADwtBgLCAgAAPC0G5r4CAAA8LQdekgIAADwtB75+AgAAPC0Hhn4CAAA8LQfqfgIAADwtB8qCAgAAPC0Gor4CAAA8LQa6ygIAADwtBiLCAgAAPC0Hsp4CAAA8LQYKigIAADwtBjp2AgAAPC0HQroCAAA8LQcqjgIAADwtBxbKAgAAPC0HfnICAAA8LQdKcgIAADwtBxKCAgAAPC0HXoICAAA8LQaKfgIAADwtB7a6AgAAPC0GrsICAAA8LQdSlgIAADwtBzK6AgAAPC0H6roCAAA8LQfyrgIAADwtB0rCAgAAPC0HxnYCAAA8LQbuggIAADwtB96uAgAAPC0GQsYCAAA8LQdexgIAADwtBoq2AgAAPC0HUp4CAAA8LQeCrgIAADwtBn6yAgAAPC0HrsYCAAA8LQdWfgIAADwtByrGAgAAPC0HepYCAAA8LQdSegIAADwtB9JyAgAAPC0GnsoCAAA8LQbGdgIAADwtBoJ2AgAAPC0G5sYCAAA8LQbywgIAADwtBkqGAgAAPC0GzpoCAAA8LQemsgIAADwtBrJ6AgAAPC0HUq4CAAA8LQfemgIAADwtBgKaAgAAPC0GwoYCAAA8LQf6egIAADwtBjaOAgAAPC0GJrYCAAA8LQfeigIAADwtBoLGAgAAPC0Gun4CAAA8LQcalgIAADwtB6J6AgAAPC0GTooCAAA8LQcKvgIAADwtBw52AgAAPC0GLrICAAA8LQeGdgIAADwtBja+AgAAPC0HqoYCAAA8LQbStgIAADwtB0q+AgAAPC0HfsoCAAA8LQdKygIAADwtB8LCAgAAPC0GpooCAAA8LQfmjgIAADwtBmZ6AgAAPC0G1rICAAA8LQZuwgIAADwtBkrKAgAAPC0G2q4CAAA8LQcKigIAADwtB+LKAgAAPC0GepYCAAA8LQdCigIAADwtBup6AgAAPC0GBnoCAAA8LEMqAgIAAAAtB1qGAgAAhAQsgAQsWACAAIAAtAC1B/gFxIAFBAEdyOgAtCxkAIAAgAC0ALUH9AXEgAUEAR0EBdHI6AC0LGQAgACAALQAtQfsBcSABQQBHQQJ0cjoALQsZACAAIAAtAC1B9wFxIAFBAEdBA3RyOgAtCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAgAiBEUNACAAIAQRgICAgAAAIQMLIAMLSQECf0EAIQMCQCAAKAI4IgRFDQAgBCgCBCIERQ0AIAAgASACIAFrIAQRgYCAgAAAIgNBf0cNACAAQcaRgIAANgIQQRghAwsgAwsuAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIwIgRFDQAgACAEEYCAgIAAACEDCyADC0kBAn9BACEDAkAgACgCOCIERQ0AIAQoAggiBEUNACAAIAEgAiABayAEEYGAgIAAACIDQX9HDQAgAEH2ioCAADYCEEEYIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCNCIERQ0AIAAgBBGAgICAAAAhAwsgAwtJAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIMIgRFDQAgACABIAIgAWsgBBGBgICAAAAiA0F/Rw0AIABB7ZqAgAA2AhBBGCEDCyADCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAjgiBEUNACAAIAQRgICAgAAAIQMLIAMLSQECf0EAIQMCQCAAKAI4IgRFDQAgBCgCECIERQ0AIAAgASACIAFrIAQRgYCAgAAAIgNBf0cNACAAQZWQgIAANgIQQRghAwsgAwsuAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAI8IgRFDQAgACAEEYCAgIAAACEDCyADC0kBAn9BACEDAkAgACgCOCIERQ0AIAQoAhQiBEUNACAAIAEgAiABayAEEYGAgIAAACIDQX9HDQAgAEGqm4CAADYCEEEYIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCQCIERQ0AIAAgBBGAgICAAAAhAwsgAwtJAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIYIgRFDQAgACABIAIgAWsgBBGBgICAAAAiA0F/Rw0AIABB7ZOAgAA2AhBBGCEDCyADCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAkQiBEUNACAAIAQRgICAgAAAIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCJCIERQ0AIAAgBBGAgICAAAAhAwsgAwsuAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIsIgRFDQAgACAEEYCAgIAAACEDCyADC0kBAn9BACEDAkAgACgCOCIERQ0AIAQoAigiBEUNACAAIAEgAiABayAEEYGAgIAAACIDQX9HDQAgAEH2iICAADYCEEEYIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCUCIERQ0AIAAgBBGAgICAAAAhAwsgAwtJAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAIcIgRFDQAgACABIAIgAWsgBBGBgICAAAAiA0F/Rw0AIABBwpmAgAA2AhBBGCEDCyADCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAkgiBEUNACAAIAQRgICAgAAAIQMLIAMLSQECf0EAIQMCQCAAKAI4IgRFDQAgBCgCICIERQ0AIAAgASACIAFrIAQRgYCAgAAAIgNBf0cNACAAQZSUgIAANgIQQRghAwsgAwsuAQJ/QQAhAwJAIAAoAjgiBEUNACAEKAJMIgRFDQAgACAEEYCAgIAAACEDCyADCy4BAn9BACEDAkAgACgCOCIERQ0AIAQoAlQiBEUNACAAIAQRgICAgAAAIQMLIAMLLgECf0EAIQMCQCAAKAI4IgRFDQAgBCgCWCIERQ0AIAAgBBGAgICAAAAhAwsgAwtFAQF/AkACQCAALwEwQRRxQRRHDQBBASEDIAAtAChBAUYNASAALwEyQeUARiEDDAELIAAtAClBBUYhAwsgACADOgAuQQAL/gEBA39BASEDAkAgAC8BMCIEQQhxDQAgACkDIEIAUiEDCwJAAkAgAC0ALkUNAEEBIQUgAC0AKUEFRg0BQQEhBSAEQcAAcUUgA3FBAUcNAQtBACEFIARBwABxDQBBAiEFIARB//8DcSIDQQhxDQACQCADQYAEcUUNAAJAIAAtAChBAUcNACAALQAtQQpxDQBBBQ8LQQQPCwJAIANBIHENAAJAIAAtAChBAUYNACAALwEyQf//A3EiAEGcf2pB5ABJDQAgAEHMAUYNACAAQbACRg0AQQQhBSAEQShxRQ0CIANBiARxQYAERg0CC0EADwtBAEEDIAApAyBQGyEFCyAFC2IBAn9BACEBAkAgAC0AKEEBRg0AIAAvATJB//8DcSICQZx/akHkAEkNACACQcwBRg0AIAJBsAJGDQAgAC8BMCIAQcAAcQ0AQQEhASAAQYgEcUGABEYNACAAQShxRSEBCyABC6cBAQN/AkACQAJAIAAtACpFDQAgAC0AK0UNAEEAIQMgAC8BMCIEQQJxRQ0BDAILQQAhAyAALwEwIgRBAXFFDQELQQEhAyAALQAoQQFGDQAgAC8BMkH//wNxIgVBnH9qQeQASQ0AIAVBzAFGDQAgBUGwAkYNACAEQcAAcQ0AQQAhAyAEQYgEcUGABEYNACAEQShxQQBHIQMLIABBADsBMCAAQQA6AC8gAwuZAQECfwJAAkACQCAALQAqRQ0AIAAtACtFDQBBACEBIAAvATAiAkECcUUNAQwCC0EAIQEgAC8BMCICQQFxRQ0BC0EBIQEgAC0AKEEBRg0AIAAvATJB//8DcSIAQZx/akHkAEkNACAAQcwBRg0AIABBsAJGDQAgAkHAAHENAEEAIQEgAkGIBHFBgARGDQAgAkEocUEARyEBCyABC0kBAXsgAEEQav0MAAAAAAAAAAAAAAAAAAAAACIB/QsDACAAIAH9CwMAIABBMGogAf0LAwAgAEEgaiAB/QsDACAAQd0BNgIcQQALewEBfwJAIAAoAgwiAw0AAkAgACgCBEUNACAAIAE2AgQLAkAgACABIAIQxICAgAAiAw0AIAAoAgwPCyAAIAM2AhxBACEDIAAoAgQiAUUNACAAIAEgAiAAKAIIEYGAgIAAACIBRQ0AIAAgAjYCFCAAIAE2AgwgASEDCyADC+TzAQMOfwN+BH8jgICAgABBEGsiAySAgICAACABIQQgASEFIAEhBiABIQcgASEIIAEhCSABIQogASELIAEhDCABIQ0gASEOIAEhDwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCAAKAIcIhBBf2oO3QHaAQHZAQIDBAUGBwgJCgsMDQ7YAQ8Q1wEREtYBExQVFhcYGRob4AHfARwdHtUBHyAhIiMkJdQBJicoKSorLNMB0gEtLtEB0AEvMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUbbAUdISUrPAc4BS80BTMwBTU5PUFFSU1RVVldYWVpbXF1eX2BhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ent8fX5/gAGBAYIBgwGEAYUBhgGHAYgBiQGKAYsBjAGNAY4BjwGQAZEBkgGTAZQBlQGWAZcBmAGZAZoBmwGcAZ0BngGfAaABoQGiAaMBpAGlAaYBpwGoAakBqgGrAawBrQGuAa8BsAGxAbIBswG0AbUBtgG3AcsBygG4AckBuQHIAboBuwG8Ab0BvgG/AcABwQHCAcMBxAHFAcYBANwBC0EAIRAMxgELQQ4hEAzFAQtBDSEQDMQBC0EPIRAMwwELQRAhEAzCAQtBEyEQDMEBC0EUIRAMwAELQRUhEAy/AQtBFiEQDL4BC0EXIRAMvQELQRghEAy8AQtBGSEQDLsBC0EaIRAMugELQRshEAy5AQtBHCEQDLgBC0EIIRAMtwELQR0hEAy2AQtBICEQDLUBC0EfIRAMtAELQQchEAyzAQtBISEQDLIBC0EiIRAMsQELQR4hEAywAQtBIyEQDK8BC0ESIRAMrgELQREhEAytAQtBJCEQDKwBC0ElIRAMqwELQSYhEAyqAQtBJyEQDKkBC0HDASEQDKgBC0EpIRAMpwELQSshEAymAQtBLCEQDKUBC0EtIRAMpAELQS4hEAyjAQtBLyEQDKIBC0HEASEQDKEBC0EwIRAMoAELQTQhEAyfAQtBDCEQDJ4BC0ExIRAMnQELQTIhEAycAQtBMyEQDJsBC0E5IRAMmgELQTUhEAyZAQtBxQEhEAyYAQtBCyEQDJcBC0E6IRAMlgELQTYhEAyVAQtBCiEQDJQBC0E3IRAMkwELQTghEAySAQtBPCEQDJEBC0E7IRAMkAELQT0hEAyPAQtBCSEQDI4BC0EoIRAMjQELQT4hEAyMAQtBPyEQDIsBC0HAACEQDIoBC0HBACEQDIkBC0HCACEQDIgBC0HDACEQDIcBC0HEACEQDIYBC0HFACEQDIUBC0HGACEQDIQBC0EqIRAMgwELQccAIRAMggELQcgAIRAMgQELQckAIRAMgAELQcoAIRAMfwtBywAhEAx+C0HNACEQDH0LQcwAIRAMfAtBzgAhEAx7C0HPACEQDHoLQdAAIRAMeQtB0QAhEAx4C0HSACEQDHcLQdMAIRAMdgtB1AAhEAx1C0HWACEQDHQLQdUAIRAMcwtBBiEQDHILQdcAIRAMcQtBBSEQDHALQdgAIRAMbwtBBCEQDG4LQdkAIRAMbQtB2gAhEAxsC0HbACEQDGsLQdwAIRAMagtBAyEQDGkLQd0AIRAMaAtB3gAhEAxnC0HfACEQDGYLQeEAIRAMZQtB4AAhEAxkC0HiACEQDGMLQeMAIRAMYgtBAiEQDGELQeQAIRAMYAtB5QAhEAxfC0HmACEQDF4LQecAIRAMXQtB6AAhEAxcC0HpACEQDFsLQeoAIRAMWgtB6wAhEAxZC0HsACEQDFgLQe0AIRAMVwtB7gAhEAxWC0HvACEQDFULQfAAIRAMVAtB8QAhEAxTC0HyACEQDFILQfMAIRAMUQtB9AAhEAxQC0H1ACEQDE8LQfYAIRAMTgtB9wAhEAxNC0H4ACEQDEwLQfkAIRAMSwtB+gAhEAxKC0H7ACEQDEkLQfwAIRAMSAtB/QAhEAxHC0H+ACEQDEYLQf8AIRAMRQtBgAEhEAxEC0GBASEQDEMLQYIBIRAMQgtBgwEhEAxBC0GEASEQDEALQYUBIRAMPwtBhgEhEAw+C0GHASEQDD0LQYgBIRAMPAtBiQEhEAw7C0GKASEQDDoLQYsBIRAMOQtBjAEhEAw4C0GNASEQDDcLQY4BIRAMNgtBjwEhEAw1C0GQASEQDDQLQZEBIRAMMwtBkgEhEAwyC0GTASEQDDELQZQBIRAMMAtBlQEhEAwvC0GWASEQDC4LQZcBIRAMLQtBmAEhEAwsC0GZASEQDCsLQZoBIRAMKgtBmwEhEAwpC0GcASEQDCgLQZ0BIRAMJwtBngEhEAwmC0GfASEQDCULQaABIRAMJAtBoQEhEAwjC0GiASEQDCILQaMBIRAMIQtBpAEhEAwgC0GlASEQDB8LQaYBIRAMHgtBpwEhEAwdC0GoASEQDBwLQakBIRAMGwtBqgEhEAwaC0GrASEQDBkLQawBIRAMGAtBrQEhEAwXC0GuASEQDBYLQQEhEAwVC0GvASEQDBQLQbABIRAMEwtBsQEhEAwSC0GzASEQDBELQbIBIRAMEAtBtAEhEAwPC0G1ASEQDA4LQbYBIRAMDQtBtwEhEAwMC0G4ASEQDAsLQbkBIRAMCgtBugEhEAwJC0G7ASEQDAgLQcYBIRAMBwtBvAEhEAwGC0G9ASEQDAULQb4BIRAMBAtBvwEhEAwDC0HAASEQDAILQcIBIRAMAQtBwQEhEAsDQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIBAOxwEAAQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB4fICEjJSg/QEFERUZHSElKS0xNT1BRUlPeA1dZW1xdYGJlZmdoaWprbG1vcHFyc3R1dnd4eXp7fH1+gAGCAYUBhgGHAYkBiwGMAY0BjgGPAZABkQGUAZUBlgGXAZgBmQGaAZsBnAGdAZ4BnwGgAaEBogGjAaQBpQGmAacBqAGpAaoBqwGsAa0BrgGvAbABsQGyAbMBtAG1AbYBtwG4AbkBugG7AbwBvQG+Ab8BwAHBAcIBwwHEAcUBxgHHAcgByQHKAcsBzAHNAc4BzwHQAdEB0gHTAdQB1QHWAdcB2AHZAdoB2wHcAd0B3gHgAeEB4gHjAeQB5QHmAecB6AHpAeoB6wHsAe0B7gHvAfAB8QHyAfMBmQKkArAC/gL+AgsgASIEIAJHDfMBQd0BIRAM/wMLIAEiECACRw3dAUHDASEQDP4DCyABIgEgAkcNkAFB9wAhEAz9AwsgASIBIAJHDYYBQe8AIRAM/AMLIAEiASACRw1/QeoAIRAM+wMLIAEiASACRw17QegAIRAM+gMLIAEiASACRw14QeYAIRAM+QMLIAEiASACRw0aQRghEAz4AwsgASIBIAJHDRRBEiEQDPcDCyABIgEgAkcNWUHFACEQDPYDCyABIgEgAkcNSkE/IRAM9QMLIAEiASACRw1IQTwhEAz0AwsgASIBIAJHDUFBMSEQDPMDCyAALQAuQQFGDesDDIcCCyAAIAEiASACEMCAgIAAQQFHDeYBIABCADcDIAznAQsgACABIgEgAhC0gICAACIQDecBIAEhAQz1AgsCQCABIgEgAkcNAEEGIRAM8AMLIAAgAUEBaiIBIAIQu4CAgAAiEA3oASABIQEMMQsgAEIANwMgQRIhEAzVAwsgASIQIAJHDStBHSEQDO0DCwJAIAEiASACRg0AIAFBAWohAUEQIRAM1AMLQQchEAzsAwsgAEIAIAApAyAiESACIAEiEGutIhJ9IhMgEyARVhs3AyAgESASViIURQ3lAUEIIRAM6wMLAkAgASIBIAJGDQAgAEGJgICAADYCCCAAIAE2AgQgASEBQRQhEAzSAwtBCSEQDOoDCyABIQEgACkDIFAN5AEgASEBDPICCwJAIAEiASACRw0AQQshEAzpAwsgACABQQFqIgEgAhC2gICAACIQDeUBIAEhAQzyAgsgACABIgEgAhC4gICAACIQDeUBIAEhAQzyAgsgACABIgEgAhC4gICAACIQDeYBIAEhAQwNCyAAIAEiASACELqAgIAAIhAN5wEgASEBDPACCwJAIAEiASACRw0AQQ8hEAzlAwsgAS0AACIQQTtGDQggEEENRw3oASABQQFqIQEM7wILIAAgASIBIAIQuoCAgAAiEA3oASABIQEM8gILA0ACQCABLQAAQfC1gIAAai0AACIQQQFGDQAgEEECRw3rASAAKAIEIRAgAEEANgIEIAAgECABQQFqIgEQuYCAgAAiEA3qASABIQEM9AILIAFBAWoiASACRw0AC0ESIRAM4gMLIAAgASIBIAIQuoCAgAAiEA3pASABIQEMCgsgASIBIAJHDQZBGyEQDOADCwJAIAEiASACRw0AQRYhEAzgAwsgAEGKgICAADYCCCAAIAE2AgQgACABIAIQuICAgAAiEA3qASABIQFBICEQDMYDCwJAIAEiASACRg0AA0ACQCABLQAAQfC3gIAAai0AACIQQQJGDQACQCAQQX9qDgTlAewBAOsB7AELIAFBAWohAUEIIRAMyAMLIAFBAWoiASACRw0AC0EVIRAM3wMLQRUhEAzeAwsDQAJAIAEtAABB8LmAgABqLQAAIhBBAkYNACAQQX9qDgTeAewB4AHrAewBCyABQQFqIgEgAkcNAAtBGCEQDN0DCwJAIAEiASACRg0AIABBi4CAgAA2AgggACABNgIEIAEhAUEHIRAMxAMLQRkhEAzcAwsgAUEBaiEBDAILAkAgASIUIAJHDQBBGiEQDNsDCyAUIQECQCAULQAAQXNqDhTdAu4C7gLuAu4C7gLuAu4C7gLuAu4C7gLuAu4C7gLuAu4C7gLuAgDuAgtBACEQIABBADYCHCAAQa+LgIAANgIQIABBAjYCDCAAIBRBAWo2AhQM2gMLAkAgAS0AACIQQTtGDQAgEEENRw3oASABQQFqIQEM5QILIAFBAWohAQtBIiEQDL8DCwJAIAEiECACRw0AQRwhEAzYAwtCACERIBAhASAQLQAAQVBqDjfnAeYBAQIDBAUGBwgAAAAAAAAACQoLDA0OAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPEBESExQAC0EeIRAMvQMLQgIhEQzlAQtCAyERDOQBC0IEIREM4wELQgUhEQziAQtCBiERDOEBC0IHIREM4AELQgghEQzfAQtCCSERDN4BC0IKIREM3QELQgshEQzcAQtCDCERDNsBC0INIREM2gELQg4hEQzZAQtCDyERDNgBC0IKIREM1wELQgshEQzWAQtCDCERDNUBC0INIREM1AELQg4hEQzTAQtCDyERDNIBC0IAIRECQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIBAtAABBUGoON+UB5AEAAQIDBAUGB+YB5gHmAeYB5gHmAeYBCAkKCwwN5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAQ4PEBESE+YBC0ICIREM5AELQgMhEQzjAQtCBCERDOIBC0IFIREM4QELQgYhEQzgAQtCByERDN8BC0IIIREM3gELQgkhEQzdAQtCCiERDNwBC0ILIREM2wELQgwhEQzaAQtCDSERDNkBC0IOIREM2AELQg8hEQzXAQtCCiERDNYBC0ILIREM1QELQgwhEQzUAQtCDSERDNMBC0IOIREM0gELQg8hEQzRAQsgAEIAIAApAyAiESACIAEiEGutIhJ9IhMgEyARVhs3AyAgESASViIURQ3SAUEfIRAMwAMLAkAgASIBIAJGDQAgAEGJgICAADYCCCAAIAE2AgQgASEBQSQhEAynAwtBICEQDL8DCyAAIAEiECACEL6AgIAAQX9qDgW2AQDFAgHRAdIBC0ERIRAMpAMLIABBAToALyAQIQEMuwMLIAEiASACRw3SAUEkIRAMuwMLIAEiDSACRw0eQcYAIRAMugMLIAAgASIBIAIQsoCAgAAiEA3UASABIQEMtQELIAEiECACRw0mQdAAIRAMuAMLAkAgASIBIAJHDQBBKCEQDLgDCyAAQQA2AgQgAEGMgICAADYCCCAAIAEgARCxgICAACIQDdMBIAEhAQzYAQsCQCABIhAgAkcNAEEpIRAMtwMLIBAtAAAiAUEgRg0UIAFBCUcN0wEgEEEBaiEBDBULAkAgASIBIAJGDQAgAUEBaiEBDBcLQSohEAy1AwsCQCABIhAgAkcNAEErIRAMtQMLAkAgEC0AACIBQQlGDQAgAUEgRw3VAQsgAC0ALEEIRg3TASAQIQEMkQMLAkAgASIBIAJHDQBBLCEQDLQDCyABLQAAQQpHDdUBIAFBAWohAQzJAgsgASIOIAJHDdUBQS8hEAyyAwsDQAJAIAEtAAAiEEEgRg0AAkAgEEF2ag4EANwB3AEA2gELIAEhAQzgAQsgAUEBaiIBIAJHDQALQTEhEAyxAwtBMiEQIAEiFCACRg2wAyACIBRrIAAoAgAiAWohFSAUIAFrQQNqIRYCQANAIBQtAAAiF0EgciAXIBdBv39qQf8BcUEaSRtB/wFxIAFB8LuAgABqLQAARw0BAkAgAUEDRw0AQQYhAQyWAwsgAUEBaiEBIBRBAWoiFCACRw0ACyAAIBU2AgAMsQMLIABBADYCACAUIQEM2QELQTMhECABIhQgAkYNrwMgAiAUayAAKAIAIgFqIRUgFCABa0EIaiEWAkADQCAULQAAIhdBIHIgFyAXQb9/akH/AXFBGkkbQf8BcSABQfS7gIAAai0AAEcNAQJAIAFBCEcNAEEFIQEMlQMLIAFBAWohASAUQQFqIhQgAkcNAAsgACAVNgIADLADCyAAQQA2AgAgFCEBDNgBC0E0IRAgASIUIAJGDa4DIAIgFGsgACgCACIBaiEVIBQgAWtBBWohFgJAA0AgFC0AACIXQSByIBcgF0G/f2pB/wFxQRpJG0H/AXEgAUHQwoCAAGotAABHDQECQCABQQVHDQBBByEBDJQDCyABQQFqIQEgFEEBaiIUIAJHDQALIAAgFTYCAAyvAwsgAEEANgIAIBQhAQzXAQsCQCABIgEgAkYNAANAAkAgAS0AAEGAvoCAAGotAAAiEEEBRg0AIBBBAkYNCiABIQEM3QELIAFBAWoiASACRw0AC0EwIRAMrgMLQTAhEAytAwsCQCABIgEgAkYNAANAAkAgAS0AACIQQSBGDQAgEEF2ag4E2QHaAdoB2QHaAQsgAUEBaiIBIAJHDQALQTghEAytAwtBOCEQDKwDCwNAAkAgAS0AACIQQSBGDQAgEEEJRw0DCyABQQFqIgEgAkcNAAtBPCEQDKsDCwNAAkAgAS0AACIQQSBGDQACQAJAIBBBdmoOBNoBAQHaAQALIBBBLEYN2wELIAEhAQwECyABQQFqIgEgAkcNAAtBPyEQDKoDCyABIQEM2wELQcAAIRAgASIUIAJGDagDIAIgFGsgACgCACIBaiEWIBQgAWtBBmohFwJAA0AgFC0AAEEgciABQYDAgIAAai0AAEcNASABQQZGDY4DIAFBAWohASAUQQFqIhQgAkcNAAsgACAWNgIADKkDCyAAQQA2AgAgFCEBC0E2IRAMjgMLAkAgASIPIAJHDQBBwQAhEAynAwsgAEGMgICAADYCCCAAIA82AgQgDyEBIAAtACxBf2oOBM0B1QHXAdkBhwMLIAFBAWohAQzMAQsCQCABIgEgAkYNAANAAkAgAS0AACIQQSByIBAgEEG/f2pB/wFxQRpJG0H/AXEiEEEJRg0AIBBBIEYNAAJAAkACQAJAIBBBnX9qDhMAAwMDAwMDAwEDAwMDAwMDAwMCAwsgAUEBaiEBQTEhEAyRAwsgAUEBaiEBQTIhEAyQAwsgAUEBaiEBQTMhEAyPAwsgASEBDNABCyABQQFqIgEgAkcNAAtBNSEQDKUDC0E1IRAMpAMLAkAgASIBIAJGDQADQAJAIAEtAABBgLyAgABqLQAAQQFGDQAgASEBDNMBCyABQQFqIgEgAkcNAAtBPSEQDKQDC0E9IRAMowMLIAAgASIBIAIQsICAgAAiEA3WASABIQEMAQsgEEEBaiEBC0E8IRAMhwMLAkAgASIBIAJHDQBBwgAhEAygAwsCQANAAkAgAS0AAEF3ag4YAAL+Av4ChAP+Av4C/gL+Av4C/gL+Av4C/gL+Av4C/gL+Av4C/gL+Av4C/gIA/gILIAFBAWoiASACRw0AC0HCACEQDKADCyABQQFqIQEgAC0ALUEBcUUNvQEgASEBC0EsIRAMhQMLIAEiASACRw3TAUHEACEQDJ0DCwNAAkAgAS0AAEGQwICAAGotAABBAUYNACABIQEMtwILIAFBAWoiASACRw0AC0HFACEQDJwDCyANLQAAIhBBIEYNswEgEEE6Rw2BAyAAKAIEIQEgAEEANgIEIAAgASANEK+AgIAAIgEN0AEgDUEBaiEBDLMCC0HHACEQIAEiDSACRg2aAyACIA1rIAAoAgAiAWohFiANIAFrQQVqIRcDQCANLQAAIhRBIHIgFCAUQb9/akH/AXFBGkkbQf8BcSABQZDCgIAAai0AAEcNgAMgAUEFRg30AiABQQFqIQEgDUEBaiINIAJHDQALIAAgFjYCAAyaAwtByAAhECABIg0gAkYNmQMgAiANayAAKAIAIgFqIRYgDSABa0EJaiEXA0AgDS0AACIUQSByIBQgFEG/f2pB/wFxQRpJG0H/AXEgAUGWwoCAAGotAABHDf8CAkAgAUEJRw0AQQIhAQz1AgsgAUEBaiEBIA1BAWoiDSACRw0ACyAAIBY2AgAMmQMLAkAgASINIAJHDQBByQAhEAyZAwsCQAJAIA0tAAAiAUEgciABIAFBv39qQf8BcUEaSRtB/wFxQZJ/ag4HAIADgAOAA4ADgAMBgAMLIA1BAWohAUE+IRAMgAMLIA1BAWohAUE/IRAM/wILQcoAIRAgASINIAJGDZcDIAIgDWsgACgCACIBaiEWIA0gAWtBAWohFwNAIA0tAAAiFEEgciAUIBRBv39qQf8BcUEaSRtB/wFxIAFBoMKAgABqLQAARw39AiABQQFGDfACIAFBAWohASANQQFqIg0gAkcNAAsgACAWNgIADJcDC0HLACEQIAEiDSACRg2WAyACIA1rIAAoAgAiAWohFiANIAFrQQ5qIRcDQCANLQAAIhRBIHIgFCAUQb9/akH/AXFBGkkbQf8BcSABQaLCgIAAai0AAEcN/AIgAUEORg3wAiABQQFqIQEgDUEBaiINIAJHDQALIAAgFjYCAAyWAwtBzAAhECABIg0gAkYNlQMgAiANayAAKAIAIgFqIRYgDSABa0EPaiEXA0AgDS0AACIUQSByIBQgFEG/f2pB/wFxQRpJG0H/AXEgAUHAwoCAAGotAABHDfsCAkAgAUEPRw0AQQMhAQzxAgsgAUEBaiEBIA1BAWoiDSACRw0ACyAAIBY2AgAMlQMLQc0AIRAgASINIAJGDZQDIAIgDWsgACgCACIBaiEWIA0gAWtBBWohFwNAIA0tAAAiFEEgciAUIBRBv39qQf8BcUEaSRtB/wFxIAFB0MKAgABqLQAARw36AgJAIAFBBUcNAEEEIQEM8AILIAFBAWohASANQQFqIg0gAkcNAAsgACAWNgIADJQDCwJAIAEiDSACRw0AQc4AIRAMlAMLAkACQAJAAkAgDS0AACIBQSByIAEgAUG/f2pB/wFxQRpJG0H/AXFBnX9qDhMA/QL9Av0C/QL9Av0C/QL9Av0C/QL9Av0CAf0C/QL9AgID/QILIA1BAWohAUHBACEQDP0CCyANQQFqIQFBwgAhEAz8AgsgDUEBaiEBQcMAIRAM+wILIA1BAWohAUHEACEQDPoCCwJAIAEiASACRg0AIABBjYCAgAA2AgggACABNgIEIAEhAUHFACEQDPoCC0HPACEQDJIDCyAQIQECQAJAIBAtAABBdmoOBAGoAqgCAKgCCyAQQQFqIQELQSchEAz4AgsCQCABIgEgAkcNAEHRACEQDJEDCwJAIAEtAABBIEYNACABIQEMjQELIAFBAWohASAALQAtQQFxRQ3HASABIQEMjAELIAEiFyACRw3IAUHSACEQDI8DC0HTACEQIAEiFCACRg2OAyACIBRrIAAoAgAiAWohFiAUIAFrQQFqIRcDQCAULQAAIAFB1sKAgABqLQAARw3MASABQQFGDccBIAFBAWohASAUQQFqIhQgAkcNAAsgACAWNgIADI4DCwJAIAEiASACRw0AQdUAIRAMjgMLIAEtAABBCkcNzAEgAUEBaiEBDMcBCwJAIAEiASACRw0AQdYAIRAMjQMLAkACQCABLQAAQXZqDgQAzQHNAQHNAQsgAUEBaiEBDMcBCyABQQFqIQFBygAhEAzzAgsgACABIgEgAhCugICAACIQDcsBIAEhAUHNACEQDPICCyAALQApQSJGDYUDDKYCCwJAIAEiASACRw0AQdsAIRAMigMLQQAhFEEBIRdBASEWQQAhEAJAAkACQAJAAkACQAJAAkACQCABLQAAQVBqDgrUAdMBAAECAwQFBgjVAQtBAiEQDAYLQQMhEAwFC0EEIRAMBAtBBSEQDAMLQQYhEAwCC0EHIRAMAQtBCCEQC0EAIRdBACEWQQAhFAzMAQtBCSEQQQEhFEEAIRdBACEWDMsBCwJAIAEiASACRw0AQd0AIRAMiQMLIAEtAABBLkcNzAEgAUEBaiEBDKYCCyABIgEgAkcNzAFB3wAhEAyHAwsCQCABIgEgAkYNACAAQY6AgIAANgIIIAAgATYCBCABIQFB0AAhEAzuAgtB4AAhEAyGAwtB4QAhECABIgEgAkYNhQMgAiABayAAKAIAIhRqIRYgASAUa0EDaiEXA0AgAS0AACAUQeLCgIAAai0AAEcNzQEgFEEDRg3MASAUQQFqIRQgAUEBaiIBIAJHDQALIAAgFjYCAAyFAwtB4gAhECABIgEgAkYNhAMgAiABayAAKAIAIhRqIRYgASAUa0ECaiEXA0AgAS0AACAUQebCgIAAai0AAEcNzAEgFEECRg3OASAUQQFqIRQgAUEBaiIBIAJHDQALIAAgFjYCAAyEAwtB4wAhECABIgEgAkYNgwMgAiABayAAKAIAIhRqIRYgASAUa0EDaiEXA0AgAS0AACAUQenCgIAAai0AAEcNywEgFEEDRg3OASAUQQFqIRQgAUEBaiIBIAJHDQALIAAgFjYCAAyDAwsCQCABIgEgAkcNAEHlACEQDIMDCyAAIAFBAWoiASACEKiAgIAAIhANzQEgASEBQdYAIRAM6QILAkAgASIBIAJGDQADQAJAIAEtAAAiEEEgRg0AAkACQAJAIBBBuH9qDgsAAc8BzwHPAc8BzwHPAc8BzwECzwELIAFBAWohAUHSACEQDO0CCyABQQFqIQFB0wAhEAzsAgsgAUEBaiEBQdQAIRAM6wILIAFBAWoiASACRw0AC0HkACEQDIIDC0HkACEQDIEDCwNAAkAgAS0AAEHwwoCAAGotAAAiEEEBRg0AIBBBfmoOA88B0AHRAdIBCyABQQFqIgEgAkcNAAtB5gAhEAyAAwsCQCABIgEgAkYNACABQQFqIQEMAwtB5wAhEAz/AgsDQAJAIAEtAABB8MSAgABqLQAAIhBBAUYNAAJAIBBBfmoOBNIB0wHUAQDVAQsgASEBQdcAIRAM5wILIAFBAWoiASACRw0AC0HoACEQDP4CCwJAIAEiASACRw0AQekAIRAM/gILAkAgAS0AACIQQXZqDhq6AdUB1QG8AdUB1QHVAdUB1QHVAdUB1QHVAdUB1QHVAdUB1QHVAdUB1QHVAcoB1QHVAQDTAQsgAUEBaiEBC0EGIRAM4wILA0ACQCABLQAAQfDGgIAAai0AAEEBRg0AIAEhAQyeAgsgAUEBaiIBIAJHDQALQeoAIRAM+wILAkAgASIBIAJGDQAgAUEBaiEBDAMLQesAIRAM+gILAkAgASIBIAJHDQBB7AAhEAz6AgsgAUEBaiEBDAELAkAgASIBIAJHDQBB7QAhEAz5AgsgAUEBaiEBC0EEIRAM3gILAkAgASIUIAJHDQBB7gAhEAz3AgsgFCEBAkACQAJAIBQtAABB8MiAgABqLQAAQX9qDgfUAdUB1gEAnAIBAtcBCyAUQQFqIQEMCgsgFEEBaiEBDM0BC0EAIRAgAEEANgIcIABBm5KAgAA2AhAgAEEHNgIMIAAgFEEBajYCFAz2AgsCQANAAkAgAS0AAEHwyICAAGotAAAiEEEERg0AAkACQCAQQX9qDgfSAdMB1AHZAQAEAdkBCyABIQFB2gAhEAzgAgsgAUEBaiEBQdwAIRAM3wILIAFBAWoiASACRw0AC0HvACEQDPYCCyABQQFqIQEMywELAkAgASIUIAJHDQBB8AAhEAz1AgsgFC0AAEEvRw3UASAUQQFqIQEMBgsCQCABIhQgAkcNAEHxACEQDPQCCwJAIBQtAAAiAUEvRw0AIBRBAWohAUHdACEQDNsCCyABQXZqIgRBFksN0wFBASAEdEGJgIACcUUN0wEMygILAkAgASIBIAJGDQAgAUEBaiEBQd4AIRAM2gILQfIAIRAM8gILAkAgASIUIAJHDQBB9AAhEAzyAgsgFCEBAkAgFC0AAEHwzICAAGotAABBf2oOA8kClAIA1AELQeEAIRAM2AILAkAgASIUIAJGDQADQAJAIBQtAABB8MqAgABqLQAAIgFBA0YNAAJAIAFBf2oOAssCANUBCyAUIQFB3wAhEAzaAgsgFEEBaiIUIAJHDQALQfMAIRAM8QILQfMAIRAM8AILAkAgASIBIAJGDQAgAEGPgICAADYCCCAAIAE2AgQgASEBQeAAIRAM1wILQfUAIRAM7wILAkAgASIBIAJHDQBB9gAhEAzvAgsgAEGPgICAADYCCCAAIAE2AgQgASEBC0EDIRAM1AILA0AgAS0AAEEgRw3DAiABQQFqIgEgAkcNAAtB9wAhEAzsAgsCQCABIgEgAkcNAEH4ACEQDOwCCyABLQAAQSBHDc4BIAFBAWohAQzvAQsgACABIgEgAhCsgICAACIQDc4BIAEhAQyOAgsCQCABIgQgAkcNAEH6ACEQDOoCCyAELQAAQcwARw3RASAEQQFqIQFBEyEQDM8BCwJAIAEiBCACRw0AQfsAIRAM6QILIAIgBGsgACgCACIBaiEUIAQgAWtBBWohEANAIAQtAAAgAUHwzoCAAGotAABHDdABIAFBBUYNzgEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBB+wAhEAzoAgsCQCABIgQgAkcNAEH8ACEQDOgCCwJAAkAgBC0AAEG9f2oODADRAdEB0QHRAdEB0QHRAdEB0QHRAQHRAQsgBEEBaiEBQeYAIRAMzwILIARBAWohAUHnACEQDM4CCwJAIAEiBCACRw0AQf0AIRAM5wILIAIgBGsgACgCACIBaiEUIAQgAWtBAmohEAJAA0AgBC0AACABQe3PgIAAai0AAEcNzwEgAUECRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQf0AIRAM5wILIABBADYCACAQQQFqIQFBECEQDMwBCwJAIAEiBCACRw0AQf4AIRAM5gILIAIgBGsgACgCACIBaiEUIAQgAWtBBWohEAJAA0AgBC0AACABQfbOgIAAai0AAEcNzgEgAUEFRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQf4AIRAM5gILIABBADYCACAQQQFqIQFBFiEQDMsBCwJAIAEiBCACRw0AQf8AIRAM5QILIAIgBGsgACgCACIBaiEUIAQgAWtBA2ohEAJAA0AgBC0AACABQfzOgIAAai0AAEcNzQEgAUEDRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQf8AIRAM5QILIABBADYCACAQQQFqIQFBBSEQDMoBCwJAIAEiBCACRw0AQYABIRAM5AILIAQtAABB2QBHDcsBIARBAWohAUEIIRAMyQELAkAgASIEIAJHDQBBgQEhEAzjAgsCQAJAIAQtAABBsn9qDgMAzAEBzAELIARBAWohAUHrACEQDMoCCyAEQQFqIQFB7AAhEAzJAgsCQCABIgQgAkcNAEGCASEQDOICCwJAAkAgBC0AAEG4f2oOCADLAcsBywHLAcsBywEBywELIARBAWohAUHqACEQDMkCCyAEQQFqIQFB7QAhEAzIAgsCQCABIgQgAkcNAEGDASEQDOECCyACIARrIAAoAgAiAWohECAEIAFrQQJqIRQCQANAIAQtAAAgAUGAz4CAAGotAABHDckBIAFBAkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgEDYCAEGDASEQDOECC0EAIRAgAEEANgIAIBRBAWohAQzGAQsCQCABIgQgAkcNAEGEASEQDOACCyACIARrIAAoAgAiAWohFCAEIAFrQQRqIRACQANAIAQtAAAgAUGDz4CAAGotAABHDcgBIAFBBEYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGEASEQDOACCyAAQQA2AgAgEEEBaiEBQSMhEAzFAQsCQCABIgQgAkcNAEGFASEQDN8CCwJAAkAgBC0AAEG0f2oOCADIAcgByAHIAcgByAEByAELIARBAWohAUHvACEQDMYCCyAEQQFqIQFB8AAhEAzFAgsCQCABIgQgAkcNAEGGASEQDN4CCyAELQAAQcUARw3FASAEQQFqIQEMgwILAkAgASIEIAJHDQBBhwEhEAzdAgsgAiAEayAAKAIAIgFqIRQgBCABa0EDaiEQAkADQCAELQAAIAFBiM+AgABqLQAARw3FASABQQNGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBhwEhEAzdAgsgAEEANgIAIBBBAWohAUEtIRAMwgELAkAgASIEIAJHDQBBiAEhEAzcAgsgAiAEayAAKAIAIgFqIRQgBCABa0EIaiEQAkADQCAELQAAIAFB0M+AgABqLQAARw3EASABQQhGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBiAEhEAzcAgsgAEEANgIAIBBBAWohAUEpIRAMwQELAkAgASIBIAJHDQBBiQEhEAzbAgtBASEQIAEtAABB3wBHDcABIAFBAWohAQyBAgsCQCABIgQgAkcNAEGKASEQDNoCCyACIARrIAAoAgAiAWohFCAEIAFrQQFqIRADQCAELQAAIAFBjM+AgABqLQAARw3BASABQQFGDa8CIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQYoBIRAM2QILAkAgASIEIAJHDQBBiwEhEAzZAgsgAiAEayAAKAIAIgFqIRQgBCABa0ECaiEQAkADQCAELQAAIAFBjs+AgABqLQAARw3BASABQQJGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBiwEhEAzZAgsgAEEANgIAIBBBAWohAUECIRAMvgELAkAgASIEIAJHDQBBjAEhEAzYAgsgAiAEayAAKAIAIgFqIRQgBCABa0EBaiEQAkADQCAELQAAIAFB8M+AgABqLQAARw3AASABQQFGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBjAEhEAzYAgsgAEEANgIAIBBBAWohAUEfIRAMvQELAkAgASIEIAJHDQBBjQEhEAzXAgsgAiAEayAAKAIAIgFqIRQgBCABa0EBaiEQAkADQCAELQAAIAFB8s+AgABqLQAARw2/ASABQQFGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBjQEhEAzXAgsgAEEANgIAIBBBAWohAUEJIRAMvAELAkAgASIEIAJHDQBBjgEhEAzWAgsCQAJAIAQtAABBt39qDgcAvwG/Ab8BvwG/AQG/AQsgBEEBaiEBQfgAIRAMvQILIARBAWohAUH5ACEQDLwCCwJAIAEiBCACRw0AQY8BIRAM1QILIAIgBGsgACgCACIBaiEUIAQgAWtBBWohEAJAA0AgBC0AACABQZHPgIAAai0AAEcNvQEgAUEFRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQY8BIRAM1QILIABBADYCACAQQQFqIQFBGCEQDLoBCwJAIAEiBCACRw0AQZABIRAM1AILIAIgBGsgACgCACIBaiEUIAQgAWtBAmohEAJAA0AgBC0AACABQZfPgIAAai0AAEcNvAEgAUECRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQZABIRAM1AILIABBADYCACAQQQFqIQFBFyEQDLkBCwJAIAEiBCACRw0AQZEBIRAM0wILIAIgBGsgACgCACIBaiEUIAQgAWtBBmohEAJAA0AgBC0AACABQZrPgIAAai0AAEcNuwEgAUEGRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQZEBIRAM0wILIABBADYCACAQQQFqIQFBFSEQDLgBCwJAIAEiBCACRw0AQZIBIRAM0gILIAIgBGsgACgCACIBaiEUIAQgAWtBBWohEAJAA0AgBC0AACABQaHPgIAAai0AAEcNugEgAUEFRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQZIBIRAM0gILIABBADYCACAQQQFqIQFBHiEQDLcBCwJAIAEiBCACRw0AQZMBIRAM0QILIAQtAABBzABHDbgBIARBAWohAUEKIRAMtgELAkAgBCACRw0AQZQBIRAM0AILAkACQCAELQAAQb9/ag4PALkBuQG5AbkBuQG5AbkBuQG5AbkBuQG5AbkBAbkBCyAEQQFqIQFB/gAhEAy3AgsgBEEBaiEBQf8AIRAMtgILAkAgBCACRw0AQZUBIRAMzwILAkACQCAELQAAQb9/ag4DALgBAbgBCyAEQQFqIQFB/QAhEAy2AgsgBEEBaiEEQYABIRAMtQILAkAgBCACRw0AQZYBIRAMzgILIAIgBGsgACgCACIBaiEUIAQgAWtBAWohEAJAA0AgBC0AACABQafPgIAAai0AAEcNtgEgAUEBRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQZYBIRAMzgILIABBADYCACAQQQFqIQFBCyEQDLMBCwJAIAQgAkcNAEGXASEQDM0CCwJAAkACQAJAIAQtAABBU2oOIwC4AbgBuAG4AbgBuAG4AbgBuAG4AbgBuAG4AbgBuAG4AbgBuAG4AbgBuAG4AbgBAbgBuAG4AbgBuAECuAG4AbgBA7gBCyAEQQFqIQFB+wAhEAy2AgsgBEEBaiEBQfwAIRAMtQILIARBAWohBEGBASEQDLQCCyAEQQFqIQRBggEhEAyzAgsCQCAEIAJHDQBBmAEhEAzMAgsgAiAEayAAKAIAIgFqIRQgBCABa0EEaiEQAkADQCAELQAAIAFBqc+AgABqLQAARw20ASABQQRGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBmAEhEAzMAgsgAEEANgIAIBBBAWohAUEZIRAMsQELAkAgBCACRw0AQZkBIRAMywILIAIgBGsgACgCACIBaiEUIAQgAWtBBWohEAJAA0AgBC0AACABQa7PgIAAai0AAEcNswEgAUEFRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQZkBIRAMywILIABBADYCACAQQQFqIQFBBiEQDLABCwJAIAQgAkcNAEGaASEQDMoCCyACIARrIAAoAgAiAWohFCAEIAFrQQFqIRACQANAIAQtAAAgAUG0z4CAAGotAABHDbIBIAFBAUYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGaASEQDMoCCyAAQQA2AgAgEEEBaiEBQRwhEAyvAQsCQCAEIAJHDQBBmwEhEAzJAgsgAiAEayAAKAIAIgFqIRQgBCABa0EBaiEQAkADQCAELQAAIAFBts+AgABqLQAARw2xASABQQFGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBmwEhEAzJAgsgAEEANgIAIBBBAWohAUEnIRAMrgELAkAgBCACRw0AQZwBIRAMyAILAkACQCAELQAAQax/ag4CAAGxAQsgBEEBaiEEQYYBIRAMrwILIARBAWohBEGHASEQDK4CCwJAIAQgAkcNAEGdASEQDMcCCyACIARrIAAoAgAiAWohFCAEIAFrQQFqIRACQANAIAQtAAAgAUG4z4CAAGotAABHDa8BIAFBAUYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGdASEQDMcCCyAAQQA2AgAgEEEBaiEBQSYhEAysAQsCQCAEIAJHDQBBngEhEAzGAgsgAiAEayAAKAIAIgFqIRQgBCABa0EBaiEQAkADQCAELQAAIAFBus+AgABqLQAARw2uASABQQFGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBngEhEAzGAgsgAEEANgIAIBBBAWohAUEDIRAMqwELAkAgBCACRw0AQZ8BIRAMxQILIAIgBGsgACgCACIBaiEUIAQgAWtBAmohEAJAA0AgBC0AACABQe3PgIAAai0AAEcNrQEgAUECRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQZ8BIRAMxQILIABBADYCACAQQQFqIQFBDCEQDKoBCwJAIAQgAkcNAEGgASEQDMQCCyACIARrIAAoAgAiAWohFCAEIAFrQQNqIRACQANAIAQtAAAgAUG8z4CAAGotAABHDawBIAFBA0YNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGgASEQDMQCCyAAQQA2AgAgEEEBaiEBQQ0hEAypAQsCQCAEIAJHDQBBoQEhEAzDAgsCQAJAIAQtAABBun9qDgsArAGsAawBrAGsAawBrAGsAawBAawBCyAEQQFqIQRBiwEhEAyqAgsgBEEBaiEEQYwBIRAMqQILAkAgBCACRw0AQaIBIRAMwgILIAQtAABB0ABHDakBIARBAWohBAzpAQsCQCAEIAJHDQBBowEhEAzBAgsCQAJAIAQtAABBt39qDgcBqgGqAaoBqgGqAQCqAQsgBEEBaiEEQY4BIRAMqAILIARBAWohAUEiIRAMpgELAkAgBCACRw0AQaQBIRAMwAILIAIgBGsgACgCACIBaiEUIAQgAWtBAWohEAJAA0AgBC0AACABQcDPgIAAai0AAEcNqAEgAUEBRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQaQBIRAMwAILIABBADYCACAQQQFqIQFBHSEQDKUBCwJAIAQgAkcNAEGlASEQDL8CCwJAAkAgBC0AAEGuf2oOAwCoAQGoAQsgBEEBaiEEQZABIRAMpgILIARBAWohAUEEIRAMpAELAkAgBCACRw0AQaYBIRAMvgILAkACQAJAAkACQCAELQAAQb9/ag4VAKoBqgGqAaoBqgGqAaoBqgGqAaoBAaoBqgECqgGqAQOqAaoBBKoBCyAEQQFqIQRBiAEhEAyoAgsgBEEBaiEEQYkBIRAMpwILIARBAWohBEGKASEQDKYCCyAEQQFqIQRBjwEhEAylAgsgBEEBaiEEQZEBIRAMpAILAkAgBCACRw0AQacBIRAMvQILIAIgBGsgACgCACIBaiEUIAQgAWtBAmohEAJAA0AgBC0AACABQe3PgIAAai0AAEcNpQEgAUECRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQacBIRAMvQILIABBADYCACAQQQFqIQFBESEQDKIBCwJAIAQgAkcNAEGoASEQDLwCCyACIARrIAAoAgAiAWohFCAEIAFrQQJqIRACQANAIAQtAAAgAUHCz4CAAGotAABHDaQBIAFBAkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGoASEQDLwCCyAAQQA2AgAgEEEBaiEBQSwhEAyhAQsCQCAEIAJHDQBBqQEhEAy7AgsgAiAEayAAKAIAIgFqIRQgBCABa0EEaiEQAkADQCAELQAAIAFBxc+AgABqLQAARw2jASABQQRGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBqQEhEAy7AgsgAEEANgIAIBBBAWohAUErIRAMoAELAkAgBCACRw0AQaoBIRAMugILIAIgBGsgACgCACIBaiEUIAQgAWtBAmohEAJAA0AgBC0AACABQcrPgIAAai0AAEcNogEgAUECRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQaoBIRAMugILIABBADYCACAQQQFqIQFBFCEQDJ8BCwJAIAQgAkcNAEGrASEQDLkCCwJAAkACQAJAIAQtAABBvn9qDg8AAQKkAaQBpAGkAaQBpAGkAaQBpAGkAaQBA6QBCyAEQQFqIQRBkwEhEAyiAgsgBEEBaiEEQZQBIRAMoQILIARBAWohBEGVASEQDKACCyAEQQFqIQRBlgEhEAyfAgsCQCAEIAJHDQBBrAEhEAy4AgsgBC0AAEHFAEcNnwEgBEEBaiEEDOABCwJAIAQgAkcNAEGtASEQDLcCCyACIARrIAAoAgAiAWohFCAEIAFrQQJqIRACQANAIAQtAAAgAUHNz4CAAGotAABHDZ8BIAFBAkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEGtASEQDLcCCyAAQQA2AgAgEEEBaiEBQQ4hEAycAQsCQCAEIAJHDQBBrgEhEAy2AgsgBC0AAEHQAEcNnQEgBEEBaiEBQSUhEAybAQsCQCAEIAJHDQBBrwEhEAy1AgsgAiAEayAAKAIAIgFqIRQgBCABa0EIaiEQAkADQCAELQAAIAFB0M+AgABqLQAARw2dASABQQhGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBrwEhEAy1AgsgAEEANgIAIBBBAWohAUEqIRAMmgELAkAgBCACRw0AQbABIRAMtAILAkACQCAELQAAQat/ag4LAJ0BnQGdAZ0BnQGdAZ0BnQGdAQGdAQsgBEEBaiEEQZoBIRAMmwILIARBAWohBEGbASEQDJoCCwJAIAQgAkcNAEGxASEQDLMCCwJAAkAgBC0AAEG/f2oOFACcAZwBnAGcAZwBnAGcAZwBnAGcAZwBnAGcAZwBnAGcAZwBnAEBnAELIARBAWohBEGZASEQDJoCCyAEQQFqIQRBnAEhEAyZAgsCQCAEIAJHDQBBsgEhEAyyAgsgAiAEayAAKAIAIgFqIRQgBCABa0EDaiEQAkADQCAELQAAIAFB2c+AgABqLQAARw2aASABQQNGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBsgEhEAyyAgsgAEEANgIAIBBBAWohAUEhIRAMlwELAkAgBCACRw0AQbMBIRAMsQILIAIgBGsgACgCACIBaiEUIAQgAWtBBmohEAJAA0AgBC0AACABQd3PgIAAai0AAEcNmQEgAUEGRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQbMBIRAMsQILIABBADYCACAQQQFqIQFBGiEQDJYBCwJAIAQgAkcNAEG0ASEQDLACCwJAAkACQCAELQAAQbt/ag4RAJoBmgGaAZoBmgGaAZoBmgGaAQGaAZoBmgGaAZoBApoBCyAEQQFqIQRBnQEhEAyYAgsgBEEBaiEEQZ4BIRAMlwILIARBAWohBEGfASEQDJYCCwJAIAQgAkcNAEG1ASEQDK8CCyACIARrIAAoAgAiAWohFCAEIAFrQQVqIRACQANAIAQtAAAgAUHkz4CAAGotAABHDZcBIAFBBUYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEG1ASEQDK8CCyAAQQA2AgAgEEEBaiEBQSghEAyUAQsCQCAEIAJHDQBBtgEhEAyuAgsgAiAEayAAKAIAIgFqIRQgBCABa0ECaiEQAkADQCAELQAAIAFB6s+AgABqLQAARw2WASABQQJGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBtgEhEAyuAgsgAEEANgIAIBBBAWohAUEHIRAMkwELAkAgBCACRw0AQbcBIRAMrQILAkACQCAELQAAQbt/ag4OAJYBlgGWAZYBlgGWAZYBlgGWAZYBlgGWAQGWAQsgBEEBaiEEQaEBIRAMlAILIARBAWohBEGiASEQDJMCCwJAIAQgAkcNAEG4ASEQDKwCCyACIARrIAAoAgAiAWohFCAEIAFrQQJqIRACQANAIAQtAAAgAUHtz4CAAGotAABHDZQBIAFBAkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgFDYCAEG4ASEQDKwCCyAAQQA2AgAgEEEBaiEBQRIhEAyRAQsCQCAEIAJHDQBBuQEhEAyrAgsgAiAEayAAKAIAIgFqIRQgBCABa0EBaiEQAkADQCAELQAAIAFB8M+AgABqLQAARw2TASABQQFGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIBQ2AgBBuQEhEAyrAgsgAEEANgIAIBBBAWohAUEgIRAMkAELAkAgBCACRw0AQboBIRAMqgILIAIgBGsgACgCACIBaiEUIAQgAWtBAWohEAJAA0AgBC0AACABQfLPgIAAai0AAEcNkgEgAUEBRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQboBIRAMqgILIABBADYCACAQQQFqIQFBDyEQDI8BCwJAIAQgAkcNAEG7ASEQDKkCCwJAAkAgBC0AAEG3f2oOBwCSAZIBkgGSAZIBAZIBCyAEQQFqIQRBpQEhEAyQAgsgBEEBaiEEQaYBIRAMjwILAkAgBCACRw0AQbwBIRAMqAILIAIgBGsgACgCACIBaiEUIAQgAWtBB2ohEAJAA0AgBC0AACABQfTPgIAAai0AAEcNkAEgAUEHRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAUNgIAQbwBIRAMqAILIABBADYCACAQQQFqIQFBGyEQDI0BCwJAIAQgAkcNAEG9ASEQDKcCCwJAAkACQCAELQAAQb5/ag4SAJEBkQGRAZEBkQGRAZEBkQGRAQGRAZEBkQGRAZEBkQECkQELIARBAWohBEGkASEQDI8CCyAEQQFqIQRBpwEhEAyOAgsgBEEBaiEEQagBIRAMjQILAkAgBCACRw0AQb4BIRAMpgILIAQtAABBzgBHDY0BIARBAWohBAzPAQsCQCAEIAJHDQBBvwEhEAylAgsCQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCAELQAAQb9/ag4VAAECA5wBBAUGnAGcAZwBBwgJCgucAQwNDg+cAQsgBEEBaiEBQegAIRAMmgILIARBAWohAUHpACEQDJkCCyAEQQFqIQFB7gAhEAyYAgsgBEEBaiEBQfIAIRAMlwILIARBAWohAUHzACEQDJYCCyAEQQFqIQFB9gAhEAyVAgsgBEEBaiEBQfcAIRAMlAILIARBAWohAUH6ACEQDJMCCyAEQQFqIQRBgwEhEAySAgsgBEEBaiEEQYQBIRAMkQILIARBAWohBEGFASEQDJACCyAEQQFqIQRBkgEhEAyPAgsgBEEBaiEEQZgBIRAMjgILIARBAWohBEGgASEQDI0CCyAEQQFqIQRBowEhEAyMAgsgBEEBaiEEQaoBIRAMiwILAkAgBCACRg0AIABBkICAgAA2AgggACAENgIEQasBIRAMiwILQcABIRAMowILIAAgBSACEKqAgIAAIgENiwEgBSEBDFwLAkAgBiACRg0AIAZBAWohBQyNAQtBwgEhEAyhAgsDQAJAIBAtAABBdmoOBIwBAACPAQALIBBBAWoiECACRw0AC0HDASEQDKACCwJAIAcgAkYNACAAQZGAgIAANgIIIAAgBzYCBCAHIQFBASEQDIcCC0HEASEQDJ8CCwJAIAcgAkcNAEHFASEQDJ8CCwJAAkAgBy0AAEF2ag4EAc4BzgEAzgELIAdBAWohBgyNAQsgB0EBaiEFDIkBCwJAIAcgAkcNAEHGASEQDJ4CCwJAAkAgBy0AAEF2ag4XAY8BjwEBjwGPAY8BjwGPAY8BjwGPAY8BjwGPAY8BjwGPAY8BjwGPAY8BAI8BCyAHQQFqIQcLQbABIRAMhAILAkAgCCACRw0AQcgBIRAMnQILIAgtAABBIEcNjQEgAEEAOwEyIAhBAWohAUGzASEQDIMCCyABIRcCQANAIBciByACRg0BIActAABBUGpB/wFxIhBBCk8NzAECQCAALwEyIhRBmTNLDQAgACAUQQpsIhQ7ATIgEEH//wNzIBRB/v8DcUkNACAHQQFqIRcgACAUIBBqIhA7ATIgEEH//wNxQegHSQ0BCwtBACEQIABBADYCHCAAQcGJgIAANgIQIABBDTYCDCAAIAdBAWo2AhQMnAILQccBIRAMmwILIAAgCCACEK6AgIAAIhBFDcoBIBBBFUcNjAEgAEHIATYCHCAAIAg2AhQgAEHJl4CAADYCECAAQRU2AgxBACEQDJoCCwJAIAkgAkcNAEHMASEQDJoCC0EAIRRBASEXQQEhFkEAIRACQAJAAkACQAJAAkACQAJAAkAgCS0AAEFQag4KlgGVAQABAgMEBQYIlwELQQIhEAwGC0EDIRAMBQtBBCEQDAQLQQUhEAwDC0EGIRAMAgtBByEQDAELQQghEAtBACEXQQAhFkEAIRQMjgELQQkhEEEBIRRBACEXQQAhFgyNAQsCQCAKIAJHDQBBzgEhEAyZAgsgCi0AAEEuRw2OASAKQQFqIQkMygELIAsgAkcNjgFB0AEhEAyXAgsCQCALIAJGDQAgAEGOgICAADYCCCAAIAs2AgRBtwEhEAz+AQtB0QEhEAyWAgsCQCAEIAJHDQBB0gEhEAyWAgsgAiAEayAAKAIAIhBqIRQgBCAQa0EEaiELA0AgBC0AACAQQfzPgIAAai0AAEcNjgEgEEEERg3pASAQQQFqIRAgBEEBaiIEIAJHDQALIAAgFDYCAEHSASEQDJUCCyAAIAwgAhCsgICAACIBDY0BIAwhAQy4AQsCQCAEIAJHDQBB1AEhEAyUAgsgAiAEayAAKAIAIhBqIRQgBCAQa0EBaiEMA0AgBC0AACAQQYHQgIAAai0AAEcNjwEgEEEBRg2OASAQQQFqIRAgBEEBaiIEIAJHDQALIAAgFDYCAEHUASEQDJMCCwJAIAQgAkcNAEHWASEQDJMCCyACIARrIAAoAgAiEGohFCAEIBBrQQJqIQsDQCAELQAAIBBBg9CAgABqLQAARw2OASAQQQJGDZABIBBBAWohECAEQQFqIgQgAkcNAAsgACAUNgIAQdYBIRAMkgILAkAgBCACRw0AQdcBIRAMkgILAkACQCAELQAAQbt/ag4QAI8BjwGPAY8BjwGPAY8BjwGPAY8BjwGPAY8BjwEBjwELIARBAWohBEG7ASEQDPkBCyAEQQFqIQRBvAEhEAz4AQsCQCAEIAJHDQBB2AEhEAyRAgsgBC0AAEHIAEcNjAEgBEEBaiEEDMQBCwJAIAQgAkYNACAAQZCAgIAANgIIIAAgBDYCBEG+ASEQDPcBC0HZASEQDI8CCwJAIAQgAkcNAEHaASEQDI8CCyAELQAAQcgARg3DASAAQQE6ACgMuQELIABBAjoALyAAIAQgAhCmgICAACIQDY0BQcIBIRAM9AELIAAtAChBf2oOArcBuQG4AQsDQAJAIAQtAABBdmoOBACOAY4BAI4BCyAEQQFqIgQgAkcNAAtB3QEhEAyLAgsgAEEAOgAvIAAtAC1BBHFFDYQCCyAAQQA6AC8gAEEBOgA0IAEhAQyMAQsgEEEVRg3aASAAQQA2AhwgACABNgIUIABBp46AgAA2AhAgAEESNgIMQQAhEAyIAgsCQCAAIBAgAhC0gICAACIEDQAgECEBDIECCwJAIARBFUcNACAAQQM2AhwgACAQNgIUIABBsJiAgAA2AhAgAEEVNgIMQQAhEAyIAgsgAEEANgIcIAAgEDYCFCAAQaeOgIAANgIQIABBEjYCDEEAIRAMhwILIBBBFUYN1gEgAEEANgIcIAAgATYCFCAAQdqNgIAANgIQIABBFDYCDEEAIRAMhgILIAAoAgQhFyAAQQA2AgQgECARp2oiFiEBIAAgFyAQIBYgFBsiEBC1gICAACIURQ2NASAAQQc2AhwgACAQNgIUIAAgFDYCDEEAIRAMhQILIAAgAC8BMEGAAXI7ATAgASEBC0EqIRAM6gELIBBBFUYN0QEgAEEANgIcIAAgATYCFCAAQYOMgIAANgIQIABBEzYCDEEAIRAMggILIBBBFUYNzwEgAEEANgIcIAAgATYCFCAAQZqPgIAANgIQIABBIjYCDEEAIRAMgQILIAAoAgQhECAAQQA2AgQCQCAAIBAgARC3gICAACIQDQAgAUEBaiEBDI0BCyAAQQw2AhwgACAQNgIMIAAgAUEBajYCFEEAIRAMgAILIBBBFUYNzAEgAEEANgIcIAAgATYCFCAAQZqPgIAANgIQIABBIjYCDEEAIRAM/wELIAAoAgQhECAAQQA2AgQCQCAAIBAgARC3gICAACIQDQAgAUEBaiEBDIwBCyAAQQ02AhwgACAQNgIMIAAgAUEBajYCFEEAIRAM/gELIBBBFUYNyQEgAEEANgIcIAAgATYCFCAAQcaMgIAANgIQIABBIzYCDEEAIRAM/QELIAAoAgQhECAAQQA2AgQCQCAAIBAgARC5gICAACIQDQAgAUEBaiEBDIsBCyAAQQ42AhwgACAQNgIMIAAgAUEBajYCFEEAIRAM/AELIABBADYCHCAAIAE2AhQgAEHAlYCAADYCECAAQQI2AgxBACEQDPsBCyAQQRVGDcUBIABBADYCHCAAIAE2AhQgAEHGjICAADYCECAAQSM2AgxBACEQDPoBCyAAQRA2AhwgACABNgIUIAAgEDYCDEEAIRAM+QELIAAoAgQhBCAAQQA2AgQCQCAAIAQgARC5gICAACIEDQAgAUEBaiEBDPEBCyAAQRE2AhwgACAENgIMIAAgAUEBajYCFEEAIRAM+AELIBBBFUYNwQEgAEEANgIcIAAgATYCFCAAQcaMgIAANgIQIABBIzYCDEEAIRAM9wELIAAoAgQhECAAQQA2AgQCQCAAIBAgARC5gICAACIQDQAgAUEBaiEBDIgBCyAAQRM2AhwgACAQNgIMIAAgAUEBajYCFEEAIRAM9gELIAAoAgQhBCAAQQA2AgQCQCAAIAQgARC5gICAACIEDQAgAUEBaiEBDO0BCyAAQRQ2AhwgACAENgIMIAAgAUEBajYCFEEAIRAM9QELIBBBFUYNvQEgAEEANgIcIAAgATYCFCAAQZqPgIAANgIQIABBIjYCDEEAIRAM9AELIAAoAgQhECAAQQA2AgQCQCAAIBAgARC3gICAACIQDQAgAUEBaiEBDIYBCyAAQRY2AhwgACAQNgIMIAAgAUEBajYCFEEAIRAM8wELIAAoAgQhBCAAQQA2AgQCQCAAIAQgARC3gICAACIEDQAgAUEBaiEBDOkBCyAAQRc2AhwgACAENgIMIAAgAUEBajYCFEEAIRAM8gELIABBADYCHCAAIAE2AhQgAEHNk4CAADYCECAAQQw2AgxBACEQDPEBC0IBIRELIBBBAWohAQJAIAApAyAiEkL//////////w9WDQAgACASQgSGIBGENwMgIAEhAQyEAQsgAEEANgIcIAAgATYCFCAAQa2JgIAANgIQIABBDDYCDEEAIRAM7wELIABBADYCHCAAIBA2AhQgAEHNk4CAADYCECAAQQw2AgxBACEQDO4BCyAAKAIEIRcgAEEANgIEIBAgEadqIhYhASAAIBcgECAWIBQbIhAQtYCAgAAiFEUNcyAAQQU2AhwgACAQNgIUIAAgFDYCDEEAIRAM7QELIABBADYCHCAAIBA2AhQgAEGqnICAADYCECAAQQ82AgxBACEQDOwBCyAAIBAgAhC0gICAACIBDQEgECEBC0EOIRAM0QELAkAgAUEVRw0AIABBAjYCHCAAIBA2AhQgAEGwmICAADYCECAAQRU2AgxBACEQDOoBCyAAQQA2AhwgACAQNgIUIABBp46AgAA2AhAgAEESNgIMQQAhEAzpAQsgAUEBaiEQAkAgAC8BMCIBQYABcUUNAAJAIAAgECACELuAgIAAIgENACAQIQEMcAsgAUEVRw26ASAAQQU2AhwgACAQNgIUIABB+ZeAgAA2AhAgAEEVNgIMQQAhEAzpAQsCQCABQaAEcUGgBEcNACAALQAtQQJxDQAgAEEANgIcIAAgEDYCFCAAQZaTgIAANgIQIABBBDYCDEEAIRAM6QELIAAgECACEL2AgIAAGiAQIQECQAJAAkACQAJAIAAgECACELOAgIAADhYCAQAEBAQEBAQEBAQEBAQEBAQEBAQDBAsgAEEBOgAuCyAAIAAvATBBwAByOwEwIBAhAQtBJiEQDNEBCyAAQSM2AhwgACAQNgIUIABBpZaAgAA2AhAgAEEVNgIMQQAhEAzpAQsgAEEANgIcIAAgEDYCFCAAQdWLgIAANgIQIABBETYCDEEAIRAM6AELIAAtAC1BAXFFDQFBwwEhEAzOAQsCQCANIAJGDQADQAJAIA0tAABBIEYNACANIQEMxAELIA1BAWoiDSACRw0AC0ElIRAM5wELQSUhEAzmAQsgACgCBCEEIABBADYCBCAAIAQgDRCvgICAACIERQ2tASAAQSY2AhwgACAENgIMIAAgDUEBajYCFEEAIRAM5QELIBBBFUYNqwEgAEEANgIcIAAgATYCFCAAQf2NgIAANgIQIABBHTYCDEEAIRAM5AELIABBJzYCHCAAIAE2AhQgACAQNgIMQQAhEAzjAQsgECEBQQEhFAJAAkACQAJAAkACQAJAIAAtACxBfmoOBwYFBQMBAgAFCyAAIAAvATBBCHI7ATAMAwtBAiEUDAELQQQhFAsgAEEBOgAsIAAgAC8BMCAUcjsBMAsgECEBC0ErIRAMygELIABBADYCHCAAIBA2AhQgAEGrkoCAADYCECAAQQs2AgxBACEQDOIBCyAAQQA2AhwgACABNgIUIABB4Y+AgAA2AhAgAEEKNgIMQQAhEAzhAQsgAEEAOgAsIBAhAQy9AQsgECEBQQEhFAJAAkACQAJAAkAgAC0ALEF7ag4EAwECAAULIAAgAC8BMEEIcjsBMAwDC0ECIRQMAQtBBCEUCyAAQQE6ACwgACAALwEwIBRyOwEwCyAQIQELQSkhEAzFAQsgAEEANgIcIAAgATYCFCAAQfCUgIAANgIQIABBAzYCDEEAIRAM3QELAkAgDi0AAEENRw0AIAAoAgQhASAAQQA2AgQCQCAAIAEgDhCxgICAACIBDQAgDkEBaiEBDHULIABBLDYCHCAAIAE2AgwgACAOQQFqNgIUQQAhEAzdAQsgAC0ALUEBcUUNAUHEASEQDMMBCwJAIA4gAkcNAEEtIRAM3AELAkACQANAAkAgDi0AAEF2ag4EAgAAAwALIA5BAWoiDiACRw0AC0EtIRAM3QELIAAoAgQhASAAQQA2AgQCQCAAIAEgDhCxgICAACIBDQAgDiEBDHQLIABBLDYCHCAAIA42AhQgACABNgIMQQAhEAzcAQsgACgCBCEBIABBADYCBAJAIAAgASAOELGAgIAAIgENACAOQQFqIQEMcwsgAEEsNgIcIAAgATYCDCAAIA5BAWo2AhRBACEQDNsBCyAAKAIEIQQgAEEANgIEIAAgBCAOELGAgIAAIgQNoAEgDiEBDM4BCyAQQSxHDQEgAUEBaiEQQQEhAQJAAkACQAJAAkAgAC0ALEF7ag4EAwECBAALIBAhAQwEC0ECIQEMAQtBBCEBCyAAQQE6ACwgACAALwEwIAFyOwEwIBAhAQwBCyAAIAAvATBBCHI7ATAgECEBC0E5IRAMvwELIABBADoALCABIQELQTQhEAy9AQsgACAALwEwQSByOwEwIAEhAQwCCyAAKAIEIQQgAEEANgIEAkAgACAEIAEQsYCAgAAiBA0AIAEhAQzHAQsgAEE3NgIcIAAgATYCFCAAIAQ2AgxBACEQDNQBCyAAQQg6ACwgASEBC0EwIRAMuQELAkAgAC0AKEEBRg0AIAEhAQwECyAALQAtQQhxRQ2TASABIQEMAwsgAC0AMEEgcQ2UAUHFASEQDLcBCwJAIA8gAkYNAAJAA0ACQCAPLQAAQVBqIgFB/wFxQQpJDQAgDyEBQTUhEAy6AQsgACkDICIRQpmz5syZs+bMGVYNASAAIBFCCn4iETcDICARIAGtQv8BgyISQn+FVg0BIAAgESASfDcDICAPQQFqIg8gAkcNAAtBOSEQDNEBCyAAKAIEIQIgAEEANgIEIAAgAiAPQQFqIgQQsYCAgAAiAg2VASAEIQEMwwELQTkhEAzPAQsCQCAALwEwIgFBCHFFDQAgAC0AKEEBRw0AIAAtAC1BCHFFDZABCyAAIAFB9/sDcUGABHI7ATAgDyEBC0E3IRAMtAELIAAgAC8BMEEQcjsBMAyrAQsgEEEVRg2LASAAQQA2AhwgACABNgIUIABB8I6AgAA2AhAgAEEcNgIMQQAhEAzLAQsgAEHDADYCHCAAIAE2AgwgACANQQFqNgIUQQAhEAzKAQsCQCABLQAAQTpHDQAgACgCBCEQIABBADYCBAJAIAAgECABEK+AgIAAIhANACABQQFqIQEMYwsgAEHDADYCHCAAIBA2AgwgACABQQFqNgIUQQAhEAzKAQsgAEEANgIcIAAgATYCFCAAQbGRgIAANgIQIABBCjYCDEEAIRAMyQELIABBADYCHCAAIAE2AhQgAEGgmYCAADYCECAAQR42AgxBACEQDMgBCyAAQQA2AgALIABBgBI7ASogACAXQQFqIgEgAhCogICAACIQDQEgASEBC0HHACEQDKwBCyAQQRVHDYMBIABB0QA2AhwgACABNgIUIABB45eAgAA2AhAgAEEVNgIMQQAhEAzEAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMXgsgAEHSADYCHCAAIAE2AhQgACAQNgIMQQAhEAzDAQsgAEEANgIcIAAgFDYCFCAAQcGogIAANgIQIABBBzYCDCAAQQA2AgBBACEQDMIBCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxdCyAAQdMANgIcIAAgATYCFCAAIBA2AgxBACEQDMEBC0EAIRAgAEEANgIcIAAgATYCFCAAQYCRgIAANgIQIABBCTYCDAzAAQsgEEEVRg19IABBADYCHCAAIAE2AhQgAEGUjYCAADYCECAAQSE2AgxBACEQDL8BC0EBIRZBACEXQQAhFEEBIRALIAAgEDoAKyABQQFqIQECQAJAIAAtAC1BEHENAAJAAkACQCAALQAqDgMBAAIECyAWRQ0DDAILIBQNAQwCCyAXRQ0BCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQrYCAgAAiEA0AIAEhAQxcCyAAQdgANgIcIAAgATYCFCAAIBA2AgxBACEQDL4BCyAAKAIEIQQgAEEANgIEAkAgACAEIAEQrYCAgAAiBA0AIAEhAQytAQsgAEHZADYCHCAAIAE2AhQgACAENgIMQQAhEAy9AQsgACgCBCEEIABBADYCBAJAIAAgBCABEK2AgIAAIgQNACABIQEMqwELIABB2gA2AhwgACABNgIUIAAgBDYCDEEAIRAMvAELIAAoAgQhBCAAQQA2AgQCQCAAIAQgARCtgICAACIEDQAgASEBDKkBCyAAQdwANgIcIAAgATYCFCAAIAQ2AgxBACEQDLsBCwJAIAEtAABBUGoiEEH/AXFBCk8NACAAIBA6ACogAUEBaiEBQc8AIRAMogELIAAoAgQhBCAAQQA2AgQCQCAAIAQgARCtgICAACIEDQAgASEBDKcBCyAAQd4ANgIcIAAgATYCFCAAIAQ2AgxBACEQDLoBCyAAQQA2AgAgF0EBaiEBAkAgAC0AKUEjTw0AIAEhAQxZCyAAQQA2AhwgACABNgIUIABB04mAgAA2AhAgAEEINgIMQQAhEAy5AQsgAEEANgIAC0EAIRAgAEEANgIcIAAgATYCFCAAQZCzgIAANgIQIABBCDYCDAy3AQsgAEEANgIAIBdBAWohAQJAIAAtAClBIUcNACABIQEMVgsgAEEANgIcIAAgATYCFCAAQZuKgIAANgIQIABBCDYCDEEAIRAMtgELIABBADYCACAXQQFqIQECQCAALQApIhBBXWpBC08NACABIQEMVQsCQCAQQQZLDQBBASAQdEHKAHFFDQAgASEBDFULQQAhECAAQQA2AhwgACABNgIUIABB94mAgAA2AhAgAEEINgIMDLUBCyAQQRVGDXEgAEEANgIcIAAgATYCFCAAQbmNgIAANgIQIABBGjYCDEEAIRAMtAELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDFQLIABB5QA2AhwgACABNgIUIAAgEDYCDEEAIRAMswELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDE0LIABB0gA2AhwgACABNgIUIAAgEDYCDEEAIRAMsgELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDE0LIABB0wA2AhwgACABNgIUIAAgEDYCDEEAIRAMsQELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDFELIABB5QA2AhwgACABNgIUIAAgEDYCDEEAIRAMsAELIABBADYCHCAAIAE2AhQgAEHGioCAADYCECAAQQc2AgxBACEQDK8BCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxJCyAAQdIANgIcIAAgATYCFCAAIBA2AgxBACEQDK4BCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxJCyAAQdMANgIcIAAgATYCFCAAIBA2AgxBACEQDK0BCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxNCyAAQeUANgIcIAAgATYCFCAAIBA2AgxBACEQDKwBCyAAQQA2AhwgACABNgIUIABB3IiAgAA2AhAgAEEHNgIMQQAhEAyrAQsgEEE/Rw0BIAFBAWohAQtBBSEQDJABC0EAIRAgAEEANgIcIAAgATYCFCAAQf2SgIAANgIQIABBBzYCDAyoAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMQgsgAEHSADYCHCAAIAE2AhQgACAQNgIMQQAhEAynAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMQgsgAEHTADYCHCAAIAE2AhQgACAQNgIMQQAhEAymAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMRgsgAEHlADYCHCAAIAE2AhQgACAQNgIMQQAhEAylAQsgACgCBCEBIABBADYCBAJAIAAgASAUEKeAgIAAIgENACAUIQEMPwsgAEHSADYCHCAAIBQ2AhQgACABNgIMQQAhEAykAQsgACgCBCEBIABBADYCBAJAIAAgASAUEKeAgIAAIgENACAUIQEMPwsgAEHTADYCHCAAIBQ2AhQgACABNgIMQQAhEAyjAQsgACgCBCEBIABBADYCBAJAIAAgASAUEKeAgIAAIgENACAUIQEMQwsgAEHlADYCHCAAIBQ2AhQgACABNgIMQQAhEAyiAQsgAEEANgIcIAAgFDYCFCAAQcOPgIAANgIQIABBBzYCDEEAIRAMoQELIABBADYCHCAAIAE2AhQgAEHDj4CAADYCECAAQQc2AgxBACEQDKABC0EAIRAgAEEANgIcIAAgFDYCFCAAQYycgIAANgIQIABBBzYCDAyfAQsgAEEANgIcIAAgFDYCFCAAQYycgIAANgIQIABBBzYCDEEAIRAMngELIABBADYCHCAAIBQ2AhQgAEH+kYCAADYCECAAQQc2AgxBACEQDJ0BCyAAQQA2AhwgACABNgIUIABBjpuAgAA2AhAgAEEGNgIMQQAhEAycAQsgEEEVRg1XIABBADYCHCAAIAE2AhQgAEHMjoCAADYCECAAQSA2AgxBACEQDJsBCyAAQQA2AgAgEEEBaiEBQSQhEAsgACAQOgApIAAoAgQhECAAQQA2AgQgACAQIAEQq4CAgAAiEA1UIAEhAQw+CyAAQQA2AgALQQAhECAAQQA2AhwgACAENgIUIABB8ZuAgAA2AhAgAEEGNgIMDJcBCyABQRVGDVAgAEEANgIcIAAgBTYCFCAAQfCMgIAANgIQIABBGzYCDEEAIRAMlgELIAAoAgQhBSAAQQA2AgQgACAFIBAQqYCAgAAiBQ0BIBBBAWohBQtBrQEhEAx7CyAAQcEBNgIcIAAgBTYCDCAAIBBBAWo2AhRBACEQDJMBCyAAKAIEIQYgAEEANgIEIAAgBiAQEKmAgIAAIgYNASAQQQFqIQYLQa4BIRAMeAsgAEHCATYCHCAAIAY2AgwgACAQQQFqNgIUQQAhEAyQAQsgAEEANgIcIAAgBzYCFCAAQZeLgIAANgIQIABBDTYCDEEAIRAMjwELIABBADYCHCAAIAg2AhQgAEHjkICAADYCECAAQQk2AgxBACEQDI4BCyAAQQA2AhwgACAINgIUIABBlI2AgAA2AhAgAEEhNgIMQQAhEAyNAQtBASEWQQAhF0EAIRRBASEQCyAAIBA6ACsgCUEBaiEIAkACQCAALQAtQRBxDQACQAJAAkAgAC0AKg4DAQACBAsgFkUNAwwCCyAUDQEMAgsgF0UNAQsgACgCBCEQIABBADYCBCAAIBAgCBCtgICAACIQRQ09IABByQE2AhwgACAINgIUIAAgEDYCDEEAIRAMjAELIAAoAgQhBCAAQQA2AgQgACAEIAgQrYCAgAAiBEUNdiAAQcoBNgIcIAAgCDYCFCAAIAQ2AgxBACEQDIsBCyAAKAIEIQQgAEEANgIEIAAgBCAJEK2AgIAAIgRFDXQgAEHLATYCHCAAIAk2AhQgACAENgIMQQAhEAyKAQsgACgCBCEEIABBADYCBCAAIAQgChCtgICAACIERQ1yIABBzQE2AhwgACAKNgIUIAAgBDYCDEEAIRAMiQELAkAgCy0AAEFQaiIQQf8BcUEKTw0AIAAgEDoAKiALQQFqIQpBtgEhEAxwCyAAKAIEIQQgAEEANgIEIAAgBCALEK2AgIAAIgRFDXAgAEHPATYCHCAAIAs2AhQgACAENgIMQQAhEAyIAQsgAEEANgIcIAAgBDYCFCAAQZCzgIAANgIQIABBCDYCDCAAQQA2AgBBACEQDIcBCyABQRVGDT8gAEEANgIcIAAgDDYCFCAAQcyOgIAANgIQIABBIDYCDEEAIRAMhgELIABBgQQ7ASggACgCBCEQIABCADcDACAAIBAgDEEBaiIMEKuAgIAAIhBFDTggAEHTATYCHCAAIAw2AhQgACAQNgIMQQAhEAyFAQsgAEEANgIAC0EAIRAgAEEANgIcIAAgBDYCFCAAQdibgIAANgIQIABBCDYCDAyDAQsgACgCBCEQIABCADcDACAAIBAgC0EBaiILEKuAgIAAIhANAUHGASEQDGkLIABBAjoAKAxVCyAAQdUBNgIcIAAgCzYCFCAAIBA2AgxBACEQDIABCyAQQRVGDTcgAEEANgIcIAAgBDYCFCAAQaSMgIAANgIQIABBEDYCDEEAIRAMfwsgAC0ANEEBRw00IAAgBCACELyAgIAAIhBFDTQgEEEVRw01IABB3AE2AhwgACAENgIUIABB1ZaAgAA2AhAgAEEVNgIMQQAhEAx+C0EAIRAgAEEANgIcIABBr4uAgAA2AhAgAEECNgIMIAAgFEEBajYCFAx9C0EAIRAMYwtBAiEQDGILQQ0hEAxhC0EPIRAMYAtBJSEQDF8LQRMhEAxeC0EVIRAMXQtBFiEQDFwLQRchEAxbC0EYIRAMWgtBGSEQDFkLQRohEAxYC0EbIRAMVwtBHCEQDFYLQR0hEAxVC0EfIRAMVAtBISEQDFMLQSMhEAxSC0HGACEQDFELQS4hEAxQC0EvIRAMTwtBOyEQDE4LQT0hEAxNC0HIACEQDEwLQckAIRAMSwtBywAhEAxKC0HMACEQDEkLQc4AIRAMSAtB0QAhEAxHC0HVACEQDEYLQdgAIRAMRQtB2QAhEAxEC0HbACEQDEMLQeQAIRAMQgtB5QAhEAxBC0HxACEQDEALQfQAIRAMPwtBjQEhEAw+C0GXASEQDD0LQakBIRAMPAtBrAEhEAw7C0HAASEQDDoLQbkBIRAMOQtBrwEhEAw4C0GxASEQDDcLQbIBIRAMNgtBtAEhEAw1C0G1ASEQDDQLQboBIRAMMwtBvQEhEAwyC0G/ASEQDDELQcEBIRAMMAsgAEEANgIcIAAgBDYCFCAAQemLgIAANgIQIABBHzYCDEEAIRAMSAsgAEHbATYCHCAAIAQ2AhQgAEH6loCAADYCECAAQRU2AgxBACEQDEcLIABB+AA2AhwgACAMNgIUIABBypiAgAA2AhAgAEEVNgIMQQAhEAxGCyAAQdEANgIcIAAgBTYCFCAAQbCXgIAANgIQIABBFTYCDEEAIRAMRQsgAEH5ADYCHCAAIAE2AhQgACAQNgIMQQAhEAxECyAAQfgANgIcIAAgATYCFCAAQcqYgIAANgIQIABBFTYCDEEAIRAMQwsgAEHkADYCHCAAIAE2AhQgAEHjl4CAADYCECAAQRU2AgxBACEQDEILIABB1wA2AhwgACABNgIUIABByZeAgAA2AhAgAEEVNgIMQQAhEAxBCyAAQQA2AhwgACABNgIUIABBuY2AgAA2AhAgAEEaNgIMQQAhEAxACyAAQcIANgIcIAAgATYCFCAAQeOYgIAANgIQIABBFTYCDEEAIRAMPwsgAEEANgIEIAAgDyAPELGAgIAAIgRFDQEgAEE6NgIcIAAgBDYCDCAAIA9BAWo2AhRBACEQDD4LIAAoAgQhBCAAQQA2AgQCQCAAIAQgARCxgICAACIERQ0AIABBOzYCHCAAIAQ2AgwgACABQQFqNgIUQQAhEAw+CyABQQFqIQEMLQsgD0EBaiEBDC0LIABBADYCHCAAIA82AhQgAEHkkoCAADYCECAAQQQ2AgxBACEQDDsLIABBNjYCHCAAIAQ2AhQgACACNgIMQQAhEAw6CyAAQS42AhwgACAONgIUIAAgBDYCDEEAIRAMOQsgAEHQADYCHCAAIAE2AhQgAEGRmICAADYCECAAQRU2AgxBACEQDDgLIA1BAWohAQwsCyAAQRU2AhwgACABNgIUIABBgpmAgAA2AhAgAEEVNgIMQQAhEAw2CyAAQRs2AhwgACABNgIUIABBkZeAgAA2AhAgAEEVNgIMQQAhEAw1CyAAQQ82AhwgACABNgIUIABBkZeAgAA2AhAgAEEVNgIMQQAhEAw0CyAAQQs2AhwgACABNgIUIABBkZeAgAA2AhAgAEEVNgIMQQAhEAwzCyAAQRo2AhwgACABNgIUIABBgpmAgAA2AhAgAEEVNgIMQQAhEAwyCyAAQQs2AhwgACABNgIUIABBgpmAgAA2AhAgAEEVNgIMQQAhEAwxCyAAQQo2AhwgACABNgIUIABB5JaAgAA2AhAgAEEVNgIMQQAhEAwwCyAAQR42AhwgACABNgIUIABB+ZeAgAA2AhAgAEEVNgIMQQAhEAwvCyAAQQA2AhwgACAQNgIUIABB2o2AgAA2AhAgAEEUNgIMQQAhEAwuCyAAQQQ2AhwgACABNgIUIABBsJiAgAA2AhAgAEEVNgIMQQAhEAwtCyAAQQA2AgAgC0EBaiELC0G4ASEQDBILIABBADYCACAQQQFqIQFB9QAhEAwRCyABIQECQCAALQApQQVHDQBB4wAhEAwRC0HiACEQDBALQQAhECAAQQA2AhwgAEHkkYCAADYCECAAQQc2AgwgACAUQQFqNgIUDCgLIABBADYCACAXQQFqIQFBwAAhEAwOC0EBIQELIAAgAToALCAAQQA2AgAgF0EBaiEBC0EoIRAMCwsgASEBC0E4IRAMCQsCQCABIg8gAkYNAANAAkAgDy0AAEGAvoCAAGotAAAiAUEBRg0AIAFBAkcNAyAPQQFqIQEMBAsgD0EBaiIPIAJHDQALQT4hEAwiC0E+IRAMIQsgAEEAOgAsIA8hAQwBC0ELIRAMBgtBOiEQDAULIAFBAWohAUEtIRAMBAsgACABOgAsIABBADYCACAWQQFqIQFBDCEQDAMLIABBADYCACAXQQFqIQFBCiEQDAILIABBADYCAAsgAEEAOgAsIA0hAUEJIRAMAAsLQQAhECAAQQA2AhwgACALNgIUIABBzZCAgAA2AhAgAEEJNgIMDBcLQQAhECAAQQA2AhwgACAKNgIUIABB6YqAgAA2AhAgAEEJNgIMDBYLQQAhECAAQQA2AhwgACAJNgIUIABBt5CAgAA2AhAgAEEJNgIMDBULQQAhECAAQQA2AhwgACAINgIUIABBnJGAgAA2AhAgAEEJNgIMDBQLQQAhECAAQQA2AhwgACABNgIUIABBzZCAgAA2AhAgAEEJNgIMDBMLQQAhECAAQQA2AhwgACABNgIUIABB6YqAgAA2AhAgAEEJNgIMDBILQQAhECAAQQA2AhwgACABNgIUIABBt5CAgAA2AhAgAEEJNgIMDBELQQAhECAAQQA2AhwgACABNgIUIABBnJGAgAA2AhAgAEEJNgIMDBALQQAhECAAQQA2AhwgACABNgIUIABBl5WAgAA2AhAgAEEPNgIMDA8LQQAhECAAQQA2AhwgACABNgIUIABBl5WAgAA2AhAgAEEPNgIMDA4LQQAhECAAQQA2AhwgACABNgIUIABBwJKAgAA2AhAgAEELNgIMDA0LQQAhECAAQQA2AhwgACABNgIUIABBlYmAgAA2AhAgAEELNgIMDAwLQQAhECAAQQA2AhwgACABNgIUIABB4Y+AgAA2AhAgAEEKNgIMDAsLQQAhECAAQQA2AhwgACABNgIUIABB+4+AgAA2AhAgAEEKNgIMDAoLQQAhECAAQQA2AhwgACABNgIUIABB8ZmAgAA2AhAgAEECNgIMDAkLQQAhECAAQQA2AhwgACABNgIUIABBxJSAgAA2AhAgAEECNgIMDAgLQQAhECAAQQA2AhwgACABNgIUIABB8pWAgAA2AhAgAEECNgIMDAcLIABBAjYCHCAAIAE2AhQgAEGcmoCAADYCECAAQRY2AgxBACEQDAYLQQEhEAwFC0HUACEQIAEiBCACRg0EIANBCGogACAEIAJB2MKAgABBChDFgICAACADKAIMIQQgAygCCA4DAQQCAAsQyoCAgAAACyAAQQA2AhwgAEG1moCAADYCECAAQRc2AgwgACAEQQFqNgIUQQAhEAwCCyAAQQA2AhwgACAENgIUIABBypqAgAA2AhAgAEEJNgIMQQAhEAwBCwJAIAEiBCACRw0AQSIhEAwBCyAAQYmAgIAANgIIIAAgBDYCBEEhIRALIANBEGokgICAgAAgEAuvAQECfyABKAIAIQYCQAJAIAIgA0YNACAEIAZqIQQgBiADaiACayEHIAIgBkF/cyAFaiIGaiEFA0ACQCACLQAAIAQtAABGDQBBAiEEDAMLAkAgBg0AQQAhBCAFIQIMAwsgBkF/aiEGIARBAWohBCACQQFqIgIgA0cNAAsgByEGIAMhAgsgAEEBNgIAIAEgBjYCACAAIAI2AgQPCyABQQA2AgAgACAENgIAIAAgAjYCBAsKACAAEMeAgIAAC/I2AQt/I4CAgIAAQRBrIgEkgICAgAACQEEAKAKg0ICAAA0AQQAQy4CAgABBgNSEgABrIgJB2QBJDQBBACEDAkBBACgC4NOAgAAiBA0AQQBCfzcC7NOAgABBAEKAgISAgIDAADcC5NOAgABBACABQQhqQXBxQdiq1aoFcyIENgLg04CAAEEAQQA2AvTTgIAAQQBBADYCxNOAgAALQQAgAjYCzNOAgABBAEGA1ISAADYCyNOAgABBAEGA1ISAADYCmNCAgABBACAENgKs0ICAAEEAQX82AqjQgIAAA0AgA0HE0ICAAGogA0G40ICAAGoiBDYCACAEIANBsNCAgABqIgU2AgAgA0G80ICAAGogBTYCACADQczQgIAAaiADQcDQgIAAaiIFNgIAIAUgBDYCACADQdTQgIAAaiADQcjQgIAAaiIENgIAIAQgBTYCACADQdDQgIAAaiAENgIAIANBIGoiA0GAAkcNAAtBgNSEgABBeEGA1ISAAGtBD3FBAEGA1ISAAEEIakEPcRsiA2oiBEEEaiACQUhqIgUgA2siA0EBcjYCAEEAQQAoAvDTgIAANgKk0ICAAEEAIAM2ApTQgIAAQQAgBDYCoNCAgABBgNSEgAAgBWpBODYCBAsCQAJAAkACQAJAAkACQAJAAkACQAJAAkAgAEHsAUsNAAJAQQAoAojQgIAAIgZBECAAQRNqQXBxIABBC0kbIgJBA3YiBHYiA0EDcUUNAAJAAkAgA0EBcSAEckEBcyIFQQN0IgRBsNCAgABqIgMgBEG40ICAAGooAgAiBCgCCCICRw0AQQAgBkF+IAV3cTYCiNCAgAAMAQsgAyACNgIIIAIgAzYCDAsgBEEIaiEDIAQgBUEDdCIFQQNyNgIEIAQgBWoiBCAEKAIEQQFyNgIEDAwLIAJBACgCkNCAgAAiB00NAQJAIANFDQACQAJAIAMgBHRBAiAEdCIDQQAgA2tycSIDQQAgA2txQX9qIgMgA0EMdkEQcSIDdiIEQQV2QQhxIgUgA3IgBCAFdiIDQQJ2QQRxIgRyIAMgBHYiA0EBdkECcSIEciADIAR2IgNBAXZBAXEiBHIgAyAEdmoiBEEDdCIDQbDQgIAAaiIFIANBuNCAgABqKAIAIgMoAggiAEcNAEEAIAZBfiAEd3EiBjYCiNCAgAAMAQsgBSAANgIIIAAgBTYCDAsgAyACQQNyNgIEIAMgBEEDdCIEaiAEIAJrIgU2AgAgAyACaiIAIAVBAXI2AgQCQCAHRQ0AIAdBeHFBsNCAgABqIQJBACgCnNCAgAAhBAJAAkAgBkEBIAdBA3Z0IghxDQBBACAGIAhyNgKI0ICAACACIQgMAQsgAigCCCEICyAIIAQ2AgwgAiAENgIIIAQgAjYCDCAEIAg2AggLIANBCGohA0EAIAA2ApzQgIAAQQAgBTYCkNCAgAAMDAtBACgCjNCAgAAiCUUNASAJQQAgCWtxQX9qIgMgA0EMdkEQcSIDdiIEQQV2QQhxIgUgA3IgBCAFdiIDQQJ2QQRxIgRyIAMgBHYiA0EBdkECcSIEciADIAR2IgNBAXZBAXEiBHIgAyAEdmpBAnRBuNKAgABqKAIAIgAoAgRBeHEgAmshBCAAIQUCQANAAkAgBSgCECIDDQAgBUEUaigCACIDRQ0CCyADKAIEQXhxIAJrIgUgBCAFIARJIgUbIQQgAyAAIAUbIQAgAyEFDAALCyAAKAIYIQoCQCAAKAIMIgggAEYNACAAKAIIIgNBACgCmNCAgABJGiAIIAM2AgggAyAINgIMDAsLAkAgAEEUaiIFKAIAIgMNACAAKAIQIgNFDQMgAEEQaiEFCwNAIAUhCyADIghBFGoiBSgCACIDDQAgCEEQaiEFIAgoAhAiAw0ACyALQQA2AgAMCgtBfyECIABBv39LDQAgAEETaiIDQXBxIQJBACgCjNCAgAAiB0UNAEEAIQsCQCACQYACSQ0AQR8hCyACQf///wdLDQAgA0EIdiIDIANBgP4/akEQdkEIcSIDdCIEIARBgOAfakEQdkEEcSIEdCIFIAVBgIAPakEQdkECcSIFdEEPdiADIARyIAVyayIDQQF0IAIgA0EVanZBAXFyQRxqIQsLQQAgAmshBAJAAkACQAJAIAtBAnRBuNKAgABqKAIAIgUNAEEAIQNBACEIDAELQQAhAyACQQBBGSALQQF2ayALQR9GG3QhAEEAIQgDQAJAIAUoAgRBeHEgAmsiBiAETw0AIAYhBCAFIQggBg0AQQAhBCAFIQggBSEDDAMLIAMgBUEUaigCACIGIAYgBSAAQR12QQRxakEQaigCACIFRhsgAyAGGyEDIABBAXQhACAFDQALCwJAIAMgCHINAEEAIQhBAiALdCIDQQAgA2tyIAdxIgNFDQMgA0EAIANrcUF/aiIDIANBDHZBEHEiA3YiBUEFdkEIcSIAIANyIAUgAHYiA0ECdkEEcSIFciADIAV2IgNBAXZBAnEiBXIgAyAFdiIDQQF2QQFxIgVyIAMgBXZqQQJ0QbjSgIAAaigCACEDCyADRQ0BCwNAIAMoAgRBeHEgAmsiBiAESSEAAkAgAygCECIFDQAgA0EUaigCACEFCyAGIAQgABshBCADIAggABshCCAFIQMgBQ0ACwsgCEUNACAEQQAoApDQgIAAIAJrTw0AIAgoAhghCwJAIAgoAgwiACAIRg0AIAgoAggiA0EAKAKY0ICAAEkaIAAgAzYCCCADIAA2AgwMCQsCQCAIQRRqIgUoAgAiAw0AIAgoAhAiA0UNAyAIQRBqIQULA0AgBSEGIAMiAEEUaiIFKAIAIgMNACAAQRBqIQUgACgCECIDDQALIAZBADYCAAwICwJAQQAoApDQgIAAIgMgAkkNAEEAKAKc0ICAACEEAkACQCADIAJrIgVBEEkNACAEIAJqIgAgBUEBcjYCBEEAIAU2ApDQgIAAQQAgADYCnNCAgAAgBCADaiAFNgIAIAQgAkEDcjYCBAwBCyAEIANBA3I2AgQgBCADaiIDIAMoAgRBAXI2AgRBAEEANgKc0ICAAEEAQQA2ApDQgIAACyAEQQhqIQMMCgsCQEEAKAKU0ICAACIAIAJNDQBBACgCoNCAgAAiAyACaiIEIAAgAmsiBUEBcjYCBEEAIAU2ApTQgIAAQQAgBDYCoNCAgAAgAyACQQNyNgIEIANBCGohAwwKCwJAAkBBACgC4NOAgABFDQBBACgC6NOAgAAhBAwBC0EAQn83AuzTgIAAQQBCgICEgICAwAA3AuTTgIAAQQAgAUEMakFwcUHYqtWqBXM2AuDTgIAAQQBBADYC9NOAgABBAEEANgLE04CAAEGAgAQhBAtBACEDAkAgBCACQccAaiIHaiIGQQAgBGsiC3EiCCACSw0AQQBBMDYC+NOAgAAMCgsCQEEAKALA04CAACIDRQ0AAkBBACgCuNOAgAAiBCAIaiIFIARNDQAgBSADTQ0BC0EAIQNBAEEwNgL404CAAAwKC0EALQDE04CAAEEEcQ0EAkACQAJAQQAoAqDQgIAAIgRFDQBByNOAgAAhAwNAAkAgAygCACIFIARLDQAgBSADKAIEaiAESw0DCyADKAIIIgMNAAsLQQAQy4CAgAAiAEF/Rg0FIAghBgJAQQAoAuTTgIAAIgNBf2oiBCAAcUUNACAIIABrIAQgAGpBACADa3FqIQYLIAYgAk0NBSAGQf7///8HSw0FAkBBACgCwNOAgAAiA0UNAEEAKAK404CAACIEIAZqIgUgBE0NBiAFIANLDQYLIAYQy4CAgAAiAyAARw0BDAcLIAYgAGsgC3EiBkH+////B0sNBCAGEMuAgIAAIgAgAygCACADKAIEakYNAyAAIQMLAkAgA0F/Rg0AIAJByABqIAZNDQACQCAHIAZrQQAoAujTgIAAIgRqQQAgBGtxIgRB/v///wdNDQAgAyEADAcLAkAgBBDLgICAAEF/Rg0AIAQgBmohBiADIQAMBwtBACAGaxDLgICAABoMBAsgAyEAIANBf0cNBQwDC0EAIQgMBwtBACEADAULIABBf0cNAgtBAEEAKALE04CAAEEEcjYCxNOAgAALIAhB/v///wdLDQEgCBDLgICAACEAQQAQy4CAgAAhAyAAQX9GDQEgA0F/Rg0BIAAgA08NASADIABrIgYgAkE4ak0NAQtBAEEAKAK404CAACAGaiIDNgK404CAAAJAIANBACgCvNOAgABNDQBBACADNgK804CAAAsCQAJAAkACQEEAKAKg0ICAACIERQ0AQcjTgIAAIQMDQCAAIAMoAgAiBSADKAIEIghqRg0CIAMoAggiAw0ADAMLCwJAAkBBACgCmNCAgAAiA0UNACAAIANPDQELQQAgADYCmNCAgAALQQAhA0EAIAY2AszTgIAAQQAgADYCyNOAgABBAEF/NgKo0ICAAEEAQQAoAuDTgIAANgKs0ICAAEEAQQA2AtTTgIAAA0AgA0HE0ICAAGogA0G40ICAAGoiBDYCACAEIANBsNCAgABqIgU2AgAgA0G80ICAAGogBTYCACADQczQgIAAaiADQcDQgIAAaiIFNgIAIAUgBDYCACADQdTQgIAAaiADQcjQgIAAaiIENgIAIAQgBTYCACADQdDQgIAAaiAENgIAIANBIGoiA0GAAkcNAAsgAEF4IABrQQ9xQQAgAEEIakEPcRsiA2oiBCAGQUhqIgUgA2siA0EBcjYCBEEAQQAoAvDTgIAANgKk0ICAAEEAIAM2ApTQgIAAQQAgBDYCoNCAgAAgACAFakE4NgIEDAILIAMtAAxBCHENACAEIAVJDQAgBCAATw0AIARBeCAEa0EPcUEAIARBCGpBD3EbIgVqIgBBACgClNCAgAAgBmoiCyAFayIFQQFyNgIEIAMgCCAGajYCBEEAQQAoAvDTgIAANgKk0ICAAEEAIAU2ApTQgIAAQQAgADYCoNCAgAAgBCALakE4NgIEDAELAkAgAEEAKAKY0ICAACIITw0AQQAgADYCmNCAgAAgACEICyAAIAZqIQVByNOAgAAhAwJAAkACQAJAAkACQAJAA0AgAygCACAFRg0BIAMoAggiAw0ADAILCyADLQAMQQhxRQ0BC0HI04CAACEDA0ACQCADKAIAIgUgBEsNACAFIAMoAgRqIgUgBEsNAwsgAygCCCEDDAALCyADIAA2AgAgAyADKAIEIAZqNgIEIABBeCAAa0EPcUEAIABBCGpBD3EbaiILIAJBA3I2AgQgBUF4IAVrQQ9xQQAgBUEIakEPcRtqIgYgCyACaiICayEDAkAgBiAERw0AQQAgAjYCoNCAgABBAEEAKAKU0ICAACADaiIDNgKU0ICAACACIANBAXI2AgQMAwsCQCAGQQAoApzQgIAARw0AQQAgAjYCnNCAgABBAEEAKAKQ0ICAACADaiIDNgKQ0ICAACACIANBAXI2AgQgAiADaiADNgIADAMLAkAgBigCBCIEQQNxQQFHDQAgBEF4cSEHAkACQCAEQf8BSw0AIAYoAggiBSAEQQN2IghBA3RBsNCAgABqIgBGGgJAIAYoAgwiBCAFRw0AQQBBACgCiNCAgABBfiAId3E2AojQgIAADAILIAQgAEYaIAQgBTYCCCAFIAQ2AgwMAQsgBigCGCEJAkACQCAGKAIMIgAgBkYNACAGKAIIIgQgCEkaIAAgBDYCCCAEIAA2AgwMAQsCQCAGQRRqIgQoAgAiBQ0AIAZBEGoiBCgCACIFDQBBACEADAELA0AgBCEIIAUiAEEUaiIEKAIAIgUNACAAQRBqIQQgACgCECIFDQALIAhBADYCAAsgCUUNAAJAAkAgBiAGKAIcIgVBAnRBuNKAgABqIgQoAgBHDQAgBCAANgIAIAANAUEAQQAoAozQgIAAQX4gBXdxNgKM0ICAAAwCCyAJQRBBFCAJKAIQIAZGG2ogADYCACAARQ0BCyAAIAk2AhgCQCAGKAIQIgRFDQAgACAENgIQIAQgADYCGAsgBigCFCIERQ0AIABBFGogBDYCACAEIAA2AhgLIAcgA2ohAyAGIAdqIgYoAgQhBAsgBiAEQX5xNgIEIAIgA2ogAzYCACACIANBAXI2AgQCQCADQf8BSw0AIANBeHFBsNCAgABqIQQCQAJAQQAoAojQgIAAIgVBASADQQN2dCIDcQ0AQQAgBSADcjYCiNCAgAAgBCEDDAELIAQoAgghAwsgAyACNgIMIAQgAjYCCCACIAQ2AgwgAiADNgIIDAMLQR8hBAJAIANB////B0sNACADQQh2IgQgBEGA/j9qQRB2QQhxIgR0IgUgBUGA4B9qQRB2QQRxIgV0IgAgAEGAgA9qQRB2QQJxIgB0QQ92IAQgBXIgAHJrIgRBAXQgAyAEQRVqdkEBcXJBHGohBAsgAiAENgIcIAJCADcCECAEQQJ0QbjSgIAAaiEFAkBBACgCjNCAgAAiAEEBIAR0IghxDQAgBSACNgIAQQAgACAIcjYCjNCAgAAgAiAFNgIYIAIgAjYCCCACIAI2AgwMAwsgA0EAQRkgBEEBdmsgBEEfRht0IQQgBSgCACEAA0AgACIFKAIEQXhxIANGDQIgBEEddiEAIARBAXQhBCAFIABBBHFqQRBqIggoAgAiAA0ACyAIIAI2AgAgAiAFNgIYIAIgAjYCDCACIAI2AggMAgsgAEF4IABrQQ9xQQAgAEEIakEPcRsiA2oiCyAGQUhqIgggA2siA0EBcjYCBCAAIAhqQTg2AgQgBCAFQTcgBWtBD3FBACAFQUlqQQ9xG2pBQWoiCCAIIARBEGpJGyIIQSM2AgRBAEEAKALw04CAADYCpNCAgABBACADNgKU0ICAAEEAIAs2AqDQgIAAIAhBEGpBACkC0NOAgAA3AgAgCEEAKQLI04CAADcCCEEAIAhBCGo2AtDTgIAAQQAgBjYCzNOAgABBACAANgLI04CAAEEAQQA2AtTTgIAAIAhBJGohAwNAIANBBzYCACADQQRqIgMgBUkNAAsgCCAERg0DIAggCCgCBEF+cTYCBCAIIAggBGsiADYCACAEIABBAXI2AgQCQCAAQf8BSw0AIABBeHFBsNCAgABqIQMCQAJAQQAoAojQgIAAIgVBASAAQQN2dCIAcQ0AQQAgBSAAcjYCiNCAgAAgAyEFDAELIAMoAgghBQsgBSAENgIMIAMgBDYCCCAEIAM2AgwgBCAFNgIIDAQLQR8hAwJAIABB////B0sNACAAQQh2IgMgA0GA/j9qQRB2QQhxIgN0IgUgBUGA4B9qQRB2QQRxIgV0IgggCEGAgA9qQRB2QQJxIgh0QQ92IAMgBXIgCHJrIgNBAXQgACADQRVqdkEBcXJBHGohAwsgBCADNgIcIARCADcCECADQQJ0QbjSgIAAaiEFAkBBACgCjNCAgAAiCEEBIAN0IgZxDQAgBSAENgIAQQAgCCAGcjYCjNCAgAAgBCAFNgIYIAQgBDYCCCAEIAQ2AgwMBAsgAEEAQRkgA0EBdmsgA0EfRht0IQMgBSgCACEIA0AgCCIFKAIEQXhxIABGDQMgA0EddiEIIANBAXQhAyAFIAhBBHFqQRBqIgYoAgAiCA0ACyAGIAQ2AgAgBCAFNgIYIAQgBDYCDCAEIAQ2AggMAwsgBSgCCCIDIAI2AgwgBSACNgIIIAJBADYCGCACIAU2AgwgAiADNgIICyALQQhqIQMMBQsgBSgCCCIDIAQ2AgwgBSAENgIIIARBADYCGCAEIAU2AgwgBCADNgIIC0EAKAKU0ICAACIDIAJNDQBBACgCoNCAgAAiBCACaiIFIAMgAmsiA0EBcjYCBEEAIAM2ApTQgIAAQQAgBTYCoNCAgAAgBCACQQNyNgIEIARBCGohAwwDC0EAIQNBAEEwNgL404CAAAwCCwJAIAtFDQACQAJAIAggCCgCHCIFQQJ0QbjSgIAAaiIDKAIARw0AIAMgADYCACAADQFBACAHQX4gBXdxIgc2AozQgIAADAILIAtBEEEUIAsoAhAgCEYbaiAANgIAIABFDQELIAAgCzYCGAJAIAgoAhAiA0UNACAAIAM2AhAgAyAANgIYCyAIQRRqKAIAIgNFDQAgAEEUaiADNgIAIAMgADYCGAsCQAJAIARBD0sNACAIIAQgAmoiA0EDcjYCBCAIIANqIgMgAygCBEEBcjYCBAwBCyAIIAJqIgAgBEEBcjYCBCAIIAJBA3I2AgQgACAEaiAENgIAAkAgBEH/AUsNACAEQXhxQbDQgIAAaiEDAkACQEEAKAKI0ICAACIFQQEgBEEDdnQiBHENAEEAIAUgBHI2AojQgIAAIAMhBAwBCyADKAIIIQQLIAQgADYCDCADIAA2AgggACADNgIMIAAgBDYCCAwBC0EfIQMCQCAEQf///wdLDQAgBEEIdiIDIANBgP4/akEQdkEIcSIDdCIFIAVBgOAfakEQdkEEcSIFdCICIAJBgIAPakEQdkECcSICdEEPdiADIAVyIAJyayIDQQF0IAQgA0EVanZBAXFyQRxqIQMLIAAgAzYCHCAAQgA3AhAgA0ECdEG40oCAAGohBQJAIAdBASADdCICcQ0AIAUgADYCAEEAIAcgAnI2AozQgIAAIAAgBTYCGCAAIAA2AgggACAANgIMDAELIARBAEEZIANBAXZrIANBH0YbdCEDIAUoAgAhAgJAA0AgAiIFKAIEQXhxIARGDQEgA0EddiECIANBAXQhAyAFIAJBBHFqQRBqIgYoAgAiAg0ACyAGIAA2AgAgACAFNgIYIAAgADYCDCAAIAA2AggMAQsgBSgCCCIDIAA2AgwgBSAANgIIIABBADYCGCAAIAU2AgwgACADNgIICyAIQQhqIQMMAQsCQCAKRQ0AAkACQCAAIAAoAhwiBUECdEG40oCAAGoiAygCAEcNACADIAg2AgAgCA0BQQAgCUF+IAV3cTYCjNCAgAAMAgsgCkEQQRQgCigCECAARhtqIAg2AgAgCEUNAQsgCCAKNgIYAkAgACgCECIDRQ0AIAggAzYCECADIAg2AhgLIABBFGooAgAiA0UNACAIQRRqIAM2AgAgAyAINgIYCwJAAkAgBEEPSw0AIAAgBCACaiIDQQNyNgIEIAAgA2oiAyADKAIEQQFyNgIEDAELIAAgAmoiBSAEQQFyNgIEIAAgAkEDcjYCBCAFIARqIAQ2AgACQCAHRQ0AIAdBeHFBsNCAgABqIQJBACgCnNCAgAAhAwJAAkBBASAHQQN2dCIIIAZxDQBBACAIIAZyNgKI0ICAACACIQgMAQsgAigCCCEICyAIIAM2AgwgAiADNgIIIAMgAjYCDCADIAg2AggLQQAgBTYCnNCAgABBACAENgKQ0ICAAAsgAEEIaiEDCyABQRBqJICAgIAAIAMLCgAgABDJgICAAAviDQEHfwJAIABFDQAgAEF4aiIBIABBfGooAgAiAkF4cSIAaiEDAkAgAkEBcQ0AIAJBA3FFDQEgASABKAIAIgJrIgFBACgCmNCAgAAiBEkNASACIABqIQACQCABQQAoApzQgIAARg0AAkAgAkH/AUsNACABKAIIIgQgAkEDdiIFQQN0QbDQgIAAaiIGRhoCQCABKAIMIgIgBEcNAEEAQQAoAojQgIAAQX4gBXdxNgKI0ICAAAwDCyACIAZGGiACIAQ2AgggBCACNgIMDAILIAEoAhghBwJAAkAgASgCDCIGIAFGDQAgASgCCCICIARJGiAGIAI2AgggAiAGNgIMDAELAkAgAUEUaiICKAIAIgQNACABQRBqIgIoAgAiBA0AQQAhBgwBCwNAIAIhBSAEIgZBFGoiAigCACIEDQAgBkEQaiECIAYoAhAiBA0ACyAFQQA2AgALIAdFDQECQAJAIAEgASgCHCIEQQJ0QbjSgIAAaiICKAIARw0AIAIgBjYCACAGDQFBAEEAKAKM0ICAAEF+IAR3cTYCjNCAgAAMAwsgB0EQQRQgBygCECABRhtqIAY2AgAgBkUNAgsgBiAHNgIYAkAgASgCECICRQ0AIAYgAjYCECACIAY2AhgLIAEoAhQiAkUNASAGQRRqIAI2AgAgAiAGNgIYDAELIAMoAgQiAkEDcUEDRw0AIAMgAkF+cTYCBEEAIAA2ApDQgIAAIAEgAGogADYCACABIABBAXI2AgQPCyABIANPDQAgAygCBCICQQFxRQ0AAkACQCACQQJxDQACQCADQQAoAqDQgIAARw0AQQAgATYCoNCAgABBAEEAKAKU0ICAACAAaiIANgKU0ICAACABIABBAXI2AgQgAUEAKAKc0ICAAEcNA0EAQQA2ApDQgIAAQQBBADYCnNCAgAAPCwJAIANBACgCnNCAgABHDQBBACABNgKc0ICAAEEAQQAoApDQgIAAIABqIgA2ApDQgIAAIAEgAEEBcjYCBCABIABqIAA2AgAPCyACQXhxIABqIQACQAJAIAJB/wFLDQAgAygCCCIEIAJBA3YiBUEDdEGw0ICAAGoiBkYaAkAgAygCDCICIARHDQBBAEEAKAKI0ICAAEF+IAV3cTYCiNCAgAAMAgsgAiAGRhogAiAENgIIIAQgAjYCDAwBCyADKAIYIQcCQAJAIAMoAgwiBiADRg0AIAMoAggiAkEAKAKY0ICAAEkaIAYgAjYCCCACIAY2AgwMAQsCQCADQRRqIgIoAgAiBA0AIANBEGoiAigCACIEDQBBACEGDAELA0AgAiEFIAQiBkEUaiICKAIAIgQNACAGQRBqIQIgBigCECIEDQALIAVBADYCAAsgB0UNAAJAAkAgAyADKAIcIgRBAnRBuNKAgABqIgIoAgBHDQAgAiAGNgIAIAYNAUEAQQAoAozQgIAAQX4gBHdxNgKM0ICAAAwCCyAHQRBBFCAHKAIQIANGG2ogBjYCACAGRQ0BCyAGIAc2AhgCQCADKAIQIgJFDQAgBiACNgIQIAIgBjYCGAsgAygCFCICRQ0AIAZBFGogAjYCACACIAY2AhgLIAEgAGogADYCACABIABBAXI2AgQgAUEAKAKc0ICAAEcNAUEAIAA2ApDQgIAADwsgAyACQX5xNgIEIAEgAGogADYCACABIABBAXI2AgQLAkAgAEH/AUsNACAAQXhxQbDQgIAAaiECAkACQEEAKAKI0ICAACIEQQEgAEEDdnQiAHENAEEAIAQgAHI2AojQgIAAIAIhAAwBCyACKAIIIQALIAAgATYCDCACIAE2AgggASACNgIMIAEgADYCCA8LQR8hAgJAIABB////B0sNACAAQQh2IgIgAkGA/j9qQRB2QQhxIgJ0IgQgBEGA4B9qQRB2QQRxIgR0IgYgBkGAgA9qQRB2QQJxIgZ0QQ92IAIgBHIgBnJrIgJBAXQgACACQRVqdkEBcXJBHGohAgsgASACNgIcIAFCADcCECACQQJ0QbjSgIAAaiEEAkACQEEAKAKM0ICAACIGQQEgAnQiA3ENACAEIAE2AgBBACAGIANyNgKM0ICAACABIAQ2AhggASABNgIIIAEgATYCDAwBCyAAQQBBGSACQQF2ayACQR9GG3QhAiAEKAIAIQYCQANAIAYiBCgCBEF4cSAARg0BIAJBHXYhBiACQQF0IQIgBCAGQQRxakEQaiIDKAIAIgYNAAsgAyABNgIAIAEgBDYCGCABIAE2AgwgASABNgIIDAELIAQoAggiACABNgIMIAQgATYCCCABQQA2AhggASAENgIMIAEgADYCCAtBAEEAKAKo0ICAAEF/aiIBQX8gARs2AqjQgIAACwsEAAAAC04AAkAgAA0APwBBEHQPCwJAIABB//8DcQ0AIABBf0wNAAJAIABBEHZAACIAQX9HDQBBAEEwNgL404CAAEF/DwsgAEEQdA8LEMqAgIAAAAvyAgIDfwF+AkAgAkUNACAAIAE6AAAgAiAAaiIDQX9qIAE6AAAgAkEDSQ0AIAAgAToAAiAAIAE6AAEgA0F9aiABOgAAIANBfmogAToAACACQQdJDQAgACABOgADIANBfGogAToAACACQQlJDQAgAEEAIABrQQNxIgRqIgMgAUH/AXFBgYKECGwiATYCACADIAIgBGtBfHEiBGoiAkF8aiABNgIAIARBCUkNACADIAE2AgggAyABNgIEIAJBeGogATYCACACQXRqIAE2AgAgBEEZSQ0AIAMgATYCGCADIAE2AhQgAyABNgIQIAMgATYCDCACQXBqIAE2AgAgAkFsaiABNgIAIAJBaGogATYCACACQWRqIAE2AgAgBCADQQRxQRhyIgVrIgJBIEkNACABrUKBgICAEH4hBiADIAVqIQEDQCABIAY3AxggASAGNwMQIAEgBjcDCCABIAY3AwAgAUEgaiEBIAJBYGoiAkEfSw0ACwsgAAsLjkgBAEGACAuGSAEAAAACAAAAAwAAAAAAAAAAAAAABAAAAAUAAAAAAAAAAAAAAAYAAAAHAAAACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASW52YWxpZCBjaGFyIGluIHVybCBxdWVyeQBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX2JvZHkAQ29udGVudC1MZW5ndGggb3ZlcmZsb3cAQ2h1bmsgc2l6ZSBvdmVyZmxvdwBSZXNwb25zZSBvdmVyZmxvdwBJbnZhbGlkIG1ldGhvZCBmb3IgSFRUUC94LnggcmVxdWVzdABJbnZhbGlkIG1ldGhvZCBmb3IgUlRTUC94LnggcmVxdWVzdABFeHBlY3RlZCBTT1VSQ0UgbWV0aG9kIGZvciBJQ0UveC54IHJlcXVlc3QASW52YWxpZCBjaGFyIGluIHVybCBmcmFnbWVudCBzdGFydABFeHBlY3RlZCBkb3QAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9zdGF0dXMASW52YWxpZCByZXNwb25zZSBzdGF0dXMASW52YWxpZCBjaGFyYWN0ZXIgaW4gY2h1bmsgZXh0ZW5zaW9ucwBVc2VyIGNhbGxiYWNrIGVycm9yAGBvbl9yZXNldGAgY2FsbGJhY2sgZXJyb3IAYG9uX2NodW5rX2hlYWRlcmAgY2FsbGJhY2sgZXJyb3IAYG9uX21lc3NhZ2VfYmVnaW5gIGNhbGxiYWNrIGVycm9yAGBvbl9jaHVua19leHRlbnNpb25fdmFsdWVgIGNhbGxiYWNrIGVycm9yAGBvbl9zdGF0dXNfY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl92ZXJzaW9uX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fdXJsX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fY2h1bmtfY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl9oZWFkZXJfdmFsdWVfY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl9tZXNzYWdlX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fbWV0aG9kX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25faGVhZGVyX2ZpZWxkX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fY2h1bmtfZXh0ZW5zaW9uX25hbWVgIGNhbGxiYWNrIGVycm9yAFVuZXhwZWN0ZWQgY2hhciBpbiB1cmwgc2VydmVyAEludmFsaWQgaGVhZGVyIHZhbHVlIGNoYXIASW52YWxpZCBoZWFkZXIgZmllbGQgY2hhcgBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX3ZlcnNpb24ASW52YWxpZCBtaW5vciB2ZXJzaW9uAEludmFsaWQgbWFqb3IgdmVyc2lvbgBFeHBlY3RlZCBzcGFjZSBhZnRlciB2ZXJzaW9uAEV4cGVjdGVkIENSTEYgYWZ0ZXIgdmVyc2lvbgBJbnZhbGlkIEhUVFAgdmVyc2lvbgBJbnZhbGlkIGhlYWRlciB0b2tlbgBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX3VybABJbnZhbGlkIGNoYXJhY3RlcnMgaW4gdXJsAFVuZXhwZWN0ZWQgc3RhcnQgY2hhciBpbiB1cmwARG91YmxlIEAgaW4gdXJsAEVtcHR5IENvbnRlbnQtTGVuZ3RoAEludmFsaWQgY2hhcmFjdGVyIGluIENvbnRlbnQtTGVuZ3RoAER1cGxpY2F0ZSBDb250ZW50LUxlbmd0aABJbnZhbGlkIGNoYXIgaW4gdXJsIHBhdGgAQ29udGVudC1MZW5ndGggY2FuJ3QgYmUgcHJlc2VudCB3aXRoIFRyYW5zZmVyLUVuY29kaW5nAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIHNpemUAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9oZWFkZXJfdmFsdWUAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9jaHVua19leHRlbnNpb25fdmFsdWUASW52YWxpZCBjaGFyYWN0ZXIgaW4gY2h1bmsgZXh0ZW5zaW9ucyB2YWx1ZQBNaXNzaW5nIGV4cGVjdGVkIExGIGFmdGVyIGhlYWRlciB2YWx1ZQBJbnZhbGlkIGBUcmFuc2Zlci1FbmNvZGluZ2AgaGVhZGVyIHZhbHVlAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIGV4dGVuc2lvbnMgcXVvdGUgdmFsdWUASW52YWxpZCBjaGFyYWN0ZXIgaW4gY2h1bmsgZXh0ZW5zaW9ucyBxdW90ZWQgdmFsdWUAUGF1c2VkIGJ5IG9uX2hlYWRlcnNfY29tcGxldGUASW52YWxpZCBFT0Ygc3RhdGUAb25fcmVzZXQgcGF1c2UAb25fY2h1bmtfaGVhZGVyIHBhdXNlAG9uX21lc3NhZ2VfYmVnaW4gcGF1c2UAb25fY2h1bmtfZXh0ZW5zaW9uX3ZhbHVlIHBhdXNlAG9uX3N0YXR1c19jb21wbGV0ZSBwYXVzZQBvbl92ZXJzaW9uX2NvbXBsZXRlIHBhdXNlAG9uX3VybF9jb21wbGV0ZSBwYXVzZQBvbl9jaHVua19jb21wbGV0ZSBwYXVzZQBvbl9oZWFkZXJfdmFsdWVfY29tcGxldGUgcGF1c2UAb25fbWVzc2FnZV9jb21wbGV0ZSBwYXVzZQBvbl9tZXRob2RfY29tcGxldGUgcGF1c2UAb25faGVhZGVyX2ZpZWxkX2NvbXBsZXRlIHBhdXNlAG9uX2NodW5rX2V4dGVuc2lvbl9uYW1lIHBhdXNlAFVuZXhwZWN0ZWQgc3BhY2UgYWZ0ZXIgc3RhcnQgbGluZQBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX2NodW5rX2V4dGVuc2lvbl9uYW1lAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIGV4dGVuc2lvbnMgbmFtZQBQYXVzZSBvbiBDT05ORUNUL1VwZ3JhZGUAUGF1c2Ugb24gUFJJL1VwZ3JhZGUARXhwZWN0ZWQgSFRUUC8yIENvbm5lY3Rpb24gUHJlZmFjZQBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX21ldGhvZABFeHBlY3RlZCBzcGFjZSBhZnRlciBtZXRob2QAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9oZWFkZXJfZmllbGQAUGF1c2VkAEludmFsaWQgd29yZCBlbmNvdW50ZXJlZABJbnZhbGlkIG1ldGhvZCBlbmNvdW50ZXJlZABVbmV4cGVjdGVkIGNoYXIgaW4gdXJsIHNjaGVtYQBSZXF1ZXN0IGhhcyBpbnZhbGlkIGBUcmFuc2Zlci1FbmNvZGluZ2AAU1dJVENIX1BST1hZAFVTRV9QUk9YWQBNS0FDVElWSVRZAFVOUFJPQ0VTU0FCTEVfRU5USVRZAENPUFkATU9WRURfUEVSTUFORU5UTFkAVE9PX0VBUkxZAE5PVElGWQBGQUlMRURfREVQRU5ERU5DWQBCQURfR0FURVdBWQBQTEFZAFBVVABDSEVDS09VVABHQVRFV0FZX1RJTUVPVVQAUkVRVUVTVF9USU1FT1VUAE5FVFdPUktfQ09OTkVDVF9USU1FT1VUAENPTk5FQ1RJT05fVElNRU9VVABMT0dJTl9USU1FT1VUAE5FVFdPUktfUkVBRF9USU1FT1VUAFBPU1QATUlTRElSRUNURURfUkVRVUVTVABDTElFTlRfQ0xPU0VEX1JFUVVFU1QAQ0xJRU5UX0NMT1NFRF9MT0FEX0JBTEFOQ0VEX1JFUVVFU1QAQkFEX1JFUVVFU1QASFRUUF9SRVFVRVNUX1NFTlRfVE9fSFRUUFNfUE9SVABSRVBPUlQASU1fQV9URUFQT1QAUkVTRVRfQ09OVEVOVABOT19DT05URU5UAFBBUlRJQUxfQ09OVEVOVABIUEVfSU5WQUxJRF9DT05TVEFOVABIUEVfQ0JfUkVTRVQAR0VUAEhQRV9TVFJJQ1QAQ09ORkxJQ1QAVEVNUE9SQVJZX1JFRElSRUNUAFBFUk1BTkVOVF9SRURJUkVDVABDT05ORUNUAE1VTFRJX1NUQVRVUwBIUEVfSU5WQUxJRF9TVEFUVVMAVE9PX01BTllfUkVRVUVTVFMARUFSTFlfSElOVFMAVU5BVkFJTEFCTEVfRk9SX0xFR0FMX1JFQVNPTlMAT1BUSU9OUwBTV0lUQ0hJTkdfUFJPVE9DT0xTAFZBUklBTlRfQUxTT19ORUdPVElBVEVTAE1VTFRJUExFX0NIT0lDRVMASU5URVJOQUxfU0VSVkVSX0VSUk9SAFdFQl9TRVJWRVJfVU5LTk9XTl9FUlJPUgBSQUlMR1VOX0VSUk9SAElERU5USVRZX1BST1ZJREVSX0FVVEhFTlRJQ0FUSU9OX0VSUk9SAFNTTF9DRVJUSUZJQ0FURV9FUlJPUgBJTlZBTElEX1hfRk9SV0FSREVEX0ZPUgBTRVRfUEFSQU1FVEVSAEdFVF9QQVJBTUVURVIASFBFX1VTRVIAU0VFX09USEVSAEhQRV9DQl9DSFVOS19IRUFERVIATUtDQUxFTkRBUgBTRVRVUABXRUJfU0VSVkVSX0lTX0RPV04AVEVBUkRPV04ASFBFX0NMT1NFRF9DT05ORUNUSU9OAEhFVVJJU1RJQ19FWFBJUkFUSU9OAERJU0NPTk5FQ1RFRF9PUEVSQVRJT04ATk9OX0FVVEhPUklUQVRJVkVfSU5GT1JNQVRJT04ASFBFX0lOVkFMSURfVkVSU0lPTgBIUEVfQ0JfTUVTU0FHRV9CRUdJTgBTSVRFX0lTX0ZST1pFTgBIUEVfSU5WQUxJRF9IRUFERVJfVE9LRU4ASU5WQUxJRF9UT0tFTgBGT1JCSURERU4ARU5IQU5DRV9ZT1VSX0NBTE0ASFBFX0lOVkFMSURfVVJMAEJMT0NLRURfQllfUEFSRU5UQUxfQ09OVFJPTABNS0NPTABBQ0wASFBFX0lOVEVSTkFMAFJFUVVFU1RfSEVBREVSX0ZJRUxEU19UT09fTEFSR0VfVU5PRkZJQ0lBTABIUEVfT0sAVU5MSU5LAFVOTE9DSwBQUkkAUkVUUllfV0lUSABIUEVfSU5WQUxJRF9DT05URU5UX0xFTkdUSABIUEVfVU5FWFBFQ1RFRF9DT05URU5UX0xFTkdUSABGTFVTSABQUk9QUEFUQ0gATS1TRUFSQ0gAVVJJX1RPT19MT05HAFBST0NFU1NJTkcATUlTQ0VMTEFORU9VU19QRVJTSVNURU5UX1dBUk5JTkcATUlTQ0VMTEFORU9VU19XQVJOSU5HAEhQRV9JTlZBTElEX1RSQU5TRkVSX0VOQ09ESU5HAEV4cGVjdGVkIENSTEYASFBFX0lOVkFMSURfQ0hVTktfU0laRQBNT1ZFAENPTlRJTlVFAEhQRV9DQl9TVEFUVVNfQ09NUExFVEUASFBFX0NCX0hFQURFUlNfQ09NUExFVEUASFBFX0NCX1ZFUlNJT05fQ09NUExFVEUASFBFX0NCX1VSTF9DT01QTEVURQBIUEVfQ0JfQ0hVTktfQ09NUExFVEUASFBFX0NCX0hFQURFUl9WQUxVRV9DT01QTEVURQBIUEVfQ0JfQ0hVTktfRVhURU5TSU9OX1ZBTFVFX0NPTVBMRVRFAEhQRV9DQl9DSFVOS19FWFRFTlNJT05fTkFNRV9DT01QTEVURQBIUEVfQ0JfTUVTU0FHRV9DT01QTEVURQBIUEVfQ0JfTUVUSE9EX0NPTVBMRVRFAEhQRV9DQl9IRUFERVJfRklFTERfQ09NUExFVEUAREVMRVRFAEhQRV9JTlZBTElEX0VPRl9TVEFURQBJTlZBTElEX1NTTF9DRVJUSUZJQ0FURQBQQVVTRQBOT19SRVNQT05TRQBVTlNVUFBPUlRFRF9NRURJQV9UWVBFAEdPTkUATk9UX0FDQ0VQVEFCTEUAU0VSVklDRV9VTkFWQUlMQUJMRQBSQU5HRV9OT1RfU0FUSVNGSUFCTEUAT1JJR0lOX0lTX1VOUkVBQ0hBQkxFAFJFU1BPTlNFX0lTX1NUQUxFAFBVUkdFAE1FUkdFAFJFUVVFU1RfSEVBREVSX0ZJRUxEU19UT09fTEFSR0UAUkVRVUVTVF9IRUFERVJfVE9PX0xBUkdFAFBBWUxPQURfVE9PX0xBUkdFAElOU1VGRklDSUVOVF9TVE9SQUdFAEhQRV9QQVVTRURfVVBHUkFERQBIUEVfUEFVU0VEX0gyX1VQR1JBREUAU09VUkNFAEFOTk9VTkNFAFRSQUNFAEhQRV9VTkVYUEVDVEVEX1NQQUNFAERFU0NSSUJFAFVOU1VCU0NSSUJFAFJFQ09SRABIUEVfSU5WQUxJRF9NRVRIT0QATk9UX0ZPVU5EAFBST1BGSU5EAFVOQklORABSRUJJTkQAVU5BVVRIT1JJWkVEAE1FVEhPRF9OT1RfQUxMT1dFRABIVFRQX1ZFUlNJT05fTk9UX1NVUFBPUlRFRABBTFJFQURZX1JFUE9SVEVEAEFDQ0VQVEVEAE5PVF9JTVBMRU1FTlRFRABMT09QX0RFVEVDVEVEAEhQRV9DUl9FWFBFQ1RFRABIUEVfTEZfRVhQRUNURUQAQ1JFQVRFRABJTV9VU0VEAEhQRV9QQVVTRUQAVElNRU9VVF9PQ0NVUkVEAFBBWU1FTlRfUkVRVUlSRUQAUFJFQ09ORElUSU9OX1JFUVVJUkVEAFBST1hZX0FVVEhFTlRJQ0FUSU9OX1JFUVVJUkVEAE5FVFdPUktfQVVUSEVOVElDQVRJT05fUkVRVUlSRUQATEVOR1RIX1JFUVVJUkVEAFNTTF9DRVJUSUZJQ0FURV9SRVFVSVJFRABVUEdSQURFX1JFUVVJUkVEAFBBR0VfRVhQSVJFRABQUkVDT05ESVRJT05fRkFJTEVEAEVYUEVDVEFUSU9OX0ZBSUxFRABSRVZBTElEQVRJT05fRkFJTEVEAFNTTF9IQU5EU0hBS0VfRkFJTEVEAExPQ0tFRABUUkFOU0ZPUk1BVElPTl9BUFBMSUVEAE5PVF9NT0RJRklFRABOT1RfRVhURU5ERUQAQkFORFdJRFRIX0xJTUlUX0VYQ0VFREVEAFNJVEVfSVNfT1ZFUkxPQURFRABIRUFEAEV4cGVjdGVkIEhUVFAvAABeEwAAJhMAADAQAADwFwAAnRMAABUSAAA5FwAA8BIAAAoQAAB1EgAArRIAAIITAABPFAAAfxAAAKAVAAAjFAAAiRIAAIsUAABNFQAA1BEAAM8UAAAQGAAAyRYAANwWAADBEQAA4BcAALsUAAB0FAAAfBUAAOUUAAAIFwAAHxAAAGUVAACjFAAAKBUAAAIVAACZFQAALBAAAIsZAABPDwAA1A4AAGoQAADOEAAAAhcAAIkOAABuEwAAHBMAAGYUAABWFwAAwRMAAM0TAABsEwAAaBcAAGYXAABfFwAAIhMAAM4PAABpDgAA2A4AAGMWAADLEwAAqg4AACgXAAAmFwAAxRMAAF0WAADoEQAAZxMAAGUTAADyFgAAcxMAAB0XAAD5FgAA8xEAAM8OAADOFQAADBIAALMRAAClEQAAYRAAADIXAAC7EwAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEBAgEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAgMCAgICAgAAAgIAAgIAAgICAgICAgICAgAEAAAAAAACAgICAgICAgICAgICAgICAgICAgICAgICAgAAAAICAgICAgICAgICAgICAgICAgICAgICAgICAgICAAIAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAIAAgICAgIAAAICAAICAAICAgICAgICAgIAAwAEAAAAAgICAgICAgICAgICAgICAgICAgICAgICAgIAAAACAgICAgICAgICAgICAgICAgICAgICAgICAgICAgACAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABsb3NlZWVwLWFsaXZlAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQEBAQEBAQEBAQEBAgEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQFjaHVua2VkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAQABAQEBAQAAAQEAAQEAAQEBAQEBAQEBAQAAAAAAAAABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQAAAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGVjdGlvbmVudC1sZW5ndGhvbnJveHktY29ubmVjdGlvbgAAAAAAAAAAAAAAAAAAAHJhbnNmZXItZW5jb2RpbmdwZ3JhZGUNCg0KDQpTTQ0KDQpUVFAvQ0UvVFNQLwAAAAAAAAAAAAAAAAECAAEDAAAAAAAAAAAAAAAAAAAAAAAABAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAAAAAAAAAAABAgABAwAAAAAAAAAAAAAAAAAAAAAAAAQBAQUBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAAAAAAAAAAAAQAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQAAAAAAAAAAAAABAAACAAAAAAAAAAAAAAAAAAAAAAAAAwQAAAQEBAQEBAQEBAQEBQQEBAQEBAQEBAQEBAAEAAYHBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQABAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAQAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAAAAAAAAAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAEAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAgAAAAACAAAAAAAAAAAAAAAAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwAAAAAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAE5PVU5DRUVDS09VVE5FQ1RFVEVDUklCRUxVU0hFVEVBRFNFQVJDSFJHRUNUSVZJVFlMRU5EQVJWRU9USUZZUFRJT05TQ0hTRUFZU1RBVENIR0VPUkRJUkVDVE9SVFJDSFBBUkFNRVRFUlVSQ0VCU0NSSUJFQVJET1dOQUNFSU5ETktDS1VCU0NSSUJFSFRUUC9BRFRQLw==' /***/ }), /***/ 41891: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.enumToMap = void 0; function enumToMap(obj) { const res = {}; Object.keys(obj).forEach((key) => { const value = obj[key]; if (typeof value === 'number') { res[key] = value; } }); return res; } exports.enumToMap = enumToMap; //# sourceMappingURL=utils.js.map /***/ }), /***/ 66771: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { kClients } = __nccwpck_require__(72785) const Agent = __nccwpck_require__(7890) const { kAgent, kMockAgentSet, kMockAgentGet, kDispatches, kIsMockActive, kNetConnect, kGetNetConnect, kOptions, kFactory } = __nccwpck_require__(24347) const MockClient = __nccwpck_require__(58687) const MockPool = __nccwpck_require__(26193) const { matchValue, buildMockOptions } = __nccwpck_require__(79323) const { InvalidArgumentError, UndiciError } = __nccwpck_require__(48045) const Dispatcher = __nccwpck_require__(60412) const Pluralizer = __nccwpck_require__(78891) const PendingInterceptorsFormatter = __nccwpck_require__(86823) class FakeWeakRef { constructor (value) { this.value = value } deref () { return this.value } } class MockAgent extends Dispatcher { constructor (opts) { super(opts) this[kNetConnect] = true this[kIsMockActive] = true // Instantiate Agent and encapsulate if ((opts && opts.agent && typeof opts.agent.dispatch !== 'function')) { throw new InvalidArgumentError('Argument opts.agent must implement Agent') } const agent = opts && opts.agent ? opts.agent : new Agent(opts) this[kAgent] = agent this[kClients] = agent[kClients] this[kOptions] = buildMockOptions(opts) } get (origin) { let dispatcher = this[kMockAgentGet](origin) if (!dispatcher) { dispatcher = this[kFactory](origin) this[kMockAgentSet](origin, dispatcher) } return dispatcher } dispatch (opts, handler) { // Call MockAgent.get to perform additional setup before dispatching as normal this.get(opts.origin) return this[kAgent].dispatch(opts, handler) } async close () { await this[kAgent].close() this[kClients].clear() } deactivate () { this[kIsMockActive] = false } activate () { this[kIsMockActive] = true } enableNetConnect (matcher) { if (typeof matcher === 'string' || typeof matcher === 'function' || matcher instanceof RegExp) { if (Array.isArray(this[kNetConnect])) { this[kNetConnect].push(matcher) } else { this[kNetConnect] = [matcher] } } else if (typeof matcher === 'undefined') { this[kNetConnect] = true } else { throw new InvalidArgumentError('Unsupported matcher. Must be one of String|Function|RegExp.') } } disableNetConnect () { this[kNetConnect] = false } // This is required to bypass issues caused by using global symbols - see: // https://github.com/nodejs/undici/issues/1447 get isMockActive () { return this[kIsMockActive] } [kMockAgentSet] (origin, dispatcher) { this[kClients].set(origin, new FakeWeakRef(dispatcher)) } [kFactory] (origin) { const mockOptions = Object.assign({ agent: this }, this[kOptions]) return this[kOptions] && this[kOptions].connections === 1 ? new MockClient(origin, mockOptions) : new MockPool(origin, mockOptions) } [kMockAgentGet] (origin) { // First check if we can immediately find it const ref = this[kClients].get(origin) if (ref) { return ref.deref() } // If the origin is not a string create a dummy parent pool and return to user if (typeof origin !== 'string') { const dispatcher = this[kFactory]('http://localhost:9999') this[kMockAgentSet](origin, dispatcher) return dispatcher } // If we match, create a pool and assign the same dispatches for (const [keyMatcher, nonExplicitRef] of Array.from(this[kClients])) { const nonExplicitDispatcher = nonExplicitRef.deref() if (nonExplicitDispatcher && typeof keyMatcher !== 'string' && matchValue(keyMatcher, origin)) { const dispatcher = this[kFactory](origin) this[kMockAgentSet](origin, dispatcher) dispatcher[kDispatches] = nonExplicitDispatcher[kDispatches] return dispatcher } } } [kGetNetConnect] () { return this[kNetConnect] } pendingInterceptors () { const mockAgentClients = this[kClients] return Array.from(mockAgentClients.entries()) .flatMap(([origin, scope]) => scope.deref()[kDispatches].map(dispatch => ({ ...dispatch, origin }))) .filter(({ pending }) => pending) } assertNoPendingInterceptors ({ pendingInterceptorsFormatter = new PendingInterceptorsFormatter() } = {}) { const pending = this.pendingInterceptors() if (pending.length === 0) { return } const pluralizer = new Pluralizer('interceptor', 'interceptors').pluralize(pending.length) throw new UndiciError(` ${pluralizer.count} ${pluralizer.noun} ${pluralizer.is} pending: ${pendingInterceptorsFormatter.format(pending)} `.trim()) } } module.exports = MockAgent /***/ }), /***/ 58687: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { promisify } = __nccwpck_require__(73837) const Client = __nccwpck_require__(33598) const { buildMockDispatch } = __nccwpck_require__(79323) const { kDispatches, kMockAgent, kClose, kOriginalClose, kOrigin, kOriginalDispatch, kConnected } = __nccwpck_require__(24347) const { MockInterceptor } = __nccwpck_require__(90410) const Symbols = __nccwpck_require__(72785) const { InvalidArgumentError } = __nccwpck_require__(48045) /** * MockClient provides an API that extends the Client to influence the mockDispatches. */ class MockClient extends Client { constructor (origin, opts) { super(origin, opts) if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') { throw new InvalidArgumentError('Argument opts.agent must implement Agent') } this[kMockAgent] = opts.agent this[kOrigin] = origin this[kDispatches] = [] this[kConnected] = 1 this[kOriginalDispatch] = this.dispatch this[kOriginalClose] = this.close.bind(this) this.dispatch = buildMockDispatch.call(this) this.close = this[kClose] } get [Symbols.kConnected] () { return this[kConnected] } /** * Sets up the base interceptor for mocking replies from undici. */ intercept (opts) { return new MockInterceptor(opts, this[kDispatches]) } async [kClose] () { await promisify(this[kOriginalClose])() this[kConnected] = 0 this[kMockAgent][Symbols.kClients].delete(this[kOrigin]) } } module.exports = MockClient /***/ }), /***/ 50888: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { UndiciError } = __nccwpck_require__(48045) class MockNotMatchedError extends UndiciError { constructor (message) { super(message) Error.captureStackTrace(this, MockNotMatchedError) this.name = 'MockNotMatchedError' this.message = message || 'The request does not match any registered mock dispatches' this.code = 'UND_MOCK_ERR_MOCK_NOT_MATCHED' } } module.exports = { MockNotMatchedError } /***/ }), /***/ 90410: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { getResponseData, buildKey, addMockDispatch } = __nccwpck_require__(79323) const { kDispatches, kDispatchKey, kDefaultHeaders, kDefaultTrailers, kContentLength, kMockDispatch } = __nccwpck_require__(24347) const { InvalidArgumentError } = __nccwpck_require__(48045) const { buildURL } = __nccwpck_require__(83983) /** * Defines the scope API for an interceptor reply */ class MockScope { constructor (mockDispatch) { this[kMockDispatch] = mockDispatch } /** * Delay a reply by a set amount in ms. */ delay (waitInMs) { if (typeof waitInMs !== 'number' || !Number.isInteger(waitInMs) || waitInMs <= 0) { throw new InvalidArgumentError('waitInMs must be a valid integer > 0') } this[kMockDispatch].delay = waitInMs return this } /** * For a defined reply, never mark as consumed. */ persist () { this[kMockDispatch].persist = true return this } /** * Allow one to define a reply for a set amount of matching requests. */ times (repeatTimes) { if (typeof repeatTimes !== 'number' || !Number.isInteger(repeatTimes) || repeatTimes <= 0) { throw new InvalidArgumentError('repeatTimes must be a valid integer > 0') } this[kMockDispatch].times = repeatTimes return this } } /** * Defines an interceptor for a Mock */ class MockInterceptor { constructor (opts, mockDispatches) { if (typeof opts !== 'object') { throw new InvalidArgumentError('opts must be an object') } if (typeof opts.path === 'undefined') { throw new InvalidArgumentError('opts.path must be defined') } if (typeof opts.method === 'undefined') { opts.method = 'GET' } // See https://github.com/nodejs/undici/issues/1245 // As per RFC 3986, clients are not supposed to send URI // fragments to servers when they retrieve a document, if (typeof opts.path === 'string') { if (opts.query) { opts.path = buildURL(opts.path, opts.query) } else { // Matches https://github.com/nodejs/undici/blob/main/lib/fetch/index.js#L1811 const parsedURL = new URL(opts.path, 'data://') opts.path = parsedURL.pathname + parsedURL.search } } if (typeof opts.method === 'string') { opts.method = opts.method.toUpperCase() } this[kDispatchKey] = buildKey(opts) this[kDispatches] = mockDispatches this[kDefaultHeaders] = {} this[kDefaultTrailers] = {} this[kContentLength] = false } createMockScopeDispatchData (statusCode, data, responseOptions = {}) { const responseData = getResponseData(data) const contentLength = this[kContentLength] ? { 'content-length': responseData.length } : {} const headers = { ...this[kDefaultHeaders], ...contentLength, ...responseOptions.headers } const trailers = { ...this[kDefaultTrailers], ...responseOptions.trailers } return { statusCode, data, headers, trailers } } validateReplyParameters (statusCode, data, responseOptions) { if (typeof statusCode === 'undefined') { throw new InvalidArgumentError('statusCode must be defined') } if (typeof data === 'undefined') { throw new InvalidArgumentError('data must be defined') } if (typeof responseOptions !== 'object') { throw new InvalidArgumentError('responseOptions must be an object') } } /** * Mock an undici request with a defined reply. */ reply (replyData) { // Values of reply aren't available right now as they // can only be available when the reply callback is invoked. if (typeof replyData === 'function') { // We'll first wrap the provided callback in another function, // this function will properly resolve the data from the callback // when invoked. const wrappedDefaultsCallback = (opts) => { // Our reply options callback contains the parameter for statusCode, data and options. const resolvedData = replyData(opts) // Check if it is in the right format if (typeof resolvedData !== 'object') { throw new InvalidArgumentError('reply options callback must return an object') } const { statusCode, data = '', responseOptions = {} } = resolvedData this.validateReplyParameters(statusCode, data, responseOptions) // Since the values can be obtained immediately we return them // from this higher order function that will be resolved later. return { ...this.createMockScopeDispatchData(statusCode, data, responseOptions) } } // Add usual dispatch data, but this time set the data parameter to function that will eventually provide data. const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], wrappedDefaultsCallback) return new MockScope(newMockDispatch) } // We can have either one or three parameters, if we get here, // we should have 1-3 parameters. So we spread the arguments of // this function to obtain the parameters, since replyData will always // just be the statusCode. const [statusCode, data = '', responseOptions = {}] = [...arguments] this.validateReplyParameters(statusCode, data, responseOptions) // Send in-already provided data like usual const dispatchData = this.createMockScopeDispatchData(statusCode, data, responseOptions) const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], dispatchData) return new MockScope(newMockDispatch) } /** * Mock an undici request with a defined error. */ replyWithError (error) { if (typeof error === 'undefined') { throw new InvalidArgumentError('error must be defined') } const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], { error }) return new MockScope(newMockDispatch) } /** * Set default reply headers on the interceptor for subsequent replies */ defaultReplyHeaders (headers) { if (typeof headers === 'undefined') { throw new InvalidArgumentError('headers must be defined') } this[kDefaultHeaders] = headers return this } /** * Set default reply trailers on the interceptor for subsequent replies */ defaultReplyTrailers (trailers) { if (typeof trailers === 'undefined') { throw new InvalidArgumentError('trailers must be defined') } this[kDefaultTrailers] = trailers return this } /** * Set reply content length header for replies on the interceptor */ replyContentLength () { this[kContentLength] = true return this } } module.exports.MockInterceptor = MockInterceptor module.exports.MockScope = MockScope /***/ }), /***/ 26193: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { promisify } = __nccwpck_require__(73837) const Pool = __nccwpck_require__(4634) const { buildMockDispatch } = __nccwpck_require__(79323) const { kDispatches, kMockAgent, kClose, kOriginalClose, kOrigin, kOriginalDispatch, kConnected } = __nccwpck_require__(24347) const { MockInterceptor } = __nccwpck_require__(90410) const Symbols = __nccwpck_require__(72785) const { InvalidArgumentError } = __nccwpck_require__(48045) /** * MockPool provides an API that extends the Pool to influence the mockDispatches. */ class MockPool extends Pool { constructor (origin, opts) { super(origin, opts) if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') { throw new InvalidArgumentError('Argument opts.agent must implement Agent') } this[kMockAgent] = opts.agent this[kOrigin] = origin this[kDispatches] = [] this[kConnected] = 1 this[kOriginalDispatch] = this.dispatch this[kOriginalClose] = this.close.bind(this) this.dispatch = buildMockDispatch.call(this) this.close = this[kClose] } get [Symbols.kConnected] () { return this[kConnected] } /** * Sets up the base interceptor for mocking replies from undici. */ intercept (opts) { return new MockInterceptor(opts, this[kDispatches]) } async [kClose] () { await promisify(this[kOriginalClose])() this[kConnected] = 0 this[kMockAgent][Symbols.kClients].delete(this[kOrigin]) } } module.exports = MockPool /***/ }), /***/ 24347: /***/ ((module) => { "use strict"; module.exports = { kAgent: Symbol('agent'), kOptions: Symbol('options'), kFactory: Symbol('factory'), kDispatches: Symbol('dispatches'), kDispatchKey: Symbol('dispatch key'), kDefaultHeaders: Symbol('default headers'), kDefaultTrailers: Symbol('default trailers'), kContentLength: Symbol('content length'), kMockAgent: Symbol('mock agent'), kMockAgentSet: Symbol('mock agent set'), kMockAgentGet: Symbol('mock agent get'), kMockDispatch: Symbol('mock dispatch'), kClose: Symbol('close'), kOriginalClose: Symbol('original agent close'), kOrigin: Symbol('origin'), kIsMockActive: Symbol('is mock active'), kNetConnect: Symbol('net connect'), kGetNetConnect: Symbol('get net connect'), kConnected: Symbol('connected') } /***/ }), /***/ 79323: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { MockNotMatchedError } = __nccwpck_require__(50888) const { kDispatches, kMockAgent, kOriginalDispatch, kOrigin, kGetNetConnect } = __nccwpck_require__(24347) const { buildURL, nop } = __nccwpck_require__(83983) const { STATUS_CODES } = __nccwpck_require__(13685) const { types: { isPromise } } = __nccwpck_require__(73837) function matchValue (match, value) { if (typeof match === 'string') { return match === value } if (match instanceof RegExp) { return match.test(value) } if (typeof match === 'function') { return match(value) === true } return false } function lowerCaseEntries (headers) { return Object.fromEntries( Object.entries(headers).map(([headerName, headerValue]) => { return [headerName.toLocaleLowerCase(), headerValue] }) ) } /** * @param {import('../../index').Headers|string[]|Record} headers * @param {string} key */ function getHeaderByName (headers, key) { if (Array.isArray(headers)) { for (let i = 0; i < headers.length; i += 2) { if (headers[i].toLocaleLowerCase() === key.toLocaleLowerCase()) { return headers[i + 1] } } return undefined } else if (typeof headers.get === 'function') { return headers.get(key) } else { return lowerCaseEntries(headers)[key.toLocaleLowerCase()] } } /** @param {string[]} headers */ function buildHeadersFromArray (headers) { // fetch HeadersList const clone = headers.slice() const entries = [] for (let index = 0; index < clone.length; index += 2) { entries.push([clone[index], clone[index + 1]]) } return Object.fromEntries(entries) } function matchHeaders (mockDispatch, headers) { if (typeof mockDispatch.headers === 'function') { if (Array.isArray(headers)) { // fetch HeadersList headers = buildHeadersFromArray(headers) } return mockDispatch.headers(headers ? lowerCaseEntries(headers) : {}) } if (typeof mockDispatch.headers === 'undefined') { return true } if (typeof headers !== 'object' || typeof mockDispatch.headers !== 'object') { return false } for (const [matchHeaderName, matchHeaderValue] of Object.entries(mockDispatch.headers)) { const headerValue = getHeaderByName(headers, matchHeaderName) if (!matchValue(matchHeaderValue, headerValue)) { return false } } return true } function safeUrl (path) { if (typeof path !== 'string') { return path } const pathSegments = path.split('?') if (pathSegments.length !== 2) { return path } const qp = new URLSearchParams(pathSegments.pop()) qp.sort() return [...pathSegments, qp.toString()].join('?') } function matchKey (mockDispatch, { path, method, body, headers }) { const pathMatch = matchValue(mockDispatch.path, path) const methodMatch = matchValue(mockDispatch.method, method) const bodyMatch = typeof mockDispatch.body !== 'undefined' ? matchValue(mockDispatch.body, body) : true const headersMatch = matchHeaders(mockDispatch, headers) return pathMatch && methodMatch && bodyMatch && headersMatch } function getResponseData (data) { if (Buffer.isBuffer(data)) { return data } else if (typeof data === 'object') { return JSON.stringify(data) } else { return data.toString() } } function getMockDispatch (mockDispatches, key) { const basePath = key.query ? buildURL(key.path, key.query) : key.path const resolvedPath = typeof basePath === 'string' ? safeUrl(basePath) : basePath // Match path let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path }) => matchValue(safeUrl(path), resolvedPath)) if (matchedMockDispatches.length === 0) { throw new MockNotMatchedError(`Mock dispatch not matched for path '${resolvedPath}'`) } // Match method matchedMockDispatches = matchedMockDispatches.filter(({ method }) => matchValue(method, key.method)) if (matchedMockDispatches.length === 0) { throw new MockNotMatchedError(`Mock dispatch not matched for method '${key.method}'`) } // Match body matchedMockDispatches = matchedMockDispatches.filter(({ body }) => typeof body !== 'undefined' ? matchValue(body, key.body) : true) if (matchedMockDispatches.length === 0) { throw new MockNotMatchedError(`Mock dispatch not matched for body '${key.body}'`) } // Match headers matchedMockDispatches = matchedMockDispatches.filter((mockDispatch) => matchHeaders(mockDispatch, key.headers)) if (matchedMockDispatches.length === 0) { throw new MockNotMatchedError(`Mock dispatch not matched for headers '${typeof key.headers === 'object' ? JSON.stringify(key.headers) : key.headers}'`) } return matchedMockDispatches[0] } function addMockDispatch (mockDispatches, key, data) { const baseData = { timesInvoked: 0, times: 1, persist: false, consumed: false } const replyData = typeof data === 'function' ? { callback: data } : { ...data } const newMockDispatch = { ...baseData, ...key, pending: true, data: { error: null, ...replyData } } mockDispatches.push(newMockDispatch) return newMockDispatch } function deleteMockDispatch (mockDispatches, key) { const index = mockDispatches.findIndex(dispatch => { if (!dispatch.consumed) { return false } return matchKey(dispatch, key) }) if (index !== -1) { mockDispatches.splice(index, 1) } } function buildKey (opts) { const { path, method, body, headers, query } = opts return { path, method, body, headers, query } } function generateKeyValues (data) { return Object.entries(data).reduce((keyValuePairs, [key, value]) => [ ...keyValuePairs, Buffer.from(`${key}`), Array.isArray(value) ? value.map(x => Buffer.from(`${x}`)) : Buffer.from(`${value}`) ], []) } /** * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Status * @param {number} statusCode */ function getStatusText (statusCode) { return STATUS_CODES[statusCode] || 'unknown' } async function getResponse (body) { const buffers = [] for await (const data of body) { buffers.push(data) } return Buffer.concat(buffers).toString('utf8') } /** * Mock dispatch function used to simulate undici dispatches */ function mockDispatch (opts, handler) { // Get mock dispatch from built key const key = buildKey(opts) const mockDispatch = getMockDispatch(this[kDispatches], key) mockDispatch.timesInvoked++ // Here's where we resolve a callback if a callback is present for the dispatch data. if (mockDispatch.data.callback) { mockDispatch.data = { ...mockDispatch.data, ...mockDispatch.data.callback(opts) } } // Parse mockDispatch data const { data: { statusCode, data, headers, trailers, error }, delay, persist } = mockDispatch const { timesInvoked, times } = mockDispatch // If it's used up and not persistent, mark as consumed mockDispatch.consumed = !persist && timesInvoked >= times mockDispatch.pending = timesInvoked < times // If specified, trigger dispatch error if (error !== null) { deleteMockDispatch(this[kDispatches], key) handler.onError(error) return true } // Handle the request with a delay if necessary if (typeof delay === 'number' && delay > 0) { setTimeout(() => { handleReply(this[kDispatches]) }, delay) } else { handleReply(this[kDispatches]) } function handleReply (mockDispatches, _data = data) { // fetch's HeadersList is a 1D string array const optsHeaders = Array.isArray(opts.headers) ? buildHeadersFromArray(opts.headers) : opts.headers const body = typeof _data === 'function' ? _data({ ...opts, headers: optsHeaders }) : _data // util.types.isPromise is likely needed for jest. if (isPromise(body)) { // If handleReply is asynchronous, throwing an error // in the callback will reject the promise, rather than // synchronously throw the error, which breaks some tests. // Rather, we wait for the callback to resolve if it is a // promise, and then re-run handleReply with the new body. body.then((newData) => handleReply(mockDispatches, newData)) return } const responseData = getResponseData(body) const responseHeaders = generateKeyValues(headers) const responseTrailers = generateKeyValues(trailers) handler.abort = nop handler.onHeaders(statusCode, responseHeaders, resume, getStatusText(statusCode)) handler.onData(Buffer.from(responseData)) handler.onComplete(responseTrailers) deleteMockDispatch(mockDispatches, key) } function resume () {} return true } function buildMockDispatch () { const agent = this[kMockAgent] const origin = this[kOrigin] const originalDispatch = this[kOriginalDispatch] return function dispatch (opts, handler) { if (agent.isMockActive) { try { mockDispatch.call(this, opts, handler) } catch (error) { if (error instanceof MockNotMatchedError) { const netConnect = agent[kGetNetConnect]() if (netConnect === false) { throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect disabled)`) } if (checkNetConnect(netConnect, origin)) { originalDispatch.call(this, opts, handler) } else { throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect is not enabled for this origin)`) } } else { throw error } } } else { originalDispatch.call(this, opts, handler) } } } function checkNetConnect (netConnect, origin) { const url = new URL(origin) if (netConnect === true) { return true } else if (Array.isArray(netConnect) && netConnect.some((matcher) => matchValue(matcher, url.host))) { return true } return false } function buildMockOptions (opts) { if (opts) { const { agent, ...mockOptions } = opts return mockOptions } } module.exports = { getResponseData, getMockDispatch, addMockDispatch, deleteMockDispatch, buildKey, generateKeyValues, matchValue, getResponse, getStatusText, mockDispatch, buildMockDispatch, checkNetConnect, buildMockOptions, getHeaderByName } /***/ }), /***/ 86823: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { Transform } = __nccwpck_require__(12781) const { Console } = __nccwpck_require__(96206) /** * Gets the output of `console.table(…)` as a string. */ module.exports = class PendingInterceptorsFormatter { constructor ({ disableColors } = {}) { this.transform = new Transform({ transform (chunk, _enc, cb) { cb(null, chunk) } }) this.logger = new Console({ stdout: this.transform, inspectOptions: { colors: !disableColors && !process.env.CI } }) } format (pendingInterceptors) { const withPrettyHeaders = pendingInterceptors.map( ({ method, path, data: { statusCode }, persist, times, timesInvoked, origin }) => ({ Method: method, Origin: origin, Path: path, 'Status code': statusCode, Persistent: persist ? '✅' : '❌', Invocations: timesInvoked, Remaining: persist ? Infinity : times - timesInvoked })) this.logger.table(withPrettyHeaders) return this.transform.read().toString() } } /***/ }), /***/ 78891: /***/ ((module) => { "use strict"; const singulars = { pronoun: 'it', is: 'is', was: 'was', this: 'this' } const plurals = { pronoun: 'they', is: 'are', was: 'were', this: 'these' } module.exports = class Pluralizer { constructor (singular, plural) { this.singular = singular this.plural = plural } pluralize (count) { const one = count === 1 const keys = one ? singulars : plurals const noun = one ? this.singular : this.plural return { ...keys, count, noun } } } /***/ }), /***/ 68266: /***/ ((module) => { "use strict"; /* eslint-disable */ // Extracted from node/lib/internal/fixed_queue.js // Currently optimal queue size, tested on V8 6.0 - 6.6. Must be power of two. const kSize = 2048; const kMask = kSize - 1; // The FixedQueue is implemented as a singly-linked list of fixed-size // circular buffers. It looks something like this: // // head tail // | | // v v // +-----------+ <-----\ +-----------+ <------\ +-----------+ // | [null] | \----- | next | \------- | next | // +-----------+ +-----------+ +-----------+ // | item | <-- bottom | item | <-- bottom | [empty] | // | item | | item | | [empty] | // | item | | item | | [empty] | // | item | | item | | [empty] | // | item | | item | bottom --> | item | // | item | | item | | item | // | ... | | ... | | ... | // | item | | item | | item | // | item | | item | | item | // | [empty] | <-- top | item | | item | // | [empty] | | item | | item | // | [empty] | | [empty] | <-- top top --> | [empty] | // +-----------+ +-----------+ +-----------+ // // Or, if there is only one circular buffer, it looks something // like either of these: // // head tail head tail // | | | | // v v v v // +-----------+ +-----------+ // | [null] | | [null] | // +-----------+ +-----------+ // | [empty] | | item | // | [empty] | | item | // | item | <-- bottom top --> | [empty] | // | item | | [empty] | // | [empty] | <-- top bottom --> | item | // | [empty] | | item | // +-----------+ +-----------+ // // Adding a value means moving `top` forward by one, removing means // moving `bottom` forward by one. After reaching the end, the queue // wraps around. // // When `top === bottom` the current queue is empty and when // `top + 1 === bottom` it's full. This wastes a single space of storage // but allows much quicker checks. class FixedCircularBuffer { constructor() { this.bottom = 0; this.top = 0; this.list = new Array(kSize); this.next = null; } isEmpty() { return this.top === this.bottom; } isFull() { return ((this.top + 1) & kMask) === this.bottom; } push(data) { this.list[this.top] = data; this.top = (this.top + 1) & kMask; } shift() { const nextItem = this.list[this.bottom]; if (nextItem === undefined) return null; this.list[this.bottom] = undefined; this.bottom = (this.bottom + 1) & kMask; return nextItem; } } module.exports = class FixedQueue { constructor() { this.head = this.tail = new FixedCircularBuffer(); } isEmpty() { return this.head.isEmpty(); } push(data) { if (this.head.isFull()) { // Head is full: Creates a new queue, sets the old queue's `.next` to it, // and sets it as the new main queue. this.head = this.head.next = new FixedCircularBuffer(); } this.head.push(data); } shift() { const tail = this.tail; const next = tail.shift(); if (tail.isEmpty() && tail.next !== null) { // If there is another queue, it forms the new tail. this.tail = tail.next; } return next; } }; /***/ }), /***/ 73198: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const DispatcherBase = __nccwpck_require__(74839) const FixedQueue = __nccwpck_require__(68266) const { kConnected, kSize, kRunning, kPending, kQueued, kBusy, kFree, kUrl, kClose, kDestroy, kDispatch } = __nccwpck_require__(72785) const PoolStats = __nccwpck_require__(39689) const kClients = Symbol('clients') const kNeedDrain = Symbol('needDrain') const kQueue = Symbol('queue') const kClosedResolve = Symbol('closed resolve') const kOnDrain = Symbol('onDrain') const kOnConnect = Symbol('onConnect') const kOnDisconnect = Symbol('onDisconnect') const kOnConnectionError = Symbol('onConnectionError') const kGetDispatcher = Symbol('get dispatcher') const kAddClient = Symbol('add client') const kRemoveClient = Symbol('remove client') const kStats = Symbol('stats') class PoolBase extends DispatcherBase { constructor () { super() this[kQueue] = new FixedQueue() this[kClients] = [] this[kQueued] = 0 const pool = this this[kOnDrain] = function onDrain (origin, targets) { const queue = pool[kQueue] let needDrain = false while (!needDrain) { const item = queue.shift() if (!item) { break } pool[kQueued]-- needDrain = !this.dispatch(item.opts, item.handler) } this[kNeedDrain] = needDrain if (!this[kNeedDrain] && pool[kNeedDrain]) { pool[kNeedDrain] = false pool.emit('drain', origin, [pool, ...targets]) } if (pool[kClosedResolve] && queue.isEmpty()) { Promise .all(pool[kClients].map(c => c.close())) .then(pool[kClosedResolve]) } } this[kOnConnect] = (origin, targets) => { pool.emit('connect', origin, [pool, ...targets]) } this[kOnDisconnect] = (origin, targets, err) => { pool.emit('disconnect', origin, [pool, ...targets], err) } this[kOnConnectionError] = (origin, targets, err) => { pool.emit('connectionError', origin, [pool, ...targets], err) } this[kStats] = new PoolStats(this) } get [kBusy] () { return this[kNeedDrain] } get [kConnected] () { return this[kClients].filter(client => client[kConnected]).length } get [kFree] () { return this[kClients].filter(client => client[kConnected] && !client[kNeedDrain]).length } get [kPending] () { let ret = this[kQueued] for (const { [kPending]: pending } of this[kClients]) { ret += pending } return ret } get [kRunning] () { let ret = 0 for (const { [kRunning]: running } of this[kClients]) { ret += running } return ret } get [kSize] () { let ret = this[kQueued] for (const { [kSize]: size } of this[kClients]) { ret += size } return ret } get stats () { return this[kStats] } async [kClose] () { if (this[kQueue].isEmpty()) { return Promise.all(this[kClients].map(c => c.close())) } else { return new Promise((resolve) => { this[kClosedResolve] = resolve }) } } async [kDestroy] (err) { while (true) { const item = this[kQueue].shift() if (!item) { break } item.handler.onError(err) } return Promise.all(this[kClients].map(c => c.destroy(err))) } [kDispatch] (opts, handler) { const dispatcher = this[kGetDispatcher]() if (!dispatcher) { this[kNeedDrain] = true this[kQueue].push({ opts, handler }) this[kQueued]++ } else if (!dispatcher.dispatch(opts, handler)) { dispatcher[kNeedDrain] = true this[kNeedDrain] = !this[kGetDispatcher]() } return !this[kNeedDrain] } [kAddClient] (client) { client .on('drain', this[kOnDrain]) .on('connect', this[kOnConnect]) .on('disconnect', this[kOnDisconnect]) .on('connectionError', this[kOnConnectionError]) this[kClients].push(client) if (this[kNeedDrain]) { process.nextTick(() => { if (this[kNeedDrain]) { this[kOnDrain](client[kUrl], [this, client]) } }) } return this } [kRemoveClient] (client) { client.close(() => { const idx = this[kClients].indexOf(client) if (idx !== -1) { this[kClients].splice(idx, 1) } }) this[kNeedDrain] = this[kClients].some(dispatcher => ( !dispatcher[kNeedDrain] && dispatcher.closed !== true && dispatcher.destroyed !== true )) } } module.exports = { PoolBase, kClients, kNeedDrain, kAddClient, kRemoveClient, kGetDispatcher } /***/ }), /***/ 39689: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { kFree, kConnected, kPending, kQueued, kRunning, kSize } = __nccwpck_require__(72785) const kPool = Symbol('pool') class PoolStats { constructor (pool) { this[kPool] = pool } get connected () { return this[kPool][kConnected] } get free () { return this[kPool][kFree] } get pending () { return this[kPool][kPending] } get queued () { return this[kPool][kQueued] } get running () { return this[kPool][kRunning] } get size () { return this[kPool][kSize] } } module.exports = PoolStats /***/ }), /***/ 4634: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { PoolBase, kClients, kNeedDrain, kAddClient, kGetDispatcher } = __nccwpck_require__(73198) const Client = __nccwpck_require__(33598) const { InvalidArgumentError } = __nccwpck_require__(48045) const util = __nccwpck_require__(83983) const { kUrl, kInterceptors } = __nccwpck_require__(72785) const buildConnector = __nccwpck_require__(82067) const kOptions = Symbol('options') const kConnections = Symbol('connections') const kFactory = Symbol('factory') function defaultFactory (origin, opts) { return new Client(origin, opts) } class Pool extends PoolBase { constructor (origin, { connections, factory = defaultFactory, connect, connectTimeout, tls, maxCachedSessions, socketPath, autoSelectFamily, autoSelectFamilyAttemptTimeout, allowH2, ...options } = {}) { super() if (connections != null && (!Number.isFinite(connections) || connections < 0)) { throw new InvalidArgumentError('invalid connections') } 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 connect !== 'function') { connect = buildConnector({ ...tls, maxCachedSessions, allowH2, socketPath, timeout: connectTimeout, ...(util.nodeHasAutoSelectFamily && autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined), ...connect }) } this[kInterceptors] = options.interceptors && options.interceptors.Pool && Array.isArray(options.interceptors.Pool) ? options.interceptors.Pool : [] this[kConnections] = connections || null this[kUrl] = util.parseOrigin(origin) this[kOptions] = { ...util.deepClone(options), connect, allowH2 } this[kOptions].interceptors = options.interceptors ? { ...options.interceptors } : undefined this[kFactory] = factory } [kGetDispatcher] () { let dispatcher = this[kClients].find(dispatcher => !dispatcher[kNeedDrain]) if (dispatcher) { return dispatcher } if (!this[kConnections] || this[kClients].length < this[kConnections]) { dispatcher = this[kFactory](this[kUrl], this[kOptions]) this[kAddClient](dispatcher) } return dispatcher } } module.exports = Pool /***/ }), /***/ 97858: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { kProxy, kClose, kDestroy, kInterceptors } = __nccwpck_require__(72785) const { URL } = __nccwpck_require__(57310) const Agent = __nccwpck_require__(7890) const Pool = __nccwpck_require__(4634) const DispatcherBase = __nccwpck_require__(74839) const { InvalidArgumentError, RequestAbortedError } = __nccwpck_require__(48045) const buildConnector = __nccwpck_require__(82067) const kAgent = Symbol('proxy agent') const kClient = Symbol('proxy client') const kProxyHeaders = Symbol('proxy headers') const kRequestTls = Symbol('request tls settings') const kProxyTls = Symbol('proxy tls settings') const kConnectEndpoint = Symbol('connect endpoint function') function defaultProtocolPort (protocol) { return protocol === 'https:' ? 443 : 80 } function buildProxyOptions (opts) { if (typeof opts === 'string') { opts = { uri: opts } } if (!opts || !opts.uri) { throw new InvalidArgumentError('Proxy opts.uri is mandatory') } return { uri: opts.uri, protocol: opts.protocol || 'https' } } function defaultFactory (origin, opts) { return new Pool(origin, opts) } class ProxyAgent extends DispatcherBase { constructor (opts) { super(opts) this[kProxy] = buildProxyOptions(opts) this[kAgent] = new Agent(opts) this[kInterceptors] = opts.interceptors && opts.interceptors.ProxyAgent && Array.isArray(opts.interceptors.ProxyAgent) ? opts.interceptors.ProxyAgent : [] if (typeof opts === 'string') { opts = { uri: opts } } if (!opts || !opts.uri) { throw new InvalidArgumentError('Proxy opts.uri is mandatory') } const { clientFactory = defaultFactory } = opts if (typeof clientFactory !== 'function') { throw new InvalidArgumentError('Proxy opts.clientFactory must be a function.') } this[kRequestTls] = opts.requestTls this[kProxyTls] = opts.proxyTls this[kProxyHeaders] = opts.headers || {} const resolvedUrl = new URL(opts.uri) const { origin, port, host, username, password } = resolvedUrl if (opts.auth && opts.token) { throw new InvalidArgumentError('opts.auth cannot be used in combination with opts.token') } else if (opts.auth) { /* @deprecated in favour of opts.token */ this[kProxyHeaders]['proxy-authorization'] = `Basic ${opts.auth}` } else if (opts.token) { this[kProxyHeaders]['proxy-authorization'] = opts.token } else if (username && password) { this[kProxyHeaders]['proxy-authorization'] = `Basic ${Buffer.from(`${decodeURIComponent(username)}:${decodeURIComponent(password)}`).toString('base64')}` } const connect = buildConnector({ ...opts.proxyTls }) this[kConnectEndpoint] = buildConnector({ ...opts.requestTls }) this[kClient] = clientFactory(resolvedUrl, { connect }) this[kAgent] = new Agent({ ...opts, connect: async (opts, callback) => { let requestedHost = opts.host if (!opts.port) { requestedHost += `:${defaultProtocolPort(opts.protocol)}` } try { const { socket, statusCode } = await this[kClient].connect({ origin, port, path: requestedHost, signal: opts.signal, headers: { ...this[kProxyHeaders], host } }) if (statusCode !== 200) { socket.on('error', () => {}).destroy() callback(new RequestAbortedError(`Proxy response (${statusCode}) !== 200 when HTTP Tunneling`)) } if (opts.protocol !== 'https:') { callback(null, socket) return } let servername if (this[kRequestTls]) { servername = this[kRequestTls].servername } else { servername = opts.servername } this[kConnectEndpoint]({ ...opts, servername, httpSocket: socket }, callback) } catch (err) { callback(err) } } }) } dispatch (opts, handler) { const { host } = new URL(opts.origin) const headers = buildHeaders(opts.headers) throwIfProxyAuthIsSent(headers) return this[kAgent].dispatch( { ...opts, headers: { ...headers, host } }, handler ) } async [kClose] () { await this[kAgent].close() await this[kClient].close() } async [kDestroy] () { await this[kAgent].destroy() await this[kClient].destroy() } } /** * @param {string[] | Record} headers * @returns {Record} */ function buildHeaders (headers) { // When using undici.fetch, the headers list is stored // as an array. if (Array.isArray(headers)) { /** @type {Record} */ const headersPair = {} for (let i = 0; i < headers.length; i += 2) { headersPair[headers[i]] = headers[i + 1] } return headersPair } return headers } /** * @param {Record} headers * * Previous versions of ProxyAgent suggests the Proxy-Authorization in request headers * Nevertheless, it was changed and to avoid a security vulnerability by end users * this check was created. * It should be removed in the next major version for performance reasons */ function throwIfProxyAuthIsSent (headers) { const existProxyAuth = headers && Object.keys(headers) .find((key) => key.toLowerCase() === 'proxy-authorization') if (existProxyAuth) { throw new InvalidArgumentError('Proxy-Authorization should be sent in ProxyAgent constructor') } } module.exports = ProxyAgent /***/ }), /***/ 29459: /***/ ((module) => { "use strict"; let fastNow = Date.now() let fastNowTimeout const fastTimers = [] function onTimeout () { fastNow = Date.now() let len = fastTimers.length let idx = 0 while (idx < len) { const timer = fastTimers[idx] if (timer.state === 0) { timer.state = fastNow + timer.delay } else if (timer.state > 0 && fastNow >= timer.state) { timer.state = -1 timer.callback(timer.opaque) } if (timer.state === -1) { timer.state = -2 if (idx !== len - 1) { fastTimers[idx] = fastTimers.pop() } else { fastTimers.pop() } len -= 1 } else { idx += 1 } } if (fastTimers.length > 0) { refreshTimeout() } } function refreshTimeout () { if (fastNowTimeout && fastNowTimeout.refresh) { fastNowTimeout.refresh() } else { clearTimeout(fastNowTimeout) fastNowTimeout = setTimeout(onTimeout, 1e3) if (fastNowTimeout.unref) { fastNowTimeout.unref() } } } class Timeout { constructor (callback, delay, opaque) { this.callback = callback this.delay = delay this.opaque = opaque // -2 not in timer list // -1 in timer list but inactive // 0 in timer list waiting for time // > 0 in timer list waiting for time to expire this.state = -2 this.refresh() } refresh () { if (this.state === -2) { fastTimers.push(this) if (!fastNowTimeout || fastTimers.length === 1) { refreshTimeout() } } this.state = 0 } clear () { this.state = -1 } } module.exports = { setTimeout (callback, delay, opaque) { return delay < 1e3 ? setTimeout(callback, delay, opaque) : new Timeout(callback, delay, opaque) }, clearTimeout (timeout) { if (timeout instanceof Timeout) { timeout.clear() } else { clearTimeout(timeout) } } } /***/ }), /***/ 35354: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const diagnosticsChannel = __nccwpck_require__(67643) const { uid, states } = __nccwpck_require__(19188) const { kReadyState, kSentClose, kByteParser, kReceivedClose } = __nccwpck_require__(37578) const { fireEvent, failWebsocketConnection } = __nccwpck_require__(25515) const { CloseEvent } = __nccwpck_require__(52611) const { makeRequest } = __nccwpck_require__(48359) const { fetching } = __nccwpck_require__(74881) const { Headers } = __nccwpck_require__(10554) const { getGlobalDispatcher } = __nccwpck_require__(21892) const { kHeadersList } = __nccwpck_require__(72785) const channels = {} channels.open = diagnosticsChannel.channel('undici:websocket:open') channels.close = diagnosticsChannel.channel('undici:websocket:close') channels.socketError = diagnosticsChannel.channel('undici:websocket:socket_error') /** @type {import('crypto')} */ let crypto try { crypto = __nccwpck_require__(6113) } catch { } /** * @see https://websockets.spec.whatwg.org/#concept-websocket-establish * @param {URL} url * @param {string|string[]} protocols * @param {import('./websocket').WebSocket} ws * @param {(response: any) => void} onEstablish * @param {Partial} options */ function establishWebSocketConnection (url, protocols, ws, onEstablish, options) { // 1. Let requestURL be a copy of url, with its scheme set to "http", if url’s // scheme is "ws", and to "https" otherwise. const requestURL = url requestURL.protocol = url.protocol === 'ws:' ? 'http:' : 'https:' // 2. Let request be a new request, whose URL is requestURL, client is client, // service-workers mode is "none", referrer is "no-referrer", mode is // "websocket", credentials mode is "include", cache mode is "no-store" , // and redirect mode is "error". const request = makeRequest({ urlList: [requestURL], serviceWorkers: 'none', referrer: 'no-referrer', mode: 'websocket', credentials: 'include', cache: 'no-store', redirect: 'error' }) // Note: undici extension, allow setting custom headers. if (options.headers) { const headersList = new Headers(options.headers)[kHeadersList] request.headersList = headersList } // 3. Append (`Upgrade`, `websocket`) to request’s header list. // 4. Append (`Connection`, `Upgrade`) to request’s header list. // Note: both of these are handled by undici currently. // https://github.com/nodejs/undici/blob/68c269c4144c446f3f1220951338daef4a6b5ec4/lib/client.js#L1397 // 5. Let keyValue be a nonce consisting of a randomly selected // 16-byte value that has been forgiving-base64-encoded and // isomorphic encoded. const keyValue = crypto.randomBytes(16).toString('base64') // 6. Append (`Sec-WebSocket-Key`, keyValue) to request’s // header list. request.headersList.append('sec-websocket-key', keyValue) // 7. Append (`Sec-WebSocket-Version`, `13`) to request’s // header list. request.headersList.append('sec-websocket-version', '13') // 8. For each protocol in protocols, combine // (`Sec-WebSocket-Protocol`, protocol) in request’s header // list. for (const protocol of protocols) { request.headersList.append('sec-websocket-protocol', protocol) } // 9. Let permessageDeflate be a user-agent defined // "permessage-deflate" extension header value. // https://github.com/mozilla/gecko-dev/blob/ce78234f5e653a5d3916813ff990f053510227bc/netwerk/protocol/websocket/WebSocketChannel.cpp#L2673 // TODO: enable once permessage-deflate is supported const permessageDeflate = '' // 'permessage-deflate; 15' // 10. Append (`Sec-WebSocket-Extensions`, permessageDeflate) to // request’s header list. // request.headersList.append('sec-websocket-extensions', permessageDeflate) // 11. Fetch request with useParallelQueue set to true, and // processResponse given response being these steps: const controller = fetching({ request, useParallelQueue: true, dispatcher: options.dispatcher ?? getGlobalDispatcher(), processResponse (response) { // 1. If response is a network error or its status is not 101, // fail the WebSocket connection. if (response.type === 'error' || response.status !== 101) { failWebsocketConnection(ws, 'Received network error or non-101 status code.') return } // 2. If protocols is not the empty list and extracting header // list values given `Sec-WebSocket-Protocol` and response’s // header list results in null, failure, or the empty byte // sequence, then fail the WebSocket connection. if (protocols.length !== 0 && !response.headersList.get('Sec-WebSocket-Protocol')) { failWebsocketConnection(ws, 'Server did not respond with sent protocols.') return } // 3. Follow the requirements stated step 2 to step 6, inclusive, // of the last set of steps in section 4.1 of The WebSocket // Protocol to validate response. This either results in fail // the WebSocket connection or the WebSocket connection is // established. // 2. If the response lacks an |Upgrade| header field or the |Upgrade| // header field contains a value that is not an ASCII case- // insensitive match for the value "websocket", the client MUST // _Fail the WebSocket Connection_. if (response.headersList.get('Upgrade')?.toLowerCase() !== 'websocket') { failWebsocketConnection(ws, 'Server did not set Upgrade header to "websocket".') return } // 3. If the response lacks a |Connection| header field or the // |Connection| header field doesn't contain a token that is an // ASCII case-insensitive match for the value "Upgrade", the client // MUST _Fail the WebSocket Connection_. if (response.headersList.get('Connection')?.toLowerCase() !== 'upgrade') { failWebsocketConnection(ws, 'Server did not set Connection header to "upgrade".') return } // 4. If the response lacks a |Sec-WebSocket-Accept| header field or // the |Sec-WebSocket-Accept| contains a value other than the // base64-encoded SHA-1 of the concatenation of the |Sec-WebSocket- // Key| (as a string, not base64-decoded) with the string "258EAFA5- // E914-47DA-95CA-C5AB0DC85B11" but ignoring any leading and // trailing whitespace, the client MUST _Fail the WebSocket // Connection_. const secWSAccept = response.headersList.get('Sec-WebSocket-Accept') const digest = crypto.createHash('sha1').update(keyValue + uid).digest('base64') if (secWSAccept !== digest) { failWebsocketConnection(ws, 'Incorrect hash received in Sec-WebSocket-Accept header.') return } // 5. If the response includes a |Sec-WebSocket-Extensions| header // field and this header field indicates the use of an extension // that was not present in the client's handshake (the server has // indicated an extension not requested by the client), the client // MUST _Fail the WebSocket Connection_. (The parsing of this // header field to determine which extensions are requested is // discussed in Section 9.1.) const secExtension = response.headersList.get('Sec-WebSocket-Extensions') if (secExtension !== null && secExtension !== permessageDeflate) { failWebsocketConnection(ws, 'Received different permessage-deflate than the one set.') return } // 6. If the response includes a |Sec-WebSocket-Protocol| header field // and this header field indicates the use of a subprotocol that was // not present in the client's handshake (the server has indicated a // subprotocol not requested by the client), the client MUST _Fail // the WebSocket Connection_. const secProtocol = response.headersList.get('Sec-WebSocket-Protocol') if (secProtocol !== null && secProtocol !== request.headersList.get('Sec-WebSocket-Protocol')) { failWebsocketConnection(ws, 'Protocol was not set in the opening handshake.') return } response.socket.on('data', onSocketData) response.socket.on('close', onSocketClose) response.socket.on('error', onSocketError) if (channels.open.hasSubscribers) { channels.open.publish({ address: response.socket.address(), protocol: secProtocol, extensions: secExtension }) } onEstablish(response) } }) return controller } /** * @param {Buffer} chunk */ function onSocketData (chunk) { if (!this.ws[kByteParser].write(chunk)) { this.pause() } } /** * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.4 */ function onSocketClose () { const { ws } = this // If the TCP connection was closed after the // WebSocket closing handshake was completed, the WebSocket connection // is said to have been closed _cleanly_. const wasClean = ws[kSentClose] && ws[kReceivedClose] let code = 1005 let reason = '' const result = ws[kByteParser].closingInfo if (result) { code = result.code ?? 1005 reason = result.reason } else if (!ws[kSentClose]) { // If _The WebSocket // Connection is Closed_ and no Close control frame was received by the // endpoint (such as could occur if the underlying transport connection // is lost), _The WebSocket Connection Close Code_ is considered to be // 1006. code = 1006 } // 1. Change the ready state to CLOSED (3). ws[kReadyState] = states.CLOSED // 2. If the user agent was required to fail the WebSocket // connection, or if the WebSocket connection was closed // after being flagged as full, fire an event named error // at the WebSocket object. // TODO // 3. Fire an event named close at the WebSocket object, // using CloseEvent, with the wasClean attribute // initialized to true if the connection closed cleanly // and false otherwise, the code attribute initialized to // the WebSocket connection close code, and the reason // attribute initialized to the result of applying UTF-8 // decode without BOM to the WebSocket connection close // reason. fireEvent('close', ws, CloseEvent, { wasClean, code, reason }) if (channels.close.hasSubscribers) { channels.close.publish({ websocket: ws, code, reason }) } } function onSocketError (error) { const { ws } = this ws[kReadyState] = states.CLOSING if (channels.socketError.hasSubscribers) { channels.socketError.publish(error) } this.destroy() } module.exports = { establishWebSocketConnection } /***/ }), /***/ 19188: /***/ ((module) => { "use strict"; // This is a Globally Unique Identifier unique used // to validate that the endpoint accepts websocket // connections. // See https://www.rfc-editor.org/rfc/rfc6455.html#section-1.3 const uid = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11' /** @type {PropertyDescriptor} */ const staticPropertyDescriptors = { enumerable: true, writable: false, configurable: false } const states = { CONNECTING: 0, OPEN: 1, CLOSING: 2, CLOSED: 3 } const opcodes = { CONTINUATION: 0x0, TEXT: 0x1, BINARY: 0x2, CLOSE: 0x8, PING: 0x9, PONG: 0xA } const maxUnsigned16Bit = 2 ** 16 - 1 // 65535 const parserStates = { INFO: 0, PAYLOADLENGTH_16: 2, PAYLOADLENGTH_64: 3, READ_DATA: 4 } const emptyBuffer = Buffer.allocUnsafe(0) module.exports = { uid, staticPropertyDescriptors, states, opcodes, maxUnsigned16Bit, parserStates, emptyBuffer } /***/ }), /***/ 52611: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { webidl } = __nccwpck_require__(21744) const { kEnumerableProperty } = __nccwpck_require__(83983) const { MessagePort } = __nccwpck_require__(71267) /** * @see https://html.spec.whatwg.org/multipage/comms.html#messageevent */ class MessageEvent extends Event { #eventInit constructor (type, eventInitDict = {}) { webidl.argumentLengthCheck(arguments, 1, { header: 'MessageEvent constructor' }) type = webidl.converters.DOMString(type) eventInitDict = webidl.converters.MessageEventInit(eventInitDict) super(type, eventInitDict) this.#eventInit = eventInitDict } get data () { webidl.brandCheck(this, MessageEvent) return this.#eventInit.data } get origin () { webidl.brandCheck(this, MessageEvent) return this.#eventInit.origin } get lastEventId () { webidl.brandCheck(this, MessageEvent) return this.#eventInit.lastEventId } get source () { webidl.brandCheck(this, MessageEvent) return this.#eventInit.source } get ports () { webidl.brandCheck(this, MessageEvent) if (!Object.isFrozen(this.#eventInit.ports)) { Object.freeze(this.#eventInit.ports) } return this.#eventInit.ports } initMessageEvent ( type, bubbles = false, cancelable = false, data = null, origin = '', lastEventId = '', source = null, ports = [] ) { webidl.brandCheck(this, MessageEvent) webidl.argumentLengthCheck(arguments, 1, { header: 'MessageEvent.initMessageEvent' }) return new MessageEvent(type, { bubbles, cancelable, data, origin, lastEventId, source, ports }) } } /** * @see https://websockets.spec.whatwg.org/#the-closeevent-interface */ class CloseEvent extends Event { #eventInit constructor (type, eventInitDict = {}) { webidl.argumentLengthCheck(arguments, 1, { header: 'CloseEvent constructor' }) type = webidl.converters.DOMString(type) eventInitDict = webidl.converters.CloseEventInit(eventInitDict) super(type, eventInitDict) this.#eventInit = eventInitDict } get wasClean () { webidl.brandCheck(this, CloseEvent) return this.#eventInit.wasClean } get code () { webidl.brandCheck(this, CloseEvent) return this.#eventInit.code } get reason () { webidl.brandCheck(this, CloseEvent) return this.#eventInit.reason } } // https://html.spec.whatwg.org/multipage/webappapis.html#the-errorevent-interface class ErrorEvent extends Event { #eventInit constructor (type, eventInitDict) { webidl.argumentLengthCheck(arguments, 1, { header: 'ErrorEvent constructor' }) super(type, eventInitDict) type = webidl.converters.DOMString(type) eventInitDict = webidl.converters.ErrorEventInit(eventInitDict ?? {}) this.#eventInit = eventInitDict } get message () { webidl.brandCheck(this, ErrorEvent) return this.#eventInit.message } get filename () { webidl.brandCheck(this, ErrorEvent) return this.#eventInit.filename } get lineno () { webidl.brandCheck(this, ErrorEvent) return this.#eventInit.lineno } get colno () { webidl.brandCheck(this, ErrorEvent) return this.#eventInit.colno } get error () { webidl.brandCheck(this, ErrorEvent) return this.#eventInit.error } } Object.defineProperties(MessageEvent.prototype, { [Symbol.toStringTag]: { value: 'MessageEvent', configurable: true }, data: kEnumerableProperty, origin: kEnumerableProperty, lastEventId: kEnumerableProperty, source: kEnumerableProperty, ports: kEnumerableProperty, initMessageEvent: kEnumerableProperty }) Object.defineProperties(CloseEvent.prototype, { [Symbol.toStringTag]: { value: 'CloseEvent', configurable: true }, reason: kEnumerableProperty, code: kEnumerableProperty, wasClean: kEnumerableProperty }) Object.defineProperties(ErrorEvent.prototype, { [Symbol.toStringTag]: { value: 'ErrorEvent', configurable: true }, message: kEnumerableProperty, filename: kEnumerableProperty, lineno: kEnumerableProperty, colno: kEnumerableProperty, error: kEnumerableProperty }) webidl.converters.MessagePort = webidl.interfaceConverter(MessagePort) webidl.converters['sequence'] = webidl.sequenceConverter( webidl.converters.MessagePort ) const eventInit = [ { key: 'bubbles', converter: webidl.converters.boolean, defaultValue: false }, { key: 'cancelable', converter: webidl.converters.boolean, defaultValue: false }, { key: 'composed', converter: webidl.converters.boolean, defaultValue: false } ] webidl.converters.MessageEventInit = webidl.dictionaryConverter([ ...eventInit, { key: 'data', converter: webidl.converters.any, defaultValue: null }, { key: 'origin', converter: webidl.converters.USVString, defaultValue: '' }, { key: 'lastEventId', converter: webidl.converters.DOMString, defaultValue: '' }, { key: 'source', // Node doesn't implement WindowProxy or ServiceWorker, so the only // valid value for source is a MessagePort. converter: webidl.nullableConverter(webidl.converters.MessagePort), defaultValue: null }, { key: 'ports', converter: webidl.converters['sequence'], get defaultValue () { return [] } } ]) webidl.converters.CloseEventInit = webidl.dictionaryConverter([ ...eventInit, { key: 'wasClean', converter: webidl.converters.boolean, defaultValue: false }, { key: 'code', converter: webidl.converters['unsigned short'], defaultValue: 0 }, { key: 'reason', converter: webidl.converters.USVString, defaultValue: '' } ]) webidl.converters.ErrorEventInit = webidl.dictionaryConverter([ ...eventInit, { key: 'message', converter: webidl.converters.DOMString, defaultValue: '' }, { key: 'filename', converter: webidl.converters.USVString, defaultValue: '' }, { key: 'lineno', converter: webidl.converters['unsigned long'], defaultValue: 0 }, { key: 'colno', converter: webidl.converters['unsigned long'], defaultValue: 0 }, { key: 'error', converter: webidl.converters.any } ]) module.exports = { MessageEvent, CloseEvent, ErrorEvent } /***/ }), /***/ 25444: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { maxUnsigned16Bit } = __nccwpck_require__(19188) /** @type {import('crypto')} */ let crypto try { crypto = __nccwpck_require__(6113) } catch { } class WebsocketFrameSend { /** * @param {Buffer|undefined} data */ constructor (data) { this.frameData = data this.maskKey = crypto.randomBytes(4) } createFrame (opcode) { const bodyLength = this.frameData?.byteLength ?? 0 /** @type {number} */ let payloadLength = bodyLength // 0-125 let offset = 6 if (bodyLength > maxUnsigned16Bit) { offset += 8 // payload length is next 8 bytes payloadLength = 127 } else if (bodyLength > 125) { offset += 2 // payload length is next 2 bytes payloadLength = 126 } const buffer = Buffer.allocUnsafe(bodyLength + offset) // Clear first 2 bytes, everything else is overwritten buffer[0] = buffer[1] = 0 buffer[0] |= 0x80 // FIN buffer[0] = (buffer[0] & 0xF0) + opcode // opcode /*! ws. MIT License. Einar Otto Stangvik */ buffer[offset - 4] = this.maskKey[0] buffer[offset - 3] = this.maskKey[1] buffer[offset - 2] = this.maskKey[2] buffer[offset - 1] = this.maskKey[3] buffer[1] = payloadLength if (payloadLength === 126) { buffer.writeUInt16BE(bodyLength, 2) } else if (payloadLength === 127) { // Clear extended payload length buffer[2] = buffer[3] = 0 buffer.writeUIntBE(bodyLength, 4, 6) } buffer[1] |= 0x80 // MASK // mask body for (let i = 0; i < bodyLength; i++) { buffer[offset + i] = this.frameData[i] ^ this.maskKey[i % 4] } return buffer } } module.exports = { WebsocketFrameSend } /***/ }), /***/ 11688: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { Writable } = __nccwpck_require__(12781) const diagnosticsChannel = __nccwpck_require__(67643) const { parserStates, opcodes, states, emptyBuffer } = __nccwpck_require__(19188) const { kReadyState, kSentClose, kResponse, kReceivedClose } = __nccwpck_require__(37578) const { isValidStatusCode, failWebsocketConnection, websocketMessageReceived } = __nccwpck_require__(25515) const { WebsocketFrameSend } = __nccwpck_require__(25444) // This code was influenced by ws released under the MIT license. // Copyright (c) 2011 Einar Otto Stangvik // Copyright (c) 2013 Arnout Kazemier and contributors // Copyright (c) 2016 Luigi Pinca and contributors const channels = {} channels.ping = diagnosticsChannel.channel('undici:websocket:ping') channels.pong = diagnosticsChannel.channel('undici:websocket:pong') class ByteParser extends Writable { #buffers = [] #byteOffset = 0 #state = parserStates.INFO #info = {} #fragments = [] constructor (ws) { super() this.ws = ws } /** * @param {Buffer} chunk * @param {() => void} callback */ _write (chunk, _, callback) { this.#buffers.push(chunk) this.#byteOffset += chunk.length this.run(callback) } /** * Runs whenever a new chunk is received. * Callback is called whenever there are no more chunks buffering, * or not enough bytes are buffered to parse. */ run (callback) { while (true) { if (this.#state === parserStates.INFO) { // If there aren't enough bytes to parse the payload length, etc. if (this.#byteOffset < 2) { return callback() } const buffer = this.consume(2) this.#info.fin = (buffer[0] & 0x80) !== 0 this.#info.opcode = buffer[0] & 0x0F // If we receive a fragmented message, we use the type of the first // frame to parse the full message as binary/text, when it's terminated this.#info.originalOpcode ??= this.#info.opcode this.#info.fragmented = !this.#info.fin && this.#info.opcode !== opcodes.CONTINUATION if (this.#info.fragmented && this.#info.opcode !== opcodes.BINARY && this.#info.opcode !== opcodes.TEXT) { // Only text and binary frames can be fragmented failWebsocketConnection(this.ws, 'Invalid frame type was fragmented.') return } const payloadLength = buffer[1] & 0x7F if (payloadLength <= 125) { this.#info.payloadLength = payloadLength this.#state = parserStates.READ_DATA } else if (payloadLength === 126) { this.#state = parserStates.PAYLOADLENGTH_16 } else if (payloadLength === 127) { this.#state = parserStates.PAYLOADLENGTH_64 } if (this.#info.fragmented && payloadLength > 125) { // A fragmented frame can't be fragmented itself failWebsocketConnection(this.ws, 'Fragmented frame exceeded 125 bytes.') return } else if ( (this.#info.opcode === opcodes.PING || this.#info.opcode === opcodes.PONG || this.#info.opcode === opcodes.CLOSE) && payloadLength > 125 ) { // Control frames can have a payload length of 125 bytes MAX failWebsocketConnection(this.ws, 'Payload length for control frame exceeded 125 bytes.') return } else if (this.#info.opcode === opcodes.CLOSE) { if (payloadLength === 1) { failWebsocketConnection(this.ws, 'Received close frame with a 1-byte body.') return } const body = this.consume(payloadLength) this.#info.closeInfo = this.parseCloseBody(false, body) if (!this.ws[kSentClose]) { // If an endpoint receives a Close frame and did not previously send a // Close frame, the endpoint MUST send a Close frame in response. (When // sending a Close frame in response, the endpoint typically echos the // status code it received.) const body = Buffer.allocUnsafe(2) body.writeUInt16BE(this.#info.closeInfo.code, 0) const closeFrame = new WebsocketFrameSend(body) this.ws[kResponse].socket.write( closeFrame.createFrame(opcodes.CLOSE), (err) => { if (!err) { this.ws[kSentClose] = true } } ) } // Upon either sending or receiving a Close control frame, it is said // that _The WebSocket Closing Handshake is Started_ and that the // WebSocket connection is in the CLOSING state. this.ws[kReadyState] = states.CLOSING this.ws[kReceivedClose] = true this.end() return } else if (this.#info.opcode === opcodes.PING) { // Upon receipt of a Ping frame, an endpoint MUST send a Pong frame in // response, unless it already received a Close frame. // A Pong frame sent in response to a Ping frame must have identical // "Application data" const body = this.consume(payloadLength) if (!this.ws[kReceivedClose]) { const frame = new WebsocketFrameSend(body) this.ws[kResponse].socket.write(frame.createFrame(opcodes.PONG)) if (channels.ping.hasSubscribers) { channels.ping.publish({ payload: body }) } } this.#state = parserStates.INFO if (this.#byteOffset > 0) { continue } else { callback() return } } else if (this.#info.opcode === opcodes.PONG) { // A Pong frame MAY be sent unsolicited. This serves as a // unidirectional heartbeat. A response to an unsolicited Pong frame is // not expected. const body = this.consume(payloadLength) if (channels.pong.hasSubscribers) { channels.pong.publish({ payload: body }) } if (this.#byteOffset > 0) { continue } else { callback() return } } } else if (this.#state === parserStates.PAYLOADLENGTH_16) { if (this.#byteOffset < 2) { return callback() } const buffer = this.consume(2) this.#info.payloadLength = buffer.readUInt16BE(0) this.#state = parserStates.READ_DATA } else if (this.#state === parserStates.PAYLOADLENGTH_64) { if (this.#byteOffset < 8) { return callback() } const buffer = this.consume(8) const upper = buffer.readUInt32BE(0) // 2^31 is the maxinimum bytes an arraybuffer can contain // on 32-bit systems. Although, on 64-bit systems, this is // 2^53-1 bytes. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Invalid_array_length // https://source.chromium.org/chromium/chromium/src/+/main:v8/src/common/globals.h;drc=1946212ac0100668f14eb9e2843bdd846e510a1e;bpv=1;bpt=1;l=1275 // https://source.chromium.org/chromium/chromium/src/+/main:v8/src/objects/js-array-buffer.h;l=34;drc=1946212ac0100668f14eb9e2843bdd846e510a1e if (upper > 2 ** 31 - 1) { failWebsocketConnection(this.ws, 'Received payload length > 2^31 bytes.') return } const lower = buffer.readUInt32BE(4) this.#info.payloadLength = (upper << 8) + lower this.#state = parserStates.READ_DATA } else if (this.#state === parserStates.READ_DATA) { if (this.#byteOffset < this.#info.payloadLength) { // If there is still more data in this chunk that needs to be read return callback() } else if (this.#byteOffset >= this.#info.payloadLength) { // If the server sent multiple frames in a single chunk const body = this.consume(this.#info.payloadLength) this.#fragments.push(body) // If the frame is unfragmented, or a fragmented frame was terminated, // a message was received if (!this.#info.fragmented || (this.#info.fin && this.#info.opcode === opcodes.CONTINUATION)) { const fullMessage = Buffer.concat(this.#fragments) websocketMessageReceived(this.ws, this.#info.originalOpcode, fullMessage) this.#info = {} this.#fragments.length = 0 } this.#state = parserStates.INFO } } if (this.#byteOffset > 0) { continue } else { callback() break } } } /** * Take n bytes from the buffered Buffers * @param {number} n * @returns {Buffer|null} */ consume (n) { if (n > this.#byteOffset) { return null } else if (n === 0) { return emptyBuffer } if (this.#buffers[0].length === n) { this.#byteOffset -= this.#buffers[0].length return this.#buffers.shift() } const buffer = Buffer.allocUnsafe(n) let offset = 0 while (offset !== n) { const next = this.#buffers[0] const { length } = next if (length + offset === n) { buffer.set(this.#buffers.shift(), offset) break } else if (length + offset > n) { buffer.set(next.subarray(0, n - offset), offset) this.#buffers[0] = next.subarray(n - offset) break } else { buffer.set(this.#buffers.shift(), offset) offset += next.length } } this.#byteOffset -= n return buffer } parseCloseBody (onlyCode, data) { // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5 /** @type {number|undefined} */ let code if (data.length >= 2) { // _The WebSocket Connection Close Code_ is // defined as the status code (Section 7.4) contained in the first Close // control frame received by the application code = data.readUInt16BE(0) } if (onlyCode) { if (!isValidStatusCode(code)) { return null } return { code } } // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.6 /** @type {Buffer} */ let reason = data.subarray(2) // Remove BOM if (reason[0] === 0xEF && reason[1] === 0xBB && reason[2] === 0xBF) { reason = reason.subarray(3) } if (code !== undefined && !isValidStatusCode(code)) { return null } try { // TODO: optimize this reason = new TextDecoder('utf-8', { fatal: true }).decode(reason) } catch { return null } return { code, reason } } get closingInfo () { return this.#info.closeInfo } } module.exports = { ByteParser } /***/ }), /***/ 37578: /***/ ((module) => { "use strict"; module.exports = { kWebSocketURL: Symbol('url'), kReadyState: Symbol('ready state'), kController: Symbol('controller'), kResponse: Symbol('response'), kBinaryType: Symbol('binary type'), kSentClose: Symbol('sent close'), kReceivedClose: Symbol('received close'), kByteParser: Symbol('byte parser') } /***/ }), /***/ 25515: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { kReadyState, kController, kResponse, kBinaryType, kWebSocketURL } = __nccwpck_require__(37578) const { states, opcodes } = __nccwpck_require__(19188) const { MessageEvent, ErrorEvent } = __nccwpck_require__(52611) /* globals Blob */ /** * @param {import('./websocket').WebSocket} ws */ function isEstablished (ws) { // If the server's response is validated as provided for above, it is // said that _The WebSocket Connection is Established_ and that the // WebSocket Connection is in the OPEN state. return ws[kReadyState] === states.OPEN } /** * @param {import('./websocket').WebSocket} ws */ function isClosing (ws) { // Upon either sending or receiving a Close control frame, it is said // that _The WebSocket Closing Handshake is Started_ and that the // WebSocket connection is in the CLOSING state. return ws[kReadyState] === states.CLOSING } /** * @param {import('./websocket').WebSocket} ws */ function isClosed (ws) { return ws[kReadyState] === states.CLOSED } /** * @see https://dom.spec.whatwg.org/#concept-event-fire * @param {string} e * @param {EventTarget} target * @param {EventInit | undefined} eventInitDict */ function fireEvent (e, target, eventConstructor = Event, eventInitDict) { // 1. If eventConstructor is not given, then let eventConstructor be Event. // 2. Let event be the result of creating an event given eventConstructor, // in the relevant realm of target. // 3. Initialize event’s type attribute to e. const event = new eventConstructor(e, eventInitDict) // eslint-disable-line new-cap // 4. Initialize any other IDL attributes of event as described in the // invocation of this algorithm. // 5. Return the result of dispatching event at target, with legacy target // override flag set if set. target.dispatchEvent(event) } /** * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol * @param {import('./websocket').WebSocket} ws * @param {number} type Opcode * @param {Buffer} data application data */ function websocketMessageReceived (ws, type, data) { // 1. If ready state is not OPEN (1), then return. if (ws[kReadyState] !== states.OPEN) { return } // 2. Let dataForEvent be determined by switching on type and binary type: let dataForEvent if (type === opcodes.TEXT) { // -> type indicates that the data is Text // a new DOMString containing data try { dataForEvent = new TextDecoder('utf-8', { fatal: true }).decode(data) } catch { failWebsocketConnection(ws, 'Received invalid UTF-8 in text frame.') return } } else if (type === opcodes.BINARY) { if (ws[kBinaryType] === 'blob') { // -> type indicates that the data is Binary and binary type is "blob" // a new Blob object, created in the relevant Realm of the WebSocket // object, that represents data as its raw data dataForEvent = new Blob([data]) } else { // -> type indicates that the data is Binary and binary type is "arraybuffer" // a new ArrayBuffer object, created in the relevant Realm of the // WebSocket object, whose contents are data dataForEvent = new Uint8Array(data).buffer } } // 3. Fire an event named message at the WebSocket object, using MessageEvent, // with the origin attribute initialized to the serialization of the WebSocket // object’s url's origin, and the data attribute initialized to dataForEvent. fireEvent('message', ws, MessageEvent, { origin: ws[kWebSocketURL].origin, data: dataForEvent }) } /** * @see https://datatracker.ietf.org/doc/html/rfc6455 * @see https://datatracker.ietf.org/doc/html/rfc2616 * @see https://bugs.chromium.org/p/chromium/issues/detail?id=398407 * @param {string} protocol */ function isValidSubprotocol (protocol) { // If present, this value indicates one // or more comma-separated subprotocol the client wishes to speak, // ordered by preference. The elements that comprise this value // MUST be non-empty strings with characters in the range U+0021 to // U+007E not including separator characters as defined in // [RFC2616] and MUST all be unique strings. if (protocol.length === 0) { return false } for (const char of protocol) { const code = char.charCodeAt(0) if ( code < 0x21 || code > 0x7E || char === '(' || char === ')' || char === '<' || char === '>' || char === '@' || char === ',' || char === ';' || char === ':' || char === '\\' || char === '"' || char === '/' || char === '[' || char === ']' || char === '?' || char === '=' || char === '{' || char === '}' || code === 32 || // SP code === 9 // HT ) { return false } } return true } /** * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7-4 * @param {number} code */ function isValidStatusCode (code) { if (code >= 1000 && code < 1015) { return ( code !== 1004 && // reserved code !== 1005 && // "MUST NOT be set as a status code" code !== 1006 // "MUST NOT be set as a status code" ) } return code >= 3000 && code <= 4999 } /** * @param {import('./websocket').WebSocket} ws * @param {string|undefined} reason */ function failWebsocketConnection (ws, reason) { const { [kController]: controller, [kResponse]: response } = ws controller.abort() if (response?.socket && !response.socket.destroyed) { response.socket.destroy() } if (reason) { fireEvent('error', ws, ErrorEvent, { error: new Error(reason) }) } } module.exports = { isEstablished, isClosing, isClosed, fireEvent, isValidSubprotocol, isValidStatusCode, failWebsocketConnection, websocketMessageReceived } /***/ }), /***/ 54284: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { webidl } = __nccwpck_require__(21744) const { DOMException } = __nccwpck_require__(41037) const { URLSerializer } = __nccwpck_require__(685) const { getGlobalOrigin } = __nccwpck_require__(71246) const { staticPropertyDescriptors, states, opcodes, emptyBuffer } = __nccwpck_require__(19188) const { kWebSocketURL, kReadyState, kController, kBinaryType, kResponse, kSentClose, kByteParser } = __nccwpck_require__(37578) const { isEstablished, isClosing, isValidSubprotocol, failWebsocketConnection, fireEvent } = __nccwpck_require__(25515) const { establishWebSocketConnection } = __nccwpck_require__(35354) const { WebsocketFrameSend } = __nccwpck_require__(25444) const { ByteParser } = __nccwpck_require__(11688) const { kEnumerableProperty, isBlobLike } = __nccwpck_require__(83983) const { getGlobalDispatcher } = __nccwpck_require__(21892) const { types } = __nccwpck_require__(73837) let experimentalWarned = false // https://websockets.spec.whatwg.org/#interface-definition class WebSocket extends EventTarget { #events = { open: null, error: null, close: null, message: null } #bufferedAmount = 0 #protocol = '' #extensions = '' /** * @param {string} url * @param {string|string[]} protocols */ constructor (url, protocols = []) { super() webidl.argumentLengthCheck(arguments, 1, { header: 'WebSocket constructor' }) if (!experimentalWarned) { experimentalWarned = true process.emitWarning('WebSockets are experimental, expect them to change at any time.', { code: 'UNDICI-WS' }) } const options = webidl.converters['DOMString or sequence or WebSocketInit'](protocols) url = webidl.converters.USVString(url) protocols = options.protocols // 1. Let baseURL be this's relevant settings object's API base URL. const baseURL = getGlobalOrigin() // 1. Let urlRecord be the result of applying the URL parser to url with baseURL. let urlRecord try { urlRecord = new URL(url, baseURL) } catch (e) { // 3. If urlRecord is failure, then throw a "SyntaxError" DOMException. throw new DOMException(e, 'SyntaxError') } // 4. If urlRecord’s scheme is "http", then set urlRecord’s scheme to "ws". if (urlRecord.protocol === 'http:') { urlRecord.protocol = 'ws:' } else if (urlRecord.protocol === 'https:') { // 5. Otherwise, if urlRecord’s scheme is "https", set urlRecord’s scheme to "wss". urlRecord.protocol = 'wss:' } // 6. If urlRecord’s scheme is not "ws" or "wss", then throw a "SyntaxError" DOMException. if (urlRecord.protocol !== 'ws:' && urlRecord.protocol !== 'wss:') { throw new DOMException( `Expected a ws: or wss: protocol, got ${urlRecord.protocol}`, 'SyntaxError' ) } // 7. If urlRecord’s fragment is non-null, then throw a "SyntaxError" // DOMException. if (urlRecord.hash || urlRecord.href.endsWith('#')) { throw new DOMException('Got fragment', 'SyntaxError') } // 8. If protocols is a string, set protocols to a sequence consisting // of just that string. if (typeof protocols === 'string') { protocols = [protocols] } // 9. If any of the values in protocols occur more than once or otherwise // fail to match the requirements for elements that comprise the value // of `Sec-WebSocket-Protocol` fields as defined by The WebSocket // protocol, then throw a "SyntaxError" DOMException. if (protocols.length !== new Set(protocols.map(p => p.toLowerCase())).size) { throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError') } if (protocols.length > 0 && !protocols.every(p => isValidSubprotocol(p))) { throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError') } // 10. Set this's url to urlRecord. this[kWebSocketURL] = new URL(urlRecord.href) // 11. Let client be this's relevant settings object. // 12. Run this step in parallel: // 1. Establish a WebSocket connection given urlRecord, protocols, // and client. this[kController] = establishWebSocketConnection( urlRecord, protocols, this, (response) => this.#onConnectionEstablished(response), options ) // Each WebSocket object has an associated ready state, which is a // number representing the state of the connection. Initially it must // be CONNECTING (0). this[kReadyState] = WebSocket.CONNECTING // The extensions attribute must initially return the empty string. // The protocol attribute must initially return the empty string. // Each WebSocket object has an associated binary type, which is a // BinaryType. Initially it must be "blob". this[kBinaryType] = 'blob' } /** * @see https://websockets.spec.whatwg.org/#dom-websocket-close * @param {number|undefined} code * @param {string|undefined} reason */ close (code = undefined, reason = undefined) { webidl.brandCheck(this, WebSocket) if (code !== undefined) { code = webidl.converters['unsigned short'](code, { clamp: true }) } if (reason !== undefined) { reason = webidl.converters.USVString(reason) } // 1. If code is present, but is neither an integer equal to 1000 nor an // integer in the range 3000 to 4999, inclusive, throw an // "InvalidAccessError" DOMException. if (code !== undefined) { if (code !== 1000 && (code < 3000 || code > 4999)) { throw new DOMException('invalid code', 'InvalidAccessError') } } let reasonByteLength = 0 // 2. If reason is present, then run these substeps: if (reason !== undefined) { // 1. Let reasonBytes be the result of encoding reason. // 2. If reasonBytes is longer than 123 bytes, then throw a // "SyntaxError" DOMException. reasonByteLength = Buffer.byteLength(reason) if (reasonByteLength > 123) { throw new DOMException( `Reason must be less than 123 bytes; received ${reasonByteLength}`, 'SyntaxError' ) } } // 3. Run the first matching steps from the following list: if (this[kReadyState] === WebSocket.CLOSING || this[kReadyState] === WebSocket.CLOSED) { // If this's ready state is CLOSING (2) or CLOSED (3) // Do nothing. } else if (!isEstablished(this)) { // If the WebSocket connection is not yet established // Fail the WebSocket connection and set this's ready state // to CLOSING (2). failWebsocketConnection(this, 'Connection was closed before it was established.') this[kReadyState] = WebSocket.CLOSING } else if (!isClosing(this)) { // If the WebSocket closing handshake has not yet been started // Start the WebSocket closing handshake and set this's ready // state to CLOSING (2). // - If neither code nor reason is present, the WebSocket Close // message must not have a body. // - If code is present, then the status code to use in the // WebSocket Close message must be the integer given by code. // - If reason is also present, then reasonBytes must be // provided in the Close message after the status code. const frame = new WebsocketFrameSend() // If neither code nor reason is present, the WebSocket Close // message must not have a body. // If code is present, then the status code to use in the // WebSocket Close message must be the integer given by code. if (code !== undefined && reason === undefined) { frame.frameData = Buffer.allocUnsafe(2) frame.frameData.writeUInt16BE(code, 0) } else if (code !== undefined && reason !== undefined) { // If reason is also present, then reasonBytes must be // provided in the Close message after the status code. frame.frameData = Buffer.allocUnsafe(2 + reasonByteLength) frame.frameData.writeUInt16BE(code, 0) // the body MAY contain UTF-8-encoded data with value /reason/ frame.frameData.write(reason, 2, 'utf-8') } else { frame.frameData = emptyBuffer } /** @type {import('stream').Duplex} */ const socket = this[kResponse].socket socket.write(frame.createFrame(opcodes.CLOSE), (err) => { if (!err) { this[kSentClose] = true } }) // Upon either sending or receiving a Close control frame, it is said // that _The WebSocket Closing Handshake is Started_ and that the // WebSocket connection is in the CLOSING state. this[kReadyState] = states.CLOSING } else { // Otherwise // Set this's ready state to CLOSING (2). this[kReadyState] = WebSocket.CLOSING } } /** * @see https://websockets.spec.whatwg.org/#dom-websocket-send * @param {NodeJS.TypedArray|ArrayBuffer|Blob|string} data */ send (data) { webidl.brandCheck(this, WebSocket) webidl.argumentLengthCheck(arguments, 1, { header: 'WebSocket.send' }) data = webidl.converters.WebSocketSendData(data) // 1. If this's ready state is CONNECTING, then throw an // "InvalidStateError" DOMException. if (this[kReadyState] === WebSocket.CONNECTING) { throw new DOMException('Sent before connected.', 'InvalidStateError') } // 2. Run the appropriate set of steps from the following list: // https://datatracker.ietf.org/doc/html/rfc6455#section-6.1 // https://datatracker.ietf.org/doc/html/rfc6455#section-5.2 if (!isEstablished(this) || isClosing(this)) { return } /** @type {import('stream').Duplex} */ const socket = this[kResponse].socket // If data is a string if (typeof data === 'string') { // If the WebSocket connection is established and the WebSocket // closing handshake has not yet started, then the user agent // must send a WebSocket Message comprised of the data argument // using a text frame opcode; if the data cannot be sent, e.g. // because it would need to be buffered but the buffer is full, // the user agent must flag the WebSocket as full and then close // the WebSocket connection. Any invocation of this method with a // string argument that does not throw an exception must increase // the bufferedAmount attribute by the number of bytes needed to // express the argument as UTF-8. const value = Buffer.from(data) const frame = new WebsocketFrameSend(value) const buffer = frame.createFrame(opcodes.TEXT) this.#bufferedAmount += value.byteLength socket.write(buffer, () => { this.#bufferedAmount -= value.byteLength }) } else if (types.isArrayBuffer(data)) { // If the WebSocket connection is established, and the WebSocket // closing handshake has not yet started, then the user agent must // send a WebSocket Message comprised of data using a binary frame // opcode; if the data cannot be sent, e.g. because it would need // to be buffered but the buffer is full, the user agent must flag // the WebSocket as full and then close the WebSocket connection. // The data to be sent is the data stored in the buffer described // by the ArrayBuffer object. Any invocation of this method with an // ArrayBuffer argument that does not throw an exception must // increase the bufferedAmount attribute by the length of the // ArrayBuffer in bytes. const value = Buffer.from(data) const frame = new WebsocketFrameSend(value) const buffer = frame.createFrame(opcodes.BINARY) this.#bufferedAmount += value.byteLength socket.write(buffer, () => { this.#bufferedAmount -= value.byteLength }) } else if (ArrayBuffer.isView(data)) { // If the WebSocket connection is established, and the WebSocket // closing handshake has not yet started, then the user agent must // send a WebSocket Message comprised of data using a binary frame // opcode; if the data cannot be sent, e.g. because it would need to // be buffered but the buffer is full, the user agent must flag the // WebSocket as full and then close the WebSocket connection. The // data to be sent is the data stored in the section of the buffer // described by the ArrayBuffer object that data references. Any // invocation of this method with this kind of argument that does // not throw an exception must increase the bufferedAmount attribute // by the length of data’s buffer in bytes. const ab = Buffer.from(data, data.byteOffset, data.byteLength) const frame = new WebsocketFrameSend(ab) const buffer = frame.createFrame(opcodes.BINARY) this.#bufferedAmount += ab.byteLength socket.write(buffer, () => { this.#bufferedAmount -= ab.byteLength }) } else if (isBlobLike(data)) { // If the WebSocket connection is established, and the WebSocket // closing handshake has not yet started, then the user agent must // send a WebSocket Message comprised of data using a binary frame // opcode; if the data cannot be sent, e.g. because it would need to // be buffered but the buffer is full, the user agent must flag the // WebSocket as full and then close the WebSocket connection. The data // to be sent is the raw data represented by the Blob object. Any // invocation of this method with a Blob argument that does not throw // an exception must increase the bufferedAmount attribute by the size // of the Blob object’s raw data, in bytes. const frame = new WebsocketFrameSend() data.arrayBuffer().then((ab) => { const value = Buffer.from(ab) frame.frameData = value const buffer = frame.createFrame(opcodes.BINARY) this.#bufferedAmount += value.byteLength socket.write(buffer, () => { this.#bufferedAmount -= value.byteLength }) }) } } get readyState () { webidl.brandCheck(this, WebSocket) // The readyState getter steps are to return this's ready state. return this[kReadyState] } get bufferedAmount () { webidl.brandCheck(this, WebSocket) return this.#bufferedAmount } get url () { webidl.brandCheck(this, WebSocket) // The url getter steps are to return this's url, serialized. return URLSerializer(this[kWebSocketURL]) } get extensions () { webidl.brandCheck(this, WebSocket) return this.#extensions } get protocol () { webidl.brandCheck(this, WebSocket) return this.#protocol } get onopen () { webidl.brandCheck(this, WebSocket) return this.#events.open } set onopen (fn) { webidl.brandCheck(this, WebSocket) if (this.#events.open) { this.removeEventListener('open', this.#events.open) } if (typeof fn === 'function') { this.#events.open = fn this.addEventListener('open', fn) } else { this.#events.open = null } } get onerror () { webidl.brandCheck(this, WebSocket) return this.#events.error } set onerror (fn) { webidl.brandCheck(this, WebSocket) if (this.#events.error) { this.removeEventListener('error', this.#events.error) } if (typeof fn === 'function') { this.#events.error = fn this.addEventListener('error', fn) } else { this.#events.error = null } } get onclose () { webidl.brandCheck(this, WebSocket) return this.#events.close } set onclose (fn) { webidl.brandCheck(this, WebSocket) if (this.#events.close) { this.removeEventListener('close', this.#events.close) } if (typeof fn === 'function') { this.#events.close = fn this.addEventListener('close', fn) } else { this.#events.close = null } } get onmessage () { webidl.brandCheck(this, WebSocket) return this.#events.message } set onmessage (fn) { webidl.brandCheck(this, WebSocket) if (this.#events.message) { this.removeEventListener('message', this.#events.message) } if (typeof fn === 'function') { this.#events.message = fn this.addEventListener('message', fn) } else { this.#events.message = null } } get binaryType () { webidl.brandCheck(this, WebSocket) return this[kBinaryType] } set binaryType (type) { webidl.brandCheck(this, WebSocket) if (type !== 'blob' && type !== 'arraybuffer') { this[kBinaryType] = 'blob' } else { this[kBinaryType] = type } } /** * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol */ #onConnectionEstablished (response) { // processResponse is called when the "response’s header list has been received and initialized." // once this happens, the connection is open this[kResponse] = response const parser = new ByteParser(this) parser.on('drain', function onParserDrain () { this.ws[kResponse].socket.resume() }) response.socket.ws = this this[kByteParser] = parser // 1. Change the ready state to OPEN (1). this[kReadyState] = states.OPEN // 2. Change the extensions attribute’s value to the extensions in use, if // it is not the null value. // https://datatracker.ietf.org/doc/html/rfc6455#section-9.1 const extensions = response.headersList.get('sec-websocket-extensions') if (extensions !== null) { this.#extensions = extensions } // 3. Change the protocol attribute’s value to the subprotocol in use, if // it is not the null value. // https://datatracker.ietf.org/doc/html/rfc6455#section-1.9 const protocol = response.headersList.get('sec-websocket-protocol') if (protocol !== null) { this.#protocol = protocol } // 4. Fire an event named open at the WebSocket object. fireEvent('open', this) } } // https://websockets.spec.whatwg.org/#dom-websocket-connecting WebSocket.CONNECTING = WebSocket.prototype.CONNECTING = states.CONNECTING // https://websockets.spec.whatwg.org/#dom-websocket-open WebSocket.OPEN = WebSocket.prototype.OPEN = states.OPEN // https://websockets.spec.whatwg.org/#dom-websocket-closing WebSocket.CLOSING = WebSocket.prototype.CLOSING = states.CLOSING // https://websockets.spec.whatwg.org/#dom-websocket-closed WebSocket.CLOSED = WebSocket.prototype.CLOSED = states.CLOSED Object.defineProperties(WebSocket.prototype, { CONNECTING: staticPropertyDescriptors, OPEN: staticPropertyDescriptors, CLOSING: staticPropertyDescriptors, CLOSED: staticPropertyDescriptors, url: kEnumerableProperty, readyState: kEnumerableProperty, bufferedAmount: kEnumerableProperty, onopen: kEnumerableProperty, onerror: kEnumerableProperty, onclose: kEnumerableProperty, close: kEnumerableProperty, onmessage: kEnumerableProperty, binaryType: kEnumerableProperty, send: kEnumerableProperty, extensions: kEnumerableProperty, protocol: kEnumerableProperty, [Symbol.toStringTag]: { value: 'WebSocket', writable: false, enumerable: false, configurable: true } }) Object.defineProperties(WebSocket, { CONNECTING: staticPropertyDescriptors, OPEN: staticPropertyDescriptors, CLOSING: staticPropertyDescriptors, CLOSED: staticPropertyDescriptors }) webidl.converters['sequence'] = webidl.sequenceConverter( webidl.converters.DOMString ) webidl.converters['DOMString or sequence'] = function (V) { if (webidl.util.Type(V) === 'Object' && Symbol.iterator in V) { return webidl.converters['sequence'](V) } return webidl.converters.DOMString(V) } // This implements the propsal made in https://github.com/whatwg/websockets/issues/42 webidl.converters.WebSocketInit = webidl.dictionaryConverter([ { key: 'protocols', converter: webidl.converters['DOMString or sequence'], get defaultValue () { return [] } }, { key: 'dispatcher', converter: (V) => V, get defaultValue () { return getGlobalDispatcher() } }, { key: 'headers', converter: webidl.nullableConverter(webidl.converters.HeadersInit) } ]) webidl.converters['DOMString or sequence or WebSocketInit'] = function (V) { if (webidl.util.Type(V) === 'Object' && !(Symbol.iterator in V)) { return webidl.converters.WebSocketInit(V) } return { protocols: webidl.converters['DOMString or sequence'](V) } } webidl.converters.WebSocketSendData = function (V) { if (webidl.util.Type(V) === 'Object') { if (isBlobLike(V)) { return webidl.converters.Blob(V, { strict: false }) } if (ArrayBuffer.isView(V) || types.isAnyArrayBuffer(V)) { return webidl.converters.BufferSource(V) } } return webidl.converters.USVString(V) } module.exports = { WebSocket } /***/ }), /***/ 45030: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); function getUserAgent() { if (typeof navigator === "object" && "userAgent" in navigator) { return navigator.userAgent; } if (typeof process === "object" && "version" in process) { return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`; } return ""; } exports.getUserAgent = getUserAgent; //# sourceMappingURL=index.js.map /***/ }), /***/ 70020: /***/ (function(__unused_webpack_module, exports) { /** @license URI.js v4.4.1 (c) 2011 Gary Court. License: http://github.com/garycourt/uri-js */ (function (global, factory) { true ? factory(exports) : 0; }(this, (function (exports) { 'use strict'; function merge() { for (var _len = arguments.length, sets = Array(_len), _key = 0; _key < _len; _key++) { sets[_key] = arguments[_key]; } if (sets.length > 1) { sets[0] = sets[0].slice(0, -1); var xl = sets.length - 1; for (var x = 1; x < xl; ++x) { sets[x] = sets[x].slice(1, -1); } sets[xl] = sets[xl].slice(1); return sets.join(''); } else { return sets[0]; } } function subexp(str) { return "(?:" + str + ")"; } function typeOf(o) { return o === undefined ? "undefined" : o === null ? "null" : Object.prototype.toString.call(o).split(" ").pop().split("]").shift().toLowerCase(); } function toUpperCase(str) { return str.toUpperCase(); } function toArray(obj) { return obj !== undefined && obj !== null ? obj instanceof Array ? obj : typeof obj.length !== "number" || obj.split || obj.setInterval || obj.call ? [obj] : Array.prototype.slice.call(obj) : []; } function assign(target, source) { var obj = target; if (source) { for (var key in source) { obj[key] = source[key]; } } return obj; } function buildExps(isIRI) { var ALPHA$$ = "[A-Za-z]", CR$ = "[\\x0D]", DIGIT$$ = "[0-9]", DQUOTE$$ = "[\\x22]", HEXDIG$$ = merge(DIGIT$$, "[A-Fa-f]"), //case-insensitive LF$$ = "[\\x0A]", SP$$ = "[\\x20]", PCT_ENCODED$ = subexp(subexp("%[EFef]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%[89A-Fa-f]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%" + HEXDIG$$ + HEXDIG$$)), //expanded GEN_DELIMS$$ = "[\\:\\/\\?\\#\\[\\]\\@]", SUB_DELIMS$$ = "[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]", RESERVED$$ = merge(GEN_DELIMS$$, SUB_DELIMS$$), UCSCHAR$$ = isIRI ? "[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]" : "[]", //subset, excludes bidi control characters IPRIVATE$$ = isIRI ? "[\\uE000-\\uF8FF]" : "[]", //subset UNRESERVED$$ = merge(ALPHA$$, DIGIT$$, "[\\-\\.\\_\\~]", UCSCHAR$$), SCHEME$ = subexp(ALPHA$$ + merge(ALPHA$$, DIGIT$$, "[\\+\\-\\.]") + "*"), USERINFO$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:]")) + "*"), DEC_OCTET$ = subexp(subexp("25[0-5]") + "|" + subexp("2[0-4]" + DIGIT$$) + "|" + subexp("1" + DIGIT$$ + DIGIT$$) + "|" + subexp("[1-9]" + DIGIT$$) + "|" + DIGIT$$), DEC_OCTET_RELAXED$ = subexp(subexp("25[0-5]") + "|" + subexp("2[0-4]" + DIGIT$$) + "|" + subexp("1" + DIGIT$$ + DIGIT$$) + "|" + subexp("0?[1-9]" + DIGIT$$) + "|0?0?" + DIGIT$$), //relaxed parsing rules IPV4ADDRESS$ = subexp(DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$), H16$ = subexp(HEXDIG$$ + "{1,4}"), LS32$ = subexp(subexp(H16$ + "\\:" + H16$) + "|" + IPV4ADDRESS$), IPV6ADDRESS1$ = subexp(subexp(H16$ + "\\:") + "{6}" + LS32$), // 6( h16 ":" ) ls32 IPV6ADDRESS2$ = subexp("\\:\\:" + subexp(H16$ + "\\:") + "{5}" + LS32$), // "::" 5( h16 ":" ) ls32 IPV6ADDRESS3$ = subexp(subexp(H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{4}" + LS32$), //[ h16 ] "::" 4( h16 ":" ) ls32 IPV6ADDRESS4$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,1}" + H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{3}" + LS32$), //[ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32 IPV6ADDRESS5$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,2}" + H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{2}" + LS32$), //[ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32 IPV6ADDRESS6$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,3}" + H16$) + "?\\:\\:" + H16$ + "\\:" + LS32$), //[ *3( h16 ":" ) h16 ] "::" h16 ":" ls32 IPV6ADDRESS7$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,4}" + H16$) + "?\\:\\:" + LS32$), //[ *4( h16 ":" ) h16 ] "::" ls32 IPV6ADDRESS8$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,5}" + H16$) + "?\\:\\:" + H16$), //[ *5( h16 ":" ) h16 ] "::" h16 IPV6ADDRESS9$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,6}" + H16$) + "?\\:\\:"), //[ *6( h16 ":" ) h16 ] "::" IPV6ADDRESS$ = subexp([IPV6ADDRESS1$, IPV6ADDRESS2$, IPV6ADDRESS3$, IPV6ADDRESS4$, IPV6ADDRESS5$, IPV6ADDRESS6$, IPV6ADDRESS7$, IPV6ADDRESS8$, IPV6ADDRESS9$].join("|")), ZONEID$ = subexp(subexp(UNRESERVED$$ + "|" + PCT_ENCODED$) + "+"), //RFC 6874 IPV6ADDRZ$ = subexp(IPV6ADDRESS$ + "\\%25" + ZONEID$), //RFC 6874 IPV6ADDRZ_RELAXED$ = subexp(IPV6ADDRESS$ + subexp("\\%25|\\%(?!" + HEXDIG$$ + "{2})") + ZONEID$), //RFC 6874, with relaxed parsing rules IPVFUTURE$ = subexp("[vV]" + HEXDIG$$ + "+\\." + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:]") + "+"), IP_LITERAL$ = subexp("\\[" + subexp(IPV6ADDRZ_RELAXED$ + "|" + IPV6ADDRESS$ + "|" + IPVFUTURE$) + "\\]"), //RFC 6874 REG_NAME$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$)) + "*"), HOST$ = subexp(IP_LITERAL$ + "|" + IPV4ADDRESS$ + "(?!" + REG_NAME$ + ")" + "|" + REG_NAME$), PORT$ = subexp(DIGIT$$ + "*"), AUTHORITY$ = subexp(subexp(USERINFO$ + "@") + "?" + HOST$ + subexp("\\:" + PORT$) + "?"), PCHAR$ = subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@]")), SEGMENT$ = subexp(PCHAR$ + "*"), SEGMENT_NZ$ = subexp(PCHAR$ + "+"), SEGMENT_NZ_NC$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\@]")) + "+"), PATH_ABEMPTY$ = subexp(subexp("\\/" + SEGMENT$) + "*"), PATH_ABSOLUTE$ = subexp("\\/" + subexp(SEGMENT_NZ$ + PATH_ABEMPTY$) + "?"), //simplified PATH_NOSCHEME$ = subexp(SEGMENT_NZ_NC$ + PATH_ABEMPTY$), //simplified PATH_ROOTLESS$ = subexp(SEGMENT_NZ$ + PATH_ABEMPTY$), //simplified PATH_EMPTY$ = "(?!" + PCHAR$ + ")", PATH$ = subexp(PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$), QUERY$ = subexp(subexp(PCHAR$ + "|" + merge("[\\/\\?]", IPRIVATE$$)) + "*"), FRAGMENT$ = subexp(subexp(PCHAR$ + "|[\\/\\?]") + "*"), HIER_PART$ = subexp(subexp("\\/\\/" + AUTHORITY$ + PATH_ABEMPTY$) + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$), URI$ = subexp(SCHEME$ + "\\:" + HIER_PART$ + subexp("\\?" + QUERY$) + "?" + subexp("\\#" + FRAGMENT$) + "?"), RELATIVE_PART$ = subexp(subexp("\\/\\/" + AUTHORITY$ + PATH_ABEMPTY$) + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_EMPTY$), RELATIVE$ = subexp(RELATIVE_PART$ + subexp("\\?" + QUERY$) + "?" + subexp("\\#" + FRAGMENT$) + "?"), URI_REFERENCE$ = subexp(URI$ + "|" + RELATIVE$), ABSOLUTE_URI$ = subexp(SCHEME$ + "\\:" + HIER_PART$ + subexp("\\?" + QUERY$) + "?"), GENERIC_REF$ = "^(" + SCHEME$ + ")\\:" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?" + subexp("\\#(" + FRAGMENT$ + ")") + "?$", RELATIVE_REF$ = "^(){0}" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?" + subexp("\\#(" + FRAGMENT$ + ")") + "?$", ABSOLUTE_REF$ = "^(" + SCHEME$ + ")\\:" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?$", SAMEDOC_REF$ = "^" + subexp("\\#(" + FRAGMENT$ + ")") + "?$", AUTHORITY_REF$ = "^" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?$"; return { NOT_SCHEME: new RegExp(merge("[^]", ALPHA$$, DIGIT$$, "[\\+\\-\\.]"), "g"), NOT_USERINFO: new RegExp(merge("[^\\%\\:]", UNRESERVED$$, SUB_DELIMS$$), "g"), NOT_HOST: new RegExp(merge("[^\\%\\[\\]\\:]", UNRESERVED$$, SUB_DELIMS$$), "g"), NOT_PATH: new RegExp(merge("[^\\%\\/\\:\\@]", UNRESERVED$$, SUB_DELIMS$$), "g"), NOT_PATH_NOSCHEME: new RegExp(merge("[^\\%\\/\\@]", UNRESERVED$$, SUB_DELIMS$$), "g"), NOT_QUERY: new RegExp(merge("[^\\%]", UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@\\/\\?]", IPRIVATE$$), "g"), NOT_FRAGMENT: new RegExp(merge("[^\\%]", UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@\\/\\?]"), "g"), ESCAPE: new RegExp(merge("[^]", UNRESERVED$$, SUB_DELIMS$$), "g"), UNRESERVED: new RegExp(UNRESERVED$$, "g"), OTHER_CHARS: new RegExp(merge("[^\\%]", UNRESERVED$$, RESERVED$$), "g"), PCT_ENCODED: new RegExp(PCT_ENCODED$, "g"), IPV4ADDRESS: new RegExp("^(" + IPV4ADDRESS$ + ")$"), IPV6ADDRESS: new RegExp("^\\[?(" + IPV6ADDRESS$ + ")" + subexp(subexp("\\%25|\\%(?!" + HEXDIG$$ + "{2})") + "(" + ZONEID$ + ")") + "?\\]?$") //RFC 6874, with relaxed parsing rules }; } var URI_PROTOCOL = buildExps(false); var IRI_PROTOCOL = buildExps(true); var slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); var toConsumableArray = function (arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; return arr2; } else { return Array.from(arr); } }; /** Highest positive signed 32-bit float value */ var maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1 /** Bootstring parameters */ var base = 36; var tMin = 1; var tMax = 26; var skew = 38; var damp = 700; var initialBias = 72; var initialN = 128; // 0x80 var delimiter = '-'; // '\x2D' /** Regular expressions */ var regexPunycode = /^xn--/; var regexNonASCII = /[^\0-\x7E]/; // non-ASCII chars var regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators /** Error messages */ var errors = { 'overflow': 'Overflow: input needs wider integers to process', 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', 'invalid-input': 'Invalid input' }; /** Convenience shortcuts */ var baseMinusTMin = base - tMin; var floor = Math.floor; var stringFromCharCode = String.fromCharCode; /*--------------------------------------------------------------------------*/ /** * A generic error utility function. * @private * @param {String} type The error type. * @returns {Error} Throws a `RangeError` with the applicable error message. */ function error$1(type) { throw new RangeError(errors[type]); } /** * A generic `Array#map` utility function. * @private * @param {Array} array The array to iterate over. * @param {Function} callback The function that gets called for every array * item. * @returns {Array} A new array of values returned by the callback function. */ function map(array, fn) { var result = []; var length = array.length; while (length--) { result[length] = fn(array[length]); } return result; } /** * A simple `Array#map`-like wrapper to work with domain name strings or email * addresses. * @private * @param {String} domain The domain name or email address. * @param {Function} callback The function that gets called for every * character. * @returns {Array} A new string of characters returned by the callback * function. */ function mapDomain(string, fn) { var parts = string.split('@'); var result = ''; if (parts.length > 1) { // In email addresses, only the domain name should be punycoded. Leave // the local part (i.e. everything up to `@`) intact. result = parts[0] + '@'; string = parts[1]; } // Avoid `split(regex)` for IE8 compatibility. See #17. string = string.replace(regexSeparators, '\x2E'); var labels = string.split('.'); var encoded = map(labels, fn).join('.'); return result + encoded; } /** * Creates an array containing the numeric code points of each Unicode * character in the string. While JavaScript uses UCS-2 internally, * this function will convert a pair of surrogate halves (each of which * UCS-2 exposes as separate characters) into a single code point, * matching UTF-16. * @see `punycode.ucs2.encode` * @see * @memberOf punycode.ucs2 * @name decode * @param {String} string The Unicode input string (UCS-2). * @returns {Array} The new array of code points. */ function ucs2decode(string) { var output = []; var counter = 0; var length = string.length; while (counter < length) { var value = string.charCodeAt(counter++); if (value >= 0xD800 && value <= 0xDBFF && counter < length) { // It's a high surrogate, and there is a next character. var extra = string.charCodeAt(counter++); if ((extra & 0xFC00) == 0xDC00) { // Low surrogate. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); } else { // It's an unmatched surrogate; only append this code unit, in case the // next code unit is the high surrogate of a surrogate pair. output.push(value); counter--; } } else { output.push(value); } } return output; } /** * Creates a string based on an array of numeric code points. * @see `punycode.ucs2.decode` * @memberOf punycode.ucs2 * @name encode * @param {Array} codePoints The array of numeric code points. * @returns {String} The new Unicode string (UCS-2). */ var ucs2encode = function ucs2encode(array) { return String.fromCodePoint.apply(String, toConsumableArray(array)); }; /** * Converts a basic code point into a digit/integer. * @see `digitToBasic()` * @private * @param {Number} codePoint The basic numeric code point value. * @returns {Number} The numeric value of a basic code point (for use in * representing integers) in the range `0` to `base - 1`, or `base` if * the code point does not represent a value. */ var basicToDigit = function basicToDigit(codePoint) { if (codePoint - 0x30 < 0x0A) { return codePoint - 0x16; } if (codePoint - 0x41 < 0x1A) { return codePoint - 0x41; } if (codePoint - 0x61 < 0x1A) { return codePoint - 0x61; } return base; }; /** * Converts a digit/integer into a basic code point. * @see `basicToDigit()` * @private * @param {Number} digit The numeric value of a basic code point. * @returns {Number} The basic code point whose value (when used for * representing integers) is `digit`, which needs to be in the range * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is * used; else, the lowercase form is used. The behavior is undefined * if `flag` is non-zero and `digit` has no uppercase form. */ var digitToBasic = function digitToBasic(digit, flag) { // 0..25 map to ASCII a..z or A..Z // 26..35 map to ASCII 0..9 return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); }; /** * Bias adaptation function as per section 3.4 of RFC 3492. * https://tools.ietf.org/html/rfc3492#section-3.4 * @private */ var adapt = function adapt(delta, numPoints, firstTime) { var k = 0; delta = firstTime ? floor(delta / damp) : delta >> 1; delta += floor(delta / numPoints); for (; /* no initialization */delta > baseMinusTMin * tMax >> 1; k += base) { delta = floor(delta / baseMinusTMin); } return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); }; /** * Converts a Punycode string of ASCII-only symbols to a string of Unicode * symbols. * @memberOf punycode * @param {String} input The Punycode string of ASCII-only symbols. * @returns {String} The resulting string of Unicode symbols. */ var decode = function decode(input) { // Don't use UCS-2. var output = []; var inputLength = input.length; var i = 0; var n = initialN; var bias = initialBias; // Handle the basic code points: let `basic` be the number of input code // points before the last delimiter, or `0` if there is none, then copy // the first basic code points to the output. var basic = input.lastIndexOf(delimiter); if (basic < 0) { basic = 0; } for (var j = 0; j < basic; ++j) { // if it's not a basic code point if (input.charCodeAt(j) >= 0x80) { error$1('not-basic'); } output.push(input.charCodeAt(j)); } // Main decoding loop: start just after the last delimiter if any basic code // points were copied; start at the beginning otherwise. for (var index = basic > 0 ? basic + 1 : 0; index < inputLength;) /* no final expression */{ // `index` is the index of the next character to be consumed. // Decode a generalized variable-length integer into `delta`, // which gets added to `i`. The overflow checking is easier // if we increase `i` as we go, then subtract off its starting // value at the end to obtain `delta`. var oldi = i; for (var w = 1, k = base;; /* no condition */k += base) { if (index >= inputLength) { error$1('invalid-input'); } var digit = basicToDigit(input.charCodeAt(index++)); if (digit >= base || digit > floor((maxInt - i) / w)) { error$1('overflow'); } i += digit * w; var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; if (digit < t) { break; } var baseMinusT = base - t; if (w > floor(maxInt / baseMinusT)) { error$1('overflow'); } w *= baseMinusT; } var out = output.length + 1; bias = adapt(i - oldi, out, oldi == 0); // `i` was supposed to wrap around from `out` to `0`, // incrementing `n` each time, so we'll fix that now: if (floor(i / out) > maxInt - n) { error$1('overflow'); } n += floor(i / out); i %= out; // Insert `n` at position `i` of the output. output.splice(i++, 0, n); } return String.fromCodePoint.apply(String, output); }; /** * Converts a string of Unicode symbols (e.g. a domain name label) to a * Punycode string of ASCII-only symbols. * @memberOf punycode * @param {String} input The string of Unicode symbols. * @returns {String} The resulting Punycode string of ASCII-only symbols. */ var encode = function encode(input) { var output = []; // Convert the input in UCS-2 to an array of Unicode code points. input = ucs2decode(input); // Cache the length. var inputLength = input.length; // Initialize the state. var n = initialN; var delta = 0; var bias = initialBias; // Handle the basic code points. var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = input[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var _currentValue2 = _step.value; if (_currentValue2 < 0x80) { output.push(stringFromCharCode(_currentValue2)); } } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } var basicLength = output.length; var handledCPCount = basicLength; // `handledCPCount` is the number of code points that have been handled; // `basicLength` is the number of basic code points. // Finish the basic string with a delimiter unless it's empty. if (basicLength) { output.push(delimiter); } // Main encoding loop: while (handledCPCount < inputLength) { // All non-basic code points < n have been handled already. Find the next // larger one: var m = maxInt; var _iteratorNormalCompletion2 = true; var _didIteratorError2 = false; var _iteratorError2 = undefined; try { for (var _iterator2 = input[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { var currentValue = _step2.value; if (currentValue >= n && currentValue < m) { m = currentValue; } } // Increase `delta` enough to advance the decoder's state to , // but guard against overflow. } catch (err) { _didIteratorError2 = true; _iteratorError2 = err; } finally { try { if (!_iteratorNormalCompletion2 && _iterator2.return) { _iterator2.return(); } } finally { if (_didIteratorError2) { throw _iteratorError2; } } } var handledCPCountPlusOne = handledCPCount + 1; if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { error$1('overflow'); } delta += (m - n) * handledCPCountPlusOne; n = m; var _iteratorNormalCompletion3 = true; var _didIteratorError3 = false; var _iteratorError3 = undefined; try { for (var _iterator3 = input[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { var _currentValue = _step3.value; if (_currentValue < n && ++delta > maxInt) { error$1('overflow'); } if (_currentValue == n) { // Represent delta as a generalized variable-length integer. var q = delta; for (var k = base;; /* no condition */k += base) { var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; if (q < t) { break; } var qMinusT = q - t; var baseMinusT = base - t; output.push(stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))); q = floor(qMinusT / baseMinusT); } output.push(stringFromCharCode(digitToBasic(q, 0))); bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); delta = 0; ++handledCPCount; } } } catch (err) { _didIteratorError3 = true; _iteratorError3 = err; } finally { try { if (!_iteratorNormalCompletion3 && _iterator3.return) { _iterator3.return(); } } finally { if (_didIteratorError3) { throw _iteratorError3; } } } ++delta; ++n; } return output.join(''); }; /** * Converts a Punycode string representing a domain name or an email address * to Unicode. Only the Punycoded parts of the input will be converted, i.e. * it doesn't matter if you call it on a string that has already been * converted to Unicode. * @memberOf punycode * @param {String} input The Punycoded domain name or email address to * convert to Unicode. * @returns {String} The Unicode representation of the given Punycode * string. */ var toUnicode = function toUnicode(input) { return mapDomain(input, function (string) { return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string; }); }; /** * Converts a Unicode string representing a domain name or an email address to * Punycode. Only the non-ASCII parts of the domain name will be converted, * i.e. it doesn't matter if you call it with a domain that's already in * ASCII. * @memberOf punycode * @param {String} input The domain name or email address to convert, as a * Unicode string. * @returns {String} The Punycode representation of the given domain name or * email address. */ var toASCII = function toASCII(input) { return mapDomain(input, function (string) { return regexNonASCII.test(string) ? 'xn--' + encode(string) : string; }); }; /*--------------------------------------------------------------------------*/ /** Define the public API */ var punycode = { /** * A string representing the current Punycode.js version number. * @memberOf punycode * @type String */ 'version': '2.1.0', /** * An object of methods to convert from JavaScript's internal character * representation (UCS-2) to Unicode code points, and back. * @see * @memberOf punycode * @type Object */ 'ucs2': { 'decode': ucs2decode, 'encode': ucs2encode }, 'decode': decode, 'encode': encode, 'toASCII': toASCII, 'toUnicode': toUnicode }; /** * URI.js * * @fileoverview An RFC 3986 compliant, scheme extendable URI parsing/validating/resolving library for JavaScript. * @author Gary Court * @see http://github.com/garycourt/uri-js */ /** * Copyright 2011 Gary Court. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY GARY COURT ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GARY COURT OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of Gary Court. */ var SCHEMES = {}; function pctEncChar(chr) { var c = chr.charCodeAt(0); var e = void 0; if (c < 16) e = "%0" + c.toString(16).toUpperCase();else if (c < 128) e = "%" + c.toString(16).toUpperCase();else if (c < 2048) e = "%" + (c >> 6 | 192).toString(16).toUpperCase() + "%" + (c & 63 | 128).toString(16).toUpperCase();else e = "%" + (c >> 12 | 224).toString(16).toUpperCase() + "%" + (c >> 6 & 63 | 128).toString(16).toUpperCase() + "%" + (c & 63 | 128).toString(16).toUpperCase(); return e; } function pctDecChars(str) { var newStr = ""; var i = 0; var il = str.length; while (i < il) { var c = parseInt(str.substr(i + 1, 2), 16); if (c < 128) { newStr += String.fromCharCode(c); i += 3; } else if (c >= 194 && c < 224) { if (il - i >= 6) { var c2 = parseInt(str.substr(i + 4, 2), 16); newStr += String.fromCharCode((c & 31) << 6 | c2 & 63); } else { newStr += str.substr(i, 6); } i += 6; } else if (c >= 224) { if (il - i >= 9) { var _c = parseInt(str.substr(i + 4, 2), 16); var c3 = parseInt(str.substr(i + 7, 2), 16); newStr += String.fromCharCode((c & 15) << 12 | (_c & 63) << 6 | c3 & 63); } else { newStr += str.substr(i, 9); } i += 9; } else { newStr += str.substr(i, 3); i += 3; } } return newStr; } function _normalizeComponentEncoding(components, protocol) { function decodeUnreserved(str) { var decStr = pctDecChars(str); return !decStr.match(protocol.UNRESERVED) ? str : decStr; } if (components.scheme) components.scheme = String(components.scheme).replace(protocol.PCT_ENCODED, decodeUnreserved).toLowerCase().replace(protocol.NOT_SCHEME, ""); if (components.userinfo !== undefined) components.userinfo = String(components.userinfo).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_USERINFO, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); if (components.host !== undefined) components.host = String(components.host).replace(protocol.PCT_ENCODED, decodeUnreserved).toLowerCase().replace(protocol.NOT_HOST, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); if (components.path !== undefined) components.path = String(components.path).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(components.scheme ? protocol.NOT_PATH : protocol.NOT_PATH_NOSCHEME, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); if (components.query !== undefined) components.query = String(components.query).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_QUERY, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); if (components.fragment !== undefined) components.fragment = String(components.fragment).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_FRAGMENT, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); return components; } function _stripLeadingZeros(str) { return str.replace(/^0*(.*)/, "$1") || "0"; } function _normalizeIPv4(host, protocol) { var matches = host.match(protocol.IPV4ADDRESS) || []; var _matches = slicedToArray(matches, 2), address = _matches[1]; if (address) { return address.split(".").map(_stripLeadingZeros).join("."); } else { return host; } } function _normalizeIPv6(host, protocol) { var matches = host.match(protocol.IPV6ADDRESS) || []; var _matches2 = slicedToArray(matches, 3), address = _matches2[1], zone = _matches2[2]; if (address) { var _address$toLowerCase$ = address.toLowerCase().split('::').reverse(), _address$toLowerCase$2 = slicedToArray(_address$toLowerCase$, 2), last = _address$toLowerCase$2[0], first = _address$toLowerCase$2[1]; var firstFields = first ? first.split(":").map(_stripLeadingZeros) : []; var lastFields = last.split(":").map(_stripLeadingZeros); var isLastFieldIPv4Address = protocol.IPV4ADDRESS.test(lastFields[lastFields.length - 1]); var fieldCount = isLastFieldIPv4Address ? 7 : 8; var lastFieldsStart = lastFields.length - fieldCount; var fields = Array(fieldCount); for (var x = 0; x < fieldCount; ++x) { fields[x] = firstFields[x] || lastFields[lastFieldsStart + x] || ''; } if (isLastFieldIPv4Address) { fields[fieldCount - 1] = _normalizeIPv4(fields[fieldCount - 1], protocol); } var allZeroFields = fields.reduce(function (acc, field, index) { if (!field || field === "0") { var lastLongest = acc[acc.length - 1]; if (lastLongest && lastLongest.index + lastLongest.length === index) { lastLongest.length++; } else { acc.push({ index: index, length: 1 }); } } return acc; }, []); var longestZeroFields = allZeroFields.sort(function (a, b) { return b.length - a.length; })[0]; var newHost = void 0; if (longestZeroFields && longestZeroFields.length > 1) { var newFirst = fields.slice(0, longestZeroFields.index); var newLast = fields.slice(longestZeroFields.index + longestZeroFields.length); newHost = newFirst.join(":") + "::" + newLast.join(":"); } else { newHost = fields.join(":"); } if (zone) { newHost += "%" + zone; } return newHost; } else { return host; } } var URI_PARSE = /^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i; var NO_MATCH_IS_UNDEFINED = "".match(/(){0}/)[1] === undefined; function parse(uriString) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var components = {}; var protocol = options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL; if (options.reference === "suffix") uriString = (options.scheme ? options.scheme + ":" : "") + "//" + uriString; var matches = uriString.match(URI_PARSE); if (matches) { if (NO_MATCH_IS_UNDEFINED) { //store each component components.scheme = matches[1]; components.userinfo = matches[3]; components.host = matches[4]; components.port = parseInt(matches[5], 10); components.path = matches[6] || ""; components.query = matches[7]; components.fragment = matches[8]; //fix port number if (isNaN(components.port)) { components.port = matches[5]; } } else { //IE FIX for improper RegExp matching //store each component components.scheme = matches[1] || undefined; components.userinfo = uriString.indexOf("@") !== -1 ? matches[3] : undefined; components.host = uriString.indexOf("//") !== -1 ? matches[4] : undefined; components.port = parseInt(matches[5], 10); components.path = matches[6] || ""; components.query = uriString.indexOf("?") !== -1 ? matches[7] : undefined; components.fragment = uriString.indexOf("#") !== -1 ? matches[8] : undefined; //fix port number if (isNaN(components.port)) { components.port = uriString.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/) ? matches[4] : undefined; } } if (components.host) { //normalize IP hosts components.host = _normalizeIPv6(_normalizeIPv4(components.host, protocol), protocol); } //determine reference type if (components.scheme === undefined && components.userinfo === undefined && components.host === undefined && components.port === undefined && !components.path && components.query === undefined) { components.reference = "same-document"; } else if (components.scheme === undefined) { components.reference = "relative"; } else if (components.fragment === undefined) { components.reference = "absolute"; } else { components.reference = "uri"; } //check for reference errors if (options.reference && options.reference !== "suffix" && options.reference !== components.reference) { components.error = components.error || "URI is not a " + options.reference + " reference."; } //find scheme handler var schemeHandler = SCHEMES[(options.scheme || components.scheme || "").toLowerCase()]; //check if scheme can't handle IRIs if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) { //if host component is a domain name if (components.host && (options.domainHost || schemeHandler && schemeHandler.domainHost)) { //convert Unicode IDN -> ASCII IDN try { components.host = punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase()); } catch (e) { components.error = components.error || "Host's domain name can not be converted to ASCII via punycode: " + e; } } //convert IRI -> URI _normalizeComponentEncoding(components, URI_PROTOCOL); } else { //normalize encodings _normalizeComponentEncoding(components, protocol); } //perform scheme specific parsing if (schemeHandler && schemeHandler.parse) { schemeHandler.parse(components, options); } } else { components.error = components.error || "URI can not be parsed."; } return components; } function _recomposeAuthority(components, options) { var protocol = options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL; var uriTokens = []; if (components.userinfo !== undefined) { uriTokens.push(components.userinfo); uriTokens.push("@"); } if (components.host !== undefined) { //normalize IP hosts, add brackets and escape zone separator for IPv6 uriTokens.push(_normalizeIPv6(_normalizeIPv4(String(components.host), protocol), protocol).replace(protocol.IPV6ADDRESS, function (_, $1, $2) { return "[" + $1 + ($2 ? "%25" + $2 : "") + "]"; })); } if (typeof components.port === "number" || typeof components.port === "string") { uriTokens.push(":"); uriTokens.push(String(components.port)); } return uriTokens.length ? uriTokens.join("") : undefined; } var RDS1 = /^\.\.?\//; var RDS2 = /^\/\.(\/|$)/; var RDS3 = /^\/\.\.(\/|$)/; var RDS5 = /^\/?(?:.|\n)*?(?=\/|$)/; function removeDotSegments(input) { var output = []; while (input.length) { if (input.match(RDS1)) { input = input.replace(RDS1, ""); } else if (input.match(RDS2)) { input = input.replace(RDS2, "/"); } else if (input.match(RDS3)) { input = input.replace(RDS3, "/"); output.pop(); } else if (input === "." || input === "..") { input = ""; } else { var im = input.match(RDS5); if (im) { var s = im[0]; input = input.slice(s.length); output.push(s); } else { throw new Error("Unexpected dot segment condition"); } } } return output.join(""); } function serialize(components) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var protocol = options.iri ? IRI_PROTOCOL : URI_PROTOCOL; var uriTokens = []; //find scheme handler var schemeHandler = SCHEMES[(options.scheme || components.scheme || "").toLowerCase()]; //perform scheme specific serialization if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(components, options); if (components.host) { //if host component is an IPv6 address if (protocol.IPV6ADDRESS.test(components.host)) {} //TODO: normalize IPv6 address as per RFC 5952 //if host component is a domain name else if (options.domainHost || schemeHandler && schemeHandler.domainHost) { //convert IDN via punycode try { components.host = !options.iri ? punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase()) : punycode.toUnicode(components.host); } catch (e) { components.error = components.error || "Host's domain name can not be converted to " + (!options.iri ? "ASCII" : "Unicode") + " via punycode: " + e; } } } //normalize encoding _normalizeComponentEncoding(components, protocol); if (options.reference !== "suffix" && components.scheme) { uriTokens.push(components.scheme); uriTokens.push(":"); } var authority = _recomposeAuthority(components, options); if (authority !== undefined) { if (options.reference !== "suffix") { uriTokens.push("//"); } uriTokens.push(authority); if (components.path && components.path.charAt(0) !== "/") { uriTokens.push("/"); } } if (components.path !== undefined) { var s = components.path; if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) { s = removeDotSegments(s); } if (authority === undefined) { s = s.replace(/^\/\//, "/%2F"); //don't allow the path to start with "//" } uriTokens.push(s); } if (components.query !== undefined) { uriTokens.push("?"); uriTokens.push(components.query); } if (components.fragment !== undefined) { uriTokens.push("#"); uriTokens.push(components.fragment); } return uriTokens.join(""); //merge tokens into a string } function resolveComponents(base, relative) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var skipNormalization = arguments[3]; var target = {}; if (!skipNormalization) { base = parse(serialize(base, options), options); //normalize base components relative = parse(serialize(relative, options), options); //normalize relative components } options = options || {}; if (!options.tolerant && relative.scheme) { target.scheme = relative.scheme; //target.authority = relative.authority; target.userinfo = relative.userinfo; target.host = relative.host; target.port = relative.port; target.path = removeDotSegments(relative.path || ""); target.query = relative.query; } else { if (relative.userinfo !== undefined || relative.host !== undefined || relative.port !== undefined) { //target.authority = relative.authority; target.userinfo = relative.userinfo; target.host = relative.host; target.port = relative.port; target.path = removeDotSegments(relative.path || ""); target.query = relative.query; } else { if (!relative.path) { target.path = base.path; if (relative.query !== undefined) { target.query = relative.query; } else { target.query = base.query; } } else { if (relative.path.charAt(0) === "/") { target.path = removeDotSegments(relative.path); } else { if ((base.userinfo !== undefined || base.host !== undefined || base.port !== undefined) && !base.path) { target.path = "/" + relative.path; } else if (!base.path) { target.path = relative.path; } else { target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path; } target.path = removeDotSegments(target.path); } target.query = relative.query; } //target.authority = base.authority; target.userinfo = base.userinfo; target.host = base.host; target.port = base.port; } target.scheme = base.scheme; } target.fragment = relative.fragment; return target; } function resolve(baseURI, relativeURI, options) { var schemelessOptions = assign({ scheme: 'null' }, options); return serialize(resolveComponents(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true), schemelessOptions); } function normalize(uri, options) { if (typeof uri === "string") { uri = serialize(parse(uri, options), options); } else if (typeOf(uri) === "object") { uri = parse(serialize(uri, options), options); } return uri; } function equal(uriA, uriB, options) { if (typeof uriA === "string") { uriA = serialize(parse(uriA, options), options); } else if (typeOf(uriA) === "object") { uriA = serialize(uriA, options); } if (typeof uriB === "string") { uriB = serialize(parse(uriB, options), options); } else if (typeOf(uriB) === "object") { uriB = serialize(uriB, options); } return uriA === uriB; } function escapeComponent(str, options) { return str && str.toString().replace(!options || !options.iri ? URI_PROTOCOL.ESCAPE : IRI_PROTOCOL.ESCAPE, pctEncChar); } function unescapeComponent(str, options) { return str && str.toString().replace(!options || !options.iri ? URI_PROTOCOL.PCT_ENCODED : IRI_PROTOCOL.PCT_ENCODED, pctDecChars); } var handler = { scheme: "http", domainHost: true, parse: function parse(components, options) { //report missing host if (!components.host) { components.error = components.error || "HTTP URIs must have a host."; } return components; }, serialize: function serialize(components, options) { var secure = String(components.scheme).toLowerCase() === "https"; //normalize the default port if (components.port === (secure ? 443 : 80) || components.port === "") { components.port = undefined; } //normalize the empty path if (!components.path) { components.path = "/"; } //NOTE: We do not parse query strings for HTTP URIs //as WWW Form Url Encoded query strings are part of the HTML4+ spec, //and not the HTTP spec. return components; } }; var handler$1 = { scheme: "https", domainHost: handler.domainHost, parse: handler.parse, serialize: handler.serialize }; function isSecure(wsComponents) { return typeof wsComponents.secure === 'boolean' ? wsComponents.secure : String(wsComponents.scheme).toLowerCase() === "wss"; } //RFC 6455 var handler$2 = { scheme: "ws", domainHost: true, parse: function parse(components, options) { var wsComponents = components; //indicate if the secure flag is set wsComponents.secure = isSecure(wsComponents); //construct resouce name wsComponents.resourceName = (wsComponents.path || '/') + (wsComponents.query ? '?' + wsComponents.query : ''); wsComponents.path = undefined; wsComponents.query = undefined; return wsComponents; }, serialize: function serialize(wsComponents, options) { //normalize the default port if (wsComponents.port === (isSecure(wsComponents) ? 443 : 80) || wsComponents.port === "") { wsComponents.port = undefined; } //ensure scheme matches secure flag if (typeof wsComponents.secure === 'boolean') { wsComponents.scheme = wsComponents.secure ? 'wss' : 'ws'; wsComponents.secure = undefined; } //reconstruct path from resource name if (wsComponents.resourceName) { var _wsComponents$resourc = wsComponents.resourceName.split('?'), _wsComponents$resourc2 = slicedToArray(_wsComponents$resourc, 2), path = _wsComponents$resourc2[0], query = _wsComponents$resourc2[1]; wsComponents.path = path && path !== '/' ? path : undefined; wsComponents.query = query; wsComponents.resourceName = undefined; } //forbid fragment component wsComponents.fragment = undefined; return wsComponents; } }; var handler$3 = { scheme: "wss", domainHost: handler$2.domainHost, parse: handler$2.parse, serialize: handler$2.serialize }; var O = {}; var isIRI = true; //RFC 3986 var UNRESERVED$$ = "[A-Za-z0-9\\-\\.\\_\\~" + (isIRI ? "\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF" : "") + "]"; var HEXDIG$$ = "[0-9A-Fa-f]"; //case-insensitive var PCT_ENCODED$ = subexp(subexp("%[EFef]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%[89A-Fa-f]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%" + HEXDIG$$ + HEXDIG$$)); //expanded //RFC 5322, except these symbols as per RFC 6068: @ : / ? # [ ] & ; = //const ATEXT$$ = "[A-Za-z0-9\\!\\#\\$\\%\\&\\'\\*\\+\\-\\/\\=\\?\\^\\_\\`\\{\\|\\}\\~]"; //const WSP$$ = "[\\x20\\x09]"; //const OBS_QTEXT$$ = "[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x7F]"; //(%d1-8 / %d11-12 / %d14-31 / %d127) //const QTEXT$$ = merge("[\\x21\\x23-\\x5B\\x5D-\\x7E]", OBS_QTEXT$$); //%d33 / %d35-91 / %d93-126 / obs-qtext //const VCHAR$$ = "[\\x21-\\x7E]"; //const WSP$$ = "[\\x20\\x09]"; //const OBS_QP$ = subexp("\\\\" + merge("[\\x00\\x0D\\x0A]", OBS_QTEXT$$)); //%d0 / CR / LF / obs-qtext //const FWS$ = subexp(subexp(WSP$$ + "*" + "\\x0D\\x0A") + "?" + WSP$$ + "+"); //const QUOTED_PAIR$ = subexp(subexp("\\\\" + subexp(VCHAR$$ + "|" + WSP$$)) + "|" + OBS_QP$); //const QUOTED_STRING$ = subexp('\\"' + subexp(FWS$ + "?" + QCONTENT$) + "*" + FWS$ + "?" + '\\"'); var ATEXT$$ = "[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]"; var QTEXT$$ = "[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]"; var VCHAR$$ = merge(QTEXT$$, "[\\\"\\\\]"); var SOME_DELIMS$$ = "[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]"; var UNRESERVED = new RegExp(UNRESERVED$$, "g"); var PCT_ENCODED = new RegExp(PCT_ENCODED$, "g"); var NOT_LOCAL_PART = new RegExp(merge("[^]", ATEXT$$, "[\\.]", '[\\"]', VCHAR$$), "g"); var NOT_HFNAME = new RegExp(merge("[^]", UNRESERVED$$, SOME_DELIMS$$), "g"); var NOT_HFVALUE = NOT_HFNAME; function decodeUnreserved(str) { var decStr = pctDecChars(str); return !decStr.match(UNRESERVED) ? str : decStr; } var handler$4 = { scheme: "mailto", parse: function parse$$1(components, options) { var mailtoComponents = components; var to = mailtoComponents.to = mailtoComponents.path ? mailtoComponents.path.split(",") : []; mailtoComponents.path = undefined; if (mailtoComponents.query) { var unknownHeaders = false; var headers = {}; var hfields = mailtoComponents.query.split("&"); for (var x = 0, xl = hfields.length; x < xl; ++x) { var hfield = hfields[x].split("="); switch (hfield[0]) { case "to": var toAddrs = hfield[1].split(","); for (var _x = 0, _xl = toAddrs.length; _x < _xl; ++_x) { to.push(toAddrs[_x]); } break; case "subject": mailtoComponents.subject = unescapeComponent(hfield[1], options); break; case "body": mailtoComponents.body = unescapeComponent(hfield[1], options); break; default: unknownHeaders = true; headers[unescapeComponent(hfield[0], options)] = unescapeComponent(hfield[1], options); break; } } if (unknownHeaders) mailtoComponents.headers = headers; } mailtoComponents.query = undefined; for (var _x2 = 0, _xl2 = to.length; _x2 < _xl2; ++_x2) { var addr = to[_x2].split("@"); addr[0] = unescapeComponent(addr[0]); if (!options.unicodeSupport) { //convert Unicode IDN -> ASCII IDN try { addr[1] = punycode.toASCII(unescapeComponent(addr[1], options).toLowerCase()); } catch (e) { mailtoComponents.error = mailtoComponents.error || "Email address's domain name can not be converted to ASCII via punycode: " + e; } } else { addr[1] = unescapeComponent(addr[1], options).toLowerCase(); } to[_x2] = addr.join("@"); } return mailtoComponents; }, serialize: function serialize$$1(mailtoComponents, options) { var components = mailtoComponents; var to = toArray(mailtoComponents.to); if (to) { for (var x = 0, xl = to.length; x < xl; ++x) { var toAddr = String(to[x]); var atIdx = toAddr.lastIndexOf("@"); var localPart = toAddr.slice(0, atIdx).replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_LOCAL_PART, pctEncChar); var domain = toAddr.slice(atIdx + 1); //convert IDN via punycode try { domain = !options.iri ? punycode.toASCII(unescapeComponent(domain, options).toLowerCase()) : punycode.toUnicode(domain); } catch (e) { components.error = components.error || "Email address's domain name can not be converted to " + (!options.iri ? "ASCII" : "Unicode") + " via punycode: " + e; } to[x] = localPart + "@" + domain; } components.path = to.join(","); } var headers = mailtoComponents.headers = mailtoComponents.headers || {}; if (mailtoComponents.subject) headers["subject"] = mailtoComponents.subject; if (mailtoComponents.body) headers["body"] = mailtoComponents.body; var fields = []; for (var name in headers) { if (headers[name] !== O[name]) { fields.push(name.replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFNAME, pctEncChar) + "=" + headers[name].replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFVALUE, pctEncChar)); } } if (fields.length) { components.query = fields.join("&"); } return components; } }; var URN_PARSE = /^([^\:]+)\:(.*)/; //RFC 2141 var handler$5 = { scheme: "urn", parse: function parse$$1(components, options) { var matches = components.path && components.path.match(URN_PARSE); var urnComponents = components; if (matches) { var scheme = options.scheme || urnComponents.scheme || "urn"; var nid = matches[1].toLowerCase(); var nss = matches[2]; var urnScheme = scheme + ":" + (options.nid || nid); var schemeHandler = SCHEMES[urnScheme]; urnComponents.nid = nid; urnComponents.nss = nss; urnComponents.path = undefined; if (schemeHandler) { urnComponents = schemeHandler.parse(urnComponents, options); } } else { urnComponents.error = urnComponents.error || "URN can not be parsed."; } return urnComponents; }, serialize: function serialize$$1(urnComponents, options) { var scheme = options.scheme || urnComponents.scheme || "urn"; var nid = urnComponents.nid; var urnScheme = scheme + ":" + (options.nid || nid); var schemeHandler = SCHEMES[urnScheme]; if (schemeHandler) { urnComponents = schemeHandler.serialize(urnComponents, options); } var uriComponents = urnComponents; var nss = urnComponents.nss; uriComponents.path = (nid || options.nid) + ":" + nss; return uriComponents; } }; var UUID = /^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/; //RFC 4122 var handler$6 = { scheme: "urn:uuid", parse: function parse(urnComponents, options) { var uuidComponents = urnComponents; uuidComponents.uuid = uuidComponents.nss; uuidComponents.nss = undefined; if (!options.tolerant && (!uuidComponents.uuid || !uuidComponents.uuid.match(UUID))) { uuidComponents.error = uuidComponents.error || "UUID is not valid."; } return uuidComponents; }, serialize: function serialize(uuidComponents, options) { var urnComponents = uuidComponents; //normalize UUID urnComponents.nss = (uuidComponents.uuid || "").toLowerCase(); return urnComponents; } }; SCHEMES[handler.scheme] = handler; SCHEMES[handler$1.scheme] = handler$1; SCHEMES[handler$2.scheme] = handler$2; SCHEMES[handler$3.scheme] = handler$3; SCHEMES[handler$4.scheme] = handler$4; SCHEMES[handler$5.scheme] = handler$5; SCHEMES[handler$6.scheme] = handler$6; exports.SCHEMES = SCHEMES; exports.pctEncChar = pctEncChar; exports.pctDecChars = pctDecChars; exports.parse = parse; exports.removeDotSegments = removeDotSegments; exports.serialize = serialize; exports.resolveComponents = resolveComponents; exports.resolve = resolve; exports.normalize = normalize; exports.equal = equal; exports.escapeComponent = escapeComponent; exports.unescapeComponent = unescapeComponent; Object.defineProperty(exports, '__esModule', { value: true }); }))); //# sourceMappingURL=uri.all.js.map /***/ }), /***/ 81692: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /* * verror.js: richer JavaScript errors */ var mod_assertplus = __nccwpck_require__(66631); var mod_util = __nccwpck_require__(73837); var mod_extsprintf = __nccwpck_require__(41508); var mod_isError = (__nccwpck_require__(95898)/* .isError */ .VZ); var sprintf = mod_extsprintf.sprintf; /* * Public interface */ /* So you can 'var VError = require('verror')' */ module.exports = VError; /* For compatibility */ VError.VError = VError; /* Other exported classes */ VError.SError = SError; VError.WError = WError; VError.MultiError = MultiError; /* * Common function used to parse constructor arguments for VError, WError, and * SError. Named arguments to this function: * * strict force strict interpretation of sprintf arguments, even * if the options in "argv" don't say so * * argv error's constructor arguments, which are to be * interpreted as described in README.md. For quick * reference, "argv" has one of the following forms: * * [ sprintf_args... ] (argv[0] is a string) * [ cause, sprintf_args... ] (argv[0] is an Error) * [ options, sprintf_args... ] (argv[0] is an object) * * This function normalizes these forms, producing an object with the following * properties: * * options equivalent to "options" in third form. This will never * be a direct reference to what the caller passed in * (i.e., it may be a shallow copy), so it can be freely * modified. * * shortmessage result of sprintf(sprintf_args), taking options.strict * into account as described in README.md. */ function parseConstructorArguments(args) { var argv, options, sprintf_args, shortmessage, k; mod_assertplus.object(args, 'args'); mod_assertplus.bool(args.strict, 'args.strict'); mod_assertplus.array(args.argv, 'args.argv'); argv = args.argv; /* * First, figure out which form of invocation we've been given. */ if (argv.length === 0) { options = {}; sprintf_args = []; } else if (mod_isError(argv[0])) { options = { 'cause': argv[0] }; sprintf_args = argv.slice(1); } else if (typeof (argv[0]) === 'object') { options = {}; for (k in argv[0]) { options[k] = argv[0][k]; } sprintf_args = argv.slice(1); } else { mod_assertplus.string(argv[0], 'first argument to VError, SError, or WError ' + 'constructor must be a string, object, or Error'); options = {}; sprintf_args = argv; } /* * Now construct the error's message. * * extsprintf (which we invoke here with our caller's arguments in order * to construct this Error's message) is strict in its interpretation of * values to be processed by the "%s" specifier. The value passed to * extsprintf must actually be a string or something convertible to a * String using .toString(). Passing other values (notably "null" and * "undefined") is considered a programmer error. The assumption is * that if you actually want to print the string "null" or "undefined", * then that's easy to do that when you're calling extsprintf; on the * other hand, if you did NOT want that (i.e., there's actually a bug * where the program assumes some variable is non-null and tries to * print it, which might happen when constructing a packet or file in * some specific format), then it's better to stop immediately than * produce bogus output. * * However, sometimes the bug is only in the code calling VError, and a * programmer might prefer to have the error message contain "null" or * "undefined" rather than have the bug in the error path crash the * program (making the first bug harder to identify). For that reason, * by default VError converts "null" or "undefined" arguments to their * string representations and passes those to extsprintf. Programmers * desiring the strict behavior can use the SError class or pass the * "strict" option to the VError constructor. */ mod_assertplus.object(options); if (!options.strict && !args.strict) { sprintf_args = sprintf_args.map(function (a) { return (a === null ? 'null' : a === undefined ? 'undefined' : a); }); } if (sprintf_args.length === 0) { shortmessage = ''; } else { shortmessage = sprintf.apply(null, sprintf_args); } return ({ 'options': options, 'shortmessage': shortmessage }); } /* * See README.md for reference documentation. */ function VError() { var args, obj, parsed, cause, ctor, message, k; args = Array.prototype.slice.call(arguments, 0); /* * This is a regrettable pattern, but JavaScript's built-in Error class * is defined to work this way, so we allow the constructor to be called * without "new". */ if (!(this instanceof VError)) { obj = Object.create(VError.prototype); VError.apply(obj, arguments); return (obj); } /* * For convenience and backwards compatibility, we support several * different calling forms. Normalize them here. */ parsed = parseConstructorArguments({ 'argv': args, 'strict': false }); /* * If we've been given a name, apply it now. */ if (parsed.options.name) { mod_assertplus.string(parsed.options.name, 'error\'s "name" must be a string'); this.name = parsed.options.name; } /* * For debugging, we keep track of the original short message (attached * this Error particularly) separately from the complete message (which * includes the messages of our cause chain). */ this.jse_shortmsg = parsed.shortmessage; message = parsed.shortmessage; /* * If we've been given a cause, record a reference to it and update our * message appropriately. */ cause = parsed.options.cause; if (cause) { mod_assertplus.ok(mod_isError(cause), 'cause is not an Error'); this.jse_cause = cause; if (!parsed.options.skipCauseMessage) { message += ': ' + cause.message; } } /* * If we've been given an object with properties, shallow-copy that * here. We don't want to use a deep copy in case there are non-plain * objects here, but we don't want to use the original object in case * the caller modifies it later. */ this.jse_info = {}; if (parsed.options.info) { for (k in parsed.options.info) { this.jse_info[k] = parsed.options.info[k]; } } this.message = message; Error.call(this, message); if (Error.captureStackTrace) { ctor = parsed.options.constructorOpt || this.constructor; Error.captureStackTrace(this, ctor); } return (this); } mod_util.inherits(VError, Error); VError.prototype.name = 'VError'; VError.prototype.toString = function ve_toString() { var str = (this.hasOwnProperty('name') && this.name || this.constructor.name || this.constructor.prototype.name); if (this.message) str += ': ' + this.message; return (str); }; /* * This method is provided for compatibility. New callers should use * VError.cause() instead. That method also uses the saner `null` return value * when there is no cause. */ VError.prototype.cause = function ve_cause() { var cause = VError.cause(this); return (cause === null ? undefined : cause); }; /* * Static methods * * These class-level methods are provided so that callers can use them on * instances of Errors that are not VErrors. New interfaces should be provided * only using static methods to eliminate the class of programming mistake where * people fail to check whether the Error object has the corresponding methods. */ VError.cause = function (err) { mod_assertplus.ok(mod_isError(err), 'err must be an Error'); return (mod_isError(err.jse_cause) ? err.jse_cause : null); }; VError.info = function (err) { var rv, cause, k; mod_assertplus.ok(mod_isError(err), 'err must be an Error'); cause = VError.cause(err); if (cause !== null) { rv = VError.info(cause); } else { rv = {}; } if (typeof (err.jse_info) == 'object' && err.jse_info !== null) { for (k in err.jse_info) { rv[k] = err.jse_info[k]; } } return (rv); }; VError.findCauseByName = function (err, name) { var cause; mod_assertplus.ok(mod_isError(err), 'err must be an Error'); mod_assertplus.string(name, 'name'); mod_assertplus.ok(name.length > 0, 'name cannot be empty'); for (cause = err; cause !== null; cause = VError.cause(cause)) { mod_assertplus.ok(mod_isError(cause)); if (cause.name == name) { return (cause); } } return (null); }; VError.hasCauseWithName = function (err, name) { return (VError.findCauseByName(err, name) !== null); }; VError.fullStack = function (err) { mod_assertplus.ok(mod_isError(err), 'err must be an Error'); var cause = VError.cause(err); if (cause) { return (err.stack + '\ncaused by: ' + VError.fullStack(cause)); } return (err.stack); }; VError.errorFromList = function (errors) { mod_assertplus.arrayOfObject(errors, 'errors'); if (errors.length === 0) { return (null); } errors.forEach(function (e) { mod_assertplus.ok(mod_isError(e)); }); if (errors.length == 1) { return (errors[0]); } return (new MultiError(errors)); }; VError.errorForEach = function (err, func) { mod_assertplus.ok(mod_isError(err), 'err must be an Error'); mod_assertplus.func(func, 'func'); if (err instanceof MultiError) { err.errors().forEach(function iterError(e) { func(e); }); } else { func(err); } }; /* * SError is like VError, but stricter about types. You cannot pass "null" or * "undefined" as string arguments to the formatter. */ function SError() { var args, obj, parsed, options; args = Array.prototype.slice.call(arguments, 0); if (!(this instanceof SError)) { obj = Object.create(SError.prototype); SError.apply(obj, arguments); return (obj); } parsed = parseConstructorArguments({ 'argv': args, 'strict': true }); options = parsed.options; VError.call(this, options, '%s', parsed.shortmessage); return (this); } /* * We don't bother setting SError.prototype.name because once constructed, * SErrors are just like VErrors. */ mod_util.inherits(SError, VError); /* * Represents a collection of errors for the purpose of consumers that generally * only deal with one error. Callers can extract the individual errors * contained in this object, but may also just treat it as a normal single * error, in which case a summary message will be printed. */ function MultiError(errors) { mod_assertplus.array(errors, 'list of errors'); mod_assertplus.ok(errors.length > 0, 'must be at least one error'); this.ase_errors = errors; VError.call(this, { 'cause': errors[0] }, 'first of %d error%s', errors.length, errors.length == 1 ? '' : 's'); } mod_util.inherits(MultiError, VError); MultiError.prototype.name = 'MultiError'; MultiError.prototype.errors = function me_errors() { return (this.ase_errors.slice(0)); }; /* * See README.md for reference details. */ function WError() { var args, obj, parsed, options; args = Array.prototype.slice.call(arguments, 0); if (!(this instanceof WError)) { obj = Object.create(WError.prototype); WError.apply(obj, args); return (obj); } parsed = parseConstructorArguments({ 'argv': args, 'strict': false }); options = parsed.options; options['skipCauseMessage'] = true; VError.call(this, options, '%s', parsed.shortmessage); return (this); } mod_util.inherits(WError, VError); WError.prototype.name = 'WError'; WError.prototype.toString = function we_toString() { var str = (this.hasOwnProperty('name') && this.name || this.constructor.name || this.constructor.prototype.name); if (this.message) str += ': ' + this.message; if (this.jse_cause && this.jse_cause.message) str += '; caused by ' + this.jse_cause.toString(); return (str); }; /* * For purely historical reasons, WError's cause() function allows you to set * the cause. */ WError.prototype.cause = function we_cause(c) { if (mod_isError(c)) this.jse_cause = c; return (this.jse_cause); }; /***/ }), /***/ 41508: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { /* * extsprintf.js: extended POSIX-style sprintf */ var mod_assert = __nccwpck_require__(39491); var mod_util = __nccwpck_require__(73837); /* * Public interface */ exports.sprintf = jsSprintf; exports.printf = jsPrintf; exports.fprintf = jsFprintf; /* * Stripped down version of s[n]printf(3c). We make a best effort to throw an * exception when given a format string we don't understand, rather than * ignoring it, so that we won't break existing programs if/when we go implement * the rest of this. * * This implementation currently supports specifying * - field alignment ('-' flag), * - zero-pad ('0' flag) * - always show numeric sign ('+' flag), * - field width * - conversions for strings, decimal integers, and floats (numbers). * - argument size specifiers. These are all accepted but ignored, since * Javascript has no notion of the physical size of an argument. * * Everything else is currently unsupported, most notably precision, unsigned * numbers, non-decimal numbers, and characters. */ function jsSprintf(ofmt) { var regex = [ '([^%]*)', /* normal text */ '%', /* start of format */ '([\'\\-+ #0]*?)', /* flags (optional) */ '([1-9]\\d*)?', /* width (optional) */ '(\\.([1-9]\\d*))?', /* precision (optional) */ '[lhjztL]*?', /* length mods (ignored) */ '([diouxXfFeEgGaAcCsSp%jr])' /* conversion */ ].join(''); var re = new RegExp(regex); /* variadic arguments used to fill in conversion specifiers */ var args = Array.prototype.slice.call(arguments, 1); /* remaining format string */ var fmt = ofmt; /* components of the current conversion specifier */ var flags, width, precision, conversion; var left, pad, sign, arg, match; /* return value */ var ret = ''; /* current variadic argument (1-based) */ var argn = 1; /* 0-based position in the format string that we've read */ var posn = 0; /* 1-based position in the format string of the current conversion */ var convposn; /* current conversion specifier */ var curconv; mod_assert.equal('string', typeof (fmt), 'first argument must be a format string'); while ((match = re.exec(fmt)) !== null) { ret += match[1]; fmt = fmt.substring(match[0].length); /* * Update flags related to the current conversion specifier's * position so that we can report clear error messages. */ curconv = match[0].substring(match[1].length); convposn = posn + match[1].length + 1; posn += match[0].length; flags = match[2] || ''; width = match[3] || 0; precision = match[4] || ''; conversion = match[6]; left = false; sign = false; pad = ' '; if (conversion == '%') { ret += '%'; continue; } if (args.length === 0) { throw (jsError(ofmt, convposn, curconv, 'has no matching argument ' + '(too few arguments passed)')); } arg = args.shift(); argn++; if (flags.match(/[\' #]/)) { throw (jsError(ofmt, convposn, curconv, 'uses unsupported flags')); } if (precision.length > 0) { throw (jsError(ofmt, convposn, curconv, 'uses non-zero precision (not supported)')); } if (flags.match(/-/)) left = true; if (flags.match(/0/)) pad = '0'; if (flags.match(/\+/)) sign = true; switch (conversion) { case 's': if (arg === undefined || arg === null) { throw (jsError(ofmt, convposn, curconv, 'attempted to print undefined or null ' + 'as a string (argument ' + argn + ' to ' + 'sprintf)')); } ret += doPad(pad, width, left, arg.toString()); break; case 'd': arg = Math.floor(arg); /*jsl:fallthru*/ case 'f': sign = sign && arg > 0 ? '+' : ''; ret += sign + doPad(pad, width, left, arg.toString()); break; case 'x': ret += doPad(pad, width, left, arg.toString(16)); break; case 'j': /* non-standard */ if (width === 0) width = 10; ret += mod_util.inspect(arg, false, width); break; case 'r': /* non-standard */ ret += dumpException(arg); break; default: throw (jsError(ofmt, convposn, curconv, 'is not supported')); } } ret += fmt; return (ret); } function jsError(fmtstr, convposn, curconv, reason) { mod_assert.equal(typeof (fmtstr), 'string'); mod_assert.equal(typeof (curconv), 'string'); mod_assert.equal(typeof (convposn), 'number'); mod_assert.equal(typeof (reason), 'string'); return (new Error('format string "' + fmtstr + '": conversion specifier "' + curconv + '" at character ' + convposn + ' ' + reason)); } function jsPrintf() { var args = Array.prototype.slice.call(arguments); args.unshift(process.stdout); jsFprintf.apply(null, args); } function jsFprintf(stream) { var args = Array.prototype.slice.call(arguments, 1); return (stream.write(jsSprintf.apply(this, args))); } function doPad(chr, width, left, str) { var ret = str; while (ret.length < width) { if (left) ret += chr; else ret = chr + ret; } return (ret); } /* * This function dumps long stack traces for exceptions having a cause() method. * See node-verror for an example. */ function dumpException(ex) { var ret; if (!(ex instanceof Error)) throw (new Error(jsSprintf('invalid type for %%r: %j', ex))); /* Note that V8 prepends "ex.stack" with ex.toString(). */ ret = 'EXCEPTION: ' + ex.constructor.name + ': ' + ex.stack; if (ex.cause && typeof (ex.cause) === 'function') { var cex = ex.cause(); if (cex) { ret += '\nCaused by: ' + dumpException(cex); } } return (ret); } /***/ }), /***/ 34207: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const isWindows = process.platform === 'win32' || process.env.OSTYPE === 'cygwin' || process.env.OSTYPE === 'msys' const path = __nccwpck_require__(71017) const COLON = isWindows ? ';' : ':' const isexe = __nccwpck_require__(97126) const getNotFoundError = (cmd) => Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' }) const getPathInfo = (cmd, opt) => { const colon = opt.colon || COLON // If it has a slash, then we don't bother searching the pathenv. // just check the file itself, and that's it. const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? [''] : ( [ // windows always checks the cwd first ...(isWindows ? [process.cwd()] : []), ...(opt.path || process.env.PATH || /* istanbul ignore next: very unusual */ '').split(colon), ] ) const pathExtExe = isWindows ? opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM' : '' const pathExt = isWindows ? pathExtExe.split(colon) : [''] if (isWindows) { if (cmd.indexOf('.') !== -1 && pathExt[0] !== '') pathExt.unshift('') } return { pathEnv, pathExt, pathExtExe, } } const which = (cmd, opt, cb) => { if (typeof opt === 'function') { cb = opt opt = {} } if (!opt) opt = {} const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt) const found = [] const step = i => new Promise((resolve, reject) => { if (i === pathEnv.length) return opt.all && found.length ? resolve(found) : reject(getNotFoundError(cmd)) const ppRaw = pathEnv[i] const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw const pCmd = path.join(pathPart, cmd) const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd resolve(subStep(p, i, 0)) }) const subStep = (p, i, ii) => new Promise((resolve, reject) => { if (ii === pathExt.length) return resolve(step(i + 1)) const ext = pathExt[ii] isexe(p + ext, { pathExt: pathExtExe }, (er, is) => { if (!er && is) { if (opt.all) found.push(p + ext) else return resolve(p + ext) } return resolve(subStep(p, i, ii + 1)) }) }) return cb ? step(0).then(res => cb(null, res), cb) : step(0) } const whichSync = (cmd, opt) => { opt = opt || {} const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt) const found = [] for (let i = 0; i < pathEnv.length; i ++) { const ppRaw = pathEnv[i] const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw const pCmd = path.join(pathPart, cmd) const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd for (let j = 0; j < pathExt.length; j ++) { const cur = p + pathExt[j] try { const is = isexe.sync(cur, { pathExt: pathExtExe }) if (is) { if (opt.all) found.push(cur) else return cur } } catch (ex) {} } } if (opt.all && found.length) return found if (opt.nothrow) return null throw getNotFoundError(cmd) } module.exports = which which.sync = whichSync /***/ }), /***/ 62940: /***/ ((module) => { // Returns a wrapper function that returns a wrapped callback // The wrapper function should do some stuff, and return a // presumably different callback function. // This makes sure that own properties are retained, so that // decorations and such are not lost along the way. module.exports = wrappy function wrappy (fn, cb) { if (fn && cb) return wrappy(fn)(cb) if (typeof fn !== 'function') throw new TypeError('need wrapper function') Object.keys(fn).forEach(function (k) { wrapper[k] = fn[k] }) return wrapper function wrapper() { var args = new Array(arguments.length) for (var i = 0; i < args.length; i++) { args[i] = arguments[i] } var ret = fn.apply(this, args) var cb = args[args.length-1] if (typeof ret === 'function' && ret !== cb) { Object.keys(cb).forEach(function (k) { ret[k] = cb[k] }) } return ret } } /***/ }), /***/ 88867: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const WebSocket = __nccwpck_require__(91518); WebSocket.createWebSocketStream = __nccwpck_require__(41658); WebSocket.Server = __nccwpck_require__(58887); WebSocket.Receiver = __nccwpck_require__(25066); WebSocket.Sender = __nccwpck_require__(36947); module.exports = WebSocket; /***/ }), /***/ 9436: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { EMPTY_BUFFER } = __nccwpck_require__(15949); /** * Merges an array of buffers into a new buffer. * * @param {Buffer[]} list The array of buffers to concat * @param {Number} totalLength The total length of buffers in the list * @return {Buffer} The resulting buffer * @public */ function concat(list, totalLength) { if (list.length === 0) return EMPTY_BUFFER; if (list.length === 1) return list[0]; const target = Buffer.allocUnsafe(totalLength); let offset = 0; for (let i = 0; i < list.length; i++) { const buf = list[i]; target.set(buf, offset); offset += buf.length; } if (offset < totalLength) return target.slice(0, offset); return target; } /** * Masks a buffer using the given mask. * * @param {Buffer} source The buffer to mask * @param {Buffer} mask The mask to use * @param {Buffer} output The buffer where to store the result * @param {Number} offset The offset at which to start writing * @param {Number} length The number of bytes to mask. * @public */ function _mask(source, mask, output, offset, length) { for (let i = 0; i < length; i++) { output[offset + i] = source[i] ^ mask[i & 3]; } } /** * Unmasks a buffer using the given mask. * * @param {Buffer} buffer The buffer to unmask * @param {Buffer} mask The mask to use * @public */ function _unmask(buffer, mask) { // Required until https://github.com/nodejs/node/issues/9006 is resolved. const length = buffer.length; for (let i = 0; i < length; i++) { buffer[i] ^= mask[i & 3]; } } /** * Converts a buffer to an `ArrayBuffer`. * * @param {Buffer} buf The buffer to convert * @return {ArrayBuffer} Converted buffer * @public */ function toArrayBuffer(buf) { if (buf.byteLength === buf.buffer.byteLength) { return buf.buffer; } return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); } /** * Converts `data` to a `Buffer`. * * @param {*} data The data to convert * @return {Buffer} The buffer * @throws {TypeError} * @public */ function toBuffer(data) { toBuffer.readOnly = true; if (Buffer.isBuffer(data)) return data; let buf; if (data instanceof ArrayBuffer) { buf = Buffer.from(data); } else if (ArrayBuffer.isView(data)) { buf = Buffer.from(data.buffer, data.byteOffset, data.byteLength); } else { buf = Buffer.from(data); toBuffer.readOnly = false; } return buf; } try { const bufferUtil = __nccwpck_require__(71269); const bu = bufferUtil.BufferUtil || bufferUtil; module.exports = { concat, mask(source, mask, output, offset, length) { if (length < 48) _mask(source, mask, output, offset, length); else bu.mask(source, mask, output, offset, length); }, toArrayBuffer, toBuffer, unmask(buffer, mask) { if (buffer.length < 32) _unmask(buffer, mask); else bu.unmask(buffer, mask); } }; } catch (e) /* istanbul ignore next */ { module.exports = { concat, mask: _mask, toArrayBuffer, toBuffer, unmask: _unmask }; } /***/ }), /***/ 15949: /***/ ((module) => { "use strict"; module.exports = { BINARY_TYPES: ['nodebuffer', 'arraybuffer', 'fragments'], GUID: '258EAFA5-E914-47DA-95CA-C5AB0DC85B11', kStatusCode: Symbol('status-code'), kWebSocket: Symbol('websocket'), EMPTY_BUFFER: Buffer.alloc(0), NOOP: () => {} }; /***/ }), /***/ 64561: /***/ ((module) => { "use strict"; /** * Class representing an event. * * @private */ class Event { /** * Create a new `Event`. * * @param {String} type The name of the event * @param {Object} target A reference to the target to which the event was * dispatched */ constructor(type, target) { this.target = target; this.type = type; } } /** * Class representing a message event. * * @extends Event * @private */ class MessageEvent extends Event { /** * Create a new `MessageEvent`. * * @param {(String|Buffer|ArrayBuffer|Buffer[])} data The received data * @param {WebSocket} target A reference to the target to which the event was * dispatched */ constructor(data, target) { super('message', target); this.data = data; } } /** * Class representing a close event. * * @extends Event * @private */ class CloseEvent extends Event { /** * Create a new `CloseEvent`. * * @param {Number} code The status code explaining why the connection is being * closed * @param {String} reason A human-readable string explaining why the * connection is closing * @param {WebSocket} target A reference to the target to which the event was * dispatched */ constructor(code, reason, target) { super('close', target); this.wasClean = target._closeFrameReceived && target._closeFrameSent; this.reason = reason; this.code = code; } } /** * Class representing an open event. * * @extends Event * @private */ class OpenEvent extends Event { /** * Create a new `OpenEvent`. * * @param {WebSocket} target A reference to the target to which the event was * dispatched */ constructor(target) { super('open', target); } } /** * Class representing an error event. * * @extends Event * @private */ class ErrorEvent extends Event { /** * Create a new `ErrorEvent`. * * @param {Object} error The error that generated this event * @param {WebSocket} target A reference to the target to which the event was * dispatched */ constructor(error, target) { super('error', target); this.message = error.message; this.error = error; } } /** * This provides methods for emulating the `EventTarget` interface. It's not * meant to be used directly. * * @mixin */ const EventTarget = { /** * Register an event listener. * * @param {String} type A string representing the event type to listen for * @param {Function} listener The listener to add * @param {Object} [options] An options object specifies characteristics about * the event listener * @param {Boolean} [options.once=false] A `Boolean`` indicating that the * listener should be invoked at most once after being added. If `true`, * the listener would be automatically removed when invoked. * @public */ addEventListener(type, listener, options) { if (typeof listener !== 'function') return; function onMessage(data) { listener.call(this, new MessageEvent(data, this)); } function onClose(code, message) { listener.call(this, new CloseEvent(code, message, this)); } function onError(error) { listener.call(this, new ErrorEvent(error, this)); } function onOpen() { listener.call(this, new OpenEvent(this)); } const method = options && options.once ? 'once' : 'on'; if (type === 'message') { onMessage._listener = listener; this[method](type, onMessage); } else if (type === 'close') { onClose._listener = listener; this[method](type, onClose); } else if (type === 'error') { onError._listener = listener; this[method](type, onError); } else if (type === 'open') { onOpen._listener = listener; this[method](type, onOpen); } else { this[method](type, listener); } }, /** * Remove an event listener. * * @param {String} type A string representing the event type to remove * @param {Function} listener The listener to remove * @public */ removeEventListener(type, listener) { const listeners = this.listeners(type); for (let i = 0; i < listeners.length; i++) { if (listeners[i] === listener || listeners[i]._listener === listener) { this.removeListener(type, listeners[i]); } } } }; module.exports = EventTarget; /***/ }), /***/ 92035: /***/ ((module) => { "use strict"; // // Allowed token characters: // // '!', '#', '$', '%', '&', ''', '*', '+', '-', // '.', 0-9, A-Z, '^', '_', '`', a-z, '|', '~' // // tokenChars[32] === 0 // ' ' // tokenChars[33] === 1 // '!' // tokenChars[34] === 0 // '"' // ... // // prettier-ignore const tokenChars = [ 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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64 - 79 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, // 80 - 95 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 111 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0 // 112 - 127 ]; /** * Adds an offer to the map of extension offers or a parameter to the map of * parameters. * * @param {Object} dest The map of extension offers or parameters * @param {String} name The extension or parameter name * @param {(Object|Boolean|String)} elem The extension parameters or the * parameter value * @private */ function push(dest, name, elem) { if (dest[name] === undefined) dest[name] = [elem]; else dest[name].push(elem); } /** * Parses the `Sec-WebSocket-Extensions` header into an object. * * @param {String} header The field value of the header * @return {Object} The parsed object * @public */ function parse(header) { const offers = Object.create(null); if (header === undefined || header === '') return offers; let params = Object.create(null); let mustUnescape = false; let isEscaping = false; let inQuotes = false; let extensionName; let paramName; let start = -1; let end = -1; let i = 0; for (; i < header.length; i++) { const code = header.charCodeAt(i); if (extensionName === undefined) { if (end === -1 && tokenChars[code] === 1) { if (start === -1) start = i; } else if (code === 0x20 /* ' ' */ || code === 0x09 /* '\t' */) { if (end === -1 && start !== -1) end = i; } else if (code === 0x3b /* ';' */ || code === 0x2c /* ',' */) { if (start === -1) { throw new SyntaxError(`Unexpected character at index ${i}`); } if (end === -1) end = i; const name = header.slice(start, end); if (code === 0x2c) { push(offers, name, params); params = Object.create(null); } else { extensionName = name; } start = end = -1; } else { throw new SyntaxError(`Unexpected character at index ${i}`); } } else if (paramName === undefined) { if (end === -1 && tokenChars[code] === 1) { if (start === -1) start = i; } else if (code === 0x20 || code === 0x09) { if (end === -1 && start !== -1) end = i; } else if (code === 0x3b || code === 0x2c) { if (start === -1) { throw new SyntaxError(`Unexpected character at index ${i}`); } if (end === -1) end = i; push(params, header.slice(start, end), true); if (code === 0x2c) { push(offers, extensionName, params); params = Object.create(null); extensionName = undefined; } start = end = -1; } else if (code === 0x3d /* '=' */ && start !== -1 && end === -1) { paramName = header.slice(start, i); start = end = -1; } else { throw new SyntaxError(`Unexpected character at index ${i}`); } } else { // // The value of a quoted-string after unescaping must conform to the // token ABNF, so only token characters are valid. // Ref: https://tools.ietf.org/html/rfc6455#section-9.1 // if (isEscaping) { if (tokenChars[code] !== 1) { throw new SyntaxError(`Unexpected character at index ${i}`); } if (start === -1) start = i; else if (!mustUnescape) mustUnescape = true; isEscaping = false; } else if (inQuotes) { if (tokenChars[code] === 1) { if (start === -1) start = i; } else if (code === 0x22 /* '"' */ && start !== -1) { inQuotes = false; end = i; } else if (code === 0x5c /* '\' */) { isEscaping = true; } else { throw new SyntaxError(`Unexpected character at index ${i}`); } } else if (code === 0x22 && header.charCodeAt(i - 1) === 0x3d) { inQuotes = true; } else if (end === -1 && tokenChars[code] === 1) { if (start === -1) start = i; } else if (start !== -1 && (code === 0x20 || code === 0x09)) { if (end === -1) end = i; } else if (code === 0x3b || code === 0x2c) { if (start === -1) { throw new SyntaxError(`Unexpected character at index ${i}`); } if (end === -1) end = i; let value = header.slice(start, end); if (mustUnescape) { value = value.replace(/\\/g, ''); mustUnescape = false; } push(params, paramName, value); if (code === 0x2c) { push(offers, extensionName, params); params = Object.create(null); extensionName = undefined; } paramName = undefined; start = end = -1; } else { throw new SyntaxError(`Unexpected character at index ${i}`); } } } if (start === -1 || inQuotes) { throw new SyntaxError('Unexpected end of input'); } if (end === -1) end = i; const token = header.slice(start, end); if (extensionName === undefined) { push(offers, token, params); } else { if (paramName === undefined) { push(params, token, true); } else if (mustUnescape) { push(params, paramName, token.replace(/\\/g, '')); } else { push(params, paramName, token); } push(offers, extensionName, params); } return offers; } /** * Builds the `Sec-WebSocket-Extensions` header field value. * * @param {Object} extensions The map of extensions and parameters to format * @return {String} A string representing the given object * @public */ function format(extensions) { return Object.keys(extensions) .map((extension) => { let configurations = extensions[extension]; if (!Array.isArray(configurations)) configurations = [configurations]; return configurations .map((params) => { return [extension] .concat( Object.keys(params).map((k) => { let values = params[k]; if (!Array.isArray(values)) values = [values]; return values .map((v) => (v === true ? k : `${k}=${v}`)) .join('; '); }) ) .join('; '); }) .join(', '); }) .join(', '); } module.exports = { format, parse }; /***/ }), /***/ 41356: /***/ ((module) => { "use strict"; const kDone = Symbol('kDone'); const kRun = Symbol('kRun'); /** * A very simple job queue with adjustable concurrency. Adapted from * https://github.com/STRML/async-limiter */ class Limiter { /** * Creates a new `Limiter`. * * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed * to run concurrently */ constructor(concurrency) { this[kDone] = () => { this.pending--; this[kRun](); }; this.concurrency = concurrency || Infinity; this.jobs = []; this.pending = 0; } /** * Adds a job to the queue. * * @param {Function} job The job to run * @public */ add(job) { this.jobs.push(job); this[kRun](); } /** * Removes a job from the queue and runs it if possible. * * @private */ [kRun]() { if (this.pending === this.concurrency) return; if (this.jobs.length) { const job = this.jobs.shift(); this.pending++; job(this[kDone]); } } } module.exports = Limiter; /***/ }), /***/ 56684: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const zlib = __nccwpck_require__(59796); const bufferUtil = __nccwpck_require__(9436); const Limiter = __nccwpck_require__(41356); const { kStatusCode, NOOP } = __nccwpck_require__(15949); const TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]); const kPerMessageDeflate = Symbol('permessage-deflate'); const kTotalLength = Symbol('total-length'); const kCallback = Symbol('callback'); const kBuffers = Symbol('buffers'); const kError = Symbol('error'); // // We limit zlib concurrency, which prevents severe memory fragmentation // as documented in https://github.com/nodejs/node/issues/8871#issuecomment-250915913 // and https://github.com/websockets/ws/issues/1202 // // Intentionally global; it's the global thread pool that's an issue. // let zlibLimiter; /** * permessage-deflate implementation. */ class PerMessageDeflate { /** * Creates a PerMessageDeflate instance. * * @param {Object} [options] Configuration options * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept * disabling of server context takeover * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/ * acknowledge disabling of client context takeover * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the * use of a custom server window size * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support * for, or request, a custom client window size * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on * deflate * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on * inflate * @param {Number} [options.threshold=1024] Size (in bytes) below which * messages should not be compressed * @param {Number} [options.concurrencyLimit=10] The number of concurrent * calls to zlib * @param {Boolean} [isServer=false] Create the instance in either server or * client mode * @param {Number} [maxPayload=0] The maximum allowed message length */ constructor(options, isServer, maxPayload) { this._maxPayload = maxPayload | 0; this._options = options || {}; this._threshold = this._options.threshold !== undefined ? this._options.threshold : 1024; this._isServer = !!isServer; this._deflate = null; this._inflate = null; this.params = null; if (!zlibLimiter) { const concurrency = this._options.concurrencyLimit !== undefined ? this._options.concurrencyLimit : 10; zlibLimiter = new Limiter(concurrency); } } /** * @type {String} */ static get extensionName() { return 'permessage-deflate'; } /** * Create an extension negotiation offer. * * @return {Object} Extension parameters * @public */ offer() { const params = {}; if (this._options.serverNoContextTakeover) { params.server_no_context_takeover = true; } if (this._options.clientNoContextTakeover) { params.client_no_context_takeover = true; } if (this._options.serverMaxWindowBits) { params.server_max_window_bits = this._options.serverMaxWindowBits; } if (this._options.clientMaxWindowBits) { params.client_max_window_bits = this._options.clientMaxWindowBits; } else if (this._options.clientMaxWindowBits == null) { params.client_max_window_bits = true; } return params; } /** * Accept an extension negotiation offer/response. * * @param {Array} configurations The extension negotiation offers/reponse * @return {Object} Accepted configuration * @public */ accept(configurations) { configurations = this.normalizeParams(configurations); this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations); return this.params; } /** * Releases all resources used by the extension. * * @public */ cleanup() { if (this._inflate) { this._inflate.close(); this._inflate = null; } if (this._deflate) { const callback = this._deflate[kCallback]; this._deflate.close(); this._deflate = null; if (callback) { callback( new Error( 'The deflate stream was closed while data was being processed' ) ); } } } /** * Accept an extension negotiation offer. * * @param {Array} offers The extension negotiation offers * @return {Object} Accepted configuration * @private */ acceptAsServer(offers) { const opts = this._options; const accepted = offers.find((params) => { if ( (opts.serverNoContextTakeover === false && params.server_no_context_takeover) || (params.server_max_window_bits && (opts.serverMaxWindowBits === false || (typeof opts.serverMaxWindowBits === 'number' && opts.serverMaxWindowBits > params.server_max_window_bits))) || (typeof opts.clientMaxWindowBits === 'number' && !params.client_max_window_bits) ) { return false; } return true; }); if (!accepted) { throw new Error('None of the extension offers can be accepted'); } if (opts.serverNoContextTakeover) { accepted.server_no_context_takeover = true; } if (opts.clientNoContextTakeover) { accepted.client_no_context_takeover = true; } if (typeof opts.serverMaxWindowBits === 'number') { accepted.server_max_window_bits = opts.serverMaxWindowBits; } if (typeof opts.clientMaxWindowBits === 'number') { accepted.client_max_window_bits = opts.clientMaxWindowBits; } else if ( accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false ) { delete accepted.client_max_window_bits; } return accepted; } /** * Accept the extension negotiation response. * * @param {Array} response The extension negotiation response * @return {Object} Accepted configuration * @private */ acceptAsClient(response) { const params = response[0]; if ( this._options.clientNoContextTakeover === false && params.client_no_context_takeover ) { throw new Error('Unexpected parameter "client_no_context_takeover"'); } if (!params.client_max_window_bits) { if (typeof this._options.clientMaxWindowBits === 'number') { params.client_max_window_bits = this._options.clientMaxWindowBits; } } else if ( this._options.clientMaxWindowBits === false || (typeof this._options.clientMaxWindowBits === 'number' && params.client_max_window_bits > this._options.clientMaxWindowBits) ) { throw new Error( 'Unexpected or invalid parameter "client_max_window_bits"' ); } return params; } /** * Normalize parameters. * * @param {Array} configurations The extension negotiation offers/reponse * @return {Array} The offers/response with normalized parameters * @private */ normalizeParams(configurations) { configurations.forEach((params) => { Object.keys(params).forEach((key) => { let value = params[key]; if (value.length > 1) { throw new Error(`Parameter "${key}" must have only a single value`); } value = value[0]; if (key === 'client_max_window_bits') { if (value !== true) { const num = +value; if (!Number.isInteger(num) || num < 8 || num > 15) { throw new TypeError( `Invalid value for parameter "${key}": ${value}` ); } value = num; } else if (!this._isServer) { throw new TypeError( `Invalid value for parameter "${key}": ${value}` ); } } else if (key === 'server_max_window_bits') { const num = +value; if (!Number.isInteger(num) || num < 8 || num > 15) { throw new TypeError( `Invalid value for parameter "${key}": ${value}` ); } value = num; } else if ( key === 'client_no_context_takeover' || key === 'server_no_context_takeover' ) { if (value !== true) { throw new TypeError( `Invalid value for parameter "${key}": ${value}` ); } } else { throw new Error(`Unknown parameter "${key}"`); } params[key] = value; }); }); return configurations; } /** * Decompress data. Concurrency limited. * * @param {Buffer} data Compressed data * @param {Boolean} fin Specifies whether or not this is the last fragment * @param {Function} callback Callback * @public */ decompress(data, fin, callback) { zlibLimiter.add((done) => { this._decompress(data, fin, (err, result) => { done(); callback(err, result); }); }); } /** * Compress data. Concurrency limited. * * @param {Buffer} data Data to compress * @param {Boolean} fin Specifies whether or not this is the last fragment * @param {Function} callback Callback * @public */ compress(data, fin, callback) { zlibLimiter.add((done) => { this._compress(data, fin, (err, result) => { done(); callback(err, result); }); }); } /** * Decompress data. * * @param {Buffer} data Compressed data * @param {Boolean} fin Specifies whether or not this is the last fragment * @param {Function} callback Callback * @private */ _decompress(data, fin, callback) { const endpoint = this._isServer ? 'client' : 'server'; if (!this._inflate) { const key = `${endpoint}_max_window_bits`; const windowBits = typeof this.params[key] !== 'number' ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key]; this._inflate = zlib.createInflateRaw({ ...this._options.zlibInflateOptions, windowBits }); this._inflate[kPerMessageDeflate] = this; this._inflate[kTotalLength] = 0; this._inflate[kBuffers] = []; this._inflate.on('error', inflateOnError); this._inflate.on('data', inflateOnData); } this._inflate[kCallback] = callback; this._inflate.write(data); if (fin) this._inflate.write(TRAILER); this._inflate.flush(() => { const err = this._inflate[kError]; if (err) { this._inflate.close(); this._inflate = null; callback(err); return; } const data = bufferUtil.concat( this._inflate[kBuffers], this._inflate[kTotalLength] ); if (this._inflate._readableState.endEmitted) { this._inflate.close(); this._inflate = null; } else { this._inflate[kTotalLength] = 0; this._inflate[kBuffers] = []; if (fin && this.params[`${endpoint}_no_context_takeover`]) { this._inflate.reset(); } } callback(null, data); }); } /** * Compress data. * * @param {Buffer} data Data to compress * @param {Boolean} fin Specifies whether or not this is the last fragment * @param {Function} callback Callback * @private */ _compress(data, fin, callback) { const endpoint = this._isServer ? 'server' : 'client'; if (!this._deflate) { const key = `${endpoint}_max_window_bits`; const windowBits = typeof this.params[key] !== 'number' ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key]; this._deflate = zlib.createDeflateRaw({ ...this._options.zlibDeflateOptions, windowBits }); this._deflate[kTotalLength] = 0; this._deflate[kBuffers] = []; // // An `'error'` event is emitted, only on Node.js < 10.0.0, if the // `zlib.DeflateRaw` instance is closed while data is being processed. // This can happen if `PerMessageDeflate#cleanup()` is called at the wrong // time due to an abnormal WebSocket closure. // this._deflate.on('error', NOOP); this._deflate.on('data', deflateOnData); } this._deflate[kCallback] = callback; this._deflate.write(data); this._deflate.flush(zlib.Z_SYNC_FLUSH, () => { if (!this._deflate) { // // The deflate stream was closed while data was being processed. // return; } let data = bufferUtil.concat( this._deflate[kBuffers], this._deflate[kTotalLength] ); if (fin) data = data.slice(0, data.length - 4); // // Ensure that the callback will not be called again in // `PerMessageDeflate#cleanup()`. // this._deflate[kCallback] = null; this._deflate[kTotalLength] = 0; this._deflate[kBuffers] = []; if (fin && this.params[`${endpoint}_no_context_takeover`]) { this._deflate.reset(); } callback(null, data); }); } } module.exports = PerMessageDeflate; /** * The listener of the `zlib.DeflateRaw` stream `'data'` event. * * @param {Buffer} chunk A chunk of data * @private */ function deflateOnData(chunk) { this[kBuffers].push(chunk); this[kTotalLength] += chunk.length; } /** * The listener of the `zlib.InflateRaw` stream `'data'` event. * * @param {Buffer} chunk A chunk of data * @private */ function inflateOnData(chunk) { this[kTotalLength] += chunk.length; if ( this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload ) { this[kBuffers].push(chunk); return; } this[kError] = new RangeError('Max payload size exceeded'); this[kError].code = 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'; this[kError][kStatusCode] = 1009; this.removeListener('data', inflateOnData); this.reset(); } /** * The listener of the `zlib.InflateRaw` stream `'error'` event. * * @param {Error} err The emitted error * @private */ function inflateOnError(err) { // // There is no need to call `Zlib#close()` as the handle is automatically // closed when an error is emitted. // this[kPerMessageDeflate]._inflate = null; err[kStatusCode] = 1007; this[kCallback](err); } /***/ }), /***/ 25066: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { Writable } = __nccwpck_require__(12781); const PerMessageDeflate = __nccwpck_require__(56684); const { BINARY_TYPES, EMPTY_BUFFER, kStatusCode, kWebSocket } = __nccwpck_require__(15949); const { concat, toArrayBuffer, unmask } = __nccwpck_require__(9436); const { isValidStatusCode, isValidUTF8 } = __nccwpck_require__(86279); const GET_INFO = 0; const GET_PAYLOAD_LENGTH_16 = 1; const GET_PAYLOAD_LENGTH_64 = 2; const GET_MASK = 3; const GET_DATA = 4; const INFLATING = 5; /** * HyBi Receiver implementation. * * @extends Writable */ class Receiver extends Writable { /** * Creates a Receiver instance. * * @param {String} [binaryType=nodebuffer] The type for binary data * @param {Object} [extensions] An object containing the negotiated extensions * @param {Boolean} [isServer=false] Specifies whether to operate in client or * server mode * @param {Number} [maxPayload=0] The maximum allowed message length */ constructor(binaryType, extensions, isServer, maxPayload) { super(); this._binaryType = binaryType || BINARY_TYPES[0]; this[kWebSocket] = undefined; this._extensions = extensions || {}; this._isServer = !!isServer; this._maxPayload = maxPayload | 0; this._bufferedBytes = 0; this._buffers = []; this._compressed = false; this._payloadLength = 0; this._mask = undefined; this._fragmented = 0; this._masked = false; this._fin = false; this._opcode = 0; this._totalPayloadLength = 0; this._messageLength = 0; this._fragments = []; this._state = GET_INFO; this._loop = false; } /** * Implements `Writable.prototype._write()`. * * @param {Buffer} chunk The chunk of data to write * @param {String} encoding The character encoding of `chunk` * @param {Function} cb Callback * @private */ _write(chunk, encoding, cb) { if (this._opcode === 0x08 && this._state == GET_INFO) return cb(); this._bufferedBytes += chunk.length; this._buffers.push(chunk); this.startLoop(cb); } /** * Consumes `n` bytes from the buffered data. * * @param {Number} n The number of bytes to consume * @return {Buffer} The consumed bytes * @private */ consume(n) { this._bufferedBytes -= n; if (n === this._buffers[0].length) return this._buffers.shift(); if (n < this._buffers[0].length) { const buf = this._buffers[0]; this._buffers[0] = buf.slice(n); return buf.slice(0, n); } const dst = Buffer.allocUnsafe(n); do { const buf = this._buffers[0]; const offset = dst.length - n; if (n >= buf.length) { dst.set(this._buffers.shift(), offset); } else { dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset); this._buffers[0] = buf.slice(n); } n -= buf.length; } while (n > 0); return dst; } /** * Starts the parsing loop. * * @param {Function} cb Callback * @private */ startLoop(cb) { let err; this._loop = true; do { switch (this._state) { case GET_INFO: err = this.getInfo(); break; case GET_PAYLOAD_LENGTH_16: err = this.getPayloadLength16(); break; case GET_PAYLOAD_LENGTH_64: err = this.getPayloadLength64(); break; case GET_MASK: this.getMask(); break; case GET_DATA: err = this.getData(cb); break; default: // `INFLATING` this._loop = false; return; } } while (this._loop); cb(err); } /** * Reads the first two bytes of a frame. * * @return {(RangeError|undefined)} A possible error * @private */ getInfo() { if (this._bufferedBytes < 2) { this._loop = false; return; } const buf = this.consume(2); if ((buf[0] & 0x30) !== 0x00) { this._loop = false; return error( RangeError, 'RSV2 and RSV3 must be clear', true, 1002, 'WS_ERR_UNEXPECTED_RSV_2_3' ); } const compressed = (buf[0] & 0x40) === 0x40; if (compressed && !this._extensions[PerMessageDeflate.extensionName]) { this._loop = false; return error( RangeError, 'RSV1 must be clear', true, 1002, 'WS_ERR_UNEXPECTED_RSV_1' ); } this._fin = (buf[0] & 0x80) === 0x80; this._opcode = buf[0] & 0x0f; this._payloadLength = buf[1] & 0x7f; if (this._opcode === 0x00) { if (compressed) { this._loop = false; return error( RangeError, 'RSV1 must be clear', true, 1002, 'WS_ERR_UNEXPECTED_RSV_1' ); } if (!this._fragmented) { this._loop = false; return error( RangeError, 'invalid opcode 0', true, 1002, 'WS_ERR_INVALID_OPCODE' ); } this._opcode = this._fragmented; } else if (this._opcode === 0x01 || this._opcode === 0x02) { if (this._fragmented) { this._loop = false; return error( RangeError, `invalid opcode ${this._opcode}`, true, 1002, 'WS_ERR_INVALID_OPCODE' ); } this._compressed = compressed; } else if (this._opcode > 0x07 && this._opcode < 0x0b) { if (!this._fin) { this._loop = false; return error( RangeError, 'FIN must be set', true, 1002, 'WS_ERR_EXPECTED_FIN' ); } if (compressed) { this._loop = false; return error( RangeError, 'RSV1 must be clear', true, 1002, 'WS_ERR_UNEXPECTED_RSV_1' ); } if (this._payloadLength > 0x7d) { this._loop = false; return error( RangeError, `invalid payload length ${this._payloadLength}`, true, 1002, 'WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH' ); } } else { this._loop = false; return error( RangeError, `invalid opcode ${this._opcode}`, true, 1002, 'WS_ERR_INVALID_OPCODE' ); } if (!this._fin && !this._fragmented) this._fragmented = this._opcode; this._masked = (buf[1] & 0x80) === 0x80; if (this._isServer) { if (!this._masked) { this._loop = false; return error( RangeError, 'MASK must be set', true, 1002, 'WS_ERR_EXPECTED_MASK' ); } } else if (this._masked) { this._loop = false; return error( RangeError, 'MASK must be clear', true, 1002, 'WS_ERR_UNEXPECTED_MASK' ); } if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16; else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64; else return this.haveLength(); } /** * Gets extended payload length (7+16). * * @return {(RangeError|undefined)} A possible error * @private */ getPayloadLength16() { if (this._bufferedBytes < 2) { this._loop = false; return; } this._payloadLength = this.consume(2).readUInt16BE(0); return this.haveLength(); } /** * Gets extended payload length (7+64). * * @return {(RangeError|undefined)} A possible error * @private */ getPayloadLength64() { if (this._bufferedBytes < 8) { this._loop = false; return; } const buf = this.consume(8); const num = buf.readUInt32BE(0); // // The maximum safe integer in JavaScript is 2^53 - 1. An error is returned // if payload length is greater than this number. // if (num > Math.pow(2, 53 - 32) - 1) { this._loop = false; return error( RangeError, 'Unsupported WebSocket frame: payload length > 2^53 - 1', false, 1009, 'WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH' ); } this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4); return this.haveLength(); } /** * Payload length has been read. * * @return {(RangeError|undefined)} A possible error * @private */ haveLength() { if (this._payloadLength && this._opcode < 0x08) { this._totalPayloadLength += this._payloadLength; if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) { this._loop = false; return error( RangeError, 'Max payload size exceeded', false, 1009, 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH' ); } } if (this._masked) this._state = GET_MASK; else this._state = GET_DATA; } /** * Reads mask bytes. * * @private */ getMask() { if (this._bufferedBytes < 4) { this._loop = false; return; } this._mask = this.consume(4); this._state = GET_DATA; } /** * Reads data bytes. * * @param {Function} cb Callback * @return {(Error|RangeError|undefined)} A possible error * @private */ getData(cb) { let data = EMPTY_BUFFER; if (this._payloadLength) { if (this._bufferedBytes < this._payloadLength) { this._loop = false; return; } data = this.consume(this._payloadLength); if (this._masked) unmask(data, this._mask); } if (this._opcode > 0x07) return this.controlMessage(data); if (this._compressed) { this._state = INFLATING; this.decompress(data, cb); return; } if (data.length) { // // This message is not compressed so its lenght is the sum of the payload // length of all fragments. // this._messageLength = this._totalPayloadLength; this._fragments.push(data); } return this.dataMessage(); } /** * Decompresses data. * * @param {Buffer} data Compressed data * @param {Function} cb Callback * @private */ decompress(data, cb) { const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; perMessageDeflate.decompress(data, this._fin, (err, buf) => { if (err) return cb(err); if (buf.length) { this._messageLength += buf.length; if (this._messageLength > this._maxPayload && this._maxPayload > 0) { return cb( error( RangeError, 'Max payload size exceeded', false, 1009, 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH' ) ); } this._fragments.push(buf); } const er = this.dataMessage(); if (er) return cb(er); this.startLoop(cb); }); } /** * Handles a data message. * * @return {(Error|undefined)} A possible error * @private */ dataMessage() { if (this._fin) { const messageLength = this._messageLength; const fragments = this._fragments; this._totalPayloadLength = 0; this._messageLength = 0; this._fragmented = 0; this._fragments = []; if (this._opcode === 2) { let data; if (this._binaryType === 'nodebuffer') { data = concat(fragments, messageLength); } else if (this._binaryType === 'arraybuffer') { data = toArrayBuffer(concat(fragments, messageLength)); } else { data = fragments; } this.emit('message', data); } else { const buf = concat(fragments, messageLength); if (!isValidUTF8(buf)) { this._loop = false; return error( Error, 'invalid UTF-8 sequence', true, 1007, 'WS_ERR_INVALID_UTF8' ); } this.emit('message', buf.toString()); } } this._state = GET_INFO; } /** * Handles a control message. * * @param {Buffer} data Data to handle * @return {(Error|RangeError|undefined)} A possible error * @private */ controlMessage(data) { if (this._opcode === 0x08) { this._loop = false; if (data.length === 0) { this.emit('conclude', 1005, ''); this.end(); } else if (data.length === 1) { return error( RangeError, 'invalid payload length 1', true, 1002, 'WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH' ); } else { const code = data.readUInt16BE(0); if (!isValidStatusCode(code)) { return error( RangeError, `invalid status code ${code}`, true, 1002, 'WS_ERR_INVALID_CLOSE_CODE' ); } const buf = data.slice(2); if (!isValidUTF8(buf)) { return error( Error, 'invalid UTF-8 sequence', true, 1007, 'WS_ERR_INVALID_UTF8' ); } this.emit('conclude', code, buf.toString()); this.end(); } } else if (this._opcode === 0x09) { this.emit('ping', data); } else { this.emit('pong', data); } this._state = GET_INFO; } } module.exports = Receiver; /** * Builds an error object. * * @param {function(new:Error|RangeError)} ErrorCtor The error constructor * @param {String} message The error message * @param {Boolean} prefix Specifies whether or not to add a default prefix to * `message` * @param {Number} statusCode The status code * @param {String} errorCode The exposed error code * @return {(Error|RangeError)} The error * @private */ function error(ErrorCtor, message, prefix, statusCode, errorCode) { const err = new ErrorCtor( prefix ? `Invalid WebSocket frame: ${message}` : message ); Error.captureStackTrace(err, error); err.code = errorCode; err[kStatusCode] = statusCode; return err; } /***/ }), /***/ 36947: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^net|tls$" }] */ const net = __nccwpck_require__(41808); const tls = __nccwpck_require__(24404); const { randomFillSync } = __nccwpck_require__(6113); const PerMessageDeflate = __nccwpck_require__(56684); const { EMPTY_BUFFER } = __nccwpck_require__(15949); const { isValidStatusCode } = __nccwpck_require__(86279); const { mask: applyMask, toBuffer } = __nccwpck_require__(9436); const mask = Buffer.alloc(4); /** * HyBi Sender implementation. */ class Sender { /** * Creates a Sender instance. * * @param {(net.Socket|tls.Socket)} socket The connection socket * @param {Object} [extensions] An object containing the negotiated extensions */ constructor(socket, extensions) { this._extensions = extensions || {}; this._socket = socket; this._firstFragment = true; this._compress = false; this._bufferedBytes = 0; this._deflating = false; this._queue = []; } /** * Frames a piece of data according to the HyBi WebSocket protocol. * * @param {Buffer} data The data to frame * @param {Object} options Options object * @param {Number} options.opcode The opcode * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be * modified * @param {Boolean} [options.fin=false] Specifies whether or not to set the * FIN bit * @param {Boolean} [options.mask=false] Specifies whether or not to mask * `data` * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the * RSV1 bit * @return {Buffer[]} The framed data as a list of `Buffer` instances * @public */ static frame(data, options) { const merge = options.mask && options.readOnly; let offset = options.mask ? 6 : 2; let payloadLength = data.length; if (data.length >= 65536) { offset += 8; payloadLength = 127; } else if (data.length > 125) { offset += 2; payloadLength = 126; } const target = Buffer.allocUnsafe(merge ? data.length + offset : offset); target[0] = options.fin ? options.opcode | 0x80 : options.opcode; if (options.rsv1) target[0] |= 0x40; target[1] = payloadLength; if (payloadLength === 126) { target.writeUInt16BE(data.length, 2); } else if (payloadLength === 127) { target.writeUInt32BE(0, 2); target.writeUInt32BE(data.length, 6); } if (!options.mask) return [target, data]; randomFillSync(mask, 0, 4); target[1] |= 0x80; target[offset - 4] = mask[0]; target[offset - 3] = mask[1]; target[offset - 2] = mask[2]; target[offset - 1] = mask[3]; if (merge) { applyMask(data, mask, target, offset, data.length); return [target]; } applyMask(data, mask, data, 0, data.length); return [target, data]; } /** * Sends a close message to the other peer. * * @param {Number} [code] The status code component of the body * @param {String} [data] The message component of the body * @param {Boolean} [mask=false] Specifies whether or not to mask the message * @param {Function} [cb] Callback * @public */ close(code, data, mask, cb) { let buf; if (code === undefined) { buf = EMPTY_BUFFER; } else if (typeof code !== 'number' || !isValidStatusCode(code)) { throw new TypeError('First argument must be a valid error code number'); } else if (data === undefined || data === '') { buf = Buffer.allocUnsafe(2); buf.writeUInt16BE(code, 0); } else { const length = Buffer.byteLength(data); if (length > 123) { throw new RangeError('The message must not be greater than 123 bytes'); } buf = Buffer.allocUnsafe(2 + length); buf.writeUInt16BE(code, 0); buf.write(data, 2); } if (this._deflating) { this.enqueue([this.doClose, buf, mask, cb]); } else { this.doClose(buf, mask, cb); } } /** * Frames and sends a close message. * * @param {Buffer} data The message to send * @param {Boolean} [mask=false] Specifies whether or not to mask `data` * @param {Function} [cb] Callback * @private */ doClose(data, mask, cb) { this.sendFrame( Sender.frame(data, { fin: true, rsv1: false, opcode: 0x08, mask, readOnly: false }), cb ); } /** * Sends a ping message to the other peer. * * @param {*} data The message to send * @param {Boolean} [mask=false] Specifies whether or not to mask `data` * @param {Function} [cb] Callback * @public */ ping(data, mask, cb) { const buf = toBuffer(data); if (buf.length > 125) { throw new RangeError('The data size must not be greater than 125 bytes'); } if (this._deflating) { this.enqueue([this.doPing, buf, mask, toBuffer.readOnly, cb]); } else { this.doPing(buf, mask, toBuffer.readOnly, cb); } } /** * Frames and sends a ping message. * * @param {Buffer} data The message to send * @param {Boolean} [mask=false] Specifies whether or not to mask `data` * @param {Boolean} [readOnly=false] Specifies whether `data` can be modified * @param {Function} [cb] Callback * @private */ doPing(data, mask, readOnly, cb) { this.sendFrame( Sender.frame(data, { fin: true, rsv1: false, opcode: 0x09, mask, readOnly }), cb ); } /** * Sends a pong message to the other peer. * * @param {*} data The message to send * @param {Boolean} [mask=false] Specifies whether or not to mask `data` * @param {Function} [cb] Callback * @public */ pong(data, mask, cb) { const buf = toBuffer(data); if (buf.length > 125) { throw new RangeError('The data size must not be greater than 125 bytes'); } if (this._deflating) { this.enqueue([this.doPong, buf, mask, toBuffer.readOnly, cb]); } else { this.doPong(buf, mask, toBuffer.readOnly, cb); } } /** * Frames and sends a pong message. * * @param {Buffer} data The message to send * @param {Boolean} [mask=false] Specifies whether or not to mask `data` * @param {Boolean} [readOnly=false] Specifies whether `data` can be modified * @param {Function} [cb] Callback * @private */ doPong(data, mask, readOnly, cb) { this.sendFrame( Sender.frame(data, { fin: true, rsv1: false, opcode: 0x0a, mask, readOnly }), cb ); } /** * Sends a data message to the other peer. * * @param {*} data The message to send * @param {Object} options Options object * @param {Boolean} [options.compress=false] Specifies whether or not to * compress `data` * @param {Boolean} [options.binary=false] Specifies whether `data` is binary * or text * @param {Boolean} [options.fin=false] Specifies whether the fragment is the * last one * @param {Boolean} [options.mask=false] Specifies whether or not to mask * `data` * @param {Function} [cb] Callback * @public */ send(data, options, cb) { const buf = toBuffer(data); const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; let opcode = options.binary ? 2 : 1; let rsv1 = options.compress; if (this._firstFragment) { this._firstFragment = false; if (rsv1 && perMessageDeflate) { rsv1 = buf.length >= perMessageDeflate._threshold; } this._compress = rsv1; } else { rsv1 = false; opcode = 0; } if (options.fin) this._firstFragment = true; if (perMessageDeflate) { const opts = { fin: options.fin, rsv1, opcode, mask: options.mask, readOnly: toBuffer.readOnly }; if (this._deflating) { this.enqueue([this.dispatch, buf, this._compress, opts, cb]); } else { this.dispatch(buf, this._compress, opts, cb); } } else { this.sendFrame( Sender.frame(buf, { fin: options.fin, rsv1: false, opcode, mask: options.mask, readOnly: toBuffer.readOnly }), cb ); } } /** * Dispatches a data message. * * @param {Buffer} data The message to send * @param {Boolean} [compress=false] Specifies whether or not to compress * `data` * @param {Object} options Options object * @param {Number} options.opcode The opcode * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be * modified * @param {Boolean} [options.fin=false] Specifies whether or not to set the * FIN bit * @param {Boolean} [options.mask=false] Specifies whether or not to mask * `data` * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the * RSV1 bit * @param {Function} [cb] Callback * @private */ dispatch(data, compress, options, cb) { if (!compress) { this.sendFrame(Sender.frame(data, options), cb); return; } const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; this._bufferedBytes += data.length; this._deflating = true; perMessageDeflate.compress(data, options.fin, (_, buf) => { if (this._socket.destroyed) { const err = new Error( 'The socket was closed while data was being compressed' ); if (typeof cb === 'function') cb(err); for (let i = 0; i < this._queue.length; i++) { const callback = this._queue[i][4]; if (typeof callback === 'function') callback(err); } return; } this._bufferedBytes -= data.length; this._deflating = false; options.readOnly = false; this.sendFrame(Sender.frame(buf, options), cb); this.dequeue(); }); } /** * Executes queued send operations. * * @private */ dequeue() { while (!this._deflating && this._queue.length) { const params = this._queue.shift(); this._bufferedBytes -= params[1].length; Reflect.apply(params[0], this, params.slice(1)); } } /** * Enqueues a send operation. * * @param {Array} params Send operation parameters. * @private */ enqueue(params) { this._bufferedBytes += params[1].length; this._queue.push(params); } /** * Sends a frame. * * @param {Buffer[]} list The frame to send * @param {Function} [cb] Callback * @private */ sendFrame(list, cb) { if (list.length === 2) { this._socket.cork(); this._socket.write(list[0]); this._socket.write(list[1], cb); this._socket.uncork(); } else { this._socket.write(list[0], cb); } } } module.exports = Sender; /***/ }), /***/ 41658: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { Duplex } = __nccwpck_require__(12781); /** * Emits the `'close'` event on a stream. * * @param {Duplex} stream The stream. * @private */ function emitClose(stream) { stream.emit('close'); } /** * The listener of the `'end'` event. * * @private */ function duplexOnEnd() { if (!this.destroyed && this._writableState.finished) { this.destroy(); } } /** * The listener of the `'error'` event. * * @param {Error} err The error * @private */ function duplexOnError(err) { this.removeListener('error', duplexOnError); this.destroy(); if (this.listenerCount('error') === 0) { // Do not suppress the throwing behavior. this.emit('error', err); } } /** * Wraps a `WebSocket` in a duplex stream. * * @param {WebSocket} ws The `WebSocket` to wrap * @param {Object} [options] The options for the `Duplex` constructor * @return {Duplex} The duplex stream * @public */ function createWebSocketStream(ws, options) { let resumeOnReceiverDrain = true; let terminateOnDestroy = true; function receiverOnDrain() { if (resumeOnReceiverDrain) ws._socket.resume(); } if (ws.readyState === ws.CONNECTING) { ws.once('open', function open() { ws._receiver.removeAllListeners('drain'); ws._receiver.on('drain', receiverOnDrain); }); } else { ws._receiver.removeAllListeners('drain'); ws._receiver.on('drain', receiverOnDrain); } const duplex = new Duplex({ ...options, autoDestroy: false, emitClose: false, objectMode: false, writableObjectMode: false }); ws.on('message', function message(msg) { if (!duplex.push(msg)) { resumeOnReceiverDrain = false; ws._socket.pause(); } }); ws.once('error', function error(err) { if (duplex.destroyed) return; // Prevent `ws.terminate()` from being called by `duplex._destroy()`. // // - If the `'error'` event is emitted before the `'open'` event, then // `ws.terminate()` is a noop as no socket is assigned. // - Otherwise, the error is re-emitted by the listener of the `'error'` // event of the `Receiver` object. The listener already closes the // connection by calling `ws.close()`. This allows a close frame to be // sent to the other peer. If `ws.terminate()` is called right after this, // then the close frame might not be sent. terminateOnDestroy = false; duplex.destroy(err); }); ws.once('close', function close() { if (duplex.destroyed) return; duplex.push(null); }); duplex._destroy = function (err, callback) { if (ws.readyState === ws.CLOSED) { callback(err); process.nextTick(emitClose, duplex); return; } let called = false; ws.once('error', function error(err) { called = true; callback(err); }); ws.once('close', function close() { if (!called) callback(err); process.nextTick(emitClose, duplex); }); if (terminateOnDestroy) ws.terminate(); }; duplex._final = function (callback) { if (ws.readyState === ws.CONNECTING) { ws.once('open', function open() { duplex._final(callback); }); return; } // If the value of the `_socket` property is `null` it means that `ws` is a // client websocket and the handshake failed. In fact, when this happens, a // socket is never assigned to the websocket. Wait for the `'error'` event // that will be emitted by the websocket. if (ws._socket === null) return; if (ws._socket._writableState.finished) { callback(); if (duplex._readableState.endEmitted) duplex.destroy(); } else { ws._socket.once('finish', function finish() { // `duplex` is not destroyed here because the `'end'` event will be // emitted on `duplex` after this `'finish'` event. The EOF signaling // `null` chunk is, in fact, pushed when the websocket emits `'close'`. callback(); }); ws.close(); } }; duplex._read = function () { if ( (ws.readyState === ws.OPEN || ws.readyState === ws.CLOSING) && !resumeOnReceiverDrain ) { resumeOnReceiverDrain = true; if (!ws._receiver._writableState.needDrain) ws._socket.resume(); } }; duplex._write = function (chunk, encoding, callback) { if (ws.readyState === ws.CONNECTING) { ws.once('open', function open() { duplex._write(chunk, encoding, callback); }); return; } ws.send(chunk, callback); }; duplex.on('end', duplexOnEnd); duplex.on('error', duplexOnError); return duplex; } module.exports = createWebSocketStream; /***/ }), /***/ 86279: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /** * Checks if a status code is allowed in a close frame. * * @param {Number} code The status code * @return {Boolean} `true` if the status code is valid, else `false` * @public */ function isValidStatusCode(code) { return ( (code >= 1000 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006) || (code >= 3000 && code <= 4999) ); } /** * Checks if a given buffer contains only correct UTF-8. * Ported from https://www.cl.cam.ac.uk/%7Emgk25/ucs/utf8_check.c by * Markus Kuhn. * * @param {Buffer} buf The buffer to check * @return {Boolean} `true` if `buf` contains only correct UTF-8, else `false` * @public */ function _isValidUTF8(buf) { const len = buf.length; let i = 0; while (i < len) { if ((buf[i] & 0x80) === 0) { // 0xxxxxxx i++; } else if ((buf[i] & 0xe0) === 0xc0) { // 110xxxxx 10xxxxxx if ( i + 1 === len || (buf[i + 1] & 0xc0) !== 0x80 || (buf[i] & 0xfe) === 0xc0 // Overlong ) { return false; } i += 2; } else if ((buf[i] & 0xf0) === 0xe0) { // 1110xxxx 10xxxxxx 10xxxxxx if ( i + 2 >= len || (buf[i + 1] & 0xc0) !== 0x80 || (buf[i + 2] & 0xc0) !== 0x80 || (buf[i] === 0xe0 && (buf[i + 1] & 0xe0) === 0x80) || // Overlong (buf[i] === 0xed && (buf[i + 1] & 0xe0) === 0xa0) // Surrogate (U+D800 - U+DFFF) ) { return false; } i += 3; } else if ((buf[i] & 0xf8) === 0xf0) { // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx if ( i + 3 >= len || (buf[i + 1] & 0xc0) !== 0x80 || (buf[i + 2] & 0xc0) !== 0x80 || (buf[i + 3] & 0xc0) !== 0x80 || (buf[i] === 0xf0 && (buf[i + 1] & 0xf0) === 0x80) || // Overlong (buf[i] === 0xf4 && buf[i + 1] > 0x8f) || buf[i] > 0xf4 // > U+10FFFF ) { return false; } i += 4; } else { return false; } } return true; } try { let isValidUTF8 = __nccwpck_require__(24592); /* istanbul ignore if */ if (typeof isValidUTF8 === 'object') { isValidUTF8 = isValidUTF8.Validation.isValidUTF8; // utf-8-validate@<3.0.0 } module.exports = { isValidStatusCode, isValidUTF8(buf) { return buf.length < 150 ? _isValidUTF8(buf) : isValidUTF8(buf); } }; } catch (e) /* istanbul ignore next */ { module.exports = { isValidStatusCode, isValidUTF8: _isValidUTF8 }; } /***/ }), /***/ 58887: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^net|tls|https$" }] */ const EventEmitter = __nccwpck_require__(82361); const http = __nccwpck_require__(13685); const https = __nccwpck_require__(95687); const net = __nccwpck_require__(41808); const tls = __nccwpck_require__(24404); const { createHash } = __nccwpck_require__(6113); const PerMessageDeflate = __nccwpck_require__(56684); const WebSocket = __nccwpck_require__(91518); const { format, parse } = __nccwpck_require__(92035); const { GUID, kWebSocket } = __nccwpck_require__(15949); const keyRegex = /^[+/0-9A-Za-z]{22}==$/; const RUNNING = 0; const CLOSING = 1; const CLOSED = 2; /** * Class representing a WebSocket server. * * @extends EventEmitter */ class WebSocketServer extends EventEmitter { /** * Create a `WebSocketServer` instance. * * @param {Object} options Configuration options * @param {Number} [options.backlog=511] The maximum length of the queue of * pending connections * @param {Boolean} [options.clientTracking=true] Specifies whether or not to * track clients * @param {Function} [options.handleProtocols] A hook to handle protocols * @param {String} [options.host] The hostname where to bind the server * @param {Number} [options.maxPayload=104857600] The maximum allowed message * size * @param {Boolean} [options.noServer=false] Enable no server mode * @param {String} [options.path] Accept only connections matching this path * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable * permessage-deflate * @param {Number} [options.port] The port where to bind the server * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S * server to use * @param {Function} [options.verifyClient] A hook to reject connections * @param {Function} [callback] A listener for the `listening` event */ constructor(options, callback) { super(); options = { maxPayload: 100 * 1024 * 1024, perMessageDeflate: false, handleProtocols: null, clientTracking: true, verifyClient: null, noServer: false, backlog: null, // use default (511 as implemented in net.js) server: null, host: null, path: null, port: null, ...options }; if ( (options.port == null && !options.server && !options.noServer) || (options.port != null && (options.server || options.noServer)) || (options.server && options.noServer) ) { throw new TypeError( 'One and only one of the "port", "server", or "noServer" options ' + 'must be specified' ); } if (options.port != null) { this._server = http.createServer((req, res) => { const body = http.STATUS_CODES[426]; res.writeHead(426, { 'Content-Length': body.length, 'Content-Type': 'text/plain' }); res.end(body); }); this._server.listen( options.port, options.host, options.backlog, callback ); } else if (options.server) { this._server = options.server; } if (this._server) { const emitConnection = this.emit.bind(this, 'connection'); this._removeListeners = addListeners(this._server, { listening: this.emit.bind(this, 'listening'), error: this.emit.bind(this, 'error'), upgrade: (req, socket, head) => { this.handleUpgrade(req, socket, head, emitConnection); } }); } if (options.perMessageDeflate === true) options.perMessageDeflate = {}; if (options.clientTracking) this.clients = new Set(); this.options = options; this._state = RUNNING; } /** * Returns the bound address, the address family name, and port of the server * as reported by the operating system if listening on an IP socket. * If the server is listening on a pipe or UNIX domain socket, the name is * returned as a string. * * @return {(Object|String|null)} The address of the server * @public */ address() { if (this.options.noServer) { throw new Error('The server is operating in "noServer" mode'); } if (!this._server) return null; return this._server.address(); } /** * Close the server. * * @param {Function} [cb] Callback * @public */ close(cb) { if (cb) this.once('close', cb); if (this._state === CLOSED) { process.nextTick(emitClose, this); return; } if (this._state === CLOSING) return; this._state = CLOSING; // // Terminate all associated clients. // if (this.clients) { for (const client of this.clients) client.terminate(); } const server = this._server; if (server) { this._removeListeners(); this._removeListeners = this._server = null; // // Close the http server if it was internally created. // if (this.options.port != null) { server.close(emitClose.bind(undefined, this)); return; } } process.nextTick(emitClose, this); } /** * See if a given request should be handled by this server instance. * * @param {http.IncomingMessage} req Request object to inspect * @return {Boolean} `true` if the request is valid, else `false` * @public */ shouldHandle(req) { if (this.options.path) { const index = req.url.indexOf('?'); const pathname = index !== -1 ? req.url.slice(0, index) : req.url; if (pathname !== this.options.path) return false; } return true; } /** * Handle a HTTP Upgrade request. * * @param {http.IncomingMessage} req The request object * @param {(net.Socket|tls.Socket)} socket The network socket between the * server and client * @param {Buffer} head The first packet of the upgraded stream * @param {Function} cb Callback * @public */ handleUpgrade(req, socket, head, cb) { socket.on('error', socketOnError); const key = req.headers['sec-websocket-key'] !== undefined ? req.headers['sec-websocket-key'].trim() : false; const version = +req.headers['sec-websocket-version']; const extensions = {}; if ( req.method !== 'GET' || req.headers.upgrade.toLowerCase() !== 'websocket' || !key || !keyRegex.test(key) || (version !== 8 && version !== 13) || !this.shouldHandle(req) ) { return abortHandshake(socket, 400); } if (this.options.perMessageDeflate) { const perMessageDeflate = new PerMessageDeflate( this.options.perMessageDeflate, true, this.options.maxPayload ); try { const offers = parse(req.headers['sec-websocket-extensions']); if (offers[PerMessageDeflate.extensionName]) { perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]); extensions[PerMessageDeflate.extensionName] = perMessageDeflate; } } catch (err) { return abortHandshake(socket, 400); } } // // Optionally call external client verification handler. // if (this.options.verifyClient) { const info = { origin: req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`], secure: !!(req.socket.authorized || req.socket.encrypted), req }; if (this.options.verifyClient.length === 2) { this.options.verifyClient(info, (verified, code, message, headers) => { if (!verified) { return abortHandshake(socket, code || 401, message, headers); } this.completeUpgrade(key, extensions, req, socket, head, cb); }); return; } if (!this.options.verifyClient(info)) return abortHandshake(socket, 401); } this.completeUpgrade(key, extensions, req, socket, head, cb); } /** * Upgrade the connection to WebSocket. * * @param {String} key The value of the `Sec-WebSocket-Key` header * @param {Object} extensions The accepted extensions * @param {http.IncomingMessage} req The request object * @param {(net.Socket|tls.Socket)} socket The network socket between the * server and client * @param {Buffer} head The first packet of the upgraded stream * @param {Function} cb Callback * @throws {Error} If called more than once with the same socket * @private */ completeUpgrade(key, extensions, req, socket, head, cb) { // // Destroy the socket if the client has already sent a FIN packet. // if (!socket.readable || !socket.writable) return socket.destroy(); if (socket[kWebSocket]) { throw new Error( 'server.handleUpgrade() was called more than once with the same ' + 'socket, possibly due to a misconfiguration' ); } if (this._state > RUNNING) return abortHandshake(socket, 503); const digest = createHash('sha1') .update(key + GUID) .digest('base64'); const headers = [ 'HTTP/1.1 101 Switching Protocols', 'Upgrade: websocket', 'Connection: Upgrade', `Sec-WebSocket-Accept: ${digest}` ]; const ws = new WebSocket(null); let protocol = req.headers['sec-websocket-protocol']; if (protocol) { protocol = protocol.split(',').map(trim); // // Optionally call external protocol selection handler. // if (this.options.handleProtocols) { protocol = this.options.handleProtocols(protocol, req); } else { protocol = protocol[0]; } if (protocol) { headers.push(`Sec-WebSocket-Protocol: ${protocol}`); ws._protocol = protocol; } } if (extensions[PerMessageDeflate.extensionName]) { const params = extensions[PerMessageDeflate.extensionName].params; const value = format({ [PerMessageDeflate.extensionName]: [params] }); headers.push(`Sec-WebSocket-Extensions: ${value}`); ws._extensions = extensions; } // // Allow external modification/inspection of handshake headers. // this.emit('headers', headers, req); socket.write(headers.concat('\r\n').join('\r\n')); socket.removeListener('error', socketOnError); ws.setSocket(socket, head, this.options.maxPayload); if (this.clients) { this.clients.add(ws); ws.on('close', () => this.clients.delete(ws)); } cb(ws, req); } } module.exports = WebSocketServer; /** * Add event listeners on an `EventEmitter` using a map of * pairs. * * @param {EventEmitter} server The event emitter * @param {Object.} map The listeners to add * @return {Function} A function that will remove the added listeners when * called * @private */ function addListeners(server, map) { for (const event of Object.keys(map)) server.on(event, map[event]); return function removeListeners() { for (const event of Object.keys(map)) { server.removeListener(event, map[event]); } }; } /** * Emit a `'close'` event on an `EventEmitter`. * * @param {EventEmitter} server The event emitter * @private */ function emitClose(server) { server._state = CLOSED; server.emit('close'); } /** * Handle premature socket errors. * * @private */ function socketOnError() { this.destroy(); } /** * Close the connection when preconditions are not fulfilled. * * @param {(net.Socket|tls.Socket)} socket The socket of the upgrade request * @param {Number} code The HTTP response status code * @param {String} [message] The HTTP response body * @param {Object} [headers] Additional HTTP response headers * @private */ function abortHandshake(socket, code, message, headers) { if (socket.writable) { message = message || http.STATUS_CODES[code]; headers = { Connection: 'close', 'Content-Type': 'text/html', 'Content-Length': Buffer.byteLength(message), ...headers }; socket.write( `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r\n` + Object.keys(headers) .map((h) => `${h}: ${headers[h]}`) .join('\r\n') + '\r\n\r\n' + message ); } socket.removeListener('error', socketOnError); socket.destroy(); } /** * Remove whitespace characters from both ends of a string. * * @param {String} str The string * @return {String} A new string representing `str` stripped of whitespace * characters from both its beginning and end * @private */ function trim(str) { return str.trim(); } /***/ }), /***/ 91518: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Readable$" }] */ const EventEmitter = __nccwpck_require__(82361); const https = __nccwpck_require__(95687); const http = __nccwpck_require__(13685); const net = __nccwpck_require__(41808); const tls = __nccwpck_require__(24404); const { randomBytes, createHash } = __nccwpck_require__(6113); const { Readable } = __nccwpck_require__(12781); const { URL } = __nccwpck_require__(57310); const PerMessageDeflate = __nccwpck_require__(56684); const Receiver = __nccwpck_require__(25066); const Sender = __nccwpck_require__(36947); const { BINARY_TYPES, EMPTY_BUFFER, GUID, kStatusCode, kWebSocket, NOOP } = __nccwpck_require__(15949); const { addEventListener, removeEventListener } = __nccwpck_require__(64561); const { format, parse } = __nccwpck_require__(92035); const { toBuffer } = __nccwpck_require__(9436); const readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED']; const protocolVersions = [8, 13]; const closeTimeout = 30 * 1000; /** * Class representing a WebSocket. * * @extends EventEmitter */ class WebSocket extends EventEmitter { /** * Create a new `WebSocket`. * * @param {(String|URL)} address The URL to which to connect * @param {(String|String[])} [protocols] The subprotocols * @param {Object} [options] Connection options */ constructor(address, protocols, options) { super(); this._binaryType = BINARY_TYPES[0]; this._closeCode = 1006; this._closeFrameReceived = false; this._closeFrameSent = false; this._closeMessage = ''; this._closeTimer = null; this._extensions = {}; this._protocol = ''; this._readyState = WebSocket.CONNECTING; this._receiver = null; this._sender = null; this._socket = null; if (address !== null) { this._bufferedAmount = 0; this._isServer = false; this._redirects = 0; if (Array.isArray(protocols)) { protocols = protocols.join(', '); } else if (typeof protocols === 'object' && protocols !== null) { options = protocols; protocols = undefined; } initAsClient(this, address, protocols, options); } else { this._isServer = true; } } /** * This deviates from the WHATWG interface since ws doesn't support the * required default "blob" type (instead we define a custom "nodebuffer" * type). * * @type {String} */ get binaryType() { return this._binaryType; } set binaryType(type) { if (!BINARY_TYPES.includes(type)) return; this._binaryType = type; // // Allow to change `binaryType` on the fly. // if (this._receiver) this._receiver._binaryType = type; } /** * @type {Number} */ get bufferedAmount() { if (!this._socket) return this._bufferedAmount; return this._socket._writableState.length + this._sender._bufferedBytes; } /** * @type {String} */ get extensions() { return Object.keys(this._extensions).join(); } /** * @type {Function} */ /* istanbul ignore next */ get onclose() { return undefined; } /* istanbul ignore next */ set onclose(listener) {} /** * @type {Function} */ /* istanbul ignore next */ get onerror() { return undefined; } /* istanbul ignore next */ set onerror(listener) {} /** * @type {Function} */ /* istanbul ignore next */ get onopen() { return undefined; } /* istanbul ignore next */ set onopen(listener) {} /** * @type {Function} */ /* istanbul ignore next */ get onmessage() { return undefined; } /* istanbul ignore next */ set onmessage(listener) {} /** * @type {String} */ get protocol() { return this._protocol; } /** * @type {Number} */ get readyState() { return this._readyState; } /** * @type {String} */ get url() { return this._url; } /** * Set up the socket and the internal resources. * * @param {(net.Socket|tls.Socket)} socket The network socket between the * server and client * @param {Buffer} head The first packet of the upgraded stream * @param {Number} [maxPayload=0] The maximum allowed message size * @private */ setSocket(socket, head, maxPayload) { const receiver = new Receiver( this.binaryType, this._extensions, this._isServer, maxPayload ); this._sender = new Sender(socket, this._extensions); this._receiver = receiver; this._socket = socket; receiver[kWebSocket] = this; socket[kWebSocket] = this; receiver.on('conclude', receiverOnConclude); receiver.on('drain', receiverOnDrain); receiver.on('error', receiverOnError); receiver.on('message', receiverOnMessage); receiver.on('ping', receiverOnPing); receiver.on('pong', receiverOnPong); socket.setTimeout(0); socket.setNoDelay(); if (head.length > 0) socket.unshift(head); socket.on('close', socketOnClose); socket.on('data', socketOnData); socket.on('end', socketOnEnd); socket.on('error', socketOnError); this._readyState = WebSocket.OPEN; this.emit('open'); } /** * Emit the `'close'` event. * * @private */ emitClose() { if (!this._socket) { this._readyState = WebSocket.CLOSED; this.emit('close', this._closeCode, this._closeMessage); return; } if (this._extensions[PerMessageDeflate.extensionName]) { this._extensions[PerMessageDeflate.extensionName].cleanup(); } this._receiver.removeAllListeners(); this._readyState = WebSocket.CLOSED; this.emit('close', this._closeCode, this._closeMessage); } /** * Start a closing handshake. * * +----------+ +-----------+ +----------+ * - - -|ws.close()|-->|close frame|-->|ws.close()|- - - * | +----------+ +-----------+ +----------+ | * +----------+ +-----------+ | * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING * +----------+ +-----------+ | * | | | +---+ | * +------------------------+-->|fin| - - - - * | +---+ | +---+ * - - - - -|fin|<---------------------+ * +---+ * * @param {Number} [code] Status code explaining why the connection is closing * @param {String} [data] A string explaining why the connection is closing * @public */ close(code, data) { if (this.readyState === WebSocket.CLOSED) return; if (this.readyState === WebSocket.CONNECTING) { const msg = 'WebSocket was closed before the connection was established'; return abortHandshake(this, this._req, msg); } if (this.readyState === WebSocket.CLOSING) { if ( this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted) ) { this._socket.end(); } return; } this._readyState = WebSocket.CLOSING; this._sender.close(code, data, !this._isServer, (err) => { // // This error is handled by the `'error'` listener on the socket. We only // want to know if the close frame has been sent here. // if (err) return; this._closeFrameSent = true; if ( this._closeFrameReceived || this._receiver._writableState.errorEmitted ) { this._socket.end(); } }); // // Specify a timeout for the closing handshake to complete. // this._closeTimer = setTimeout( this._socket.destroy.bind(this._socket), closeTimeout ); } /** * Send a ping. * * @param {*} [data] The data to send * @param {Boolean} [mask] Indicates whether or not to mask `data` * @param {Function} [cb] Callback which is executed when the ping is sent * @public */ ping(data, mask, cb) { if (this.readyState === WebSocket.CONNECTING) { throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); } if (typeof data === 'function') { cb = data; data = mask = undefined; } else if (typeof mask === 'function') { cb = mask; mask = undefined; } if (typeof data === 'number') data = data.toString(); if (this.readyState !== WebSocket.OPEN) { sendAfterClose(this, data, cb); return; } if (mask === undefined) mask = !this._isServer; this._sender.ping(data || EMPTY_BUFFER, mask, cb); } /** * Send a pong. * * @param {*} [data] The data to send * @param {Boolean} [mask] Indicates whether or not to mask `data` * @param {Function} [cb] Callback which is executed when the pong is sent * @public */ pong(data, mask, cb) { if (this.readyState === WebSocket.CONNECTING) { throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); } if (typeof data === 'function') { cb = data; data = mask = undefined; } else if (typeof mask === 'function') { cb = mask; mask = undefined; } if (typeof data === 'number') data = data.toString(); if (this.readyState !== WebSocket.OPEN) { sendAfterClose(this, data, cb); return; } if (mask === undefined) mask = !this._isServer; this._sender.pong(data || EMPTY_BUFFER, mask, cb); } /** * Send a data message. * * @param {*} data The message to send * @param {Object} [options] Options object * @param {Boolean} [options.compress] Specifies whether or not to compress * `data` * @param {Boolean} [options.binary] Specifies whether `data` is binary or * text * @param {Boolean} [options.fin=true] Specifies whether the fragment is the * last one * @param {Boolean} [options.mask] Specifies whether or not to mask `data` * @param {Function} [cb] Callback which is executed when data is written out * @public */ send(data, options, cb) { if (this.readyState === WebSocket.CONNECTING) { throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); } if (typeof options === 'function') { cb = options; options = {}; } if (typeof data === 'number') data = data.toString(); if (this.readyState !== WebSocket.OPEN) { sendAfterClose(this, data, cb); return; } const opts = { binary: typeof data !== 'string', mask: !this._isServer, compress: true, fin: true, ...options }; if (!this._extensions[PerMessageDeflate.extensionName]) { opts.compress = false; } this._sender.send(data || EMPTY_BUFFER, opts, cb); } /** * Forcibly close the connection. * * @public */ terminate() { if (this.readyState === WebSocket.CLOSED) return; if (this.readyState === WebSocket.CONNECTING) { const msg = 'WebSocket was closed before the connection was established'; return abortHandshake(this, this._req, msg); } if (this._socket) { this._readyState = WebSocket.CLOSING; this._socket.destroy(); } } } /** * @constant {Number} CONNECTING * @memberof WebSocket */ Object.defineProperty(WebSocket, 'CONNECTING', { enumerable: true, value: readyStates.indexOf('CONNECTING') }); /** * @constant {Number} CONNECTING * @memberof WebSocket.prototype */ Object.defineProperty(WebSocket.prototype, 'CONNECTING', { enumerable: true, value: readyStates.indexOf('CONNECTING') }); /** * @constant {Number} OPEN * @memberof WebSocket */ Object.defineProperty(WebSocket, 'OPEN', { enumerable: true, value: readyStates.indexOf('OPEN') }); /** * @constant {Number} OPEN * @memberof WebSocket.prototype */ Object.defineProperty(WebSocket.prototype, 'OPEN', { enumerable: true, value: readyStates.indexOf('OPEN') }); /** * @constant {Number} CLOSING * @memberof WebSocket */ Object.defineProperty(WebSocket, 'CLOSING', { enumerable: true, value: readyStates.indexOf('CLOSING') }); /** * @constant {Number} CLOSING * @memberof WebSocket.prototype */ Object.defineProperty(WebSocket.prototype, 'CLOSING', { enumerable: true, value: readyStates.indexOf('CLOSING') }); /** * @constant {Number} CLOSED * @memberof WebSocket */ Object.defineProperty(WebSocket, 'CLOSED', { enumerable: true, value: readyStates.indexOf('CLOSED') }); /** * @constant {Number} CLOSED * @memberof WebSocket.prototype */ Object.defineProperty(WebSocket.prototype, 'CLOSED', { enumerable: true, value: readyStates.indexOf('CLOSED') }); [ 'binaryType', 'bufferedAmount', 'extensions', 'protocol', 'readyState', 'url' ].forEach((property) => { Object.defineProperty(WebSocket.prototype, property, { enumerable: true }); }); // // Add the `onopen`, `onerror`, `onclose`, and `onmessage` attributes. // See https://html.spec.whatwg.org/multipage/comms.html#the-websocket-interface // ['open', 'error', 'close', 'message'].forEach((method) => { Object.defineProperty(WebSocket.prototype, `on${method}`, { enumerable: true, get() { const listeners = this.listeners(method); for (let i = 0; i < listeners.length; i++) { if (listeners[i]._listener) return listeners[i]._listener; } return undefined; }, set(listener) { const listeners = this.listeners(method); for (let i = 0; i < listeners.length; i++) { // // Remove only the listeners added via `addEventListener`. // if (listeners[i]._listener) this.removeListener(method, listeners[i]); } this.addEventListener(method, listener); } }); }); WebSocket.prototype.addEventListener = addEventListener; WebSocket.prototype.removeEventListener = removeEventListener; module.exports = WebSocket; /** * Initialize a WebSocket client. * * @param {WebSocket} websocket The client to initialize * @param {(String|URL)} address The URL to which to connect * @param {String} [protocols] The subprotocols * @param {Object} [options] Connection options * @param {(Boolean|Object)} [options.perMessageDeflate=true] Enable/disable * permessage-deflate * @param {Number} [options.handshakeTimeout] Timeout in milliseconds for the * handshake request * @param {Number} [options.protocolVersion=13] Value of the * `Sec-WebSocket-Version` header * @param {String} [options.origin] Value of the `Origin` or * `Sec-WebSocket-Origin` header * @param {Number} [options.maxPayload=104857600] The maximum allowed message * size * @param {Boolean} [options.followRedirects=false] Whether or not to follow * redirects * @param {Number} [options.maxRedirects=10] The maximum number of redirects * allowed * @private */ function initAsClient(websocket, address, protocols, options) { const opts = { protocolVersion: protocolVersions[1], maxPayload: 100 * 1024 * 1024, perMessageDeflate: true, followRedirects: false, maxRedirects: 10, ...options, createConnection: undefined, socketPath: undefined, hostname: undefined, protocol: undefined, timeout: undefined, method: undefined, host: undefined, path: undefined, port: undefined }; if (!protocolVersions.includes(opts.protocolVersion)) { throw new RangeError( `Unsupported protocol version: ${opts.protocolVersion} ` + `(supported versions: ${protocolVersions.join(', ')})` ); } let parsedUrl; if (address instanceof URL) { parsedUrl = address; websocket._url = address.href; } else { parsedUrl = new URL(address); websocket._url = address; } const isUnixSocket = parsedUrl.protocol === 'ws+unix:'; if (!parsedUrl.host && (!isUnixSocket || !parsedUrl.pathname)) { const err = new Error(`Invalid URL: ${websocket.url}`); if (websocket._redirects === 0) { throw err; } else { emitErrorAndClose(websocket, err); return; } } const isSecure = parsedUrl.protocol === 'wss:' || parsedUrl.protocol === 'https:'; const defaultPort = isSecure ? 443 : 80; const key = randomBytes(16).toString('base64'); const get = isSecure ? https.get : http.get; let perMessageDeflate; opts.createConnection = isSecure ? tlsConnect : netConnect; opts.defaultPort = opts.defaultPort || defaultPort; opts.port = parsedUrl.port || defaultPort; opts.host = parsedUrl.hostname.startsWith('[') ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname; opts.headers = { 'Sec-WebSocket-Version': opts.protocolVersion, 'Sec-WebSocket-Key': key, Connection: 'Upgrade', Upgrade: 'websocket', ...opts.headers }; opts.path = parsedUrl.pathname + parsedUrl.search; opts.timeout = opts.handshakeTimeout; if (opts.perMessageDeflate) { perMessageDeflate = new PerMessageDeflate( opts.perMessageDeflate !== true ? opts.perMessageDeflate : {}, false, opts.maxPayload ); opts.headers['Sec-WebSocket-Extensions'] = format({ [PerMessageDeflate.extensionName]: perMessageDeflate.offer() }); } if (protocols) { opts.headers['Sec-WebSocket-Protocol'] = protocols; } if (opts.origin) { if (opts.protocolVersion < 13) { opts.headers['Sec-WebSocket-Origin'] = opts.origin; } else { opts.headers.Origin = opts.origin; } } if (parsedUrl.username || parsedUrl.password) { opts.auth = `${parsedUrl.username}:${parsedUrl.password}`; } if (isUnixSocket) { const parts = opts.path.split(':'); opts.socketPath = parts[0]; opts.path = parts[1]; } if (opts.followRedirects) { if (websocket._redirects === 0) { websocket._originalUnixSocket = isUnixSocket; websocket._originalSecure = isSecure; websocket._originalHostOrSocketPath = isUnixSocket ? opts.socketPath : parsedUrl.host; const headers = options && options.headers; // // Shallow copy the user provided options so that headers can be changed // without mutating the original object. // options = { ...options, headers: {} }; if (headers) { for (const [key, value] of Object.entries(headers)) { options.headers[key.toLowerCase()] = value; } } } else { const isSameHost = isUnixSocket ? websocket._originalUnixSocket ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalUnixSocket ? false : parsedUrl.host === websocket._originalHostOrSocketPath; if (!isSameHost || (websocket._originalSecure && !isSecure)) { // // Match curl 7.77.0 behavior and drop the following headers. These // headers are also dropped when following a redirect to a subdomain. // delete opts.headers.authorization; delete opts.headers.cookie; if (!isSameHost) delete opts.headers.host; opts.auth = undefined; } } // // Match curl 7.77.0 behavior and make the first `Authorization` header win. // If the `Authorization` header is set, then there is nothing to do as it // will take precedence. // if (opts.auth && !options.headers.authorization) { options.headers.authorization = 'Basic ' + Buffer.from(opts.auth).toString('base64'); } } let req = (websocket._req = get(opts)); if (opts.timeout) { req.on('timeout', () => { abortHandshake(websocket, req, 'Opening handshake has timed out'); }); } req.on('error', (err) => { if (req === null || req.aborted) return; req = websocket._req = null; emitErrorAndClose(websocket, err); }); req.on('response', (res) => { const location = res.headers.location; const statusCode = res.statusCode; if ( location && opts.followRedirects && statusCode >= 300 && statusCode < 400 ) { if (++websocket._redirects > opts.maxRedirects) { abortHandshake(websocket, req, 'Maximum redirects exceeded'); return; } req.abort(); let addr; try { addr = new URL(location, address); } catch (err) { emitErrorAndClose(websocket, err); return; } initAsClient(websocket, addr, protocols, options); } else if (!websocket.emit('unexpected-response', req, res)) { abortHandshake( websocket, req, `Unexpected server response: ${res.statusCode}` ); } }); req.on('upgrade', (res, socket, head) => { websocket.emit('upgrade', res); // // The user may have closed the connection from a listener of the `upgrade` // event. // if (websocket.readyState !== WebSocket.CONNECTING) return; req = websocket._req = null; if (res.headers.upgrade.toLowerCase() !== 'websocket') { abortHandshake(websocket, socket, 'Invalid Upgrade header'); return; } const digest = createHash('sha1') .update(key + GUID) .digest('base64'); if (res.headers['sec-websocket-accept'] !== digest) { abortHandshake(websocket, socket, 'Invalid Sec-WebSocket-Accept header'); return; } const serverProt = res.headers['sec-websocket-protocol']; const protList = (protocols || '').split(/, */); let protError; if (!protocols && serverProt) { protError = 'Server sent a subprotocol but none was requested'; } else if (protocols && !serverProt) { protError = 'Server sent no subprotocol'; } else if (serverProt && !protList.includes(serverProt)) { protError = 'Server sent an invalid subprotocol'; } if (protError) { abortHandshake(websocket, socket, protError); return; } if (serverProt) websocket._protocol = serverProt; const secWebSocketExtensions = res.headers['sec-websocket-extensions']; if (secWebSocketExtensions !== undefined) { if (!perMessageDeflate) { const message = 'Server sent a Sec-WebSocket-Extensions header but no extension ' + 'was requested'; abortHandshake(websocket, socket, message); return; } let extensions; try { extensions = parse(secWebSocketExtensions); } catch (err) { const message = 'Invalid Sec-WebSocket-Extensions header'; abortHandshake(websocket, socket, message); return; } const extensionNames = Object.keys(extensions); if (extensionNames.length) { if ( extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate.extensionName ) { const message = 'Server indicated an extension that was not requested'; abortHandshake(websocket, socket, message); return; } try { perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]); } catch (err) { const message = 'Invalid Sec-WebSocket-Extensions header'; abortHandshake(websocket, socket, message); return; } websocket._extensions[PerMessageDeflate.extensionName] = perMessageDeflate; } } websocket.setSocket(socket, head, opts.maxPayload); }); } /** * Emit the `'error'` and `'close'` event. * * @param {WebSocket} websocket The WebSocket instance * @param {Error} The error to emit * @private */ function emitErrorAndClose(websocket, err) { websocket._readyState = WebSocket.CLOSING; websocket.emit('error', err); websocket.emitClose(); } /** * Create a `net.Socket` and initiate a connection. * * @param {Object} options Connection options * @return {net.Socket} The newly created socket used to start the connection * @private */ function netConnect(options) { options.path = options.socketPath; return net.connect(options); } /** * Create a `tls.TLSSocket` and initiate a connection. * * @param {Object} options Connection options * @return {tls.TLSSocket} The newly created socket used to start the connection * @private */ function tlsConnect(options) { options.path = undefined; if (!options.servername && options.servername !== '') { options.servername = net.isIP(options.host) ? '' : options.host; } return tls.connect(options); } /** * Abort the handshake and emit an error. * * @param {WebSocket} websocket The WebSocket instance * @param {(http.ClientRequest|net.Socket|tls.Socket)} stream The request to * abort or the socket to destroy * @param {String} message The error message * @private */ function abortHandshake(websocket, stream, message) { websocket._readyState = WebSocket.CLOSING; const err = new Error(message); Error.captureStackTrace(err, abortHandshake); if (stream.setHeader) { stream.abort(); if (stream.socket && !stream.socket.destroyed) { // // On Node.js >= 14.3.0 `request.abort()` does not destroy the socket if // called after the request completed. See // https://github.com/websockets/ws/issues/1869. // stream.socket.destroy(); } stream.once('abort', websocket.emitClose.bind(websocket)); websocket.emit('error', err); } else { stream.destroy(err); stream.once('error', websocket.emit.bind(websocket, 'error')); stream.once('close', websocket.emitClose.bind(websocket)); } } /** * Handle cases where the `ping()`, `pong()`, or `send()` methods are called * when the `readyState` attribute is `CLOSING` or `CLOSED`. * * @param {WebSocket} websocket The WebSocket instance * @param {*} [data] The data to send * @param {Function} [cb] Callback * @private */ function sendAfterClose(websocket, data, cb) { if (data) { const length = toBuffer(data).length; // // The `_bufferedAmount` property is used only when the peer is a client and // the opening handshake fails. Under these circumstances, in fact, the // `setSocket()` method is not called, so the `_socket` and `_sender` // properties are set to `null`. // if (websocket._socket) websocket._sender._bufferedBytes += length; else websocket._bufferedAmount += length; } if (cb) { const err = new Error( `WebSocket is not open: readyState ${websocket.readyState} ` + `(${readyStates[websocket.readyState]})` ); cb(err); } } /** * The listener of the `Receiver` `'conclude'` event. * * @param {Number} code The status code * @param {String} reason The reason for closing * @private */ function receiverOnConclude(code, reason) { const websocket = this[kWebSocket]; websocket._closeFrameReceived = true; websocket._closeMessage = reason; websocket._closeCode = code; if (websocket._socket[kWebSocket] === undefined) return; websocket._socket.removeListener('data', socketOnData); process.nextTick(resume, websocket._socket); if (code === 1005) websocket.close(); else websocket.close(code, reason); } /** * The listener of the `Receiver` `'drain'` event. * * @private */ function receiverOnDrain() { this[kWebSocket]._socket.resume(); } /** * The listener of the `Receiver` `'error'` event. * * @param {(RangeError|Error)} err The emitted error * @private */ function receiverOnError(err) { const websocket = this[kWebSocket]; if (websocket._socket[kWebSocket] !== undefined) { websocket._socket.removeListener('data', socketOnData); // // On Node.js < 14.0.0 the `'error'` event is emitted synchronously. See // https://github.com/websockets/ws/issues/1940. // process.nextTick(resume, websocket._socket); websocket.close(err[kStatusCode]); } websocket.emit('error', err); } /** * The listener of the `Receiver` `'finish'` event. * * @private */ function receiverOnFinish() { this[kWebSocket].emitClose(); } /** * The listener of the `Receiver` `'message'` event. * * @param {(String|Buffer|ArrayBuffer|Buffer[])} data The message * @private */ function receiverOnMessage(data) { this[kWebSocket].emit('message', data); } /** * The listener of the `Receiver` `'ping'` event. * * @param {Buffer} data The data included in the ping frame * @private */ function receiverOnPing(data) { const websocket = this[kWebSocket]; websocket.pong(data, !websocket._isServer, NOOP); websocket.emit('ping', data); } /** * The listener of the `Receiver` `'pong'` event. * * @param {Buffer} data The data included in the pong frame * @private */ function receiverOnPong(data) { this[kWebSocket].emit('pong', data); } /** * Resume a readable stream * * @param {Readable} stream The readable stream * @private */ function resume(stream) { stream.resume(); } /** * The listener of the `net.Socket` `'close'` event. * * @private */ function socketOnClose() { const websocket = this[kWebSocket]; this.removeListener('close', socketOnClose); this.removeListener('data', socketOnData); this.removeListener('end', socketOnEnd); websocket._readyState = WebSocket.CLOSING; let chunk; // // The close frame might not have been received or the `'end'` event emitted, // for example, if the socket was destroyed due to an error. Ensure that the // `receiver` stream is closed after writing any remaining buffered data to // it. If the readable side of the socket is in flowing mode then there is no // buffered data as everything has been already written and `readable.read()` // will return `null`. If instead, the socket is paused, any possible buffered // data will be read as a single chunk. // if ( !this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && (chunk = websocket._socket.read()) !== null ) { websocket._receiver.write(chunk); } websocket._receiver.end(); this[kWebSocket] = undefined; clearTimeout(websocket._closeTimer); if ( websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted ) { websocket.emitClose(); } else { websocket._receiver.on('error', receiverOnFinish); websocket._receiver.on('finish', receiverOnFinish); } } /** * The listener of the `net.Socket` `'data'` event. * * @param {Buffer} chunk A chunk of data * @private */ function socketOnData(chunk) { if (!this[kWebSocket]._receiver.write(chunk)) { this.pause(); } } /** * The listener of the `net.Socket` `'end'` event. * * @private */ function socketOnEnd() { const websocket = this[kWebSocket]; websocket._readyState = WebSocket.CLOSING; websocket._receiver.end(); this.end(); } /** * The listener of the `net.Socket` `'error'` event. * * @private */ function socketOnError() { const websocket = this[kWebSocket]; this.removeListener('error', socketOnError); this.on('error', NOOP); if (websocket) { websocket._readyState = WebSocket.CLOSING; this.destroy(); } } /***/ }), /***/ 22624: /***/ (function(__unused_webpack_module, exports) { // Generated by CoffeeScript 1.12.7 (function() { "use strict"; exports.stripBOM = function(str) { if (str[0] === '\uFEFF') { return str.substring(1); } else { return str; } }; }).call(this); /***/ }), /***/ 43337: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { // Generated by CoffeeScript 1.12.7 (function() { "use strict"; var builder, defaults, escapeCDATA, requiresCDATA, wrapCDATA, hasProp = {}.hasOwnProperty; builder = __nccwpck_require__(52958); defaults = (__nccwpck_require__(97251).defaults); requiresCDATA = function(entry) { return typeof entry === "string" && (entry.indexOf('&') >= 0 || entry.indexOf('>') >= 0 || entry.indexOf('<') >= 0); }; wrapCDATA = function(entry) { return ""; }; escapeCDATA = function(entry) { return entry.replace(']]>', ']]]]>'); }; exports.Builder = (function() { function Builder(opts) { var key, ref, value; this.options = {}; ref = defaults["0.2"]; for (key in ref) { if (!hasProp.call(ref, key)) continue; value = ref[key]; this.options[key] = value; } for (key in opts) { if (!hasProp.call(opts, key)) continue; value = opts[key]; this.options[key] = value; } } Builder.prototype.buildObject = function(rootObj) { var attrkey, charkey, render, rootElement, rootName; attrkey = this.options.attrkey; charkey = this.options.charkey; if ((Object.keys(rootObj).length === 1) && (this.options.rootName === defaults['0.2'].rootName)) { rootName = Object.keys(rootObj)[0]; rootObj = rootObj[rootName]; } else { rootName = this.options.rootName; } render = (function(_this) { return function(element, obj) { var attr, child, entry, index, key, value; if (typeof obj !== 'object') { if (_this.options.cdata && requiresCDATA(obj)) { element.raw(wrapCDATA(obj)); } else { element.txt(obj); } } else if (Array.isArray(obj)) { for (index in obj) { if (!hasProp.call(obj, index)) continue; child = obj[index]; for (key in child) { entry = child[key]; element = render(element.ele(key), entry).up(); } } } else { for (key in obj) { if (!hasProp.call(obj, key)) continue; child = obj[key]; if (key === attrkey) { if (typeof child === "object") { for (attr in child) { value = child[attr]; element = element.att(attr, value); } } } else if (key === charkey) { if (_this.options.cdata && requiresCDATA(child)) { element = element.raw(wrapCDATA(child)); } else { element = element.txt(child); } } else if (Array.isArray(child)) { for (index in child) { if (!hasProp.call(child, index)) continue; entry = child[index]; if (typeof entry === 'string') { if (_this.options.cdata && requiresCDATA(entry)) { element = element.ele(key).raw(wrapCDATA(entry)).up(); } else { element = element.ele(key, entry).up(); } } else { element = render(element.ele(key), entry).up(); } } } else if (typeof child === "object") { element = render(element.ele(key), child).up(); } else { if (typeof child === 'string' && _this.options.cdata && requiresCDATA(child)) { element = element.ele(key).raw(wrapCDATA(child)).up(); } else { if (child == null) { child = ''; } element = element.ele(key, child.toString()).up(); } } } } return element; }; })(this); rootElement = builder.create(rootName, this.options.xmldec, this.options.doctype, { headless: this.options.headless, allowSurrogateChars: this.options.allowSurrogateChars }); return render(rootElement, rootObj).end(this.options.renderOpts); }; return Builder; })(); }).call(this); /***/ }), /***/ 97251: /***/ (function(__unused_webpack_module, exports) { // Generated by CoffeeScript 1.12.7 (function() { exports.defaults = { "0.1": { explicitCharkey: false, trim: true, normalize: true, normalizeTags: false, attrkey: "@", charkey: "#", explicitArray: false, ignoreAttrs: false, mergeAttrs: false, explicitRoot: false, validator: null, xmlns: false, explicitChildren: false, childkey: '@@', charsAsChildren: false, includeWhiteChars: false, async: false, strict: true, attrNameProcessors: null, attrValueProcessors: null, tagNameProcessors: null, valueProcessors: null, emptyTag: '' }, "0.2": { explicitCharkey: false, trim: false, normalize: false, normalizeTags: false, attrkey: "$", charkey: "_", explicitArray: true, ignoreAttrs: false, mergeAttrs: false, explicitRoot: true, validator: null, xmlns: false, explicitChildren: false, preserveChildrenOrder: false, childkey: '$$', charsAsChildren: false, includeWhiteChars: false, async: false, strict: true, attrNameProcessors: null, attrValueProcessors: null, tagNameProcessors: null, valueProcessors: null, rootName: 'root', xmldec: { 'version': '1.0', 'encoding': 'UTF-8', 'standalone': true }, doctype: null, renderOpts: { 'pretty': true, 'indent': ' ', 'newline': '\n' }, headless: false, chunkSize: 10000, emptyTag: '', cdata: false } }; }).call(this); /***/ }), /***/ 83314: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { // Generated by CoffeeScript 1.12.7 (function() { "use strict"; var bom, defaults, events, isEmpty, processItem, processors, sax, setImmediate, bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; sax = __nccwpck_require__(41695); events = __nccwpck_require__(82361); bom = __nccwpck_require__(22624); processors = __nccwpck_require__(99236); setImmediate = (__nccwpck_require__(39512).setImmediate); defaults = (__nccwpck_require__(97251).defaults); isEmpty = function(thing) { return typeof thing === "object" && (thing != null) && Object.keys(thing).length === 0; }; processItem = function(processors, item, key) { var i, len, process; for (i = 0, len = processors.length; i < len; i++) { process = processors[i]; item = process(item, key); } return item; }; exports.Parser = (function(superClass) { extend(Parser, superClass); function Parser(opts) { this.parseStringPromise = bind(this.parseStringPromise, this); this.parseString = bind(this.parseString, this); this.reset = bind(this.reset, this); this.assignOrPush = bind(this.assignOrPush, this); this.processAsync = bind(this.processAsync, this); var key, ref, value; if (!(this instanceof exports.Parser)) { return new exports.Parser(opts); } this.options = {}; ref = defaults["0.2"]; for (key in ref) { if (!hasProp.call(ref, key)) continue; value = ref[key]; this.options[key] = value; } for (key in opts) { if (!hasProp.call(opts, key)) continue; value = opts[key]; this.options[key] = value; } if (this.options.xmlns) { this.options.xmlnskey = this.options.attrkey + "ns"; } if (this.options.normalizeTags) { if (!this.options.tagNameProcessors) { this.options.tagNameProcessors = []; } this.options.tagNameProcessors.unshift(processors.normalize); } this.reset(); } Parser.prototype.processAsync = function() { var chunk, err; try { if (this.remaining.length <= this.options.chunkSize) { chunk = this.remaining; this.remaining = ''; this.saxParser = this.saxParser.write(chunk); return this.saxParser.close(); } else { chunk = this.remaining.substr(0, this.options.chunkSize); this.remaining = this.remaining.substr(this.options.chunkSize, this.remaining.length); this.saxParser = this.saxParser.write(chunk); return setImmediate(this.processAsync); } } catch (error1) { err = error1; if (!this.saxParser.errThrown) { this.saxParser.errThrown = true; return this.emit(err); } } }; Parser.prototype.assignOrPush = function(obj, key, newValue) { if (!(key in obj)) { if (!this.options.explicitArray) { return obj[key] = newValue; } else { return obj[key] = [newValue]; } } else { if (!(obj[key] instanceof Array)) { obj[key] = [obj[key]]; } return obj[key].push(newValue); } }; Parser.prototype.reset = function() { var attrkey, charkey, ontext, stack; this.removeAllListeners(); this.saxParser = sax.parser(this.options.strict, { trim: false, normalize: false, xmlns: this.options.xmlns }); this.saxParser.errThrown = false; this.saxParser.onerror = (function(_this) { return function(error) { _this.saxParser.resume(); if (!_this.saxParser.errThrown) { _this.saxParser.errThrown = true; return _this.emit("error", error); } }; })(this); this.saxParser.onend = (function(_this) { return function() { if (!_this.saxParser.ended) { _this.saxParser.ended = true; return _this.emit("end", _this.resultObject); } }; })(this); this.saxParser.ended = false; this.EXPLICIT_CHARKEY = this.options.explicitCharkey; this.resultObject = null; stack = []; attrkey = this.options.attrkey; charkey = this.options.charkey; this.saxParser.onopentag = (function(_this) { return function(node) { var key, newValue, obj, processedKey, ref; obj = Object.create(null); obj[charkey] = ""; if (!_this.options.ignoreAttrs) { ref = node.attributes; for (key in ref) { if (!hasProp.call(ref, key)) continue; if (!(attrkey in obj) && !_this.options.mergeAttrs) { obj[attrkey] = Object.create(null); } newValue = _this.options.attrValueProcessors ? processItem(_this.options.attrValueProcessors, node.attributes[key], key) : node.attributes[key]; processedKey = _this.options.attrNameProcessors ? processItem(_this.options.attrNameProcessors, key) : key; if (_this.options.mergeAttrs) { _this.assignOrPush(obj, processedKey, newValue); } else { obj[attrkey][processedKey] = newValue; } } } obj["#name"] = _this.options.tagNameProcessors ? processItem(_this.options.tagNameProcessors, node.name) : node.name; if (_this.options.xmlns) { obj[_this.options.xmlnskey] = { uri: node.uri, local: node.local }; } return stack.push(obj); }; })(this); this.saxParser.onclosetag = (function(_this) { return function() { var cdata, emptyStr, key, node, nodeName, obj, objClone, old, s, xpath; obj = stack.pop(); nodeName = obj["#name"]; if (!_this.options.explicitChildren || !_this.options.preserveChildrenOrder) { delete obj["#name"]; } if (obj.cdata === true) { cdata = obj.cdata; delete obj.cdata; } s = stack[stack.length - 1]; if (obj[charkey].match(/^\s*$/) && !cdata) { emptyStr = obj[charkey]; delete obj[charkey]; } else { if (_this.options.trim) { obj[charkey] = obj[charkey].trim(); } if (_this.options.normalize) { obj[charkey] = obj[charkey].replace(/\s{2,}/g, " ").trim(); } obj[charkey] = _this.options.valueProcessors ? processItem(_this.options.valueProcessors, obj[charkey], nodeName) : obj[charkey]; if (Object.keys(obj).length === 1 && charkey in obj && !_this.EXPLICIT_CHARKEY) { obj = obj[charkey]; } } if (isEmpty(obj)) { if (typeof _this.options.emptyTag === 'function') { obj = _this.options.emptyTag(); } else { obj = _this.options.emptyTag !== '' ? _this.options.emptyTag : emptyStr; } } if (_this.options.validator != null) { xpath = "/" + ((function() { var i, len, results; results = []; for (i = 0, len = stack.length; i < len; i++) { node = stack[i]; results.push(node["#name"]); } return results; })()).concat(nodeName).join("/"); (function() { var err; try { return obj = _this.options.validator(xpath, s && s[nodeName], obj); } catch (error1) { err = error1; return _this.emit("error", err); } })(); } if (_this.options.explicitChildren && !_this.options.mergeAttrs && typeof obj === 'object') { if (!_this.options.preserveChildrenOrder) { node = Object.create(null); if (_this.options.attrkey in obj) { node[_this.options.attrkey] = obj[_this.options.attrkey]; delete obj[_this.options.attrkey]; } if (!_this.options.charsAsChildren && _this.options.charkey in obj) { node[_this.options.charkey] = obj[_this.options.charkey]; delete obj[_this.options.charkey]; } if (Object.getOwnPropertyNames(obj).length > 0) { node[_this.options.childkey] = obj; } obj = node; } else if (s) { s[_this.options.childkey] = s[_this.options.childkey] || []; objClone = Object.create(null); for (key in obj) { if (!hasProp.call(obj, key)) continue; objClone[key] = obj[key]; } s[_this.options.childkey].push(objClone); delete obj["#name"]; if (Object.keys(obj).length === 1 && charkey in obj && !_this.EXPLICIT_CHARKEY) { obj = obj[charkey]; } } } if (stack.length > 0) { return _this.assignOrPush(s, nodeName, obj); } else { if (_this.options.explicitRoot) { old = obj; obj = Object.create(null); obj[nodeName] = old; } _this.resultObject = obj; _this.saxParser.ended = true; return _this.emit("end", _this.resultObject); } }; })(this); ontext = (function(_this) { return function(text) { var charChild, s; s = stack[stack.length - 1]; if (s) { s[charkey] += text; if (_this.options.explicitChildren && _this.options.preserveChildrenOrder && _this.options.charsAsChildren && (_this.options.includeWhiteChars || text.replace(/\\n/g, '').trim() !== '')) { s[_this.options.childkey] = s[_this.options.childkey] || []; charChild = { '#name': '__text__' }; charChild[charkey] = text; if (_this.options.normalize) { charChild[charkey] = charChild[charkey].replace(/\s{2,}/g, " ").trim(); } s[_this.options.childkey].push(charChild); } return s; } }; })(this); this.saxParser.ontext = ontext; return this.saxParser.oncdata = (function(_this) { return function(text) { var s; s = ontext(text); if (s) { return s.cdata = true; } }; })(this); }; Parser.prototype.parseString = function(str, cb) { var err; if ((cb != null) && typeof cb === "function") { this.on("end", function(result) { this.reset(); return cb(null, result); }); this.on("error", function(err) { this.reset(); return cb(err); }); } try { str = str.toString(); if (str.trim() === '') { this.emit("end", null); return true; } str = bom.stripBOM(str); if (this.options.async) { this.remaining = str; setImmediate(this.processAsync); return this.saxParser; } return this.saxParser.write(str).close(); } catch (error1) { err = error1; if (!(this.saxParser.errThrown || this.saxParser.ended)) { this.emit('error', err); return this.saxParser.errThrown = true; } else if (this.saxParser.ended) { throw err; } } }; Parser.prototype.parseStringPromise = function(str) { return new Promise((function(_this) { return function(resolve, reject) { return _this.parseString(str, function(err, value) { if (err) { return reject(err); } else { return resolve(value); } }); }; })(this)); }; return Parser; })(events); exports.parseString = function(str, a, b) { var cb, options, parser; if (b != null) { if (typeof b === 'function') { cb = b; } if (typeof a === 'object') { options = a; } } else { if (typeof a === 'function') { cb = a; } options = {}; } parser = new exports.Parser(options); return parser.parseString(str, cb); }; exports.parseStringPromise = function(str, a) { var options, parser; if (typeof a === 'object') { options = a; } parser = new exports.Parser(options); return parser.parseStringPromise(str); }; }).call(this); /***/ }), /***/ 99236: /***/ (function(__unused_webpack_module, exports) { // Generated by CoffeeScript 1.12.7 (function() { "use strict"; var prefixMatch; prefixMatch = new RegExp(/(?!xmlns)^.*:/); exports.normalize = function(str) { return str.toLowerCase(); }; exports.firstCharLowerCase = function(str) { return str.charAt(0).toLowerCase() + str.slice(1); }; exports.stripPrefix = function(str) { return str.replace(prefixMatch, ''); }; exports.parseNumbers = function(str) { if (!isNaN(str)) { str = str % 1 === 0 ? parseInt(str, 10) : parseFloat(str); } return str; }; exports.parseBooleans = function(str) { if (/^(?:true|false)$/i.test(str)) { str = str.toLowerCase() === 'true'; } return str; }; }).call(this); /***/ }), /***/ 66189: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { // Generated by CoffeeScript 1.12.7 (function() { "use strict"; var builder, defaults, parser, processors, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; defaults = __nccwpck_require__(97251); builder = __nccwpck_require__(43337); parser = __nccwpck_require__(83314); processors = __nccwpck_require__(99236); exports.defaults = defaults.defaults; exports.processors = processors; exports.ValidationError = (function(superClass) { extend(ValidationError, superClass); function ValidationError(message) { this.message = message; } return ValidationError; })(Error); exports.Builder = builder.Builder; exports.Parser = parser.Parser; exports.parseString = parser.parseString; exports.parseStringPromise = parser.parseStringPromise; }).call(this); /***/ }), /***/ 41695: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { ;(function (sax) { // wrapper for non-node envs sax.parser = function (strict, opt) { return new SAXParser(strict, opt) } sax.SAXParser = SAXParser sax.SAXStream = SAXStream sax.createStream = createStream // When we pass the MAX_BUFFER_LENGTH position, start checking for buffer overruns. // When we check, schedule the next check for MAX_BUFFER_LENGTH - (max(buffer lengths)), // since that's the earliest that a buffer overrun could occur. This way, checks are // as rare as required, but as often as necessary to ensure never crossing this bound. // Furthermore, buffers are only tested at most once per write(), so passing a very // large string into write() might have undesirable effects, but this is manageable by // the caller, so it is assumed to be safe. Thus, a call to write() may, in the extreme // edge case, result in creating at most one complete copy of the string passed in. // Set to Infinity to have unlimited buffers. sax.MAX_BUFFER_LENGTH = 64 * 1024 var buffers = [ 'comment', 'sgmlDecl', 'textNode', 'tagName', 'doctype', 'procInstName', 'procInstBody', 'entity', 'attribName', 'attribValue', 'cdata', 'script' ] sax.EVENTS = [ 'text', 'processinginstruction', 'sgmldeclaration', 'doctype', 'comment', 'opentagstart', 'attribute', 'opentag', 'closetag', 'opencdata', 'cdata', 'closecdata', 'error', 'end', 'ready', 'script', 'opennamespace', 'closenamespace' ] function SAXParser (strict, opt) { if (!(this instanceof SAXParser)) { return new SAXParser(strict, opt) } var parser = this clearBuffers(parser) parser.q = parser.c = '' parser.bufferCheckPosition = sax.MAX_BUFFER_LENGTH parser.opt = opt || {} parser.opt.lowercase = parser.opt.lowercase || parser.opt.lowercasetags parser.looseCase = parser.opt.lowercase ? 'toLowerCase' : 'toUpperCase' parser.tags = [] parser.closed = parser.closedRoot = parser.sawRoot = false parser.tag = parser.error = null parser.strict = !!strict parser.noscript = !!(strict || parser.opt.noscript) parser.state = S.BEGIN parser.strictEntities = parser.opt.strictEntities parser.ENTITIES = parser.strictEntities ? Object.create(sax.XML_ENTITIES) : Object.create(sax.ENTITIES) parser.attribList = [] // namespaces form a prototype chain. // it always points at the current tag, // which protos to its parent tag. if (parser.opt.xmlns) { parser.ns = Object.create(rootNS) } // mostly just for error reporting parser.trackPosition = parser.opt.position !== false if (parser.trackPosition) { parser.position = parser.line = parser.column = 0 } emit(parser, 'onready') } if (!Object.create) { Object.create = function (o) { function F () {} F.prototype = o var newf = new F() return newf } } if (!Object.keys) { Object.keys = function (o) { var a = [] for (var i in o) if (o.hasOwnProperty(i)) a.push(i) return a } } function checkBufferLength (parser) { var maxAllowed = Math.max(sax.MAX_BUFFER_LENGTH, 10) var maxActual = 0 for (var i = 0, l = buffers.length; i < l; i++) { var len = parser[buffers[i]].length if (len > maxAllowed) { // Text/cdata nodes can get big, and since they're buffered, // we can get here under normal conditions. // Avoid issues by emitting the text node now, // so at least it won't get any bigger. switch (buffers[i]) { case 'textNode': closeText(parser) break case 'cdata': emitNode(parser, 'oncdata', parser.cdata) parser.cdata = '' break case 'script': emitNode(parser, 'onscript', parser.script) parser.script = '' break default: error(parser, 'Max buffer length exceeded: ' + buffers[i]) } } maxActual = Math.max(maxActual, len) } // schedule the next check for the earliest possible buffer overrun. var m = sax.MAX_BUFFER_LENGTH - maxActual parser.bufferCheckPosition = m + parser.position } function clearBuffers (parser) { for (var i = 0, l = buffers.length; i < l; i++) { parser[buffers[i]] = '' } } function flushBuffers (parser) { closeText(parser) if (parser.cdata !== '') { emitNode(parser, 'oncdata', parser.cdata) parser.cdata = '' } if (parser.script !== '') { emitNode(parser, 'onscript', parser.script) parser.script = '' } } SAXParser.prototype = { end: function () { end(this) }, write: write, resume: function () { this.error = null; return this }, close: function () { return this.write(null) }, flush: function () { flushBuffers(this) } } var Stream try { Stream = (__nccwpck_require__(12781).Stream) } catch (ex) { Stream = function () {} } var streamWraps = sax.EVENTS.filter(function (ev) { return ev !== 'error' && ev !== 'end' }) function createStream (strict, opt) { return new SAXStream(strict, opt) } function SAXStream (strict, opt) { if (!(this instanceof SAXStream)) { return new SAXStream(strict, opt) } Stream.apply(this) this._parser = new SAXParser(strict, opt) this.writable = true this.readable = true var me = this this._parser.onend = function () { me.emit('end') } this._parser.onerror = function (er) { me.emit('error', er) // if didn't throw, then means error was handled. // go ahead and clear error, so we can write again. me._parser.error = null } this._decoder = null streamWraps.forEach(function (ev) { Object.defineProperty(me, 'on' + ev, { get: function () { return me._parser['on' + ev] }, set: function (h) { if (!h) { me.removeAllListeners(ev) me._parser['on' + ev] = h return h } me.on(ev, h) }, enumerable: true, configurable: false }) }) } SAXStream.prototype = Object.create(Stream.prototype, { constructor: { value: SAXStream } }) SAXStream.prototype.write = function (data) { if (typeof Buffer === 'function' && typeof Buffer.isBuffer === 'function' && Buffer.isBuffer(data)) { if (!this._decoder) { var SD = (__nccwpck_require__(71576).StringDecoder) this._decoder = new SD('utf8') } data = this._decoder.write(data) } this._parser.write(data.toString()) this.emit('data', data) return true } SAXStream.prototype.end = function (chunk) { if (chunk && chunk.length) { this.write(chunk) } this._parser.end() return true } SAXStream.prototype.on = function (ev, handler) { var me = this if (!me._parser['on' + ev] && streamWraps.indexOf(ev) !== -1) { me._parser['on' + ev] = function () { var args = arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments) args.splice(0, 0, ev) me.emit.apply(me, args) } } return Stream.prototype.on.call(me, ev, handler) } // this really needs to be replaced with character classes. // XML allows all manner of ridiculous numbers and digits. var CDATA = '[CDATA[' var DOCTYPE = 'DOCTYPE' var XML_NAMESPACE = 'http://www.w3.org/XML/1998/namespace' var XMLNS_NAMESPACE = 'http://www.w3.org/2000/xmlns/' var rootNS = { xml: XML_NAMESPACE, xmlns: XMLNS_NAMESPACE } // http://www.w3.org/TR/REC-xml/#NT-NameStartChar // This implementation works on strings, a single character at a time // as such, it cannot ever support astral-plane characters (10000-EFFFF) // without a significant breaking change to either this parser, or the // JavaScript language. Implementation of an emoji-capable xml parser // is left as an exercise for the reader. var nameStart = /[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/ var nameBody = /[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/ var entityStart = /[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/ var entityBody = /[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/ function isWhitespace (c) { return c === ' ' || c === '\n' || c === '\r' || c === '\t' } function isQuote (c) { return c === '"' || c === '\'' } function isAttribEnd (c) { return c === '>' || isWhitespace(c) } function isMatch (regex, c) { return regex.test(c) } function notMatch (regex, c) { return !isMatch(regex, c) } var S = 0 sax.STATE = { BEGIN: S++, // leading byte order mark or whitespace BEGIN_WHITESPACE: S++, // leading whitespace TEXT: S++, // general stuff TEXT_ENTITY: S++, // & and such. OPEN_WAKA: S++, // < SGML_DECL: S++, // SCRIPT: S++, //